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