blob: f5797164355d2a481d93059c96c7d2d2ab33bfe4 [file] [log] [blame]
Philip Reamesd16a9b12015-02-20 01:06:44 +00001//===- RewriteStatepointsForGC.cpp - Make GC relocations explicit ---------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Rewrite an existing set of gc.statepoints such that they make potential
11// relocations performed by the garbage collector explicit in the IR.
12//
13//===----------------------------------------------------------------------===//
14
15#include "llvm/Pass.h"
16#include "llvm/Analysis/CFG.h"
Philip Reamesabcdc5e2015-08-27 01:02:28 +000017#include "llvm/Analysis/InstructionSimplify.h"
Igor Laevskye0317182015-05-19 15:59:05 +000018#include "llvm/Analysis/TargetTransformInfo.h"
Philip Reamesd16a9b12015-02-20 01:06:44 +000019#include "llvm/ADT/SetOperations.h"
20#include "llvm/ADT/Statistic.h"
21#include "llvm/ADT/DenseSet.h"
Philip Reames4d80ede2015-04-10 23:11:26 +000022#include "llvm/ADT/SetVector.h"
Swaroop Sridhar665bc9c2015-05-20 01:07:23 +000023#include "llvm/ADT/StringRef.h"
Philip Reames15d55632015-09-09 23:26:08 +000024#include "llvm/ADT/MapVector.h"
Philip Reamesd16a9b12015-02-20 01:06:44 +000025#include "llvm/IR/BasicBlock.h"
26#include "llvm/IR/CallSite.h"
27#include "llvm/IR/Dominators.h"
28#include "llvm/IR/Function.h"
29#include "llvm/IR/IRBuilder.h"
30#include "llvm/IR/InstIterator.h"
31#include "llvm/IR/Instructions.h"
32#include "llvm/IR/Intrinsics.h"
33#include "llvm/IR/IntrinsicInst.h"
34#include "llvm/IR/Module.h"
Sanjoy Das353a19e2015-06-02 22:33:37 +000035#include "llvm/IR/MDBuilder.h"
Philip Reamesd16a9b12015-02-20 01:06:44 +000036#include "llvm/IR/Statepoint.h"
37#include "llvm/IR/Value.h"
38#include "llvm/IR/Verifier.h"
39#include "llvm/Support/Debug.h"
40#include "llvm/Support/CommandLine.h"
41#include "llvm/Transforms/Scalar.h"
42#include "llvm/Transforms/Utils/BasicBlockUtils.h"
43#include "llvm/Transforms/Utils/Cloning.h"
44#include "llvm/Transforms/Utils/Local.h"
45#include "llvm/Transforms/Utils/PromoteMemToReg.h"
46
47#define DEBUG_TYPE "rewrite-statepoints-for-gc"
48
49using namespace llvm;
50
Philip Reamesd16a9b12015-02-20 01:06:44 +000051// Print the liveset found at the insert location
52static cl::opt<bool> PrintLiveSet("spp-print-liveset", cl::Hidden,
53 cl::init(false));
Philip Reames704e78b2015-04-10 22:34:56 +000054static cl::opt<bool> PrintLiveSetSize("spp-print-liveset-size", cl::Hidden,
55 cl::init(false));
Philip Reamesd16a9b12015-02-20 01:06:44 +000056// Print out the base pointers for debugging
Philip Reames704e78b2015-04-10 22:34:56 +000057static cl::opt<bool> PrintBasePointers("spp-print-base-pointers", cl::Hidden,
58 cl::init(false));
Philip Reamesd16a9b12015-02-20 01:06:44 +000059
Igor Laevskye0317182015-05-19 15:59:05 +000060// Cost threshold measuring when it is profitable to rematerialize value instead
61// of relocating it
62static cl::opt<unsigned>
63RematerializationThreshold("spp-rematerialization-threshold", cl::Hidden,
64 cl::init(6));
65
Philip Reamese73300b2015-04-13 16:41:32 +000066#ifdef XDEBUG
67static bool ClobberNonLive = true;
68#else
69static bool ClobberNonLive = false;
70#endif
71static cl::opt<bool, true> ClobberNonLiveOverride("rs4gc-clobber-non-live",
72 cl::location(ClobberNonLive),
73 cl::Hidden);
74
Benjamin Kramer6f665452015-02-20 14:00:58 +000075namespace {
Sanjoy Dasea45f0e2015-06-02 22:33:34 +000076struct RewriteStatepointsForGC : public ModulePass {
Philip Reamesd16a9b12015-02-20 01:06:44 +000077 static char ID; // Pass identification, replacement for typeid
78
Sanjoy Dasea45f0e2015-06-02 22:33:34 +000079 RewriteStatepointsForGC() : ModulePass(ID) {
Philip Reamesd16a9b12015-02-20 01:06:44 +000080 initializeRewriteStatepointsForGCPass(*PassRegistry::getPassRegistry());
81 }
Sanjoy Dasea45f0e2015-06-02 22:33:34 +000082 bool runOnFunction(Function &F);
83 bool runOnModule(Module &M) override {
84 bool Changed = false;
85 for (Function &F : M)
86 Changed |= runOnFunction(F);
Sanjoy Das353a19e2015-06-02 22:33:37 +000087
88 if (Changed) {
89 // stripDereferenceabilityInfo asserts that shouldRewriteStatepointsIn
90 // returns true for at least one function in the module. Since at least
91 // one function changed, we know that the precondition is satisfied.
92 stripDereferenceabilityInfo(M);
93 }
94
Sanjoy Dasea45f0e2015-06-02 22:33:34 +000095 return Changed;
96 }
Philip Reamesd16a9b12015-02-20 01:06:44 +000097
98 void getAnalysisUsage(AnalysisUsage &AU) const override {
99 // We add and rewrite a bunch of instructions, but don't really do much
100 // else. We could in theory preserve a lot more analyses here.
101 AU.addRequired<DominatorTreeWrapperPass>();
Igor Laevskye0317182015-05-19 15:59:05 +0000102 AU.addRequired<TargetTransformInfoWrapperPass>();
Philip Reamesd16a9b12015-02-20 01:06:44 +0000103 }
Sanjoy Das353a19e2015-06-02 22:33:37 +0000104
105 /// The IR fed into RewriteStatepointsForGC may have had attributes implying
106 /// dereferenceability that are no longer valid/correct after
107 /// RewriteStatepointsForGC has run. This is because semantically, after
108 /// RewriteStatepointsForGC runs, all calls to gc.statepoint "free" the entire
109 /// heap. stripDereferenceabilityInfo (conservatively) restores correctness
110 /// by erasing all attributes in the module that externally imply
111 /// dereferenceability.
112 ///
113 void stripDereferenceabilityInfo(Module &M);
114
115 // Helpers for stripDereferenceabilityInfo
116 void stripDereferenceabilityInfoFromBody(Function &F);
117 void stripDereferenceabilityInfoFromPrototype(Function &F);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000118};
Benjamin Kramer6f665452015-02-20 14:00:58 +0000119} // namespace
Philip Reamesd16a9b12015-02-20 01:06:44 +0000120
121char RewriteStatepointsForGC::ID = 0;
122
Sanjoy Dasea45f0e2015-06-02 22:33:34 +0000123ModulePass *llvm::createRewriteStatepointsForGCPass() {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000124 return new RewriteStatepointsForGC();
125}
126
127INITIALIZE_PASS_BEGIN(RewriteStatepointsForGC, "rewrite-statepoints-for-gc",
128 "Make relocations explicit at statepoints", false, false)
129INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
130INITIALIZE_PASS_END(RewriteStatepointsForGC, "rewrite-statepoints-for-gc",
131 "Make relocations explicit at statepoints", false, false)
132
133namespace {
Philip Reamesdf1ef082015-04-10 22:53:14 +0000134struct GCPtrLivenessData {
135 /// Values defined in this block.
136 DenseMap<BasicBlock *, DenseSet<Value *>> KillSet;
137 /// Values used in this block (and thus live); does not included values
138 /// killed within this block.
139 DenseMap<BasicBlock *, DenseSet<Value *>> LiveSet;
140
141 /// Values live into this basic block (i.e. used by any
142 /// instruction in this basic block or ones reachable from here)
143 DenseMap<BasicBlock *, DenseSet<Value *>> LiveIn;
144
145 /// Values live out of this basic block (i.e. live into
146 /// any successor block)
147 DenseMap<BasicBlock *, DenseSet<Value *>> LiveOut;
148};
149
Philip Reamesd16a9b12015-02-20 01:06:44 +0000150// The type of the internal cache used inside the findBasePointers family
151// of functions. From the callers perspective, this is an opaque type and
152// should not be inspected.
153//
154// In the actual implementation this caches two relations:
155// - The base relation itself (i.e. this pointer is based on that one)
156// - The base defining value relation (i.e. before base_phi insertion)
157// Generally, after the execution of a full findBasePointer call, only the
158// base relation will remain. Internally, we add a mixture of the two
159// types, then update all the second type to the first type
Philip Reamese9c3b9b2015-02-20 22:48:20 +0000160typedef DenseMap<Value *, Value *> DefiningValueMapTy;
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +0000161typedef DenseSet<Value *> StatepointLiveSetTy;
Sanjoy Das40bdd042015-10-07 21:32:35 +0000162typedef DenseMap<AssertingVH<Instruction>, AssertingVH<Value>>
163 RematerializedValueMapTy;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000164
Philip Reamesd16a9b12015-02-20 01:06:44 +0000165struct PartiallyConstructedSafepointRecord {
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000166 /// The set of values known to be live across this safepoint
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +0000167 StatepointLiveSetTy LiveSet;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000168
169 /// Mapping from live pointers to a base-defining-value
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +0000170 DenseMap<Value *, Value *> PointerToBase;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000171
Philip Reames0a3240f2015-02-20 21:34:11 +0000172 /// The *new* gc.statepoint instruction itself. This produces the token
173 /// that normal path gc.relocates and the gc.result are tied to.
174 Instruction *StatepointToken;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000175
Philip Reamesf2041322015-02-20 19:26:04 +0000176 /// Instruction to which exceptional gc relocates are attached
177 /// Makes it easier to iterate through them during relocationViaAlloca.
178 Instruction *UnwindToken;
Igor Laevskye0317182015-05-19 15:59:05 +0000179
180 /// Record live values we are rematerialized instead of relocating.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +0000181 /// They are not included into 'LiveSet' field.
Igor Laevskye0317182015-05-19 15:59:05 +0000182 /// Maps rematerialized copy to it's original value.
183 RematerializedValueMapTy RematerializedValues;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000184};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000185}
Philip Reamesd16a9b12015-02-20 01:06:44 +0000186
Philip Reamesdf1ef082015-04-10 22:53:14 +0000187/// Compute the live-in set for every basic block in the function
188static void computeLiveInValues(DominatorTree &DT, Function &F,
189 GCPtrLivenessData &Data);
190
191/// Given results from the dataflow liveness computation, find the set of live
192/// Values at a particular instruction.
193static void findLiveSetAtInst(Instruction *inst, GCPtrLivenessData &Data,
194 StatepointLiveSetTy &out);
195
Philip Reamesd16a9b12015-02-20 01:06:44 +0000196// TODO: Once we can get to the GCStrategy, this becomes
197// Optional<bool> isGCManagedPointer(const Value *V) const override {
198
Craig Toppere3dcce92015-08-01 22:20:21 +0000199static bool isGCPointerType(Type *T) {
200 if (auto *PT = dyn_cast<PointerType>(T))
Philip Reamesd16a9b12015-02-20 01:06:44 +0000201 // For the sake of this example GC, we arbitrarily pick addrspace(1) as our
202 // GC managed heap. We know that a pointer into this heap needs to be
203 // updated and that no other pointer does.
204 return (1 == PT->getAddressSpace());
205 return false;
206}
207
Philip Reames8531d8c2015-04-10 21:48:25 +0000208// Return true if this type is one which a) is a gc pointer or contains a GC
209// pointer and b) is of a type this code expects to encounter as a live value.
210// (The insertion code will assert that a type which matches (a) and not (b)
Philip Reames704e78b2015-04-10 22:34:56 +0000211// is not encountered.)
Philip Reames8531d8c2015-04-10 21:48:25 +0000212static bool isHandledGCPointerType(Type *T) {
213 // We fully support gc pointers
214 if (isGCPointerType(T))
215 return true;
216 // We partially support vectors of gc pointers. The code will assert if it
217 // can't handle something.
218 if (auto VT = dyn_cast<VectorType>(T))
219 if (isGCPointerType(VT->getElementType()))
220 return true;
221 return false;
222}
223
224#ifndef NDEBUG
225/// Returns true if this type contains a gc pointer whether we know how to
226/// handle that type or not.
227static bool containsGCPtrType(Type *Ty) {
Philip Reames704e78b2015-04-10 22:34:56 +0000228 if (isGCPointerType(Ty))
Philip Reames8531d8c2015-04-10 21:48:25 +0000229 return true;
230 if (VectorType *VT = dyn_cast<VectorType>(Ty))
231 return isGCPointerType(VT->getScalarType());
232 if (ArrayType *AT = dyn_cast<ArrayType>(Ty))
233 return containsGCPtrType(AT->getElementType());
234 if (StructType *ST = dyn_cast<StructType>(Ty))
Philip Reames704e78b2015-04-10 22:34:56 +0000235 return std::any_of(
236 ST->subtypes().begin(), ST->subtypes().end(),
237 [](Type *SubType) { return containsGCPtrType(SubType); });
Philip Reames8531d8c2015-04-10 21:48:25 +0000238 return false;
239}
240
241// Returns true if this is a type which a) is a gc pointer or contains a GC
242// pointer and b) is of a type which the code doesn't expect (i.e. first class
243// aggregates). Used to trip assertions.
244static bool isUnhandledGCPointerType(Type *Ty) {
245 return containsGCPtrType(Ty) && !isHandledGCPointerType(Ty);
246}
247#endif
248
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +0000249static bool order_by_name(Value *a, Value *b) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000250 if (a->hasName() && b->hasName()) {
251 return -1 == a->getName().compare(b->getName());
252 } else if (a->hasName() && !b->hasName()) {
253 return true;
254 } else if (!a->hasName() && b->hasName()) {
255 return false;
256 } else {
257 // Better than nothing, but not stable
258 return a < b;
259 }
260}
261
Philip Reamesece70b82015-09-09 23:57:18 +0000262// Return the name of the value suffixed with the provided value, or if the
263// value didn't have a name, the default value specified.
264static std::string suffixed_name_or(Value *V, StringRef Suffix,
265 StringRef DefaultName) {
266 return V->hasName() ? (V->getName() + Suffix).str() : DefaultName.str();
267}
268
Philip Reamesdf1ef082015-04-10 22:53:14 +0000269// Conservatively identifies any definitions which might be live at the
270// given instruction. The analysis is performed immediately before the
271// given instruction. Values defined by that instruction are not considered
272// live. Values used by that instruction are considered live.
273static void analyzeParsePointLiveness(
274 DominatorTree &DT, GCPtrLivenessData &OriginalLivenessData,
275 const CallSite &CS, PartiallyConstructedSafepointRecord &result) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000276 Instruction *inst = CS.getInstruction();
277
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +0000278 StatepointLiveSetTy LiveSet;
279 findLiveSetAtInst(inst, OriginalLivenessData, LiveSet);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000280
281 if (PrintLiveSet) {
282 // Note: This output is used by several of the test cases
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000283 // The order of elements in a set is not stable, put them in a vec and sort
Philip Reamesd16a9b12015-02-20 01:06:44 +0000284 // by name
Philip Reamesdab35f32015-09-02 21:11:44 +0000285 SmallVector<Value *, 64> Temp;
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +0000286 Temp.insert(Temp.end(), LiveSet.begin(), LiveSet.end());
Philip Reamesdab35f32015-09-02 21:11:44 +0000287 std::sort(Temp.begin(), Temp.end(), order_by_name);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000288 errs() << "Live Variables:\n";
Philip Reamesdab35f32015-09-02 21:11:44 +0000289 for (Value *V : Temp)
290 dbgs() << " " << V->getName() << " " << *V << "\n";
Philip Reamesd16a9b12015-02-20 01:06:44 +0000291 }
292 if (PrintLiveSetSize) {
293 errs() << "Safepoint For: " << CS.getCalledValue()->getName() << "\n";
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +0000294 errs() << "Number live values: " << LiveSet.size() << "\n";
Philip Reamesd16a9b12015-02-20 01:06:44 +0000295 }
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +0000296 result.LiveSet = LiveSet;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000297}
298
Philip Reamesf5b8e472015-09-03 21:34:30 +0000299static bool isKnownBaseResult(Value *V);
300namespace {
301/// A single base defining value - An immediate base defining value for an
302/// instruction 'Def' is an input to 'Def' whose base is also a base of 'Def'.
303/// For instructions which have multiple pointer [vector] inputs or that
304/// transition between vector and scalar types, there is no immediate base
305/// defining value. The 'base defining value' for 'Def' is the transitive
306/// closure of this relation stopping at the first instruction which has no
307/// immediate base defining value. The b.d.v. might itself be a base pointer,
308/// but it can also be an arbitrary derived pointer.
309struct BaseDefiningValueResult {
310 /// Contains the value which is the base defining value.
311 Value * const BDV;
312 /// True if the base defining value is also known to be an actual base
313 /// pointer.
314 const bool IsKnownBase;
315 BaseDefiningValueResult(Value *BDV, bool IsKnownBase)
316 : BDV(BDV), IsKnownBase(IsKnownBase) {
317#ifndef NDEBUG
318 // Check consistency between new and old means of checking whether a BDV is
319 // a base.
320 bool MustBeBase = isKnownBaseResult(BDV);
321 assert(!MustBeBase || MustBeBase == IsKnownBase);
322#endif
323 }
324};
325}
326
327static BaseDefiningValueResult findBaseDefiningValue(Value *I);
Philip Reames311f7102015-05-12 22:19:52 +0000328
Philip Reames8fe7f132015-06-26 22:47:37 +0000329/// Return a base defining value for the 'Index' element of the given vector
330/// instruction 'I'. If Index is null, returns a BDV for the entire vector
331/// 'I'. As an optimization, this method will try to determine when the
332/// element is known to already be a base pointer. If this can be established,
333/// the second value in the returned pair will be true. Note that either a
334/// vector or a pointer typed value can be returned. For the former, the
335/// vector returned is a BDV (and possibly a base) of the entire vector 'I'.
336/// If the later, the return pointer is a BDV (or possibly a base) for the
337/// particular element in 'I'.
Philip Reamesf5b8e472015-09-03 21:34:30 +0000338static BaseDefiningValueResult
Philip Reames66287132015-09-09 23:40:12 +0000339findBaseDefiningValueOfVector(Value *I) {
Philip Reames8531d8c2015-04-10 21:48:25 +0000340 assert(I->getType()->isVectorTy() &&
341 cast<VectorType>(I->getType())->getElementType()->isPointerTy() &&
342 "Illegal to ask for the base pointer of a non-pointer type");
343
344 // Each case parallels findBaseDefiningValue below, see that code for
345 // detailed motivation.
346
347 if (isa<Argument>(I))
348 // An incoming argument to the function is a base pointer
Philip Reamesf5b8e472015-09-03 21:34:30 +0000349 return BaseDefiningValueResult(I, true);
Philip Reames8531d8c2015-04-10 21:48:25 +0000350
351 // We shouldn't see the address of a global as a vector value?
352 assert(!isa<GlobalVariable>(I) &&
353 "unexpected global variable found in base of vector");
354
355 // inlining could possibly introduce phi node that contains
356 // undef if callee has multiple returns
357 if (isa<UndefValue>(I))
358 // utterly meaningless, but useful for dealing with partially optimized
359 // code.
Philip Reamesf5b8e472015-09-03 21:34:30 +0000360 return BaseDefiningValueResult(I, true);
Philip Reames8531d8c2015-04-10 21:48:25 +0000361
362 // Due to inheritance, this must be _after_ the global variable and undef
363 // checks
364 if (Constant *Con = dyn_cast<Constant>(I)) {
365 assert(!isa<GlobalVariable>(I) && !isa<UndefValue>(I) &&
366 "order of checks wrong!");
367 assert(Con->isNullValue() && "null is the only case which makes sense");
Philip Reamesf5b8e472015-09-03 21:34:30 +0000368 return BaseDefiningValueResult(Con, true);
Philip Reames8531d8c2015-04-10 21:48:25 +0000369 }
Philip Reames8fe7f132015-06-26 22:47:37 +0000370
Philip Reames8531d8c2015-04-10 21:48:25 +0000371 if (isa<LoadInst>(I))
Philip Reamesf5b8e472015-09-03 21:34:30 +0000372 return BaseDefiningValueResult(I, true);
Philip Reamesf5b8e472015-09-03 21:34:30 +0000373
Philip Reames66287132015-09-09 23:40:12 +0000374 if (isa<InsertElementInst>(I))
Philip Reames8fe7f132015-06-26 22:47:37 +0000375 // We don't know whether this vector contains entirely base pointers or
376 // not. To be conservatively correct, we treat it as a BDV and will
377 // duplicate code as needed to construct a parallel vector of bases.
Philip Reames66287132015-09-09 23:40:12 +0000378 return BaseDefiningValueResult(I, false);
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +0000379
Philip Reames8fe7f132015-06-26 22:47:37 +0000380 if (isa<ShuffleVectorInst>(I))
381 // We don't know whether this vector contains entirely base pointers or
382 // not. To be conservatively correct, we treat it as a BDV and will
383 // duplicate code as needed to construct a parallel vector of bases.
384 // TODO: There a number of local optimizations which could be applied here
385 // for particular sufflevector patterns.
Philip Reamesf5b8e472015-09-03 21:34:30 +0000386 return BaseDefiningValueResult(I, false);
Philip Reames8fe7f132015-06-26 22:47:37 +0000387
388 // A PHI or Select is a base defining value. The outer findBasePointer
389 // algorithm is responsible for constructing a base value for this BDV.
390 assert((isa<SelectInst>(I) || isa<PHINode>(I)) &&
391 "unknown vector instruction - no base found for vector element");
Philip Reamesf5b8e472015-09-03 21:34:30 +0000392 return BaseDefiningValueResult(I, false);
Philip Reames8531d8c2015-04-10 21:48:25 +0000393}
394
Philip Reamesd16a9b12015-02-20 01:06:44 +0000395/// Helper function for findBasePointer - Will return a value which either a)
Philip Reames9ac4e382015-08-12 21:00:20 +0000396/// defines the base pointer for the input, b) blocks the simple search
397/// (i.e. a PHI or Select of two derived pointers), or c) involves a change
398/// from pointer to vector type or back.
Philip Reamesf5b8e472015-09-03 21:34:30 +0000399static BaseDefiningValueResult findBaseDefiningValue(Value *I) {
Philip Reames8fe7f132015-06-26 22:47:37 +0000400 if (I->getType()->isVectorTy())
Philip Reamesf5b8e472015-09-03 21:34:30 +0000401 return findBaseDefiningValueOfVector(I);
Philip Reames8fe7f132015-06-26 22:47:37 +0000402
Philip Reamesd16a9b12015-02-20 01:06:44 +0000403 assert(I->getType()->isPointerTy() &&
404 "Illegal to ask for the base pointer of a non-pointer type");
405
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000406 if (isa<Argument>(I))
Philip Reamesd16a9b12015-02-20 01:06:44 +0000407 // An incoming argument to the function is a base pointer
408 // We should have never reached here if this argument isn't an gc value
Philip Reamesf5b8e472015-09-03 21:34:30 +0000409 return BaseDefiningValueResult(I, true);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000410
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000411 if (isa<GlobalVariable>(I))
Philip Reamesd16a9b12015-02-20 01:06:44 +0000412 // base case
Philip Reamesf5b8e472015-09-03 21:34:30 +0000413 return BaseDefiningValueResult(I, true);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000414
415 // inlining could possibly introduce phi node that contains
416 // undef if callee has multiple returns
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000417 if (isa<UndefValue>(I))
418 // utterly meaningless, but useful for dealing with
419 // partially optimized code.
Philip Reamesf5b8e472015-09-03 21:34:30 +0000420 return BaseDefiningValueResult(I, true);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000421
422 // Due to inheritance, this must be _after_ the global variable and undef
423 // checks
Philip Reames3ea15892015-09-03 21:57:40 +0000424 if (isa<Constant>(I)) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000425 assert(!isa<GlobalVariable>(I) && !isa<UndefValue>(I) &&
426 "order of checks wrong!");
427 // Note: Finding a constant base for something marked for relocation
428 // doesn't really make sense. The most likely case is either a) some
429 // screwed up the address space usage or b) your validating against
430 // compiled C++ code w/o the proper separation. The only real exception
431 // is a null pointer. You could have generic code written to index of
432 // off a potentially null value and have proven it null. We also use
433 // null pointers in dead paths of relocation phis (which we might later
434 // want to find a base pointer for).
Philip Reames3ea15892015-09-03 21:57:40 +0000435 assert(isa<ConstantPointerNull>(I) &&
Philip Reames24c6cd52015-03-27 05:47:00 +0000436 "null is the only case which makes sense");
Philip Reamesf5b8e472015-09-03 21:34:30 +0000437 return BaseDefiningValueResult(I, true);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000438 }
439
440 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000441 Value *Def = CI->stripPointerCasts();
David Blaikie82ad7872015-02-20 23:44:24 +0000442 // If we find a cast instruction here, it means we've found a cast which is
443 // not simply a pointer cast (i.e. an inttoptr). We don't know how to
444 // handle int->ptr conversion.
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000445 assert(!isa<CastInst>(Def) && "shouldn't find another cast here");
446 return findBaseDefiningValue(Def);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000447 }
448
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000449 if (isa<LoadInst>(I))
Philip Reamesf5b8e472015-09-03 21:34:30 +0000450 // The value loaded is an gc base itself
451 return BaseDefiningValueResult(I, true);
452
Philip Reamesd16a9b12015-02-20 01:06:44 +0000453
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000454 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I))
455 // The base of this GEP is the base
456 return findBaseDefiningValue(GEP->getPointerOperand());
Philip Reamesd16a9b12015-02-20 01:06:44 +0000457
458 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
459 switch (II->getIntrinsicID()) {
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000460 case Intrinsic::experimental_gc_result_ptr:
Philip Reamesd16a9b12015-02-20 01:06:44 +0000461 default:
462 // fall through to general call handling
463 break;
464 case Intrinsic::experimental_gc_statepoint:
465 case Intrinsic::experimental_gc_result_float:
466 case Intrinsic::experimental_gc_result_int:
467 llvm_unreachable("these don't produce pointers");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000468 case Intrinsic::experimental_gc_relocate: {
469 // Rerunning safepoint insertion after safepoints are already
470 // inserted is not supported. It could probably be made to work,
471 // but why are you doing this? There's no good reason.
472 llvm_unreachable("repeat safepoint insertion is not supported");
473 }
474 case Intrinsic::gcroot:
475 // Currently, this mechanism hasn't been extended to work with gcroot.
476 // There's no reason it couldn't be, but I haven't thought about the
477 // implications much.
478 llvm_unreachable(
479 "interaction with the gcroot mechanism is not supported");
480 }
481 }
482 // We assume that functions in the source language only return base
483 // pointers. This should probably be generalized via attributes to support
484 // both source language and internal functions.
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000485 if (isa<CallInst>(I) || isa<InvokeInst>(I))
Philip Reamesf5b8e472015-09-03 21:34:30 +0000486 return BaseDefiningValueResult(I, true);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000487
488 // I have absolutely no idea how to implement this part yet. It's not
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000489 // necessarily hard, I just haven't really looked at it yet.
Philip Reamesd16a9b12015-02-20 01:06:44 +0000490 assert(!isa<LandingPadInst>(I) && "Landing Pad is unimplemented");
491
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000492 if (isa<AtomicCmpXchgInst>(I))
Philip Reamesd16a9b12015-02-20 01:06:44 +0000493 // A CAS is effectively a atomic store and load combined under a
494 // predicate. From the perspective of base pointers, we just treat it
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000495 // like a load.
Philip Reamesf5b8e472015-09-03 21:34:30 +0000496 return BaseDefiningValueResult(I, true);
Philip Reames704e78b2015-04-10 22:34:56 +0000497
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000498 assert(!isa<AtomicRMWInst>(I) && "Xchg handled above, all others are "
Philip Reames704e78b2015-04-10 22:34:56 +0000499 "binary ops which don't apply to pointers");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000500
501 // The aggregate ops. Aggregates can either be in the heap or on the
502 // stack, but in either case, this is simply a field load. As a result,
503 // this is a defining definition of the base just like a load is.
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000504 if (isa<ExtractValueInst>(I))
Philip Reamesf5b8e472015-09-03 21:34:30 +0000505 return BaseDefiningValueResult(I, true);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000506
507 // We should never see an insert vector since that would require we be
508 // tracing back a struct value not a pointer value.
509 assert(!isa<InsertValueInst>(I) &&
510 "Base pointer for a struct is meaningless");
511
Philip Reames9ac4e382015-08-12 21:00:20 +0000512 // An extractelement produces a base result exactly when it's input does.
513 // We may need to insert a parallel instruction to extract the appropriate
514 // element out of the base vector corresponding to the input. Given this,
515 // it's analogous to the phi and select case even though it's not a merge.
Philip Reames66287132015-09-09 23:40:12 +0000516 if (isa<ExtractElementInst>(I))
517 // Note: There a lot of obvious peephole cases here. This are deliberately
518 // handled after the main base pointer inference algorithm to make writing
519 // test cases to exercise that code easier.
520 return BaseDefiningValueResult(I, false);
Philip Reames9ac4e382015-08-12 21:00:20 +0000521
Philip Reamesd16a9b12015-02-20 01:06:44 +0000522 // The last two cases here don't return a base pointer. Instead, they
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000523 // return a value which dynamically selects from among several base
Philip Reamesd16a9b12015-02-20 01:06:44 +0000524 // derived pointers (each with it's own base potentially). It's the job of
525 // the caller to resolve these.
Philip Reames704e78b2015-04-10 22:34:56 +0000526 assert((isa<SelectInst>(I) || isa<PHINode>(I)) &&
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000527 "missing instruction case in findBaseDefiningValing");
Philip Reamesf5b8e472015-09-03 21:34:30 +0000528 return BaseDefiningValueResult(I, false);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000529}
530
531/// Returns the base defining value for this value.
Philip Reames18d0feb2015-03-27 05:39:32 +0000532static Value *findBaseDefiningValueCached(Value *I, DefiningValueMapTy &Cache) {
533 Value *&Cached = Cache[I];
Benjamin Kramer6f665452015-02-20 14:00:58 +0000534 if (!Cached) {
Philip Reamesf5b8e472015-09-03 21:34:30 +0000535 Cached = findBaseDefiningValue(I).BDV;
Philip Reames2a892a62015-07-23 22:25:26 +0000536 DEBUG(dbgs() << "fBDV-cached: " << I->getName() << " -> "
537 << Cached->getName() << "\n");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000538 }
Philip Reames18d0feb2015-03-27 05:39:32 +0000539 assert(Cache[I] != nullptr);
Benjamin Kramer6f665452015-02-20 14:00:58 +0000540 return Cached;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000541}
542
543/// Return a base pointer for this value if known. Otherwise, return it's
544/// base defining value.
Philip Reames18d0feb2015-03-27 05:39:32 +0000545static Value *findBaseOrBDV(Value *I, DefiningValueMapTy &Cache) {
546 Value *Def = findBaseDefiningValueCached(I, Cache);
547 auto Found = Cache.find(Def);
548 if (Found != Cache.end()) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000549 // Either a base-of relation, or a self reference. Caller must check.
Benjamin Kramer6f665452015-02-20 14:00:58 +0000550 return Found->second;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000551 }
552 // Only a BDV available
Philip Reames18d0feb2015-03-27 05:39:32 +0000553 return Def;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000554}
555
556/// Given the result of a call to findBaseDefiningValue, or findBaseOrBDV,
557/// is it known to be a base pointer? Or do we need to continue searching.
Philip Reames18d0feb2015-03-27 05:39:32 +0000558static bool isKnownBaseResult(Value *V) {
Philip Reames66287132015-09-09 23:40:12 +0000559 if (!isa<PHINode>(V) && !isa<SelectInst>(V) &&
560 !isa<ExtractElementInst>(V) && !isa<InsertElementInst>(V) &&
561 !isa<ShuffleVectorInst>(V)) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000562 // no recursion possible
563 return true;
564 }
Philip Reames18d0feb2015-03-27 05:39:32 +0000565 if (isa<Instruction>(V) &&
566 cast<Instruction>(V)->getMetadata("is_base_value")) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000567 // This is a previously inserted base phi or select. We know
568 // that this is a base value.
569 return true;
570 }
571
572 // We need to keep searching
573 return false;
574}
575
Philip Reamesd16a9b12015-02-20 01:06:44 +0000576namespace {
Philip Reames9b141ed2015-07-23 22:49:14 +0000577/// Models the state of a single base defining value in the findBasePointer
578/// algorithm for determining where a new instruction is needed to propagate
579/// the base of this BDV.
580class BDVState {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000581public:
582 enum Status { Unknown, Base, Conflict };
583
Philip Reames9b141ed2015-07-23 22:49:14 +0000584 BDVState(Status s, Value *b = nullptr) : status(s), base(b) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000585 assert(status != Base || b);
586 }
Philip Reames9b141ed2015-07-23 22:49:14 +0000587 explicit BDVState(Value *b) : status(Base), base(b) {}
588 BDVState() : status(Unknown), base(nullptr) {}
Philip Reamesd16a9b12015-02-20 01:06:44 +0000589
590 Status getStatus() const { return status; }
591 Value *getBase() const { return base; }
592
593 bool isBase() const { return getStatus() == Base; }
594 bool isUnknown() const { return getStatus() == Unknown; }
595 bool isConflict() const { return getStatus() == Conflict; }
596
Philip Reames9b141ed2015-07-23 22:49:14 +0000597 bool operator==(const BDVState &other) const {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000598 return base == other.base && status == other.status;
599 }
600
Philip Reames9b141ed2015-07-23 22:49:14 +0000601 bool operator!=(const BDVState &other) const { return !(*this == other); }
Philip Reamesd16a9b12015-02-20 01:06:44 +0000602
Philip Reames2a892a62015-07-23 22:25:26 +0000603 LLVM_DUMP_METHOD
604 void dump() const { print(dbgs()); dbgs() << '\n'; }
605
606 void print(raw_ostream &OS) const {
Philip Reamesdab35f32015-09-02 21:11:44 +0000607 switch (status) {
608 case Unknown:
609 OS << "U";
610 break;
611 case Base:
612 OS << "B";
613 break;
614 case Conflict:
615 OS << "C";
616 break;
617 };
618 OS << " (" << base << " - "
Philip Reames2a892a62015-07-23 22:25:26 +0000619 << (base ? base->getName() : "nullptr") << "): ";
Philip Reamesd16a9b12015-02-20 01:06:44 +0000620 }
621
622private:
623 Status status;
624 Value *base; // non null only if status == base
625};
Philip Reamesb3967cd2015-09-02 22:30:53 +0000626}
Philip Reamesd16a9b12015-02-20 01:06:44 +0000627
Philip Reames6906e922015-09-02 21:57:17 +0000628#ifndef NDEBUG
Philip Reamesb3967cd2015-09-02 22:30:53 +0000629static raw_ostream &operator<<(raw_ostream &OS, const BDVState &State) {
Philip Reames2a892a62015-07-23 22:25:26 +0000630 State.print(OS);
631 return OS;
632}
Philip Reames6906e922015-09-02 21:57:17 +0000633#endif
Philip Reames2a892a62015-07-23 22:25:26 +0000634
Philip Reamesb3967cd2015-09-02 22:30:53 +0000635namespace {
Philip Reames9b141ed2015-07-23 22:49:14 +0000636// Values of type BDVState form a lattice, and this is a helper
Philip Reamesd16a9b12015-02-20 01:06:44 +0000637// class that implementes the meet operation. The meat of the meet
Philip Reames9b141ed2015-07-23 22:49:14 +0000638// operation is implemented in MeetBDVStates::pureMeet
639class MeetBDVStates {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000640public:
Philip Reames273e6bb2015-07-23 21:41:27 +0000641 /// Initializes the currentResult to the TOP state so that if can be met with
642 /// any other state to produce that state.
Philip Reames9b141ed2015-07-23 22:49:14 +0000643 MeetBDVStates() {}
Philip Reamesd16a9b12015-02-20 01:06:44 +0000644
Philip Reames9b141ed2015-07-23 22:49:14 +0000645 // Destructively meet the current result with the given BDVState
646 void meetWith(BDVState otherState) {
Philip Reames273e6bb2015-07-23 21:41:27 +0000647 currentResult = meet(otherState, currentResult);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000648 }
649
Philip Reames9b141ed2015-07-23 22:49:14 +0000650 BDVState getResult() const { return currentResult; }
Philip Reamesd16a9b12015-02-20 01:06:44 +0000651
652private:
Philip Reames9b141ed2015-07-23 22:49:14 +0000653 BDVState currentResult;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000654
Philip Reames9b141ed2015-07-23 22:49:14 +0000655 /// Perform a meet operation on two elements of the BDVState lattice.
656 static BDVState meet(BDVState LHS, BDVState RHS) {
Philip Reames273e6bb2015-07-23 21:41:27 +0000657 assert((pureMeet(LHS, RHS) == pureMeet(RHS, LHS)) &&
658 "math is wrong: meet does not commute!");
Philip Reames9b141ed2015-07-23 22:49:14 +0000659 BDVState Result = pureMeet(LHS, RHS);
Philip Reames2a892a62015-07-23 22:25:26 +0000660 DEBUG(dbgs() << "meet of " << LHS << " with " << RHS
661 << " produced " << Result << "\n");
662 return Result;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000663 }
664
Philip Reames9b141ed2015-07-23 22:49:14 +0000665 static BDVState pureMeet(const BDVState &stateA, const BDVState &stateB) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000666 switch (stateA.getStatus()) {
Philip Reames9b141ed2015-07-23 22:49:14 +0000667 case BDVState::Unknown:
Philip Reamesd16a9b12015-02-20 01:06:44 +0000668 return stateB;
669
Philip Reames9b141ed2015-07-23 22:49:14 +0000670 case BDVState::Base:
Philip Reamesd16a9b12015-02-20 01:06:44 +0000671 assert(stateA.getBase() && "can't be null");
David Blaikie82ad7872015-02-20 23:44:24 +0000672 if (stateB.isUnknown())
Philip Reamesd16a9b12015-02-20 01:06:44 +0000673 return stateA;
David Blaikie82ad7872015-02-20 23:44:24 +0000674
675 if (stateB.isBase()) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000676 if (stateA.getBase() == stateB.getBase()) {
677 assert(stateA == stateB && "equality broken!");
678 return stateA;
679 }
Philip Reames9b141ed2015-07-23 22:49:14 +0000680 return BDVState(BDVState::Conflict);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000681 }
David Blaikie82ad7872015-02-20 23:44:24 +0000682 assert(stateB.isConflict() && "only three states!");
Philip Reames9b141ed2015-07-23 22:49:14 +0000683 return BDVState(BDVState::Conflict);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000684
Philip Reames9b141ed2015-07-23 22:49:14 +0000685 case BDVState::Conflict:
Philip Reamesd16a9b12015-02-20 01:06:44 +0000686 return stateA;
687 }
Reid Klecknera070ee52015-02-20 19:46:02 +0000688 llvm_unreachable("only three states!");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000689 }
690};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000691}
Philip Reamesb3967cd2015-09-02 22:30:53 +0000692
693
Philip Reamesd16a9b12015-02-20 01:06:44 +0000694/// For a given value or instruction, figure out what base ptr it's derived
695/// from. For gc objects, this is simply itself. On success, returns a value
696/// which is the base pointer. (This is reliable and can be used for
697/// relocation.) On failure, returns nullptr.
Philip Reamesba198492015-04-14 00:41:34 +0000698static Value *findBasePointer(Value *I, DefiningValueMapTy &cache) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000699 Value *def = findBaseOrBDV(I, cache);
700
701 if (isKnownBaseResult(def)) {
702 return def;
703 }
704
705 // Here's the rough algorithm:
706 // - For every SSA value, construct a mapping to either an actual base
707 // pointer or a PHI which obscures the base pointer.
708 // - Construct a mapping from PHI to unknown TOP state. Use an
709 // optimistic algorithm to propagate base pointer information. Lattice
710 // looks like:
711 // UNKNOWN
712 // b1 b2 b3 b4
713 // CONFLICT
714 // When algorithm terminates, all PHIs will either have a single concrete
715 // base or be in a conflict state.
716 // - For every conflict, insert a dummy PHI node without arguments. Add
717 // these to the base[Instruction] = BasePtr mapping. For every
718 // non-conflict, add the actual base.
719 // - For every conflict, add arguments for the base[a] of each input
720 // arguments.
721 //
722 // Note: A simpler form of this would be to add the conflict form of all
723 // PHIs without running the optimistic algorithm. This would be
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000724 // analogous to pessimistic data flow and would likely lead to an
Philip Reamesd16a9b12015-02-20 01:06:44 +0000725 // overall worse solution.
726
Philip Reames29e9ae72015-07-24 00:42:55 +0000727#ifndef NDEBUG
Philip Reames88958b22015-07-24 00:02:11 +0000728 auto isExpectedBDVType = [](Value *BDV) {
Philip Reames66287132015-09-09 23:40:12 +0000729 return isa<PHINode>(BDV) || isa<SelectInst>(BDV) ||
730 isa<ExtractElementInst>(BDV) || isa<InsertElementInst>(BDV);
Philip Reames88958b22015-07-24 00:02:11 +0000731 };
Philip Reames29e9ae72015-07-24 00:42:55 +0000732#endif
Philip Reames88958b22015-07-24 00:02:11 +0000733
734 // Once populated, will contain a mapping from each potentially non-base BDV
735 // to a lattice value (described above) which corresponds to that BDV.
Philip Reames15d55632015-09-09 23:26:08 +0000736 // We use the order of insertion (DFS over the def/use graph) to provide a
737 // stable deterministic ordering for visiting DenseMaps (which are unordered)
738 // below. This is important for deterministic compilation.
Philip Reames34d7a742015-09-10 00:22:49 +0000739 MapVector<Value *, BDVState> States;
Philip Reames15d55632015-09-09 23:26:08 +0000740
741 // Recursively fill in all base defining values reachable from the initial
742 // one for which we don't already know a definite base value for
Philip Reames88958b22015-07-24 00:02:11 +0000743 /* scope */ {
Philip Reames88958b22015-07-24 00:02:11 +0000744 SmallVector<Value*, 16> Worklist;
745 Worklist.push_back(def);
Philip Reames34d7a742015-09-10 00:22:49 +0000746 States.insert(std::make_pair(def, BDVState()));
Philip Reames88958b22015-07-24 00:02:11 +0000747 while (!Worklist.empty()) {
748 Value *Current = Worklist.pop_back_val();
749 assert(!isKnownBaseResult(Current) && "why did it get added?");
750
751 auto visitIncomingValue = [&](Value *InVal) {
752 Value *Base = findBaseOrBDV(InVal, cache);
753 if (isKnownBaseResult(Base))
754 // Known bases won't need new instructions introduced and can be
755 // ignored safely
756 return;
757 assert(isExpectedBDVType(Base) && "the only non-base values "
758 "we see should be base defining values");
Philip Reames34d7a742015-09-10 00:22:49 +0000759 if (States.insert(std::make_pair(Base, BDVState())).second)
Philip Reames88958b22015-07-24 00:02:11 +0000760 Worklist.push_back(Base);
761 };
762 if (PHINode *Phi = dyn_cast<PHINode>(Current)) {
763 for (Value *InVal : Phi->incoming_values())
764 visitIncomingValue(InVal);
Philip Reames9ac4e382015-08-12 21:00:20 +0000765 } else if (SelectInst *Sel = dyn_cast<SelectInst>(Current)) {
Philip Reames88958b22015-07-24 00:02:11 +0000766 visitIncomingValue(Sel->getTrueValue());
767 visitIncomingValue(Sel->getFalseValue());
Philip Reames9ac4e382015-08-12 21:00:20 +0000768 } else if (auto *EE = dyn_cast<ExtractElementInst>(Current)) {
769 visitIncomingValue(EE->getVectorOperand());
Philip Reames66287132015-09-09 23:40:12 +0000770 } else if (auto *IE = dyn_cast<InsertElementInst>(Current)) {
771 visitIncomingValue(IE->getOperand(0)); // vector operand
772 visitIncomingValue(IE->getOperand(1)); // scalar operand
Philip Reames9ac4e382015-08-12 21:00:20 +0000773 } else {
Philip Reames66287132015-09-09 23:40:12 +0000774 // There is one known class of instructions we know we don't handle.
775 assert(isa<ShuffleVectorInst>(Current));
Philip Reames9ac4e382015-08-12 21:00:20 +0000776 llvm_unreachable("unimplemented instruction case");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000777 }
778 }
779 }
780
Philip Reamesdab35f32015-09-02 21:11:44 +0000781#ifndef NDEBUG
782 DEBUG(dbgs() << "States after initialization:\n");
Philip Reames34d7a742015-09-10 00:22:49 +0000783 for (auto Pair : States) {
Philip Reamesdab35f32015-09-02 21:11:44 +0000784 DEBUG(dbgs() << " " << Pair.second << " for " << *Pair.first << "\n");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000785 }
Philip Reamesdab35f32015-09-02 21:11:44 +0000786#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +0000787
Philip Reames273e6bb2015-07-23 21:41:27 +0000788 // Return a phi state for a base defining value. We'll generate a new
789 // base state for known bases and expect to find a cached state otherwise.
790 auto getStateForBDV = [&](Value *baseValue) {
791 if (isKnownBaseResult(baseValue))
Philip Reames9b141ed2015-07-23 22:49:14 +0000792 return BDVState(baseValue);
Philip Reames34d7a742015-09-10 00:22:49 +0000793 auto I = States.find(baseValue);
794 assert(I != States.end() && "lookup failed!");
Philip Reames273e6bb2015-07-23 21:41:27 +0000795 return I->second;
796 };
797
Philip Reamesd16a9b12015-02-20 01:06:44 +0000798 bool progress = true;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000799 while (progress) {
Yaron Keren42a7adf2015-02-28 13:11:24 +0000800#ifndef NDEBUG
Philip Reamesb4e55f32015-09-10 00:32:56 +0000801 const size_t oldSize = States.size();
Yaron Keren42a7adf2015-02-28 13:11:24 +0000802#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +0000803 progress = false;
Philip Reames15d55632015-09-09 23:26:08 +0000804 // We're only changing values in this loop, thus safe to keep iterators.
805 // Since this is computing a fixed point, the order of visit does not
806 // effect the result. TODO: We could use a worklist here and make this run
807 // much faster.
Philip Reames34d7a742015-09-10 00:22:49 +0000808 for (auto Pair : States) {
Philip Reamesece70b82015-09-09 23:57:18 +0000809 Value *BDV = Pair.first;
810 assert(!isKnownBaseResult(BDV) && "why did it get added?");
Philip Reames273e6bb2015-07-23 21:41:27 +0000811
Philip Reames9b141ed2015-07-23 22:49:14 +0000812 // Given an input value for the current instruction, return a BDVState
Philip Reames273e6bb2015-07-23 21:41:27 +0000813 // instance which represents the BDV of that value.
814 auto getStateForInput = [&](Value *V) mutable {
815 Value *BDV = findBaseOrBDV(V, cache);
816 return getStateForBDV(BDV);
817 };
818
Philip Reames9b141ed2015-07-23 22:49:14 +0000819 MeetBDVStates calculateMeet;
Philip Reamesece70b82015-09-09 23:57:18 +0000820 if (SelectInst *select = dyn_cast<SelectInst>(BDV)) {
Philip Reames273e6bb2015-07-23 21:41:27 +0000821 calculateMeet.meetWith(getStateForInput(select->getTrueValue()));
822 calculateMeet.meetWith(getStateForInput(select->getFalseValue()));
Philip Reamesece70b82015-09-09 23:57:18 +0000823 } else if (PHINode *Phi = dyn_cast<PHINode>(BDV)) {
Philip Reames9ac4e382015-08-12 21:00:20 +0000824 for (Value *Val : Phi->incoming_values())
Philip Reames273e6bb2015-07-23 21:41:27 +0000825 calculateMeet.meetWith(getStateForInput(Val));
Philip Reamesece70b82015-09-09 23:57:18 +0000826 } else if (auto *EE = dyn_cast<ExtractElementInst>(BDV)) {
Philip Reames9ac4e382015-08-12 21:00:20 +0000827 // The 'meet' for an extractelement is slightly trivial, but it's still
828 // useful in that it drives us to conflict if our input is.
Philip Reames9ac4e382015-08-12 21:00:20 +0000829 calculateMeet.meetWith(getStateForInput(EE->getVectorOperand()));
Philip Reames66287132015-09-09 23:40:12 +0000830 } else {
831 // Given there's a inherent type mismatch between the operands, will
832 // *always* produce Conflict.
Philip Reamesece70b82015-09-09 23:57:18 +0000833 auto *IE = cast<InsertElementInst>(BDV);
Philip Reames66287132015-09-09 23:40:12 +0000834 calculateMeet.meetWith(getStateForInput(IE->getOperand(0)));
835 calculateMeet.meetWith(getStateForInput(IE->getOperand(1)));
Philip Reames9ac4e382015-08-12 21:00:20 +0000836 }
837
Philip Reames34d7a742015-09-10 00:22:49 +0000838 BDVState oldState = States[BDV];
Philip Reames9b141ed2015-07-23 22:49:14 +0000839 BDVState newState = calculateMeet.getResult();
Philip Reamesd16a9b12015-02-20 01:06:44 +0000840 if (oldState != newState) {
841 progress = true;
Philip Reames34d7a742015-09-10 00:22:49 +0000842 States[BDV] = newState;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000843 }
844 }
845
Philip Reamesb4e55f32015-09-10 00:32:56 +0000846 assert(oldSize == States.size() &&
847 "fixed point shouldn't be adding any new nodes to state");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000848 }
849
Philip Reamesdab35f32015-09-02 21:11:44 +0000850#ifndef NDEBUG
851 DEBUG(dbgs() << "States after meet iteration:\n");
Philip Reames34d7a742015-09-10 00:22:49 +0000852 for (auto Pair : States) {
Philip Reamesdab35f32015-09-02 21:11:44 +0000853 DEBUG(dbgs() << " " << Pair.second << " for " << *Pair.first << "\n");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000854 }
Philip Reamesdab35f32015-09-02 21:11:44 +0000855#endif
856
Philip Reamesd16a9b12015-02-20 01:06:44 +0000857 // Insert Phis for all conflicts
Philip Reames2e5bcbe2015-02-28 01:52:09 +0000858 // TODO: adjust naming patterns to avoid this order of iteration dependency
Philip Reames34d7a742015-09-10 00:22:49 +0000859 for (auto Pair : States) {
Philip Reames15d55632015-09-09 23:26:08 +0000860 Instruction *I = cast<Instruction>(Pair.first);
861 BDVState State = Pair.second;
Philip Reames6ff1a1e32015-07-21 19:04:38 +0000862 assert(!isKnownBaseResult(I) && "why did it get added?");
863 assert(!State.isUnknown() && "Optimistic algorithm didn't complete!");
Philip Reames9ac4e382015-08-12 21:00:20 +0000864
865 // extractelement instructions are a bit special in that we may need to
866 // insert an extract even when we know an exact base for the instruction.
867 // The problem is that we need to convert from a vector base to a scalar
868 // base for the particular indice we're interested in.
869 if (State.isBase() && isa<ExtractElementInst>(I) &&
870 isa<VectorType>(State.getBase()->getType())) {
871 auto *EE = cast<ExtractElementInst>(I);
872 // TODO: In many cases, the new instruction is just EE itself. We should
873 // exploit this, but can't do it here since it would break the invariant
874 // about the BDV not being known to be a base.
875 auto *BaseInst = ExtractElementInst::Create(State.getBase(),
876 EE->getIndexOperand(),
877 "base_ee", EE);
878 BaseInst->setMetadata("is_base_value", MDNode::get(I->getContext(), {}));
Philip Reames34d7a742015-09-10 00:22:49 +0000879 States[I] = BDVState(BDVState::Base, BaseInst);
Philip Reames9ac4e382015-08-12 21:00:20 +0000880 }
Philip Reames66287132015-09-09 23:40:12 +0000881
882 // Since we're joining a vector and scalar base, they can never be the
883 // same. As a result, we should always see insert element having reached
884 // the conflict state.
885 if (isa<InsertElementInst>(I)) {
886 assert(State.isConflict());
887 }
Philip Reames9ac4e382015-08-12 21:00:20 +0000888
Philip Reames6ff1a1e32015-07-21 19:04:38 +0000889 if (!State.isConflict())
Philip Reamesf986d682015-02-28 00:54:41 +0000890 continue;
Philip Reames704e78b2015-04-10 22:34:56 +0000891
Philip Reames6ff1a1e32015-07-21 19:04:38 +0000892 /// Create and insert a new instruction which will represent the base of
893 /// the given instruction 'I'.
894 auto MakeBaseInstPlaceholder = [](Instruction *I) -> Instruction* {
895 if (isa<PHINode>(I)) {
896 BasicBlock *BB = I->getParent();
897 int NumPreds = std::distance(pred_begin(BB), pred_end(BB));
898 assert(NumPreds > 0 && "how did we reach here");
Philip Reamesece70b82015-09-09 23:57:18 +0000899 std::string Name = suffixed_name_or(I, ".base", "base_phi");
Philip Reamesfa2c6302015-07-24 19:01:39 +0000900 return PHINode::Create(I->getType(), NumPreds, Name, I);
Philip Reames9ac4e382015-08-12 21:00:20 +0000901 } else if (SelectInst *Sel = dyn_cast<SelectInst>(I)) {
902 // The undef will be replaced later
903 UndefValue *Undef = UndefValue::get(Sel->getType());
Philip Reamesece70b82015-09-09 23:57:18 +0000904 std::string Name = suffixed_name_or(I, ".base", "base_select");
Philip Reames9ac4e382015-08-12 21:00:20 +0000905 return SelectInst::Create(Sel->getCondition(), Undef,
906 Undef, Name, Sel);
Philip Reames66287132015-09-09 23:40:12 +0000907 } else if (auto *EE = dyn_cast<ExtractElementInst>(I)) {
Philip Reames9ac4e382015-08-12 21:00:20 +0000908 UndefValue *Undef = UndefValue::get(EE->getVectorOperand()->getType());
Philip Reamesece70b82015-09-09 23:57:18 +0000909 std::string Name = suffixed_name_or(I, ".base", "base_ee");
Philip Reames9ac4e382015-08-12 21:00:20 +0000910 return ExtractElementInst::Create(Undef, EE->getIndexOperand(), Name,
911 EE);
Philip Reames66287132015-09-09 23:40:12 +0000912 } else {
913 auto *IE = cast<InsertElementInst>(I);
914 UndefValue *VecUndef = UndefValue::get(IE->getOperand(0)->getType());
915 UndefValue *ScalarUndef = UndefValue::get(IE->getOperand(1)->getType());
Philip Reamesece70b82015-09-09 23:57:18 +0000916 std::string Name = suffixed_name_or(I, ".base", "base_ie");
Philip Reames66287132015-09-09 23:40:12 +0000917 return InsertElementInst::Create(VecUndef, ScalarUndef,
918 IE->getOperand(2), Name, IE);
Philip Reames6ff1a1e32015-07-21 19:04:38 +0000919 }
Philip Reames66287132015-09-09 23:40:12 +0000920
Philip Reames6ff1a1e32015-07-21 19:04:38 +0000921 };
922 Instruction *BaseInst = MakeBaseInstPlaceholder(I);
923 // Add metadata marking this as a base value
924 BaseInst->setMetadata("is_base_value", MDNode::get(I->getContext(), {}));
Philip Reames34d7a742015-09-10 00:22:49 +0000925 States[I] = BDVState(BDVState::Conflict, BaseInst);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000926 }
927
Philip Reames3ea15892015-09-03 21:57:40 +0000928 // Returns a instruction which produces the base pointer for a given
929 // instruction. The instruction is assumed to be an input to one of the BDVs
930 // seen in the inference algorithm above. As such, we must either already
931 // know it's base defining value is a base, or have inserted a new
932 // instruction to propagate the base of it's BDV and have entered that newly
933 // introduced instruction into the state table. In either case, we are
934 // assured to be able to determine an instruction which produces it's base
935 // pointer.
936 auto getBaseForInput = [&](Value *Input, Instruction *InsertPt) {
937 Value *BDV = findBaseOrBDV(Input, cache);
938 Value *Base = nullptr;
939 if (isKnownBaseResult(BDV)) {
940 Base = BDV;
941 } else {
942 // Either conflict or base.
Philip Reames34d7a742015-09-10 00:22:49 +0000943 assert(States.count(BDV));
944 Base = States[BDV].getBase();
Philip Reames3ea15892015-09-03 21:57:40 +0000945 }
946 assert(Base && "can't be null");
947 // The cast is needed since base traversal may strip away bitcasts
948 if (Base->getType() != Input->getType() &&
949 InsertPt) {
950 Base = new BitCastInst(Base, Input->getType(), "cast",
951 InsertPt);
952 }
953 return Base;
954 };
955
Philip Reames15d55632015-09-09 23:26:08 +0000956 // Fixup all the inputs of the new PHIs. Visit order needs to be
957 // deterministic and predictable because we're naming newly created
958 // instructions.
Philip Reames34d7a742015-09-10 00:22:49 +0000959 for (auto Pair : States) {
Philip Reames7540e3a2015-09-10 00:01:53 +0000960 Instruction *BDV = cast<Instruction>(Pair.first);
Philip Reamesc8ded462015-09-10 00:27:50 +0000961 BDVState State = Pair.second;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000962
Philip Reames7540e3a2015-09-10 00:01:53 +0000963 assert(!isKnownBaseResult(BDV) && "why did it get added?");
Philip Reamesc8ded462015-09-10 00:27:50 +0000964 assert(!State.isUnknown() && "Optimistic algorithm didn't complete!");
965 if (!State.isConflict())
Philip Reames28e61ce2015-02-28 01:57:44 +0000966 continue;
Philip Reames704e78b2015-04-10 22:34:56 +0000967
Philip Reamesc8ded462015-09-10 00:27:50 +0000968 if (PHINode *basephi = dyn_cast<PHINode>(State.getBase())) {
Philip Reames7540e3a2015-09-10 00:01:53 +0000969 PHINode *phi = cast<PHINode>(BDV);
Philip Reames28e61ce2015-02-28 01:57:44 +0000970 unsigned NumPHIValues = phi->getNumIncomingValues();
971 for (unsigned i = 0; i < NumPHIValues; i++) {
972 Value *InVal = phi->getIncomingValue(i);
973 BasicBlock *InBB = phi->getIncomingBlock(i);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000974
Philip Reames28e61ce2015-02-28 01:57:44 +0000975 // If we've already seen InBB, add the same incoming value
976 // we added for it earlier. The IR verifier requires phi
977 // nodes with multiple entries from the same basic block
978 // to have the same incoming value for each of those
979 // entries. If we don't do this check here and basephi
980 // has a different type than base, we'll end up adding two
981 // bitcasts (and hence two distinct values) as incoming
982 // values for the same basic block.
Philip Reamesd16a9b12015-02-20 01:06:44 +0000983
Philip Reames28e61ce2015-02-28 01:57:44 +0000984 int blockIndex = basephi->getBasicBlockIndex(InBB);
985 if (blockIndex != -1) {
986 Value *oldBase = basephi->getIncomingValue(blockIndex);
987 basephi->addIncoming(oldBase, InBB);
Philip Reames3ea15892015-09-03 21:57:40 +0000988
Philip Reamesd16a9b12015-02-20 01:06:44 +0000989#ifndef NDEBUG
Philip Reames3ea15892015-09-03 21:57:40 +0000990 Value *Base = getBaseForInput(InVal, nullptr);
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000991 // In essence this assert states: the only way two
Philip Reames28e61ce2015-02-28 01:57:44 +0000992 // values incoming from the same basic block may be
993 // different is by being different bitcasts of the same
994 // value. A cleanup that remains TODO is changing
995 // findBaseOrBDV to return an llvm::Value of the correct
996 // type (and still remain pure). This will remove the
997 // need to add bitcasts.
Philip Reames3ea15892015-09-03 21:57:40 +0000998 assert(Base->stripPointerCasts() == oldBase->stripPointerCasts() &&
Philip Reames28e61ce2015-02-28 01:57:44 +0000999 "sanity -- findBaseOrBDV should be pure!");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001000#endif
Philip Reames28e61ce2015-02-28 01:57:44 +00001001 continue;
1002 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00001003
Philip Reames3ea15892015-09-03 21:57:40 +00001004 // Find the instruction which produces the base for each input. We may
1005 // need to insert a bitcast in the incoming block.
1006 // TODO: Need to split critical edges if insertion is needed
1007 Value *Base = getBaseForInput(InVal, InBB->getTerminator());
1008 basephi->addIncoming(Base, InBB);
Philip Reames28e61ce2015-02-28 01:57:44 +00001009 }
1010 assert(basephi->getNumIncomingValues() == NumPHIValues);
Philip Reamesc8ded462015-09-10 00:27:50 +00001011 } else if (SelectInst *BaseSel = dyn_cast<SelectInst>(State.getBase())) {
Philip Reames7540e3a2015-09-10 00:01:53 +00001012 SelectInst *Sel = cast<SelectInst>(BDV);
Philip Reames28e61ce2015-02-28 01:57:44 +00001013 // Operand 1 & 2 are true, false path respectively. TODO: refactor to
1014 // something more safe and less hacky.
1015 for (int i = 1; i <= 2; i++) {
Philip Reames3ea15892015-09-03 21:57:40 +00001016 Value *InVal = Sel->getOperand(i);
1017 // Find the instruction which produces the base for each input. We may
1018 // need to insert a bitcast.
1019 Value *Base = getBaseForInput(InVal, BaseSel);
1020 BaseSel->setOperand(i, Base);
Philip Reames28e61ce2015-02-28 01:57:44 +00001021 }
Philip Reamesc8ded462015-09-10 00:27:50 +00001022 } else if (auto *BaseEE = dyn_cast<ExtractElementInst>(State.getBase())) {
Philip Reames7540e3a2015-09-10 00:01:53 +00001023 Value *InVal = cast<ExtractElementInst>(BDV)->getVectorOperand();
Philip Reames3ea15892015-09-03 21:57:40 +00001024 // Find the instruction which produces the base for each input. We may
1025 // need to insert a bitcast.
1026 Value *Base = getBaseForInput(InVal, BaseEE);
Philip Reames9ac4e382015-08-12 21:00:20 +00001027 BaseEE->setOperand(0, Base);
Philip Reames66287132015-09-09 23:40:12 +00001028 } else {
Philip Reamesc8ded462015-09-10 00:27:50 +00001029 auto *BaseIE = cast<InsertElementInst>(State.getBase());
Philip Reames7540e3a2015-09-10 00:01:53 +00001030 auto *BdvIE = cast<InsertElementInst>(BDV);
Philip Reames66287132015-09-09 23:40:12 +00001031 auto UpdateOperand = [&](int OperandIdx) {
1032 Value *InVal = BdvIE->getOperand(OperandIdx);
Philip Reames953817b2015-09-10 00:44:10 +00001033 Value *Base = getBaseForInput(InVal, BaseIE);
Philip Reames66287132015-09-09 23:40:12 +00001034 BaseIE->setOperand(OperandIdx, Base);
1035 };
1036 UpdateOperand(0); // vector operand
1037 UpdateOperand(1); // scalar operand
Philip Reamesd16a9b12015-02-20 01:06:44 +00001038 }
Philip Reames66287132015-09-09 23:40:12 +00001039
Philip Reamesd16a9b12015-02-20 01:06:44 +00001040 }
1041
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001042 // Now that we're done with the algorithm, see if we can optimize the
1043 // results slightly by reducing the number of new instructions needed.
1044 // Arguably, this should be integrated into the algorithm above, but
1045 // doing as a post process step is easier to reason about for the moment.
1046 DenseMap<Value *, Value *> ReverseMap;
1047 SmallPtrSet<Instruction *, 16> NewInsts;
Philip Reames9546f362015-09-02 22:25:07 +00001048 SmallSetVector<AssertingVH<Instruction>, 16> Worklist;
Philip Reames246e6182015-09-03 20:24:29 +00001049 // Note: We need to visit the states in a deterministic order. We uses the
1050 // Keys we sorted above for this purpose. Note that we are papering over a
1051 // bigger problem with the algorithm above - it's visit order is not
1052 // deterministic. A larger change is needed to fix this.
Philip Reames34d7a742015-09-10 00:22:49 +00001053 for (auto Pair : States) {
Philip Reames15d55632015-09-09 23:26:08 +00001054 auto *BDV = Pair.first;
1055 auto State = Pair.second;
Philip Reames246e6182015-09-03 20:24:29 +00001056 Value *Base = State.getBase();
Philip Reames15d55632015-09-09 23:26:08 +00001057 assert(BDV && Base);
1058 assert(!isKnownBaseResult(BDV) && "why did it get added?");
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001059 assert(isKnownBaseResult(Base) &&
1060 "must be something we 'know' is a base pointer");
Philip Reames246e6182015-09-03 20:24:29 +00001061 if (!State.isConflict())
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001062 continue;
1063
Philip Reames15d55632015-09-09 23:26:08 +00001064 ReverseMap[Base] = BDV;
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001065 if (auto *BaseI = dyn_cast<Instruction>(Base)) {
1066 NewInsts.insert(BaseI);
1067 Worklist.insert(BaseI);
1068 }
1069 }
Philip Reames9546f362015-09-02 22:25:07 +00001070 auto ReplaceBaseInstWith = [&](Value *BDV, Instruction *BaseI,
1071 Value *Replacement) {
1072 // Add users which are new instructions (excluding self references)
1073 for (User *U : BaseI->users())
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001074 if (auto *UI = dyn_cast<Instruction>(U))
Philip Reames9546f362015-09-02 22:25:07 +00001075 if (NewInsts.count(UI) && UI != BaseI)
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001076 Worklist.insert(UI);
Philip Reames9546f362015-09-02 22:25:07 +00001077 // Then do the actual replacement
1078 NewInsts.erase(BaseI);
1079 ReverseMap.erase(BaseI);
1080 BaseI->replaceAllUsesWith(Replacement);
1081 BaseI->eraseFromParent();
Philip Reames34d7a742015-09-10 00:22:49 +00001082 assert(States.count(BDV));
1083 assert(States[BDV].isConflict() && States[BDV].getBase() == BaseI);
1084 States[BDV] = BDVState(BDVState::Conflict, Replacement);
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001085 };
1086 const DataLayout &DL = cast<Instruction>(def)->getModule()->getDataLayout();
1087 while (!Worklist.empty()) {
1088 Instruction *BaseI = Worklist.pop_back_val();
Philip Reamesdab35f32015-09-02 21:11:44 +00001089 assert(NewInsts.count(BaseI));
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001090 Value *Bdv = ReverseMap[BaseI];
1091 if (auto *BdvI = dyn_cast<Instruction>(Bdv))
1092 if (BaseI->isIdenticalTo(BdvI)) {
1093 DEBUG(dbgs() << "Identical Base: " << *BaseI << "\n");
Philip Reames9546f362015-09-02 22:25:07 +00001094 ReplaceBaseInstWith(Bdv, BaseI, Bdv);
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001095 continue;
1096 }
1097 if (Value *V = SimplifyInstruction(BaseI, DL)) {
1098 DEBUG(dbgs() << "Base " << *BaseI << " simplified to " << *V << "\n");
Philip Reames9546f362015-09-02 22:25:07 +00001099 ReplaceBaseInstWith(Bdv, BaseI, V);
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001100 continue;
1101 }
1102 }
1103
Philip Reamesd16a9b12015-02-20 01:06:44 +00001104 // Cache all of our results so we can cheaply reuse them
1105 // NOTE: This is actually two caches: one of the base defining value
1106 // relation and one of the base pointer relation! FIXME
Philip Reames34d7a742015-09-10 00:22:49 +00001107 for (auto Pair : States) {
Philip Reames15d55632015-09-09 23:26:08 +00001108 auto *BDV = Pair.first;
1109 Value *base = Pair.second.getBase();
1110 assert(BDV && base);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001111
Philip Reamesece70b82015-09-09 23:57:18 +00001112 std::string fromstr = cache.count(BDV) ? cache[BDV]->getName() : "none";
Philip Reamesdab35f32015-09-02 21:11:44 +00001113 DEBUG(dbgs() << "Updating base value cache"
Philip Reamesece70b82015-09-09 23:57:18 +00001114 << " for: " << BDV->getName()
Philip Reamesdab35f32015-09-02 21:11:44 +00001115 << " from: " << fromstr
Philip Reamesece70b82015-09-09 23:57:18 +00001116 << " to: " << base->getName() << "\n");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001117
Philip Reames15d55632015-09-09 23:26:08 +00001118 if (cache.count(BDV)) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001119 // Once we transition from the BDV relation being store in the cache to
1120 // the base relation being stored, it must be stable
Philip Reames15d55632015-09-09 23:26:08 +00001121 assert((!isKnownBaseResult(cache[BDV]) || cache[BDV] == base) &&
Philip Reamesd16a9b12015-02-20 01:06:44 +00001122 "base relation should be stable");
1123 }
Philip Reames15d55632015-09-09 23:26:08 +00001124 cache[BDV] = base;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001125 }
1126 assert(cache.find(def) != cache.end());
1127 return cache[def];
1128}
1129
1130// For a set of live pointers (base and/or derived), identify the base
1131// pointer of the object which they are derived from. This routine will
1132// mutate the IR graph as needed to make the 'base' pointer live at the
1133// definition site of 'derived'. This ensures that any use of 'derived' can
1134// also use 'base'. This may involve the insertion of a number of
1135// additional PHI nodes.
1136//
1137// preconditions: live is a set of pointer type Values
1138//
1139// side effects: may insert PHI nodes into the existing CFG, will preserve
1140// CFG, will not remove or mutate any existing nodes
1141//
Philip Reamesf2041322015-02-20 19:26:04 +00001142// post condition: PointerToBase contains one (derived, base) pair for every
Philip Reamesd16a9b12015-02-20 01:06:44 +00001143// pointer in live. Note that derived can be equal to base if the original
1144// pointer was a base pointer.
Philip Reames704e78b2015-04-10 22:34:56 +00001145static void
1146findBasePointers(const StatepointLiveSetTy &live,
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001147 DenseMap<Value *, Value *> &PointerToBase,
Philip Reamesba198492015-04-14 00:41:34 +00001148 DominatorTree *DT, DefiningValueMapTy &DVCache) {
Philip Reames2e5bcbe2015-02-28 01:52:09 +00001149 // For the naming of values inserted to be deterministic - which makes for
1150 // much cleaner and more stable tests - we need to assign an order to the
1151 // live values. DenseSets do not provide a deterministic order across runs.
Philip Reames704e78b2015-04-10 22:34:56 +00001152 SmallVector<Value *, 64> Temp;
Philip Reames2e5bcbe2015-02-28 01:52:09 +00001153 Temp.insert(Temp.end(), live.begin(), live.end());
1154 std::sort(Temp.begin(), Temp.end(), order_by_name);
1155 for (Value *ptr : Temp) {
Philip Reamesba198492015-04-14 00:41:34 +00001156 Value *base = findBasePointer(ptr, DVCache);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001157 assert(base && "failed to find base pointer");
Philip Reamesf2041322015-02-20 19:26:04 +00001158 PointerToBase[ptr] = base;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001159 assert((!isa<Instruction>(base) || !isa<Instruction>(ptr) ||
1160 DT->dominates(cast<Instruction>(base)->getParent(),
1161 cast<Instruction>(ptr)->getParent())) &&
1162 "The base we found better dominate the derived pointer");
1163
David Blaikie82ad7872015-02-20 23:44:24 +00001164 // If you see this trip and like to live really dangerously, the code should
1165 // be correct, just with idioms the verifier can't handle. You can try
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001166 // disabling the verifier at your own substantial risk.
Philip Reames704e78b2015-04-10 22:34:56 +00001167 assert(!isa<ConstantPointerNull>(base) &&
Philip Reames24c6cd52015-03-27 05:47:00 +00001168 "the relocation code needs adjustment to handle the relocation of "
1169 "a null pointer constant without causing false positives in the "
1170 "safepoint ir verifier.");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001171 }
1172}
1173
1174/// Find the required based pointers (and adjust the live set) for the given
1175/// parse point.
1176static void findBasePointers(DominatorTree &DT, DefiningValueMapTy &DVCache,
1177 const CallSite &CS,
1178 PartiallyConstructedSafepointRecord &result) {
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001179 DenseMap<Value *, Value *> PointerToBase;
1180 findBasePointers(result.LiveSet, PointerToBase, &DT, DVCache);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001181
1182 if (PrintBasePointers) {
Philip Reamesa5aeaf42015-02-28 00:20:48 +00001183 // Note: Need to print these in a stable order since this is checked in
1184 // some tests.
Philip Reamesd16a9b12015-02-20 01:06:44 +00001185 errs() << "Base Pairs (w/o Relocation):\n";
Philip Reames704e78b2015-04-10 22:34:56 +00001186 SmallVector<Value *, 64> Temp;
Philip Reamesa5aeaf42015-02-28 00:20:48 +00001187 Temp.reserve(PointerToBase.size());
Philip Reamesf2041322015-02-20 19:26:04 +00001188 for (auto Pair : PointerToBase) {
Philip Reamesa5aeaf42015-02-28 00:20:48 +00001189 Temp.push_back(Pair.first);
1190 }
1191 std::sort(Temp.begin(), Temp.end(), order_by_name);
1192 for (Value *Ptr : Temp) {
1193 Value *Base = PointerToBase[Ptr];
Philip Reames704e78b2015-04-10 22:34:56 +00001194 errs() << " derived %" << Ptr->getName() << " base %" << Base->getName()
1195 << "\n";
Philip Reamesd16a9b12015-02-20 01:06:44 +00001196 }
1197 }
1198
Philip Reamesf2041322015-02-20 19:26:04 +00001199 result.PointerToBase = PointerToBase;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001200}
1201
Philip Reamesdf1ef082015-04-10 22:53:14 +00001202/// Given an updated version of the dataflow liveness results, update the
1203/// liveset and base pointer maps for the call site CS.
1204static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData,
1205 const CallSite &CS,
1206 PartiallyConstructedSafepointRecord &result);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001207
Philip Reamesdf1ef082015-04-10 22:53:14 +00001208static void recomputeLiveInValues(
1209 Function &F, DominatorTree &DT, Pass *P, ArrayRef<CallSite> toUpdate,
Philip Reamesd2b66462015-02-20 22:39:41 +00001210 MutableArrayRef<struct PartiallyConstructedSafepointRecord> records) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00001211 // TODO-PERF: reuse the original liveness, then simply run the dataflow
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001212 // again. The old values are still live and will help it stabilize quickly.
Philip Reamesdf1ef082015-04-10 22:53:14 +00001213 GCPtrLivenessData RevisedLivenessData;
1214 computeLiveInValues(DT, F, RevisedLivenessData);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001215 for (size_t i = 0; i < records.size(); i++) {
1216 struct PartiallyConstructedSafepointRecord &info = records[i];
Philip Reamesd2b66462015-02-20 22:39:41 +00001217 const CallSite &CS = toUpdate[i];
Philip Reamesdf1ef082015-04-10 22:53:14 +00001218 recomputeLiveInValues(RevisedLivenessData, CS, info);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001219 }
1220}
1221
Philip Reames69e51ca2015-04-13 18:07:21 +00001222// When inserting gc.relocate calls, we need to ensure there are no uses
1223// of the original value between the gc.statepoint and the gc.relocate call.
1224// One case which can arise is a phi node starting one of the successor blocks.
1225// We also need to be able to insert the gc.relocates only on the path which
1226// goes through the statepoint. We might need to split an edge to make this
Philip Reamesf209a152015-04-13 20:00:30 +00001227// possible.
1228static BasicBlock *
Sanjoy Dasea45f0e2015-06-02 22:33:34 +00001229normalizeForInvokeSafepoint(BasicBlock *BB, BasicBlock *InvokeParent,
1230 DominatorTree &DT) {
Philip Reames69e51ca2015-04-13 18:07:21 +00001231 BasicBlock *Ret = BB;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001232 if (!BB->getUniquePredecessor()) {
Chandler Carruth96ada252015-07-22 09:52:54 +00001233 Ret = SplitBlockPredecessors(BB, InvokeParent, "", &DT);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001234 }
1235
Philip Reames69e51ca2015-04-13 18:07:21 +00001236 // Now that 'ret' has unique predecessor we can safely remove all phi nodes
1237 // from it
1238 FoldSingleEntryPHINodes(Ret);
1239 assert(!isa<PHINode>(Ret->begin()));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001240
Philip Reames69e51ca2015-04-13 18:07:21 +00001241 // At this point, we can safely insert a gc.relocate as the first instruction
1242 // in Ret if needed.
1243 return Ret;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001244}
1245
Philip Reamesd2b66462015-02-20 22:39:41 +00001246static int find_index(ArrayRef<Value *> livevec, Value *val) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001247 auto itr = std::find(livevec.begin(), livevec.end(), val);
1248 assert(livevec.end() != itr);
1249 size_t index = std::distance(livevec.begin(), itr);
1250 assert(index < livevec.size());
1251 return index;
1252}
1253
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001254// Create new attribute set containing only attributes which can be transferred
Philip Reamesd16a9b12015-02-20 01:06:44 +00001255// from original call to the safepoint.
1256static AttributeSet legalizeCallAttributes(AttributeSet AS) {
1257 AttributeSet ret;
1258
1259 for (unsigned Slot = 0; Slot < AS.getNumSlots(); Slot++) {
1260 unsigned index = AS.getSlotIndex(Slot);
1261
1262 if (index == AttributeSet::ReturnIndex ||
1263 index == AttributeSet::FunctionIndex) {
1264
1265 for (auto it = AS.begin(Slot), it_end = AS.end(Slot); it != it_end;
1266 ++it) {
1267 Attribute attr = *it;
1268
1269 // Do not allow certain attributes - just skip them
1270 // Safepoint can not be read only or read none.
1271 if (attr.hasAttribute(Attribute::ReadNone) ||
1272 attr.hasAttribute(Attribute::ReadOnly))
1273 continue;
1274
1275 ret = ret.addAttributes(
1276 AS.getContext(), index,
1277 AttributeSet::get(AS.getContext(), index, AttrBuilder(attr)));
1278 }
1279 }
1280
1281 // Just skip parameter attributes for now
1282 }
1283
1284 return ret;
1285}
1286
1287/// Helper function to place all gc relocates necessary for the given
1288/// statepoint.
1289/// Inputs:
1290/// liveVariables - list of variables to be relocated.
1291/// liveStart - index of the first live variable.
1292/// basePtrs - base pointers.
1293/// statepointToken - statepoint instruction to which relocates should be
1294/// bound.
1295/// Builder - Llvm IR builder to be used to construct new calls.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001296static void CreateGCRelocates(ArrayRef<Value *> LiveVariables,
Sanjoy Das5665c992015-05-11 23:47:27 +00001297 const int LiveStart,
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001298 ArrayRef<Value *> BasePtrs,
Sanjoy Das5665c992015-05-11 23:47:27 +00001299 Instruction *StatepointToken,
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00001300 IRBuilder<> Builder) {
Philip Reames94babb72015-07-21 17:18:03 +00001301 if (LiveVariables.empty())
1302 return;
1303
1304 // All gc_relocate are set to i8 addrspace(1)* type. We originally generated
1305 // unique declarations for each pointer type, but this proved problematic
1306 // because the intrinsic mangling code is incomplete and fragile. Since
1307 // we're moving towards a single unified pointer type anyways, we can just
1308 // cast everything to an i8* of the right address space. A bitcast is added
1309 // later to convert gc_relocate to the actual value's type.
Philip Reames74ce2e72015-07-21 16:51:17 +00001310 Module *M = StatepointToken->getModule();
Philip Reames94babb72015-07-21 17:18:03 +00001311 auto AS = cast<PointerType>(LiveVariables[0]->getType())->getAddressSpace();
1312 Type *Types[] = {Type::getInt8PtrTy(M->getContext(), AS)};
1313 Value *GCRelocateDecl =
1314 Intrinsic::getDeclaration(M, Intrinsic::experimental_gc_relocate, Types);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001315
Sanjoy Das5665c992015-05-11 23:47:27 +00001316 for (unsigned i = 0; i < LiveVariables.size(); i++) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001317 // Generate the gc.relocate call and save the result
Sanjoy Das5665c992015-05-11 23:47:27 +00001318 Value *BaseIdx =
Philip Reamesf3880502015-07-21 00:49:55 +00001319 Builder.getInt32(LiveStart + find_index(LiveVariables, BasePtrs[i]));
1320 Value *LiveIdx =
1321 Builder.getInt32(LiveStart + find_index(LiveVariables, LiveVariables[i]));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001322
1323 // only specify a debug name if we can give a useful one
Philip Reames74ce2e72015-07-21 16:51:17 +00001324 CallInst *Reloc = Builder.CreateCall(
David Blaikieff6409d2015-05-18 22:13:54 +00001325 GCRelocateDecl, {StatepointToken, BaseIdx, LiveIdx},
Philip Reamesece70b82015-09-09 23:57:18 +00001326 suffixed_name_or(LiveVariables[i], ".relocated", ""));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001327 // Trick CodeGen into thinking there are lots of free registers at this
1328 // fake call.
Philip Reames74ce2e72015-07-21 16:51:17 +00001329 Reloc->setCallingConv(CallingConv::Cold);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001330 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00001331}
1332
1333static void
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001334makeStatepointExplicitImpl(const CallSite CS, /* to replace */
1335 const SmallVectorImpl<Value *> &BasePtrs,
1336 const SmallVectorImpl<Value *> &LiveVariables,
1337 PartiallyConstructedSafepointRecord &Result) {
1338 assert(BasePtrs.size() == LiveVariables.size());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001339 assert(isStatepoint(CS) &&
1340 "This method expects to be rewriting a statepoint");
1341
Philip Reamesd16a9b12015-02-20 01:06:44 +00001342 // Then go ahead and use the builder do actually do the inserts. We insert
1343 // immediately before the previous instruction under the assumption that all
1344 // arguments will be available here. We can't insert afterwards since we may
1345 // be replacing a terminator.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001346 Instruction *InsertBefore = CS.getInstruction();
1347 IRBuilder<> Builder(InsertBefore);
1348
Sanjoy Das3c520a12015-10-08 23:18:38 +00001349 Statepoint OldSP(CS);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001350
Sanjoy Das3c520a12015-10-08 23:18:38 +00001351 ArrayRef<Value *> GCArgs(LiveVariables);
1352 uint64_t StatepointID = OldSP.getID();
1353 uint32_t NumPatchBytes = OldSP.getNumPatchBytes();
1354 uint32_t Flags = OldSP.getFlags();
1355
1356 ArrayRef<Use> CallArgs(OldSP.arg_begin(), OldSP.arg_end());
1357 ArrayRef<Use> DeoptArgs(OldSP.vm_state_begin(), OldSP.vm_state_end());
1358 ArrayRef<Use> TransitionArgs(OldSP.gc_transition_args_begin(),
1359 OldSP.gc_transition_args_end());
1360 Value *CallTarget = OldSP.getCalledValue();
Philip Reamesd16a9b12015-02-20 01:06:44 +00001361
1362 // Create the statepoint given all the arguments
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001363 Instruction *Token = nullptr;
1364 AttributeSet ReturnAttrs;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001365 if (CS.isCall()) {
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001366 CallInst *ToReplace = cast<CallInst>(CS.getInstruction());
Sanjoy Das3c520a12015-10-08 23:18:38 +00001367 CallInst *Call = Builder.CreateGCStatepointCall(
1368 StatepointID, NumPatchBytes, CallTarget, Flags, CallArgs,
1369 TransitionArgs, DeoptArgs, GCArgs, "safepoint_token");
1370
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001371 Call->setTailCall(ToReplace->isTailCall());
1372 Call->setCallingConv(ToReplace->getCallingConv());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001373
1374 // Currently we will fail on parameter attributes and on certain
1375 // function attributes.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001376 AttributeSet NewAttrs = legalizeCallAttributes(ToReplace->getAttributes());
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001377 // In case if we can handle this set of attributes - set up function attrs
Philip Reamesd16a9b12015-02-20 01:06:44 +00001378 // directly on statepoint and return attrs later for gc_result intrinsic.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001379 Call->setAttributes(NewAttrs.getFnAttributes());
1380 ReturnAttrs = NewAttrs.getRetAttributes();
Philip Reamesd16a9b12015-02-20 01:06:44 +00001381
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001382 Token = Call;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001383
1384 // Put the following gc_result and gc_relocate calls immediately after the
1385 // the old call (which we're about to delete)
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001386 assert(ToReplace->getNextNode() && "Not a terminator, must have next!");
1387 Builder.SetInsertPoint(ToReplace->getNextNode());
1388 Builder.SetCurrentDebugLocation(ToReplace->getNextNode()->getDebugLoc());
David Blaikie82ad7872015-02-20 23:44:24 +00001389 } else {
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001390 InvokeInst *ToReplace = cast<InvokeInst>(CS.getInstruction());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001391
1392 // Insert the new invoke into the old block. We'll remove the old one in a
1393 // moment at which point this will become the new terminator for the
1394 // original block.
Sanjoy Das3c520a12015-10-08 23:18:38 +00001395 InvokeInst *Invoke = Builder.CreateGCStatepointInvoke(
1396 StatepointID, NumPatchBytes, CallTarget, ToReplace->getNormalDest(),
1397 ToReplace->getUnwindDest(), Flags, CallArgs, TransitionArgs, DeoptArgs,
1398 GCArgs, "statepoint_token");
1399
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001400 Invoke->setCallingConv(ToReplace->getCallingConv());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001401
1402 // Currently we will fail on parameter attributes and on certain
1403 // function attributes.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001404 AttributeSet NewAttrs = legalizeCallAttributes(ToReplace->getAttributes());
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001405 // In case if we can handle this set of attributes - set up function attrs
Philip Reamesd16a9b12015-02-20 01:06:44 +00001406 // directly on statepoint and return attrs later for gc_result intrinsic.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001407 Invoke->setAttributes(NewAttrs.getFnAttributes());
1408 ReturnAttrs = NewAttrs.getRetAttributes();
Philip Reamesd16a9b12015-02-20 01:06:44 +00001409
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001410 Token = Invoke;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001411
1412 // Generate gc relocates in exceptional path
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001413 BasicBlock *UnwindBlock = ToReplace->getUnwindDest();
1414 assert(!isa<PHINode>(UnwindBlock->begin()) &&
1415 UnwindBlock->getUniquePredecessor() &&
Philip Reames69e51ca2015-04-13 18:07:21 +00001416 "can't safely insert in this block!");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001417
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001418 Builder.SetInsertPoint(&*UnwindBlock->getFirstInsertionPt());
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001419 Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001420
1421 // Extract second element from landingpad return value. We will attach
1422 // exceptional gc relocates to it.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001423 Instruction *ExceptionalToken =
Philip Reamesd16a9b12015-02-20 01:06:44 +00001424 cast<Instruction>(Builder.CreateExtractValue(
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001425 UnwindBlock->getLandingPadInst(), 1, "relocate_token"));
1426 Result.UnwindToken = ExceptionalToken;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001427
Sanjoy Das3c520a12015-10-08 23:18:38 +00001428 const unsigned LiveStartIdx = Statepoint(Token).gcArgsStartIdx();
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001429 CreateGCRelocates(LiveVariables, LiveStartIdx, BasePtrs, ExceptionalToken,
1430 Builder);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001431
1432 // Generate gc relocates and returns for normal block
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001433 BasicBlock *NormalDest = ToReplace->getNormalDest();
1434 assert(!isa<PHINode>(NormalDest->begin()) &&
1435 NormalDest->getUniquePredecessor() &&
Philip Reames69e51ca2015-04-13 18:07:21 +00001436 "can't safely insert in this block!");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001437
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001438 Builder.SetInsertPoint(&*NormalDest->getFirstInsertionPt());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001439
1440 // gc relocates will be generated later as if it were regular call
1441 // statepoint
Philip Reamesd16a9b12015-02-20 01:06:44 +00001442 }
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001443 assert(Token && "Should be set in one of the above branches!");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001444
1445 // Take the name of the original value call if it had one.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001446 Token->takeName(CS.getInstruction());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001447
Philip Reames704e78b2015-04-10 22:34:56 +00001448// The GCResult is already inserted, we just need to find it
David Blaikie5e5d7842015-02-22 20:58:38 +00001449#ifndef NDEBUG
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001450 Instruction *ToReplace = CS.getInstruction();
1451 assert(!ToReplace->hasNUsesOrMore(2) &&
David Blaikie5e5d7842015-02-22 20:58:38 +00001452 "only valid use before rewrite is gc.result");
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001453 assert(!ToReplace->hasOneUse() ||
1454 isGCResult(cast<Instruction>(*ToReplace->user_begin())));
David Blaikie5e5d7842015-02-22 20:58:38 +00001455#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +00001456
1457 // Update the gc.result of the original statepoint (if any) to use the newly
1458 // inserted statepoint. This is safe to do here since the token can't be
1459 // considered a live reference.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001460 CS.getInstruction()->replaceAllUsesWith(Token);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001461
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001462 Result.StatepointToken = Token;
Philip Reames0a3240f2015-02-20 21:34:11 +00001463
Philip Reamesd16a9b12015-02-20 01:06:44 +00001464 // Second, create a gc.relocate for every live variable
Sanjoy Das3c520a12015-10-08 23:18:38 +00001465 const unsigned LiveStartIdx = Statepoint(Token).gcArgsStartIdx();
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001466 CreateGCRelocates(LiveVariables, LiveStartIdx, BasePtrs, Token, Builder);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001467}
1468
1469namespace {
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001470struct NameOrdering {
1471 Value *Base;
1472 Value *Derived;
1473
1474 bool operator()(NameOrdering const &a, NameOrdering const &b) {
1475 return -1 == a.Derived->getName().compare(b.Derived->getName());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001476 }
1477};
1478}
Philip Reamesd16a9b12015-02-20 01:06:44 +00001479
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001480static void StabilizeOrder(SmallVectorImpl<Value *> &BaseVec,
1481 SmallVectorImpl<Value *> &LiveVec) {
1482 assert(BaseVec.size() == LiveVec.size());
1483
1484 SmallVector<NameOrdering, 64> Temp;
1485 for (size_t i = 0; i < BaseVec.size(); i++) {
1486 NameOrdering v;
1487 v.Base = BaseVec[i];
1488 v.Derived = LiveVec[i];
1489 Temp.push_back(v);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001490 }
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001491
1492 std::sort(Temp.begin(), Temp.end(), NameOrdering());
1493 for (size_t i = 0; i < BaseVec.size(); i++) {
1494 BaseVec[i] = Temp[i].Base;
1495 LiveVec[i] = Temp[i].Derived;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001496 }
1497}
1498
1499// Replace an existing gc.statepoint with a new one and a set of gc.relocates
1500// which make the relocations happening at this safepoint explicit.
Philip Reames704e78b2015-04-10 22:34:56 +00001501//
Philip Reamesd16a9b12015-02-20 01:06:44 +00001502// WARNING: Does not do any fixup to adjust users of the original live
1503// values. That's the callers responsibility.
1504static void
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001505makeStatepointExplicit(DominatorTree &DT, const CallSite &CS,
1506 PartiallyConstructedSafepointRecord &Result) {
Sanjoy Das1ede5362015-10-08 23:18:22 +00001507 const auto &LiveSet = Result.LiveSet;
1508 const auto &PointerToBase = Result.PointerToBase;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001509
1510 // Convert to vector for efficient cross referencing.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001511 SmallVector<Value *, 64> BaseVec, LiveVec;
1512 LiveVec.reserve(LiveSet.size());
1513 BaseVec.reserve(LiveSet.size());
1514 for (Value *L : LiveSet) {
1515 LiveVec.push_back(L);
Philip Reames74ce2e72015-07-21 16:51:17 +00001516 assert(PointerToBase.count(L));
Sanjoy Das1ede5362015-10-08 23:18:22 +00001517 Value *Base = PointerToBase.find(L)->second;
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001518 BaseVec.push_back(Base);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001519 }
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001520 assert(LiveVec.size() == BaseVec.size());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001521
1522 // To make the output IR slightly more stable (for use in diffs), ensure a
1523 // fixed order of the values in the safepoint (by sorting the value name).
1524 // The order is otherwise meaningless.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001525 StabilizeOrder(BaseVec, LiveVec);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001526
1527 // Do the actual rewriting and delete the old statepoint
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001528 makeStatepointExplicitImpl(CS, BaseVec, LiveVec, Result);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001529 CS.getInstruction()->eraseFromParent();
1530}
1531
1532// Helper function for the relocationViaAlloca.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001533//
1534// It receives iterator to the statepoint gc relocates and emits a store to the
1535// assigned location (via allocaMap) for the each one of them. It adds the
1536// visited values into the visitedLiveValues set, which we will later use them
1537// for sanity checking.
Philip Reamesd16a9b12015-02-20 01:06:44 +00001538static void
Sanjoy Das5665c992015-05-11 23:47:27 +00001539insertRelocationStores(iterator_range<Value::user_iterator> GCRelocs,
1540 DenseMap<Value *, Value *> &AllocaMap,
1541 DenseSet<Value *> &VisitedLiveValues) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001542
Sanjoy Das5665c992015-05-11 23:47:27 +00001543 for (User *U : GCRelocs) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001544 if (!isa<IntrinsicInst>(U))
1545 continue;
1546
Sanjoy Das5665c992015-05-11 23:47:27 +00001547 IntrinsicInst *RelocatedValue = cast<IntrinsicInst>(U);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001548
1549 // We only care about relocates
Sanjoy Das5665c992015-05-11 23:47:27 +00001550 if (RelocatedValue->getIntrinsicID() !=
Philip Reamesd16a9b12015-02-20 01:06:44 +00001551 Intrinsic::experimental_gc_relocate) {
1552 continue;
1553 }
1554
Sanjoy Das5665c992015-05-11 23:47:27 +00001555 GCRelocateOperands RelocateOperands(RelocatedValue);
1556 Value *OriginalValue =
1557 const_cast<Value *>(RelocateOperands.getDerivedPtr());
1558 assert(AllocaMap.count(OriginalValue));
1559 Value *Alloca = AllocaMap[OriginalValue];
Philip Reamesd16a9b12015-02-20 01:06:44 +00001560
1561 // Emit store into the related alloca
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001562 // All gc_relocates are i8 addrspace(1)* typed, and it must be bitcasted to
Sanjoy Das89c54912015-05-11 18:49:34 +00001563 // the correct type according to alloca.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001564 assert(RelocatedValue->getNextNode() &&
1565 "Should always have one since it's not a terminator");
Sanjoy Das5665c992015-05-11 23:47:27 +00001566 IRBuilder<> Builder(RelocatedValue->getNextNode());
Sanjoy Das89c54912015-05-11 18:49:34 +00001567 Value *CastedRelocatedValue =
Philip Reamesece70b82015-09-09 23:57:18 +00001568 Builder.CreateBitCast(RelocatedValue,
1569 cast<AllocaInst>(Alloca)->getAllocatedType(),
1570 suffixed_name_or(RelocatedValue, ".casted", ""));
Sanjoy Das89c54912015-05-11 18:49:34 +00001571
Sanjoy Das5665c992015-05-11 23:47:27 +00001572 StoreInst *Store = new StoreInst(CastedRelocatedValue, Alloca);
1573 Store->insertAfter(cast<Instruction>(CastedRelocatedValue));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001574
1575#ifndef NDEBUG
Sanjoy Das5665c992015-05-11 23:47:27 +00001576 VisitedLiveValues.insert(OriginalValue);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001577#endif
1578 }
1579}
1580
Igor Laevskye0317182015-05-19 15:59:05 +00001581// Helper function for the "relocationViaAlloca". Similar to the
1582// "insertRelocationStores" but works for rematerialized values.
1583static void
1584insertRematerializationStores(
1585 RematerializedValueMapTy RematerializedValues,
1586 DenseMap<Value *, Value *> &AllocaMap,
1587 DenseSet<Value *> &VisitedLiveValues) {
1588
1589 for (auto RematerializedValuePair: RematerializedValues) {
1590 Instruction *RematerializedValue = RematerializedValuePair.first;
1591 Value *OriginalValue = RematerializedValuePair.second;
1592
1593 assert(AllocaMap.count(OriginalValue) &&
1594 "Can not find alloca for rematerialized value");
1595 Value *Alloca = AllocaMap[OriginalValue];
1596
1597 StoreInst *Store = new StoreInst(RematerializedValue, Alloca);
1598 Store->insertAfter(RematerializedValue);
1599
1600#ifndef NDEBUG
1601 VisitedLiveValues.insert(OriginalValue);
1602#endif
1603 }
1604}
1605
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001606/// Do all the relocation update via allocas and mem2reg
Philip Reamesd16a9b12015-02-20 01:06:44 +00001607static void relocationViaAlloca(
Igor Laevsky285fe842015-05-19 16:29:43 +00001608 Function &F, DominatorTree &DT, ArrayRef<Value *> Live,
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001609 ArrayRef<PartiallyConstructedSafepointRecord> Records) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001610#ifndef NDEBUG
Philip Reamesa6ebf072015-03-27 05:53:16 +00001611 // record initial number of (static) allocas; we'll check we have the same
1612 // number when we get done.
1613 int InitialAllocaNum = 0;
Philip Reames704e78b2015-04-10 22:34:56 +00001614 for (auto I = F.getEntryBlock().begin(), E = F.getEntryBlock().end(); I != E;
1615 I++)
Philip Reamesa6ebf072015-03-27 05:53:16 +00001616 if (isa<AllocaInst>(*I))
1617 InitialAllocaNum++;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001618#endif
1619
1620 // TODO-PERF: change data structures, reserve
Igor Laevsky285fe842015-05-19 16:29:43 +00001621 DenseMap<Value *, Value *> AllocaMap;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001622 SmallVector<AllocaInst *, 200> PromotableAllocas;
Igor Laevskye0317182015-05-19 15:59:05 +00001623 // Used later to chack that we have enough allocas to store all values
1624 std::size_t NumRematerializedValues = 0;
Igor Laevsky285fe842015-05-19 16:29:43 +00001625 PromotableAllocas.reserve(Live.size());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001626
Igor Laevskye0317182015-05-19 15:59:05 +00001627 // Emit alloca for "LiveValue" and record it in "allocaMap" and
1628 // "PromotableAllocas"
1629 auto emitAllocaFor = [&](Value *LiveValue) {
1630 AllocaInst *Alloca = new AllocaInst(LiveValue->getType(), "",
1631 F.getEntryBlock().getFirstNonPHI());
Igor Laevsky285fe842015-05-19 16:29:43 +00001632 AllocaMap[LiveValue] = Alloca;
Igor Laevskye0317182015-05-19 15:59:05 +00001633 PromotableAllocas.push_back(Alloca);
1634 };
1635
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001636 // Emit alloca for each live gc pointer
1637 for (Value *V : Live)
1638 emitAllocaFor(V);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001639
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001640 // Emit allocas for rematerialized values
1641 for (const auto &Info : Records)
Igor Laevsky285fe842015-05-19 16:29:43 +00001642 for (auto RematerializedValuePair : Info.RematerializedValues) {
Igor Laevskye0317182015-05-19 15:59:05 +00001643 Value *OriginalValue = RematerializedValuePair.second;
Igor Laevsky285fe842015-05-19 16:29:43 +00001644 if (AllocaMap.count(OriginalValue) != 0)
Igor Laevskye0317182015-05-19 15:59:05 +00001645 continue;
1646
1647 emitAllocaFor(OriginalValue);
1648 ++NumRematerializedValues;
1649 }
Igor Laevsky285fe842015-05-19 16:29:43 +00001650
Philip Reamesd16a9b12015-02-20 01:06:44 +00001651 // The next two loops are part of the same conceptual operation. We need to
1652 // insert a store to the alloca after the original def and at each
1653 // redefinition. We need to insert a load before each use. These are split
1654 // into distinct loops for performance reasons.
1655
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001656 // Update gc pointer after each statepoint: either store a relocated value or
1657 // null (if no relocated value was found for this gc pointer and it is not a
1658 // gc_result). This must happen before we update the statepoint with load of
1659 // alloca otherwise we lose the link between statepoint and old def.
1660 for (const auto &Info : Records) {
Igor Laevsky285fe842015-05-19 16:29:43 +00001661 Value *Statepoint = Info.StatepointToken;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001662
1663 // This will be used for consistency check
Igor Laevsky285fe842015-05-19 16:29:43 +00001664 DenseSet<Value *> VisitedLiveValues;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001665
1666 // Insert stores for normal statepoint gc relocates
Igor Laevsky285fe842015-05-19 16:29:43 +00001667 insertRelocationStores(Statepoint->users(), AllocaMap, VisitedLiveValues);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001668
1669 // In case if it was invoke statepoint
1670 // we will insert stores for exceptional path gc relocates.
Philip Reames0a3240f2015-02-20 21:34:11 +00001671 if (isa<InvokeInst>(Statepoint)) {
Igor Laevsky285fe842015-05-19 16:29:43 +00001672 insertRelocationStores(Info.UnwindToken->users(), AllocaMap,
1673 VisitedLiveValues);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001674 }
1675
Igor Laevskye0317182015-05-19 15:59:05 +00001676 // Do similar thing with rematerialized values
Igor Laevsky285fe842015-05-19 16:29:43 +00001677 insertRematerializationStores(Info.RematerializedValues, AllocaMap,
1678 VisitedLiveValues);
Igor Laevskye0317182015-05-19 15:59:05 +00001679
Philip Reamese73300b2015-04-13 16:41:32 +00001680 if (ClobberNonLive) {
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001681 // As a debugging aid, pretend that an unrelocated pointer becomes null at
Philip Reamese73300b2015-04-13 16:41:32 +00001682 // the gc.statepoint. This will turn some subtle GC problems into
1683 // slightly easier to debug SEGVs. Note that on large IR files with
1684 // lots of gc.statepoints this is extremely costly both memory and time
1685 // wise.
1686 SmallVector<AllocaInst *, 64> ToClobber;
Igor Laevsky285fe842015-05-19 16:29:43 +00001687 for (auto Pair : AllocaMap) {
Philip Reamese73300b2015-04-13 16:41:32 +00001688 Value *Def = Pair.first;
1689 AllocaInst *Alloca = cast<AllocaInst>(Pair.second);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001690
Philip Reamese73300b2015-04-13 16:41:32 +00001691 // This value was relocated
Igor Laevsky285fe842015-05-19 16:29:43 +00001692 if (VisitedLiveValues.count(Def)) {
Philip Reamese73300b2015-04-13 16:41:32 +00001693 continue;
1694 }
1695 ToClobber.push_back(Alloca);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001696 }
Philip Reamesfa2fcf172015-02-20 19:51:56 +00001697
Philip Reamese73300b2015-04-13 16:41:32 +00001698 auto InsertClobbersAt = [&](Instruction *IP) {
1699 for (auto *AI : ToClobber) {
1700 auto AIType = cast<PointerType>(AI->getType());
1701 auto PT = cast<PointerType>(AIType->getElementType());
1702 Constant *CPN = ConstantPointerNull::get(PT);
Igor Laevsky285fe842015-05-19 16:29:43 +00001703 StoreInst *Store = new StoreInst(CPN, AI);
1704 Store->insertBefore(IP);
Philip Reamese73300b2015-04-13 16:41:32 +00001705 }
1706 };
1707
1708 // Insert the clobbering stores. These may get intermixed with the
1709 // gc.results and gc.relocates, but that's fine.
1710 if (auto II = dyn_cast<InvokeInst>(Statepoint)) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001711 InsertClobbersAt(&*II->getNormalDest()->getFirstInsertionPt());
1712 InsertClobbersAt(&*II->getUnwindDest()->getFirstInsertionPt());
Philip Reamese73300b2015-04-13 16:41:32 +00001713 } else {
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001714 InsertClobbersAt(cast<Instruction>(Statepoint)->getNextNode());
Philip Reamesfa2fcf172015-02-20 19:51:56 +00001715 }
David Blaikie82ad7872015-02-20 23:44:24 +00001716 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00001717 }
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001718
1719 // Update use with load allocas and add store for gc_relocated.
Igor Laevsky285fe842015-05-19 16:29:43 +00001720 for (auto Pair : AllocaMap) {
1721 Value *Def = Pair.first;
1722 Value *Alloca = Pair.second;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001723
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001724 // We pre-record the uses of allocas so that we dont have to worry about
1725 // later update that changes the user information..
1726
Igor Laevsky285fe842015-05-19 16:29:43 +00001727 SmallVector<Instruction *, 20> Uses;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001728 // PERF: trade a linear scan for repeated reallocation
Igor Laevsky285fe842015-05-19 16:29:43 +00001729 Uses.reserve(std::distance(Def->user_begin(), Def->user_end()));
1730 for (User *U : Def->users()) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001731 if (!isa<ConstantExpr>(U)) {
1732 // If the def has a ConstantExpr use, then the def is either a
1733 // ConstantExpr use itself or null. In either case
1734 // (recursively in the first, directly in the second), the oop
1735 // it is ultimately dependent on is null and this particular
1736 // use does not need to be fixed up.
Igor Laevsky285fe842015-05-19 16:29:43 +00001737 Uses.push_back(cast<Instruction>(U));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001738 }
1739 }
1740
Igor Laevsky285fe842015-05-19 16:29:43 +00001741 std::sort(Uses.begin(), Uses.end());
1742 auto Last = std::unique(Uses.begin(), Uses.end());
1743 Uses.erase(Last, Uses.end());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001744
Igor Laevsky285fe842015-05-19 16:29:43 +00001745 for (Instruction *Use : Uses) {
1746 if (isa<PHINode>(Use)) {
1747 PHINode *Phi = cast<PHINode>(Use);
1748 for (unsigned i = 0; i < Phi->getNumIncomingValues(); i++) {
1749 if (Def == Phi->getIncomingValue(i)) {
1750 LoadInst *Load = new LoadInst(
1751 Alloca, "", Phi->getIncomingBlock(i)->getTerminator());
1752 Phi->setIncomingValue(i, Load);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001753 }
1754 }
1755 } else {
Igor Laevsky285fe842015-05-19 16:29:43 +00001756 LoadInst *Load = new LoadInst(Alloca, "", Use);
1757 Use->replaceUsesOfWith(Def, Load);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001758 }
1759 }
1760
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001761 // Emit store for the initial gc value. Store must be inserted after load,
1762 // otherwise store will be in alloca's use list and an extra load will be
1763 // inserted before it.
Igor Laevsky285fe842015-05-19 16:29:43 +00001764 StoreInst *Store = new StoreInst(Def, Alloca);
1765 if (Instruction *Inst = dyn_cast<Instruction>(Def)) {
1766 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(Inst)) {
Philip Reames6da37852015-03-04 00:13:52 +00001767 // InvokeInst is a TerminatorInst so the store need to be inserted
1768 // into its normal destination block.
Igor Laevsky285fe842015-05-19 16:29:43 +00001769 BasicBlock *NormalDest = Invoke->getNormalDest();
1770 Store->insertBefore(NormalDest->getFirstNonPHI());
Philip Reames6da37852015-03-04 00:13:52 +00001771 } else {
Igor Laevsky285fe842015-05-19 16:29:43 +00001772 assert(!Inst->isTerminator() &&
Philip Reames6da37852015-03-04 00:13:52 +00001773 "The only TerminatorInst that can produce a value is "
1774 "InvokeInst which is handled above.");
Igor Laevsky285fe842015-05-19 16:29:43 +00001775 Store->insertAfter(Inst);
Philip Reames6da37852015-03-04 00:13:52 +00001776 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00001777 } else {
Igor Laevsky285fe842015-05-19 16:29:43 +00001778 assert(isa<Argument>(Def));
1779 Store->insertAfter(cast<Instruction>(Alloca));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001780 }
1781 }
1782
Igor Laevsky285fe842015-05-19 16:29:43 +00001783 assert(PromotableAllocas.size() == Live.size() + NumRematerializedValues &&
Philip Reamesd16a9b12015-02-20 01:06:44 +00001784 "we must have the same allocas with lives");
1785 if (!PromotableAllocas.empty()) {
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001786 // Apply mem2reg to promote alloca to SSA
Philip Reamesd16a9b12015-02-20 01:06:44 +00001787 PromoteMemToReg(PromotableAllocas, DT);
1788 }
1789
1790#ifndef NDEBUG
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001791 for (auto &I : F.getEntryBlock())
1792 if (isa<AllocaInst>(I))
Philip Reamesa6ebf072015-03-27 05:53:16 +00001793 InitialAllocaNum--;
1794 assert(InitialAllocaNum == 0 && "We must not introduce any extra allocas");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001795#endif
1796}
1797
1798/// Implement a unique function which doesn't require we sort the input
1799/// vector. Doing so has the effect of changing the output of a couple of
1800/// tests in ways which make them less useful in testing fused safepoints.
Philip Reamesd2b66462015-02-20 22:39:41 +00001801template <typename T> static void unique_unsorted(SmallVectorImpl<T> &Vec) {
Benjamin Kramer258ea0d2015-06-13 19:50:38 +00001802 SmallSet<T, 8> Seen;
1803 Vec.erase(std::remove_if(Vec.begin(), Vec.end(), [&](const T &V) {
1804 return !Seen.insert(V).second;
1805 }), Vec.end());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001806}
1807
Philip Reamesd16a9b12015-02-20 01:06:44 +00001808/// Insert holders so that each Value is obviously live through the entire
Philip Reamesf209a152015-04-13 20:00:30 +00001809/// lifetime of the call.
Philip Reamesd16a9b12015-02-20 01:06:44 +00001810static void insertUseHolderAfter(CallSite &CS, const ArrayRef<Value *> Values,
Philip Reamesf209a152015-04-13 20:00:30 +00001811 SmallVectorImpl<CallInst *> &Holders) {
Philip Reames21142752015-04-13 19:07:47 +00001812 if (Values.empty())
1813 // No values to hold live, might as well not insert the empty holder
1814 return;
1815
Philip Reamesd16a9b12015-02-20 01:06:44 +00001816 Module *M = CS.getInstruction()->getParent()->getParent()->getParent();
Philip Reamesf209a152015-04-13 20:00:30 +00001817 // Use a dummy vararg function to actually hold the values live
1818 Function *Func = cast<Function>(M->getOrInsertFunction(
1819 "__tmp_use", FunctionType::get(Type::getVoidTy(M->getContext()), true)));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001820 if (CS.isCall()) {
1821 // For call safepoints insert dummy calls right after safepoint
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001822 Holders.push_back(CallInst::Create(Func, Values, "",
1823 &*++CS.getInstruction()->getIterator()));
Philip Reamesf209a152015-04-13 20:00:30 +00001824 return;
1825 }
1826 // For invoke safepooints insert dummy calls both in normal and
1827 // exceptional destination blocks
1828 auto *II = cast<InvokeInst>(CS.getInstruction());
1829 Holders.push_back(CallInst::Create(
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001830 Func, Values, "", &*II->getNormalDest()->getFirstInsertionPt()));
Philip Reamesf209a152015-04-13 20:00:30 +00001831 Holders.push_back(CallInst::Create(
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001832 Func, Values, "", &*II->getUnwindDest()->getFirstInsertionPt()));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001833}
1834
1835static void findLiveReferences(
Philip Reamesd2b66462015-02-20 22:39:41 +00001836 Function &F, DominatorTree &DT, Pass *P, ArrayRef<CallSite> toUpdate,
1837 MutableArrayRef<struct PartiallyConstructedSafepointRecord> records) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00001838 GCPtrLivenessData OriginalLivenessData;
1839 computeLiveInValues(DT, F, OriginalLivenessData);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001840 for (size_t i = 0; i < records.size(); i++) {
1841 struct PartiallyConstructedSafepointRecord &info = records[i];
Philip Reamesd2b66462015-02-20 22:39:41 +00001842 const CallSite &CS = toUpdate[i];
Philip Reamesdf1ef082015-04-10 22:53:14 +00001843 analyzeParsePointLiveness(DT, OriginalLivenessData, CS, info);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001844 }
1845}
1846
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001847/// Remove any vector of pointers from the live set by scalarizing them over the
1848/// statepoint instruction. Adds the scalarized pieces to the live set. It
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001849/// would be preferable to include the vector in the statepoint itself, but
Philip Reames8531d8c2015-04-10 21:48:25 +00001850/// the lowering code currently does not handle that. Extending it would be
1851/// slightly non-trivial since it requires a format change. Given how rare
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001852/// such cases are (for the moment?) scalarizing is an acceptable compromise.
Philip Reames8531d8c2015-04-10 21:48:25 +00001853static void splitVectorValues(Instruction *StatepointInst,
Philip Reames8fe7f132015-06-26 22:47:37 +00001854 StatepointLiveSetTy &LiveSet,
1855 DenseMap<Value *, Value *>& PointerToBase,
1856 DominatorTree &DT) {
Philip Reames8531d8c2015-04-10 21:48:25 +00001857 SmallVector<Value *, 16> ToSplit;
1858 for (Value *V : LiveSet)
1859 if (isa<VectorType>(V->getType()))
1860 ToSplit.push_back(V);
1861
1862 if (ToSplit.empty())
1863 return;
1864
Philip Reames8fe7f132015-06-26 22:47:37 +00001865 DenseMap<Value *, SmallVector<Value *, 16>> ElementMapping;
1866
Philip Reames8531d8c2015-04-10 21:48:25 +00001867 Function &F = *(StatepointInst->getParent()->getParent());
1868
Philip Reames704e78b2015-04-10 22:34:56 +00001869 DenseMap<Value *, AllocaInst *> AllocaMap;
Philip Reames8531d8c2015-04-10 21:48:25 +00001870 // First is normal return, second is exceptional return (invoke only)
Philip Reames704e78b2015-04-10 22:34:56 +00001871 DenseMap<Value *, std::pair<Value *, Value *>> Replacements;
Philip Reames8531d8c2015-04-10 21:48:25 +00001872 for (Value *V : ToSplit) {
Philip Reames704e78b2015-04-10 22:34:56 +00001873 AllocaInst *Alloca =
1874 new AllocaInst(V->getType(), "", F.getEntryBlock().getFirstNonPHI());
Philip Reames8531d8c2015-04-10 21:48:25 +00001875 AllocaMap[V] = Alloca;
1876
1877 VectorType *VT = cast<VectorType>(V->getType());
1878 IRBuilder<> Builder(StatepointInst);
Philip Reames704e78b2015-04-10 22:34:56 +00001879 SmallVector<Value *, 16> Elements;
Philip Reames8531d8c2015-04-10 21:48:25 +00001880 for (unsigned i = 0; i < VT->getNumElements(); i++)
1881 Elements.push_back(Builder.CreateExtractElement(V, Builder.getInt32(i)));
Philip Reames8fe7f132015-06-26 22:47:37 +00001882 ElementMapping[V] = Elements;
Philip Reames8531d8c2015-04-10 21:48:25 +00001883
1884 auto InsertVectorReform = [&](Instruction *IP) {
1885 Builder.SetInsertPoint(IP);
1886 Builder.SetCurrentDebugLocation(IP->getDebugLoc());
1887 Value *ResultVec = UndefValue::get(VT);
1888 for (unsigned i = 0; i < VT->getNumElements(); i++)
1889 ResultVec = Builder.CreateInsertElement(ResultVec, Elements[i],
1890 Builder.getInt32(i));
1891 return ResultVec;
1892 };
1893
1894 if (isa<CallInst>(StatepointInst)) {
1895 BasicBlock::iterator Next(StatepointInst);
1896 Next++;
1897 Instruction *IP = &*(Next);
1898 Replacements[V].first = InsertVectorReform(IP);
1899 Replacements[V].second = nullptr;
1900 } else {
1901 InvokeInst *Invoke = cast<InvokeInst>(StatepointInst);
1902 // We've already normalized - check that we don't have shared destination
Philip Reames704e78b2015-04-10 22:34:56 +00001903 // blocks
Philip Reames8531d8c2015-04-10 21:48:25 +00001904 BasicBlock *NormalDest = Invoke->getNormalDest();
1905 assert(!isa<PHINode>(NormalDest->begin()));
1906 BasicBlock *UnwindDest = Invoke->getUnwindDest();
1907 assert(!isa<PHINode>(UnwindDest->begin()));
1908 // Insert insert element sequences in both successors
1909 Instruction *IP = &*(NormalDest->getFirstInsertionPt());
1910 Replacements[V].first = InsertVectorReform(IP);
1911 IP = &*(UnwindDest->getFirstInsertionPt());
1912 Replacements[V].second = InsertVectorReform(IP);
1913 }
1914 }
Philip Reames8fe7f132015-06-26 22:47:37 +00001915
Philip Reames8531d8c2015-04-10 21:48:25 +00001916 for (Value *V : ToSplit) {
1917 AllocaInst *Alloca = AllocaMap[V];
1918
1919 // Capture all users before we start mutating use lists
Philip Reames704e78b2015-04-10 22:34:56 +00001920 SmallVector<Instruction *, 16> Users;
Philip Reames8531d8c2015-04-10 21:48:25 +00001921 for (User *U : V->users())
1922 Users.push_back(cast<Instruction>(U));
1923
1924 for (Instruction *I : Users) {
1925 if (auto Phi = dyn_cast<PHINode>(I)) {
1926 for (unsigned i = 0; i < Phi->getNumIncomingValues(); i++)
1927 if (V == Phi->getIncomingValue(i)) {
Philip Reames704e78b2015-04-10 22:34:56 +00001928 LoadInst *Load = new LoadInst(
1929 Alloca, "", Phi->getIncomingBlock(i)->getTerminator());
Philip Reames8531d8c2015-04-10 21:48:25 +00001930 Phi->setIncomingValue(i, Load);
1931 }
1932 } else {
1933 LoadInst *Load = new LoadInst(Alloca, "", I);
1934 I->replaceUsesOfWith(V, Load);
1935 }
1936 }
1937
1938 // Store the original value and the replacement value into the alloca
1939 StoreInst *Store = new StoreInst(V, Alloca);
1940 if (auto I = dyn_cast<Instruction>(V))
1941 Store->insertAfter(I);
1942 else
1943 Store->insertAfter(Alloca);
Philip Reames704e78b2015-04-10 22:34:56 +00001944
Philip Reames8531d8c2015-04-10 21:48:25 +00001945 // Normal return for invoke, or call return
1946 Instruction *Replacement = cast<Instruction>(Replacements[V].first);
1947 (new StoreInst(Replacement, Alloca))->insertAfter(Replacement);
1948 // Unwind return for invoke only
1949 Replacement = cast_or_null<Instruction>(Replacements[V].second);
1950 if (Replacement)
1951 (new StoreInst(Replacement, Alloca))->insertAfter(Replacement);
1952 }
1953
1954 // apply mem2reg to promote alloca to SSA
Philip Reames704e78b2015-04-10 22:34:56 +00001955 SmallVector<AllocaInst *, 16> Allocas;
Philip Reames8531d8c2015-04-10 21:48:25 +00001956 for (Value *V : ToSplit)
1957 Allocas.push_back(AllocaMap[V]);
1958 PromoteMemToReg(Allocas, DT);
Philip Reames8fe7f132015-06-26 22:47:37 +00001959
1960 // Update our tracking of live pointers and base mappings to account for the
1961 // changes we just made.
1962 for (Value *V : ToSplit) {
1963 auto &Elements = ElementMapping[V];
1964
1965 LiveSet.erase(V);
1966 LiveSet.insert(Elements.begin(), Elements.end());
1967 // We need to update the base mapping as well.
1968 assert(PointerToBase.count(V));
1969 Value *OldBase = PointerToBase[V];
1970 auto &BaseElements = ElementMapping[OldBase];
1971 PointerToBase.erase(V);
1972 assert(Elements.size() == BaseElements.size());
1973 for (unsigned i = 0; i < Elements.size(); i++) {
1974 Value *Elem = Elements[i];
1975 PointerToBase[Elem] = BaseElements[i];
1976 }
1977 }
Philip Reames8531d8c2015-04-10 21:48:25 +00001978}
1979
Igor Laevskye0317182015-05-19 15:59:05 +00001980// Helper function for the "rematerializeLiveValues". It walks use chain
1981// starting from the "CurrentValue" until it meets "BaseValue". Only "simple"
1982// values are visited (currently it is GEP's and casts). Returns true if it
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001983// successfully reached "BaseValue" and false otherwise.
Igor Laevskye0317182015-05-19 15:59:05 +00001984// Fills "ChainToBase" array with all visited values. "BaseValue" is not
1985// recorded.
1986static bool findRematerializableChainToBasePointer(
1987 SmallVectorImpl<Instruction*> &ChainToBase,
1988 Value *CurrentValue, Value *BaseValue) {
1989
1990 // We have found a base value
1991 if (CurrentValue == BaseValue) {
1992 return true;
1993 }
1994
1995 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurrentValue)) {
1996 ChainToBase.push_back(GEP);
1997 return findRematerializableChainToBasePointer(ChainToBase,
1998 GEP->getPointerOperand(),
1999 BaseValue);
2000 }
2001
2002 if (CastInst *CI = dyn_cast<CastInst>(CurrentValue)) {
2003 Value *Def = CI->stripPointerCasts();
2004
2005 // This two checks are basically similar. First one is here for the
2006 // consistency with findBasePointers logic.
2007 assert(!isa<CastInst>(Def) && "not a pointer cast found");
2008 if (!CI->isNoopCast(CI->getModule()->getDataLayout()))
2009 return false;
2010
2011 ChainToBase.push_back(CI);
2012 return findRematerializableChainToBasePointer(ChainToBase, Def, BaseValue);
2013 }
2014
2015 // Not supported instruction in the chain
2016 return false;
2017}
2018
2019// Helper function for the "rematerializeLiveValues". Compute cost of the use
2020// chain we are going to rematerialize.
2021static unsigned
2022chainToBasePointerCost(SmallVectorImpl<Instruction*> &Chain,
2023 TargetTransformInfo &TTI) {
2024 unsigned Cost = 0;
2025
2026 for (Instruction *Instr : Chain) {
2027 if (CastInst *CI = dyn_cast<CastInst>(Instr)) {
2028 assert(CI->isNoopCast(CI->getModule()->getDataLayout()) &&
2029 "non noop cast is found during rematerialization");
2030
2031 Type *SrcTy = CI->getOperand(0)->getType();
2032 Cost += TTI.getCastInstrCost(CI->getOpcode(), CI->getType(), SrcTy);
2033
2034 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Instr)) {
2035 // Cost of the address calculation
2036 Type *ValTy = GEP->getPointerOperandType()->getPointerElementType();
2037 Cost += TTI.getAddressComputationCost(ValTy);
2038
2039 // And cost of the GEP itself
2040 // TODO: Use TTI->getGEPCost here (it exists, but appears to be not
2041 // allowed for the external usage)
2042 if (!GEP->hasAllConstantIndices())
2043 Cost += 2;
2044
2045 } else {
2046 llvm_unreachable("unsupported instruciton type during rematerialization");
2047 }
2048 }
2049
2050 return Cost;
2051}
2052
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002053// From the statepoint live set pick values that are cheaper to recompute then
2054// to relocate. Remove this values from the live set, rematerialize them after
Igor Laevskye0317182015-05-19 15:59:05 +00002055// statepoint and record them in "Info" structure. Note that similar to
2056// relocated values we don't do any user adjustments here.
2057static void rematerializeLiveValues(CallSite CS,
2058 PartiallyConstructedSafepointRecord &Info,
2059 TargetTransformInfo &TTI) {
Aaron Ballmanff7d4fa2015-05-20 14:53:50 +00002060 const unsigned int ChainLengthThreshold = 10;
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +00002061
Igor Laevskye0317182015-05-19 15:59:05 +00002062 // Record values we are going to delete from this statepoint live set.
2063 // We can not di this in following loop due to iterator invalidation.
2064 SmallVector<Value *, 32> LiveValuesToBeDeleted;
2065
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002066 for (Value *LiveValue: Info.LiveSet) {
Igor Laevskye0317182015-05-19 15:59:05 +00002067 // For each live pointer find it's defining chain
2068 SmallVector<Instruction *, 3> ChainToBase;
Philip Reames74ce2e72015-07-21 16:51:17 +00002069 assert(Info.PointerToBase.count(LiveValue));
Igor Laevskye0317182015-05-19 15:59:05 +00002070 bool FoundChain =
2071 findRematerializableChainToBasePointer(ChainToBase,
2072 LiveValue,
2073 Info.PointerToBase[LiveValue]);
2074 // Nothing to do, or chain is too long
2075 if (!FoundChain ||
2076 ChainToBase.size() == 0 ||
2077 ChainToBase.size() > ChainLengthThreshold)
2078 continue;
2079
2080 // Compute cost of this chain
2081 unsigned Cost = chainToBasePointerCost(ChainToBase, TTI);
2082 // TODO: We can also account for cases when we will be able to remove some
2083 // of the rematerialized values by later optimization passes. I.e if
2084 // we rematerialized several intersecting chains. Or if original values
2085 // don't have any uses besides this statepoint.
2086
2087 // For invokes we need to rematerialize each chain twice - for normal and
2088 // for unwind basic blocks. Model this by multiplying cost by two.
2089 if (CS.isInvoke()) {
2090 Cost *= 2;
2091 }
2092 // If it's too expensive - skip it
2093 if (Cost >= RematerializationThreshold)
2094 continue;
2095
2096 // Remove value from the live set
2097 LiveValuesToBeDeleted.push_back(LiveValue);
2098
2099 // Clone instructions and record them inside "Info" structure
2100
2101 // Walk backwards to visit top-most instructions first
2102 std::reverse(ChainToBase.begin(), ChainToBase.end());
2103
2104 // Utility function which clones all instructions from "ChainToBase"
2105 // and inserts them before "InsertBefore". Returns rematerialized value
2106 // which should be used after statepoint.
2107 auto rematerializeChain = [&ChainToBase](Instruction *InsertBefore) {
2108 Instruction *LastClonedValue = nullptr;
2109 Instruction *LastValue = nullptr;
2110 for (Instruction *Instr: ChainToBase) {
2111 // Only GEP's and casts are suported as we need to be careful to not
2112 // introduce any new uses of pointers not in the liveset.
2113 // Note that it's fine to introduce new uses of pointers which were
2114 // otherwise not used after this statepoint.
2115 assert(isa<GetElementPtrInst>(Instr) || isa<CastInst>(Instr));
2116
2117 Instruction *ClonedValue = Instr->clone();
2118 ClonedValue->insertBefore(InsertBefore);
2119 ClonedValue->setName(Instr->getName() + ".remat");
2120
2121 // If it is not first instruction in the chain then it uses previously
2122 // cloned value. We should update it to use cloned value.
2123 if (LastClonedValue) {
2124 assert(LastValue);
2125 ClonedValue->replaceUsesOfWith(LastValue, LastClonedValue);
2126#ifndef NDEBUG
Igor Laevskyd83f6972015-05-21 13:02:14 +00002127 // Assert that cloned instruction does not use any instructions from
2128 // this chain other than LastClonedValue
2129 for (auto OpValue : ClonedValue->operand_values()) {
2130 assert(std::find(ChainToBase.begin(), ChainToBase.end(), OpValue) ==
2131 ChainToBase.end() &&
2132 "incorrect use in rematerialization chain");
Igor Laevskye0317182015-05-19 15:59:05 +00002133 }
2134#endif
2135 }
2136
2137 LastClonedValue = ClonedValue;
2138 LastValue = Instr;
2139 }
2140 assert(LastClonedValue);
2141 return LastClonedValue;
2142 };
2143
2144 // Different cases for calls and invokes. For invokes we need to clone
2145 // instructions both on normal and unwind path.
2146 if (CS.isCall()) {
2147 Instruction *InsertBefore = CS.getInstruction()->getNextNode();
2148 assert(InsertBefore);
2149 Instruction *RematerializedValue = rematerializeChain(InsertBefore);
2150 Info.RematerializedValues[RematerializedValue] = LiveValue;
2151 } else {
2152 InvokeInst *Invoke = cast<InvokeInst>(CS.getInstruction());
2153
2154 Instruction *NormalInsertBefore =
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00002155 &*Invoke->getNormalDest()->getFirstInsertionPt();
Igor Laevskye0317182015-05-19 15:59:05 +00002156 Instruction *UnwindInsertBefore =
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00002157 &*Invoke->getUnwindDest()->getFirstInsertionPt();
Igor Laevskye0317182015-05-19 15:59:05 +00002158
2159 Instruction *NormalRematerializedValue =
2160 rematerializeChain(NormalInsertBefore);
2161 Instruction *UnwindRematerializedValue =
2162 rematerializeChain(UnwindInsertBefore);
2163
2164 Info.RematerializedValues[NormalRematerializedValue] = LiveValue;
2165 Info.RematerializedValues[UnwindRematerializedValue] = LiveValue;
2166 }
2167 }
2168
2169 // Remove rematerializaed values from the live set
2170 for (auto LiveValue: LiveValuesToBeDeleted) {
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002171 Info.LiveSet.erase(LiveValue);
Igor Laevskye0317182015-05-19 15:59:05 +00002172 }
2173}
2174
Philip Reamesd16a9b12015-02-20 01:06:44 +00002175static bool insertParsePoints(Function &F, DominatorTree &DT, Pass *P,
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002176 SmallVectorImpl<CallSite> &ToUpdate) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00002177#ifndef NDEBUG
2178 // sanity check the input
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002179 std::set<CallSite> Uniqued;
2180 Uniqued.insert(ToUpdate.begin(), ToUpdate.end());
2181 assert(Uniqued.size() == ToUpdate.size() && "no duplicates please!");
Philip Reamesd16a9b12015-02-20 01:06:44 +00002182
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002183 for (CallSite CS : ToUpdate) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00002184 assert(CS.getInstruction()->getParent()->getParent() == &F);
2185 assert(isStatepoint(CS) && "expected to already be a deopt statepoint");
2186 }
2187#endif
2188
Philip Reames69e51ca2015-04-13 18:07:21 +00002189 // When inserting gc.relocates for invokes, we need to be able to insert at
2190 // the top of the successor blocks. See the comment on
2191 // normalForInvokeSafepoint on exactly what is needed. Note that this step
Philip Reamesf209a152015-04-13 20:00:30 +00002192 // may restructure the CFG.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002193 for (CallSite CS : ToUpdate) {
Philip Reamesf209a152015-04-13 20:00:30 +00002194 if (!CS.isInvoke())
2195 continue;
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002196 auto *II = cast<InvokeInst>(CS.getInstruction());
2197 normalizeForInvokeSafepoint(II->getNormalDest(), II->getParent(), DT);
2198 normalizeForInvokeSafepoint(II->getUnwindDest(), II->getParent(), DT);
Philip Reamesf209a152015-04-13 20:00:30 +00002199 }
Philip Reames69e51ca2015-04-13 18:07:21 +00002200
Philip Reamesd16a9b12015-02-20 01:06:44 +00002201 // A list of dummy calls added to the IR to keep various values obviously
2202 // live in the IR. We'll remove all of these when done.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002203 SmallVector<CallInst *, 64> Holders;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002204
2205 // Insert a dummy call with all of the arguments to the vm_state we'll need
2206 // for the actual safepoint insertion. This ensures reference arguments in
2207 // the deopt argument list are considered live through the safepoint (and
2208 // thus makes sure they get relocated.)
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002209 for (CallSite CS : ToUpdate) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00002210 Statepoint StatepointCS(CS);
2211
2212 SmallVector<Value *, 64> DeoptValues;
2213 for (Use &U : StatepointCS.vm_state_args()) {
2214 Value *Arg = cast<Value>(&U);
Philip Reames8531d8c2015-04-10 21:48:25 +00002215 assert(!isUnhandledGCPointerType(Arg->getType()) &&
2216 "support for FCA unimplemented");
2217 if (isHandledGCPointerType(Arg->getType()))
Philip Reamesd16a9b12015-02-20 01:06:44 +00002218 DeoptValues.push_back(Arg);
2219 }
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002220 insertUseHolderAfter(CS, DeoptValues, Holders);
Philip Reamesd16a9b12015-02-20 01:06:44 +00002221 }
2222
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002223 SmallVector<PartiallyConstructedSafepointRecord, 64> Records(ToUpdate.size());
Philip Reamesd16a9b12015-02-20 01:06:44 +00002224
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002225 // A) Identify all gc pointers which are statically live at the given call
Philip Reamesd16a9b12015-02-20 01:06:44 +00002226 // site.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002227 findLiveReferences(F, DT, P, ToUpdate, Records);
Philip Reamesd16a9b12015-02-20 01:06:44 +00002228
2229 // B) Find the base pointers for each live pointer
2230 /* scope for caching */ {
2231 // Cache the 'defining value' relation used in the computation and
2232 // insertion of base phis and selects. This ensures that we don't insert
2233 // large numbers of duplicate base_phis.
2234 DefiningValueMapTy DVCache;
2235
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002236 for (size_t i = 0; i < Records.size(); i++) {
2237 PartiallyConstructedSafepointRecord &info = Records[i];
2238 findBasePointers(DT, DVCache, ToUpdate[i], info);
Philip Reamesd16a9b12015-02-20 01:06:44 +00002239 }
2240 } // end of cache scope
2241
2242 // The base phi insertion logic (for any safepoint) may have inserted new
2243 // instructions which are now live at some safepoint. The simplest such
2244 // example is:
2245 // loop:
2246 // phi a <-- will be a new base_phi here
2247 // safepoint 1 <-- that needs to be live here
2248 // gep a + 1
2249 // safepoint 2
2250 // br loop
Philip Reamesd16a9b12015-02-20 01:06:44 +00002251 // We insert some dummy calls after each safepoint to definitely hold live
2252 // the base pointers which were identified for that safepoint. We'll then
2253 // ask liveness for _every_ base inserted to see what is now live. Then we
2254 // remove the dummy calls.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002255 Holders.reserve(Holders.size() + Records.size());
2256 for (size_t i = 0; i < Records.size(); i++) {
2257 PartiallyConstructedSafepointRecord &Info = Records[i];
Philip Reamesd16a9b12015-02-20 01:06:44 +00002258
2259 SmallVector<Value *, 128> Bases;
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002260 for (auto Pair : Info.PointerToBase)
Philip Reamesd16a9b12015-02-20 01:06:44 +00002261 Bases.push_back(Pair.second);
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002262
2263 insertUseHolderAfter(ToUpdate[i], Bases, Holders);
Philip Reamesd16a9b12015-02-20 01:06:44 +00002264 }
2265
Philip Reamesdf1ef082015-04-10 22:53:14 +00002266 // By selecting base pointers, we've effectively inserted new uses. Thus, we
2267 // need to rerun liveness. We may *also* have inserted new defs, but that's
2268 // not the key issue.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002269 recomputeLiveInValues(F, DT, P, ToUpdate, Records);
Philip Reamesd16a9b12015-02-20 01:06:44 +00002270
Philip Reamesd16a9b12015-02-20 01:06:44 +00002271 if (PrintBasePointers) {
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002272 for (auto &Info : Records) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00002273 errs() << "Base Pairs: (w/Relocation)\n";
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002274 for (auto Pair : Info.PointerToBase)
Philip Reamesd16a9b12015-02-20 01:06:44 +00002275 errs() << " derived %" << Pair.first->getName() << " base %"
2276 << Pair.second->getName() << "\n";
Philip Reamesd16a9b12015-02-20 01:06:44 +00002277 }
2278 }
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002279
2280 for (CallInst *CI : Holders)
2281 CI->eraseFromParent();
2282
2283 Holders.clear();
Philip Reamesd16a9b12015-02-20 01:06:44 +00002284
Philip Reames8fe7f132015-06-26 22:47:37 +00002285 // Do a limited scalarization of any live at safepoint vector values which
2286 // contain pointers. This enables this pass to run after vectorization at
2287 // the cost of some possible performance loss. TODO: it would be nice to
2288 // natively support vectors all the way through the backend so we don't need
2289 // to scalarize here.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002290 for (size_t i = 0; i < Records.size(); i++) {
2291 PartiallyConstructedSafepointRecord &Info = Records[i];
2292 Instruction *Statepoint = ToUpdate[i].getInstruction();
2293 splitVectorValues(cast<Instruction>(Statepoint), Info.LiveSet,
2294 Info.PointerToBase, DT);
Philip Reames8fe7f132015-06-26 22:47:37 +00002295 }
2296
Igor Laevskye0317182015-05-19 15:59:05 +00002297 // In order to reduce live set of statepoint we might choose to rematerialize
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002298 // some values instead of relocating them. This is purely an optimization and
Igor Laevskye0317182015-05-19 15:59:05 +00002299 // does not influence correctness.
2300 TargetTransformInfo &TTI =
2301 P->getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
2302
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002303 for (size_t i = 0; i < Records.size(); i++)
2304 rematerializeLiveValues(ToUpdate[i], Records[i], TTI);
Igor Laevskye0317182015-05-19 15:59:05 +00002305
Philip Reamesd16a9b12015-02-20 01:06:44 +00002306 // Now run through and replace the existing statepoints with new ones with
2307 // the live variables listed. We do not yet update uses of the values being
2308 // relocated. We have references to live variables that need to
2309 // survive to the last iteration of this loop. (By construction, the
2310 // previous statepoint can not be a live variable, thus we can and remove
2311 // the old statepoint calls as we go.)
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002312 for (size_t i = 0; i < Records.size(); i++)
2313 makeStatepointExplicit(DT, ToUpdate[i], Records[i]);
2314
2315 ToUpdate.clear(); // prevent accident use of invalid CallSites
Philip Reamesd16a9b12015-02-20 01:06:44 +00002316
Philip Reamesd16a9b12015-02-20 01:06:44 +00002317 // Do all the fixups of the original live variables to their relocated selves
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002318 SmallVector<Value *, 128> Live;
2319 for (size_t i = 0; i < Records.size(); i++) {
2320 PartiallyConstructedSafepointRecord &Info = Records[i];
Philip Reamesd16a9b12015-02-20 01:06:44 +00002321 // We can't simply save the live set from the original insertion. One of
2322 // the live values might be the result of a call which needs a safepoint.
2323 // That Value* no longer exists and we need to use the new gc_result.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002324 // Thankfully, the live set is embedded in the statepoint (and updated), so
Philip Reamesd16a9b12015-02-20 01:06:44 +00002325 // we just grab that.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002326 Statepoint Statepoint(Info.StatepointToken);
2327 Live.insert(Live.end(), Statepoint.gc_args_begin(),
2328 Statepoint.gc_args_end());
Philip Reames9a2e01d2015-04-13 17:35:55 +00002329#ifndef NDEBUG
2330 // Do some basic sanity checks on our liveness results before performing
2331 // relocation. Relocation can and will turn mistakes in liveness results
2332 // into non-sensical code which is must harder to debug.
2333 // TODO: It would be nice to test consistency as well
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002334 assert(DT.isReachableFromEntry(Info.StatepointToken->getParent()) &&
Philip Reames9a2e01d2015-04-13 17:35:55 +00002335 "statepoint must be reachable or liveness is meaningless");
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002336 for (Value *V : Statepoint.gc_args()) {
Philip Reames9a2e01d2015-04-13 17:35:55 +00002337 if (!isa<Instruction>(V))
2338 // Non-instruction values trivial dominate all possible uses
2339 continue;
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002340 auto *LiveInst = cast<Instruction>(V);
Philip Reames9a2e01d2015-04-13 17:35:55 +00002341 assert(DT.isReachableFromEntry(LiveInst->getParent()) &&
2342 "unreachable values should never be live");
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002343 assert(DT.dominates(LiveInst, Info.StatepointToken) &&
Philip Reames9a2e01d2015-04-13 17:35:55 +00002344 "basic SSA liveness expectation violated by liveness analysis");
2345 }
2346#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +00002347 }
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002348 unique_unsorted(Live);
Philip Reamesd16a9b12015-02-20 01:06:44 +00002349
Nick Lewyckyeb3231e2015-02-20 07:14:02 +00002350#ifndef NDEBUG
Philip Reamesd16a9b12015-02-20 01:06:44 +00002351 // sanity check
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002352 for (auto *Ptr : Live)
2353 assert(isGCPointerType(Ptr->getType()) && "must be a gc pointer type");
Nick Lewyckyeb3231e2015-02-20 07:14:02 +00002354#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +00002355
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002356 relocationViaAlloca(F, DT, Live, Records);
2357 return !Records.empty();
Philip Reamesd16a9b12015-02-20 01:06:44 +00002358}
2359
Sanjoy Das353a19e2015-06-02 22:33:37 +00002360// Handles both return values and arguments for Functions and CallSites.
2361template <typename AttrHolder>
2362static void RemoveDerefAttrAtIndex(LLVMContext &Ctx, AttrHolder &AH,
2363 unsigned Index) {
2364 AttrBuilder R;
2365 if (AH.getDereferenceableBytes(Index))
2366 R.addAttribute(Attribute::get(Ctx, Attribute::Dereferenceable,
2367 AH.getDereferenceableBytes(Index)));
2368 if (AH.getDereferenceableOrNullBytes(Index))
2369 R.addAttribute(Attribute::get(Ctx, Attribute::DereferenceableOrNull,
2370 AH.getDereferenceableOrNullBytes(Index)));
2371
2372 if (!R.empty())
2373 AH.setAttributes(AH.getAttributes().removeAttributes(
2374 Ctx, Index, AttributeSet::get(Ctx, Index, R)));
Vasileios Kalintiris9f77f612015-06-03 08:51:30 +00002375}
Sanjoy Das353a19e2015-06-02 22:33:37 +00002376
2377void
2378RewriteStatepointsForGC::stripDereferenceabilityInfoFromPrototype(Function &F) {
2379 LLVMContext &Ctx = F.getContext();
2380
2381 for (Argument &A : F.args())
2382 if (isa<PointerType>(A.getType()))
2383 RemoveDerefAttrAtIndex(Ctx, F, A.getArgNo() + 1);
2384
2385 if (isa<PointerType>(F.getReturnType()))
2386 RemoveDerefAttrAtIndex(Ctx, F, AttributeSet::ReturnIndex);
2387}
2388
2389void RewriteStatepointsForGC::stripDereferenceabilityInfoFromBody(Function &F) {
2390 if (F.empty())
2391 return;
2392
2393 LLVMContext &Ctx = F.getContext();
2394 MDBuilder Builder(Ctx);
2395
Nico Rieck78199512015-08-06 19:10:45 +00002396 for (Instruction &I : instructions(F)) {
Sanjoy Das353a19e2015-06-02 22:33:37 +00002397 if (const MDNode *MD = I.getMetadata(LLVMContext::MD_tbaa)) {
2398 assert(MD->getNumOperands() < 5 && "unrecognized metadata shape!");
2399 bool IsImmutableTBAA =
2400 MD->getNumOperands() == 4 &&
2401 mdconst::extract<ConstantInt>(MD->getOperand(3))->getValue() == 1;
2402
2403 if (!IsImmutableTBAA)
2404 continue; // no work to do, MD_tbaa is already marked mutable
2405
2406 MDNode *Base = cast<MDNode>(MD->getOperand(0));
2407 MDNode *Access = cast<MDNode>(MD->getOperand(1));
2408 uint64_t Offset =
2409 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue();
2410
2411 MDNode *MutableTBAA =
2412 Builder.createTBAAStructTagNode(Base, Access, Offset);
2413 I.setMetadata(LLVMContext::MD_tbaa, MutableTBAA);
2414 }
2415
2416 if (CallSite CS = CallSite(&I)) {
2417 for (int i = 0, e = CS.arg_size(); i != e; i++)
2418 if (isa<PointerType>(CS.getArgument(i)->getType()))
2419 RemoveDerefAttrAtIndex(Ctx, CS, i + 1);
2420 if (isa<PointerType>(CS.getType()))
2421 RemoveDerefAttrAtIndex(Ctx, CS, AttributeSet::ReturnIndex);
2422 }
2423 }
2424}
2425
Philip Reamesd16a9b12015-02-20 01:06:44 +00002426/// Returns true if this function should be rewritten by this pass. The main
2427/// point of this function is as an extension point for custom logic.
2428static bool shouldRewriteStatepointsIn(Function &F) {
2429 // TODO: This should check the GCStrategy
Philip Reames2ef029c2015-02-20 18:56:14 +00002430 if (F.hasGC()) {
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +00002431 const char *FunctionGCName = F.getGC();
2432 const StringRef StatepointExampleName("statepoint-example");
2433 const StringRef CoreCLRName("coreclr");
2434 return (StatepointExampleName == FunctionGCName) ||
NAKAMURA Takumi5582a6a2015-05-25 01:43:34 +00002435 (CoreCLRName == FunctionGCName);
2436 } else
Philip Reames2ef029c2015-02-20 18:56:14 +00002437 return false;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002438}
2439
Sanjoy Das353a19e2015-06-02 22:33:37 +00002440void RewriteStatepointsForGC::stripDereferenceabilityInfo(Module &M) {
2441#ifndef NDEBUG
2442 assert(std::any_of(M.begin(), M.end(), shouldRewriteStatepointsIn) &&
2443 "precondition!");
2444#endif
2445
2446 for (Function &F : M)
2447 stripDereferenceabilityInfoFromPrototype(F);
2448
2449 for (Function &F : M)
2450 stripDereferenceabilityInfoFromBody(F);
2451}
2452
Philip Reamesd16a9b12015-02-20 01:06:44 +00002453bool RewriteStatepointsForGC::runOnFunction(Function &F) {
2454 // Nothing to do for declarations.
2455 if (F.isDeclaration() || F.empty())
2456 return false;
2457
2458 // Policy choice says not to rewrite - the most common reason is that we're
2459 // compiling code without a GCStrategy.
2460 if (!shouldRewriteStatepointsIn(F))
2461 return false;
2462
Sanjoy Dasea45f0e2015-06-02 22:33:34 +00002463 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
Philip Reames704e78b2015-04-10 22:34:56 +00002464
Philip Reames85b36a82015-04-10 22:07:04 +00002465 // Gather all the statepoints which need rewritten. Be careful to only
2466 // consider those in reachable code since we need to ask dominance queries
2467 // when rewriting. We'll delete the unreachable ones in a moment.
Philip Reamesd2b66462015-02-20 22:39:41 +00002468 SmallVector<CallSite, 64> ParsePointNeeded;
Philip Reamesf66d7372015-04-10 22:16:58 +00002469 bool HasUnreachableStatepoint = false;
Nico Rieck78199512015-08-06 19:10:45 +00002470 for (Instruction &I : instructions(F)) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00002471 // TODO: only the ones with the flag set!
Philip Reames85b36a82015-04-10 22:07:04 +00002472 if (isStatepoint(I)) {
2473 if (DT.isReachableFromEntry(I.getParent()))
2474 ParsePointNeeded.push_back(CallSite(&I));
2475 else
Philip Reamesf66d7372015-04-10 22:16:58 +00002476 HasUnreachableStatepoint = true;
Philip Reames85b36a82015-04-10 22:07:04 +00002477 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00002478 }
2479
Philip Reames85b36a82015-04-10 22:07:04 +00002480 bool MadeChange = false;
Philip Reames704e78b2015-04-10 22:34:56 +00002481
Philip Reames85b36a82015-04-10 22:07:04 +00002482 // Delete any unreachable statepoints so that we don't have unrewritten
2483 // statepoints surviving this pass. This makes testing easier and the
2484 // resulting IR less confusing to human readers. Rather than be fancy, we
2485 // just reuse a utility function which removes the unreachable blocks.
Philip Reamesf66d7372015-04-10 22:16:58 +00002486 if (HasUnreachableStatepoint)
Philip Reames85b36a82015-04-10 22:07:04 +00002487 MadeChange |= removeUnreachableBlocks(F);
2488
Philip Reamesd16a9b12015-02-20 01:06:44 +00002489 // Return early if no work to do.
2490 if (ParsePointNeeded.empty())
Philip Reames85b36a82015-04-10 22:07:04 +00002491 return MadeChange;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002492
Philip Reames85b36a82015-04-10 22:07:04 +00002493 // As a prepass, go ahead and aggressively destroy single entry phi nodes.
2494 // These are created by LCSSA. They have the effect of increasing the size
2495 // of liveness sets for no good reason. It may be harder to do this post
2496 // insertion since relocations and base phis can confuse things.
2497 for (BasicBlock &BB : F)
2498 if (BB.getUniquePredecessor()) {
2499 MadeChange = true;
2500 FoldSingleEntryPHINodes(&BB);
2501 }
2502
Philip Reames971dc3a2015-08-12 22:11:45 +00002503 // Before we start introducing relocations, we want to tweak the IR a bit to
2504 // avoid unfortunate code generation effects. The main example is that we
2505 // want to try to make sure the comparison feeding a branch is after any
2506 // safepoints. Otherwise, we end up with a comparison of pre-relocation
2507 // values feeding a branch after relocation. This is semantically correct,
2508 // but results in extra register pressure since both the pre-relocation and
2509 // post-relocation copies must be available in registers. For code without
2510 // relocations this is handled elsewhere, but teaching the scheduler to
2511 // reverse the transform we're about to do would be slightly complex.
2512 // Note: This may extend the live range of the inputs to the icmp and thus
2513 // increase the liveset of any statepoint we move over. This is profitable
2514 // as long as all statepoints are in rare blocks. If we had in-register
2515 // lowering for live values this would be a much safer transform.
2516 auto getConditionInst = [](TerminatorInst *TI) -> Instruction* {
2517 if (auto *BI = dyn_cast<BranchInst>(TI))
2518 if (BI->isConditional())
2519 return dyn_cast<Instruction>(BI->getCondition());
2520 // TODO: Extend this to handle switches
2521 return nullptr;
2522 };
2523 for (BasicBlock &BB : F) {
2524 TerminatorInst *TI = BB.getTerminator();
2525 if (auto *Cond = getConditionInst(TI))
2526 // TODO: Handle more than just ICmps here. We should be able to move
2527 // most instructions without side effects or memory access.
2528 if (isa<ICmpInst>(Cond) && Cond->hasOneUse()) {
2529 MadeChange = true;
2530 Cond->moveBefore(TI);
2531 }
2532 }
2533
Philip Reames85b36a82015-04-10 22:07:04 +00002534 MadeChange |= insertParsePoints(F, DT, this, ParsePointNeeded);
2535 return MadeChange;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002536}
Philip Reamesdf1ef082015-04-10 22:53:14 +00002537
2538// liveness computation via standard dataflow
2539// -------------------------------------------------------------------
2540
2541// TODO: Consider using bitvectors for liveness, the set of potentially
2542// interesting values should be small and easy to pre-compute.
2543
Philip Reamesdf1ef082015-04-10 22:53:14 +00002544/// Compute the live-in set for the location rbegin starting from
2545/// the live-out set of the basic block
2546static void computeLiveInValues(BasicBlock::reverse_iterator rbegin,
2547 BasicBlock::reverse_iterator rend,
2548 DenseSet<Value *> &LiveTmp) {
2549
2550 for (BasicBlock::reverse_iterator ritr = rbegin; ritr != rend; ritr++) {
2551 Instruction *I = &*ritr;
2552
2553 // KILL/Def - Remove this definition from LiveIn
2554 LiveTmp.erase(I);
2555
2556 // Don't consider *uses* in PHI nodes, we handle their contribution to
2557 // predecessor blocks when we seed the LiveOut sets
2558 if (isa<PHINode>(I))
2559 continue;
2560
2561 // USE - Add to the LiveIn set for this instruction
2562 for (Value *V : I->operands()) {
2563 assert(!isUnhandledGCPointerType(V->getType()) &&
2564 "support for FCA unimplemented");
Philip Reames63294cb2015-04-26 19:48:03 +00002565 if (isHandledGCPointerType(V->getType()) && !isa<Constant>(V)) {
2566 // The choice to exclude all things constant here is slightly subtle.
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002567 // There are two independent reasons:
Philip Reames63294cb2015-04-26 19:48:03 +00002568 // - We assume that things which are constant (from LLVM's definition)
2569 // do not move at runtime. For example, the address of a global
2570 // variable is fixed, even though it's contents may not be.
2571 // - Second, we can't disallow arbitrary inttoptr constants even
2572 // if the language frontend does. Optimization passes are free to
2573 // locally exploit facts without respect to global reachability. This
2574 // can create sections of code which are dynamically unreachable and
2575 // contain just about anything. (see constants.ll in tests)
Philip Reamesdf1ef082015-04-10 22:53:14 +00002576 LiveTmp.insert(V);
2577 }
2578 }
2579 }
2580}
2581
2582static void computeLiveOutSeed(BasicBlock *BB, DenseSet<Value *> &LiveTmp) {
2583
2584 for (BasicBlock *Succ : successors(BB)) {
2585 const BasicBlock::iterator E(Succ->getFirstNonPHI());
2586 for (BasicBlock::iterator I = Succ->begin(); I != E; I++) {
2587 PHINode *Phi = cast<PHINode>(&*I);
2588 Value *V = Phi->getIncomingValueForBlock(BB);
2589 assert(!isUnhandledGCPointerType(V->getType()) &&
2590 "support for FCA unimplemented");
Philip Reames63294cb2015-04-26 19:48:03 +00002591 if (isHandledGCPointerType(V->getType()) && !isa<Constant>(V)) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00002592 LiveTmp.insert(V);
2593 }
2594 }
2595 }
2596}
2597
2598static DenseSet<Value *> computeKillSet(BasicBlock *BB) {
2599 DenseSet<Value *> KillSet;
2600 for (Instruction &I : *BB)
2601 if (isHandledGCPointerType(I.getType()))
2602 KillSet.insert(&I);
2603 return KillSet;
2604}
2605
Philip Reames9638ff92015-04-11 00:06:47 +00002606#ifndef NDEBUG
Philip Reamesdf1ef082015-04-10 22:53:14 +00002607/// Check that the items in 'Live' dominate 'TI'. This is used as a basic
2608/// sanity check for the liveness computation.
2609static void checkBasicSSA(DominatorTree &DT, DenseSet<Value *> &Live,
2610 TerminatorInst *TI, bool TermOkay = false) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00002611 for (Value *V : Live) {
2612 if (auto *I = dyn_cast<Instruction>(V)) {
2613 // The terminator can be a member of the LiveOut set. LLVM's definition
2614 // of instruction dominance states that V does not dominate itself. As
2615 // such, we need to special case this to allow it.
2616 if (TermOkay && TI == I)
2617 continue;
2618 assert(DT.dominates(I, TI) &&
2619 "basic SSA liveness expectation violated by liveness analysis");
2620 }
2621 }
Philip Reamesdf1ef082015-04-10 22:53:14 +00002622}
2623
2624/// Check that all the liveness sets used during the computation of liveness
2625/// obey basic SSA properties. This is useful for finding cases where we miss
2626/// a def.
2627static void checkBasicSSA(DominatorTree &DT, GCPtrLivenessData &Data,
2628 BasicBlock &BB) {
2629 checkBasicSSA(DT, Data.LiveSet[&BB], BB.getTerminator());
2630 checkBasicSSA(DT, Data.LiveOut[&BB], BB.getTerminator(), true);
2631 checkBasicSSA(DT, Data.LiveIn[&BB], BB.getTerminator());
2632}
Philip Reames9638ff92015-04-11 00:06:47 +00002633#endif
Philip Reamesdf1ef082015-04-10 22:53:14 +00002634
2635static void computeLiveInValues(DominatorTree &DT, Function &F,
2636 GCPtrLivenessData &Data) {
2637
Philip Reames4d80ede2015-04-10 23:11:26 +00002638 SmallSetVector<BasicBlock *, 200> Worklist;
Philip Reamesdf1ef082015-04-10 22:53:14 +00002639 auto AddPredsToWorklist = [&](BasicBlock *BB) {
Philip Reames4d80ede2015-04-10 23:11:26 +00002640 // We use a SetVector so that we don't have duplicates in the worklist.
2641 Worklist.insert(pred_begin(BB), pred_end(BB));
Philip Reamesdf1ef082015-04-10 22:53:14 +00002642 };
2643 auto NextItem = [&]() {
2644 BasicBlock *BB = Worklist.back();
2645 Worklist.pop_back();
Philip Reamesdf1ef082015-04-10 22:53:14 +00002646 return BB;
2647 };
2648
2649 // Seed the liveness for each individual block
2650 for (BasicBlock &BB : F) {
2651 Data.KillSet[&BB] = computeKillSet(&BB);
2652 Data.LiveSet[&BB].clear();
2653 computeLiveInValues(BB.rbegin(), BB.rend(), Data.LiveSet[&BB]);
2654
2655#ifndef NDEBUG
2656 for (Value *Kill : Data.KillSet[&BB])
2657 assert(!Data.LiveSet[&BB].count(Kill) && "live set contains kill");
2658#endif
2659
2660 Data.LiveOut[&BB] = DenseSet<Value *>();
2661 computeLiveOutSeed(&BB, Data.LiveOut[&BB]);
2662 Data.LiveIn[&BB] = Data.LiveSet[&BB];
2663 set_union(Data.LiveIn[&BB], Data.LiveOut[&BB]);
2664 set_subtract(Data.LiveIn[&BB], Data.KillSet[&BB]);
2665 if (!Data.LiveIn[&BB].empty())
2666 AddPredsToWorklist(&BB);
2667 }
2668
2669 // Propagate that liveness until stable
2670 while (!Worklist.empty()) {
2671 BasicBlock *BB = NextItem();
2672
2673 // Compute our new liveout set, then exit early if it hasn't changed
2674 // despite the contribution of our successor.
2675 DenseSet<Value *> LiveOut = Data.LiveOut[BB];
2676 const auto OldLiveOutSize = LiveOut.size();
2677 for (BasicBlock *Succ : successors(BB)) {
2678 assert(Data.LiveIn.count(Succ));
2679 set_union(LiveOut, Data.LiveIn[Succ]);
2680 }
2681 // assert OutLiveOut is a subset of LiveOut
2682 if (OldLiveOutSize == LiveOut.size()) {
2683 // If the sets are the same size, then we didn't actually add anything
2684 // when unioning our successors LiveIn Thus, the LiveIn of this block
2685 // hasn't changed.
2686 continue;
2687 }
2688 Data.LiveOut[BB] = LiveOut;
2689
2690 // Apply the effects of this basic block
2691 DenseSet<Value *> LiveTmp = LiveOut;
2692 set_union(LiveTmp, Data.LiveSet[BB]);
2693 set_subtract(LiveTmp, Data.KillSet[BB]);
2694
2695 assert(Data.LiveIn.count(BB));
2696 const DenseSet<Value *> &OldLiveIn = Data.LiveIn[BB];
2697 // assert: OldLiveIn is a subset of LiveTmp
2698 if (OldLiveIn.size() != LiveTmp.size()) {
2699 Data.LiveIn[BB] = LiveTmp;
2700 AddPredsToWorklist(BB);
2701 }
2702 } // while( !worklist.empty() )
2703
2704#ifndef NDEBUG
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002705 // Sanity check our output against SSA properties. This helps catch any
Philip Reamesdf1ef082015-04-10 22:53:14 +00002706 // missing kills during the above iteration.
2707 for (BasicBlock &BB : F) {
2708 checkBasicSSA(DT, Data, BB);
2709 }
2710#endif
2711}
2712
2713static void findLiveSetAtInst(Instruction *Inst, GCPtrLivenessData &Data,
2714 StatepointLiveSetTy &Out) {
2715
2716 BasicBlock *BB = Inst->getParent();
2717
2718 // Note: The copy is intentional and required
2719 assert(Data.LiveOut.count(BB));
2720 DenseSet<Value *> LiveOut = Data.LiveOut[BB];
2721
2722 // We want to handle the statepoint itself oddly. It's
2723 // call result is not live (normal), nor are it's arguments
2724 // (unless they're used again later). This adjustment is
2725 // specifically what we need to relocate
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00002726 BasicBlock::reverse_iterator rend(Inst->getIterator());
Philip Reamesdf1ef082015-04-10 22:53:14 +00002727 computeLiveInValues(BB->rbegin(), rend, LiveOut);
2728 LiveOut.erase(Inst);
2729 Out.insert(LiveOut.begin(), LiveOut.end());
2730}
2731
2732static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData,
2733 const CallSite &CS,
2734 PartiallyConstructedSafepointRecord &Info) {
2735 Instruction *Inst = CS.getInstruction();
2736 StatepointLiveSetTy Updated;
2737 findLiveSetAtInst(Inst, RevisedLivenessData, Updated);
2738
2739#ifndef NDEBUG
2740 DenseSet<Value *> Bases;
2741 for (auto KVPair : Info.PointerToBase) {
2742 Bases.insert(KVPair.second);
2743 }
2744#endif
2745 // We may have base pointers which are now live that weren't before. We need
2746 // to update the PointerToBase structure to reflect this.
2747 for (auto V : Updated)
2748 if (!Info.PointerToBase.count(V)) {
2749 assert(Bases.count(V) && "can't find base for unexpected live value");
2750 Info.PointerToBase[V] = V;
2751 continue;
2752 }
2753
2754#ifndef NDEBUG
2755 for (auto V : Updated) {
2756 assert(Info.PointerToBase.count(V) &&
2757 "must be able to find base for live value");
2758 }
2759#endif
2760
2761 // Remove any stale base mappings - this can happen since our liveness is
2762 // more precise then the one inherent in the base pointer analysis
2763 DenseSet<Value *> ToErase;
2764 for (auto KVPair : Info.PointerToBase)
2765 if (!Updated.count(KVPair.first))
2766 ToErase.insert(KVPair.first);
2767 for (auto V : ToErase)
2768 Info.PointerToBase.erase(V);
2769
2770#ifndef NDEBUG
2771 for (auto KVPair : Info.PointerToBase)
2772 assert(Updated.count(KVPair.first) && "record for non-live value");
2773#endif
2774
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002775 Info.LiveSet = Updated;
Philip Reamesdf1ef082015-04-10 22:53:14 +00002776}