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/ErrorHandling.h"
21 #include <cstddef>
22 
23 using namespace llvm;
24 
25 namespace llvm {
26 
27 namespace {
28 
29 /// A class for maintaining the slot number definition
30 /// as a placeholder for the actual definition for forward constants defs.
31 class ConstantPlaceHolder : public ConstantExpr {
32 public:
33   explicit ConstantPlaceHolder(Type *Ty, LLVMContext &Context)
34       : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
35     Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
36   }
37 
38   ConstantPlaceHolder &operator=(const ConstantPlaceHolder &) = delete;
39 
40   // allocate space for exactly one operand
41   void *operator new(size_t s) { return User::operator new(s, 1); }
42 
43   /// Methods to support type inquiry through isa, cast, and dyn_cast.
44   static bool classof(const Value *V) {
45     return isa<ConstantExpr>(V) &&
46            cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
47   }
48 
49   /// Provide fast operand accessors
50   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
51 };
52 
53 } // end anonymous namespace
54 
55 // FIXME: can we inherit this from ConstantExpr?
56 template <>
57 struct OperandTraits<ConstantPlaceHolder>
58     : public FixedNumOperandTraits<ConstantPlaceHolder, 1> {};
59 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantPlaceHolder, Value)
60 
61 } // end namespace llvm
62 
63 void BitcodeReaderValueList::assignValue(unsigned Idx, Value *V) {
64   if (Idx == size()) {
65     push_back(V);
66     return;
67   }
68 
69   if (Idx >= size())
70     resize(Idx + 1);
71 
72   WeakTrackingVH &OldV = ValuePtrs[Idx];
73   if (!OldV) {
74     OldV = V;
75     return;
76   }
77 
78   // Handle constants and non-constants (e.g. instrs) differently for
79   // efficiency.
80   if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
81     ResolveConstants.push_back(std::make_pair(PHC, Idx));
82     OldV = V;
83   } else {
84     // If there was a forward reference to this value, replace it.
85     Value *PrevVal = OldV;
86     OldV->replaceAllUsesWith(V);
87     PrevVal->deleteValue();
88   }
89 }
90 
91 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx, Type *Ty) {
92   // Bail out for a clearly invalid value.
93   if (Idx >= RefsUpperBound)
94     return nullptr;
95 
96   if (Idx >= size())
97     resize(Idx + 1);
98 
99   if (Value *V = ValuePtrs[Idx]) {
100     if (Ty != V->getType())
101       report_fatal_error("Type mismatch in constant table!");
102     return cast<Constant>(V);
103   }
104 
105   // Create and return a placeholder, which will later be RAUW'd.
106   Constant *C = new ConstantPlaceHolder(Ty, Context);
107   ValuePtrs[Idx] = C;
108   return C;
109 }
110 
111 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
112   // Bail out for a clearly invalid value.
113   if (Idx >= RefsUpperBound)
114     return nullptr;
115 
116   if (Idx >= size())
117     resize(Idx + 1);
118 
119   if (Value *V = ValuePtrs[Idx]) {
120     // If the types don't match, it's invalid.
121     if (Ty && Ty != V->getType())
122       return nullptr;
123     return V;
124   }
125 
126   // No type specified, must be invalid reference.
127   if (!Ty)
128     return nullptr;
129 
130   // Create and return a placeholder, which will later be RAUW'd.
131   Value *V = new Argument(Ty);
132   ValuePtrs[Idx] = V;
133   return V;
134 }
135 
136 /// Once all constants are read, this method bulk resolves any forward
137 /// references.  The idea behind this is that we sometimes get constants (such
138 /// as large arrays) which reference *many* forward ref constants.  Replacing
139 /// each of these causes a lot of thrashing when building/reuniquing the
140 /// constant.  Instead of doing this, we look at all the uses and rewrite all
141 /// the place holders at once for any constant that uses a placeholder.
142 void BitcodeReaderValueList::resolveConstantForwardRefs() {
143   // Sort the values by-pointer so that they are efficient to look up with a
144   // binary search.
145   llvm::sort(ResolveConstants);
146 
147   SmallVector<Constant *, 64> NewOps;
148 
149   while (!ResolveConstants.empty()) {
150     Value *RealVal = operator[](ResolveConstants.back().second);
151     Constant *Placeholder = ResolveConstants.back().first;
152     ResolveConstants.pop_back();
153 
154     // Loop over all users of the placeholder, updating them to reference the
155     // new value.  If they reference more than one placeholder, update them all
156     // at once.
157     while (!Placeholder->use_empty()) {
158       auto UI = Placeholder->user_begin();
159       User *U = *UI;
160 
161       // If the using object isn't uniqued, just update the operands.  This
162       // handles instructions and initializers for global variables.
163       if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
164         UI.getUse().set(RealVal);
165         continue;
166       }
167 
168       // Otherwise, we have a constant that uses the placeholder.  Replace that
169       // constant with a new constant that has *all* placeholder uses updated.
170       Constant *UserC = cast<Constant>(U);
171       for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end(); I != E;
172            ++I) {
173         Value *NewOp;
174         if (!isa<ConstantPlaceHolder>(*I)) {
175           // Not a placeholder reference.
176           NewOp = *I;
177         } else if (*I == Placeholder) {
178           // Common case is that it just references this one placeholder.
179           NewOp = RealVal;
180         } else {
181           // Otherwise, look up the placeholder in ResolveConstants.
182           ResolveConstantsTy::iterator It = llvm::lower_bound(
183               ResolveConstants,
184               std::pair<Constant *, unsigned>(cast<Constant>(*I), 0));
185           assert(It != ResolveConstants.end() && It->first == *I);
186           NewOp = operator[](It->second);
187         }
188 
189         NewOps.push_back(cast<Constant>(NewOp));
190       }
191 
192       // Make the new constant.
193       Constant *NewC;
194       if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
195         NewC = ConstantArray::get(UserCA->getType(), NewOps);
196       } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
197         NewC = ConstantStruct::get(UserCS->getType(), NewOps);
198       } else if (isa<ConstantVector>(UserC)) {
199         NewC = ConstantVector::get(NewOps);
200       } else {
201         assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
202         NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
203       }
204 
205       UserC->replaceAllUsesWith(NewC);
206       UserC->destroyConstant();
207       NewOps.clear();
208     }
209 
210     // Update all ValueHandles, they should be the only users at this point.
211     Placeholder->replaceAllUsesWith(RealVal);
212     delete cast<ConstantPlaceHolder>(Placeholder);
213   }
214 }
215