LLVM  15.0.0git
ValueList.cpp
Go to the documentation of this file.
1 //===- ValueList.cpp - Internal BitcodeReader implementation --------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "ValueList.h"
10 #include "llvm/ADT/SmallVector.h"
11 #include "llvm/IR/Argument.h"
12 #include "llvm/IR/Constant.h"
13 #include "llvm/IR/Constants.h"
14 #include "llvm/IR/GlobalValue.h"
15 #include "llvm/IR/Instruction.h"
16 #include "llvm/IR/Type.h"
17 #include "llvm/IR/User.h"
18 #include "llvm/IR/Value.h"
19 #include "llvm/Support/Casting.h"
20 #include "llvm/Support/Error.h"
22 #include <cstddef>
23 
24 using namespace llvm;
25 
26 namespace llvm {
27 
28 namespace {
29 
30 /// A class for maintaining the slot number definition
31 /// as a placeholder for the actual definition for forward constants defs.
32 class ConstantPlaceHolder : public ConstantExpr {
33 public:
34  explicit ConstantPlaceHolder(Type *Ty, LLVMContext &Context)
35  : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
37  }
38 
39  ConstantPlaceHolder &operator=(const ConstantPlaceHolder &) = delete;
40 
41  // allocate space for exactly one operand
42  void *operator new(size_t s) { return User::operator new(s, 1); }
43 
44  /// Methods to support type inquiry through isa, cast, and dyn_cast.
45  static bool classof(const Value *V) {
46  return isa<ConstantExpr>(V) &&
47  cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
48  }
49 
50  /// Provide fast operand accessors
52 };
53 
54 } // end anonymous namespace
55 
56 // FIXME: can we inherit this from ConstantExpr?
57 template <>
58 struct OperandTraits<ConstantPlaceHolder>
59  : public FixedNumOperandTraits<ConstantPlaceHolder, 1> {};
60 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantPlaceHolder, Value)
61 
62 } // end namespace llvm
63 
65  unsigned TypeID) {
66  if (Idx == size()) {
67  push_back(V, TypeID);
68  return Error::success();
69  }
70 
71  if (Idx >= size())
72  resize(Idx + 1);
73 
74  auto &Old = ValuePtrs[Idx];
75  if (!Old.first) {
76  Old.first = V;
77  Old.second = TypeID;
78  return Error::success();
79  }
80 
81  // Handle constants and non-constants (e.g. instrs) differently for
82  // efficiency.
83  if (Constant *PHC = dyn_cast<Constant>(&*Old.first)) {
84  ResolveConstants.push_back(std::make_pair(PHC, Idx));
85  Old.first = V;
86  Old.second = TypeID;
87  } else {
88  // If there was a forward reference to this value, replace it.
89  Value *PrevVal = Old.first;
90  if (PrevVal->getType() != V->getType())
91  return createStringError(
92  std::errc::illegal_byte_sequence,
93  "Assigned value does not match type of forward declaration");
94  Old.first->replaceAllUsesWith(V);
95  PrevVal->deleteValue();
96  }
97  return Error::success();
98 }
99 
101  unsigned TyID) {
102  // Bail out for a clearly invalid value.
103  if (Idx >= RefsUpperBound)
104  return nullptr;
105 
106  if (Idx >= size())
107  resize(Idx + 1);
108 
109  if (Value *V = ValuePtrs[Idx].first) {
110  if (Ty != V->getType())
111  report_fatal_error("Type mismatch in constant table!");
112  return cast<Constant>(V);
113  }
114 
115  // Create and return a placeholder, which will later be RAUW'd.
116  Constant *C = new ConstantPlaceHolder(Ty, Context);
117  ValuePtrs[Idx] = {C, TyID};
118  return C;
119 }
120 
122  unsigned TyID) {
123  // Bail out for a clearly invalid value.
124  if (Idx >= RefsUpperBound)
125  return nullptr;
126 
127  if (Idx >= size())
128  resize(Idx + 1);
129 
130  if (Value *V = ValuePtrs[Idx].first) {
131  // If the types don't match, it's invalid.
132  if (Ty && Ty != V->getType())
133  return nullptr;
134  return V;
135  }
136 
137  // No type specified, must be invalid reference.
138  if (!Ty)
139  return nullptr;
140 
141  // Create and return a placeholder, which will later be RAUW'd.
142  Value *V = new Argument(Ty);
143  ValuePtrs[Idx] = {V, TyID};
144  return V;
145 }
146 
147 /// Once all constants are read, this method bulk resolves any forward
148 /// references. The idea behind this is that we sometimes get constants (such
149 /// as large arrays) which reference *many* forward ref constants. Replacing
150 /// each of these causes a lot of thrashing when building/reuniquing the
151 /// constant. Instead of doing this, we look at all the uses and rewrite all
152 /// the place holders at once for any constant that uses a placeholder.
154  // Sort the values by-pointer so that they are efficient to look up with a
155  // binary search.
156  llvm::sort(ResolveConstants);
157 
159 
160  while (!ResolveConstants.empty()) {
161  Value *RealVal = operator[](ResolveConstants.back().second);
162  Constant *Placeholder = ResolveConstants.back().first;
163  ResolveConstants.pop_back();
164 
165  // Loop over all users of the placeholder, updating them to reference the
166  // new value. If they reference more than one placeholder, update them all
167  // at once.
168  while (!Placeholder->use_empty()) {
169  auto UI = Placeholder->user_begin();
170  User *U = *UI;
171 
172  // If the using object isn't uniqued, just update the operands. This
173  // handles instructions and initializers for global variables.
174  if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
175  UI.getUse().set(RealVal);
176  continue;
177  }
178 
179  // Otherwise, we have a constant that uses the placeholder. Replace that
180  // constant with a new constant that has *all* placeholder uses updated.
181  Constant *UserC = cast<Constant>(U);
182  for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end(); I != E;
183  ++I) {
184  Value *NewOp;
185  if (!isa<ConstantPlaceHolder>(*I)) {
186  // Not a placeholder reference.
187  NewOp = *I;
188  } else if (*I == Placeholder) {
189  // Common case is that it just references this one placeholder.
190  NewOp = RealVal;
191  } else {
192  // Otherwise, look up the placeholder in ResolveConstants.
193  ResolveConstantsTy::iterator It = llvm::lower_bound(
194  ResolveConstants,
195  std::pair<Constant *, unsigned>(cast<Constant>(*I), 0));
196  assert(It != ResolveConstants.end() && It->first == *I);
197  NewOp = operator[](It->second);
198  }
199 
200  NewOps.push_back(cast<Constant>(NewOp));
201  }
202 
203  // Make the new constant.
204  Constant *NewC;
205  if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
206  NewC = ConstantArray::get(UserCA->getType(), NewOps);
207  } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
208  NewC = ConstantStruct::get(UserCS->getType(), NewOps);
209  } else if (isa<ConstantVector>(UserC)) {
210  NewC = ConstantVector::get(NewOps);
211  } else {
212  assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
213  NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
214  }
215 
216  UserC->replaceAllUsesWith(NewC);
217  UserC->destroyConstant();
218  NewOps.clear();
219  }
220 
221  // Update all ValueHandles, they should be the only users at this point.
222  Placeholder->replaceAllUsesWith(RealVal);
223  delete cast<ConstantPlaceHolder>(Placeholder);
224  }
225 }
llvm::BitcodeReaderValueList::operator[]
Value * operator[](unsigned i) const
Definition: ValueList.h:72
llvm::Argument
This class represents an incoming formal argument to a Function.
Definition: Argument.h:28
llvm
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:17
ValueList.h
llvm::lower_bound
auto lower_bound(R &&Range, T &&Value)
Provide wrappers to std::lower_bound which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:1736
llvm::ConstantStruct::get
static Constant * get(StructType *T, ArrayRef< Constant * > V)
Definition: Constants.cpp:1355
llvm::SmallVector
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1185
ErrorHandling.h
llvm::Error::success
static ErrorSuccess success()
Create a success value.
Definition: Error.h:329
Error.h
llvm::Type
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
DEFINE_TRANSPARENT_OPERAND_ACCESSORS
#define DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CLASS, VALUECLASS)
Macro for generating out-of-class operand accessor definitions.
Definition: OperandTraits.h:125
llvm::Type::getInt32Ty
static IntegerType * getInt32Ty(LLVMContext &C)
Definition: Type.cpp:239
Context
LLVMContext & Context
Definition: NVVMIntrRange.cpp:66
Instruction.h
GlobalValue.h
llvm::OperandTraits
Compile-time customization of User operands.
Definition: User.h:42
Constants.h
E
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
llvm::User
Definition: User.h:44
C
(vector float) vec_cmpeq(*A, *B) C
Definition: README_ALTIVEC.txt:86
llvm::ConstantArray
ConstantArray - Constant Array Declarations.
Definition: Constants.h:410
llvm::Instruction
Definition: Instruction.h:42
llvm::report_fatal_error
void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Definition: Error.cpp:143
llvm::UndefValue::get
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
Definition: Constants.cpp:1777
Type.h
TypeID
Type::TypeID TypeID
Definition: Mips16HardFloat.cpp:102
llvm::Constant
This is an important base class in LLVM.
Definition: Constant.h:41
s
multiplies can be turned into SHL s
Definition: README.txt:370
llvm::LLVMContext
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:68
I
#define I(x, y, z)
Definition: MD5.cpp:58
llvm::BitcodeReaderValueList::push_back
void push_back(Value *V, unsigned TypeID)
Definition: ValueList.h:63
llvm::BitcodeReaderValueList::assignValue
Error assignValue(unsigned Idx, Value *V, unsigned TypeID)
Definition: ValueList.cpp:64
llvm::BitcodeReaderValueList::getConstantFwdRef
Constant * getConstantFwdRef(unsigned Idx, Type *Ty, unsigned TyID)
Definition: ValueList.cpp:100
assert
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
llvm::BitcodeReaderValueList::resize
void resize(unsigned N)
Definition: ValueList.h:60
llvm::BitcodeReaderValueList::resolveConstantForwardRefs
void resolveConstantForwardRefs()
Once all constants are read, this method bulk resolves any forward references.
Definition: ValueList.cpp:153
llvm::BitcodeReaderValueList::size
unsigned size() const
Definition: ValueList.h:59
llvm::ConstantStruct
Definition: Constants.h:442
llvm::BitcodeReaderValueList::getValueFwdRef
Value * getValueFwdRef(unsigned Idx, Type *Ty, unsigned TyID)
Definition: ValueList.cpp:121
llvm::Value::getType
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:255
llvm::Value::replaceAllUsesWith
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition: Value.cpp:529
llvm::ConstantVector::get
static Constant * get(ArrayRef< Constant * > V)
Definition: Constants.cpp:1397
Argument.h
Constant.h
llvm::ConstantExpr
A constant value that is initialized with an expression using other constant values.
Definition: Constants.h:972
llvm::createStringError
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
Definition: Error.h:1239
llvm::AMDGPU::SendMsg::Op
Op
Definition: SIDefines.h:345
llvm::Error
Lightweight error class with error context and mandatory checking.
Definition: Error.h:155
Casting.h
llvm::sort
void sort(IteratorTy Start, IteratorTy End)
Definition: STLExtras.h:1562
llvm::ConstantArray::get
static Constant * get(ArrayType *T, ArrayRef< Constant * > V)
Definition: Constants.cpp:1290
llvm::SmallVectorImpl::clear
void clear()
Definition: SmallVector.h:591
DECLARE_TRANSPARENT_OPERAND_ACCESSORS
#define DECLARE_TRANSPARENT_OPERAND_ACCESSORS(VALUECLASS)
Macro for generating in-class operand accessor declarations.
Definition: OperandTraits.h:110
SmallVector.h
User.h
llvm::User::op_begin
op_iterator op_begin()
Definition: User.h:234
llvm::Value::deleteValue
void deleteValue()
Delete a pointer to a generic Value.
Definition: Value.cpp:106
llvm::FixedNumOperandTraits
FixedNumOperandTraits - determine the allocation regime of the Use array when it is a prefix to the U...
Definition: OperandTraits.h:30
llvm::Type::TypeID
TypeID
Definitions of all of the base types for the Type system.
Definition: Type.h:54
Value.h
llvm::Value
LLVM Value Representation.
Definition: Value.h:74
llvm::Constant::destroyConstant
void destroyConstant()
Called if some element of this constant is no longer valid.
Definition: Constants.cpp:450
llvm::Use
A Use represents the edge between a Value definition and its users.
Definition: Use.h:43
llvm::User::op_end
op_iterator op_end()
Definition: User.h:236