blob: ba24df3a9f1bbb3cfb680c576e566c201ef49492 [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"
Igor Laevskye0317182015-05-19 15:59:05 +000017#include "llvm/Analysis/TargetTransformInfo.h"
Philip Reamesd16a9b12015-02-20 01:06:44 +000018#include "llvm/ADT/SetOperations.h"
19#include "llvm/ADT/Statistic.h"
20#include "llvm/ADT/DenseSet.h"
Philip Reames4d80ede2015-04-10 23:11:26 +000021#include "llvm/ADT/SetVector.h"
Swaroop Sridhar665bc9c2015-05-20 01:07:23 +000022#include "llvm/ADT/StringRef.h"
Philip Reamesd16a9b12015-02-20 01:06:44 +000023#include "llvm/IR/BasicBlock.h"
24#include "llvm/IR/CallSite.h"
25#include "llvm/IR/Dominators.h"
26#include "llvm/IR/Function.h"
27#include "llvm/IR/IRBuilder.h"
28#include "llvm/IR/InstIterator.h"
29#include "llvm/IR/Instructions.h"
30#include "llvm/IR/Intrinsics.h"
31#include "llvm/IR/IntrinsicInst.h"
32#include "llvm/IR/Module.h"
33#include "llvm/IR/Statepoint.h"
34#include "llvm/IR/Value.h"
35#include "llvm/IR/Verifier.h"
36#include "llvm/Support/Debug.h"
37#include "llvm/Support/CommandLine.h"
38#include "llvm/Transforms/Scalar.h"
39#include "llvm/Transforms/Utils/BasicBlockUtils.h"
40#include "llvm/Transforms/Utils/Cloning.h"
41#include "llvm/Transforms/Utils/Local.h"
42#include "llvm/Transforms/Utils/PromoteMemToReg.h"
43
44#define DEBUG_TYPE "rewrite-statepoints-for-gc"
45
46using namespace llvm;
47
48// Print tracing output
49static cl::opt<bool> TraceLSP("trace-rewrite-statepoints", cl::Hidden,
50 cl::init(false));
51
52// Print the liveset found at the insert location
53static cl::opt<bool> PrintLiveSet("spp-print-liveset", cl::Hidden,
54 cl::init(false));
Philip Reames704e78b2015-04-10 22:34:56 +000055static cl::opt<bool> PrintLiveSetSize("spp-print-liveset-size", cl::Hidden,
56 cl::init(false));
Philip Reamesd16a9b12015-02-20 01:06:44 +000057// Print out the base pointers for debugging
Philip Reames704e78b2015-04-10 22:34:56 +000058static cl::opt<bool> PrintBasePointers("spp-print-base-pointers", cl::Hidden,
59 cl::init(false));
Philip Reamesd16a9b12015-02-20 01:06:44 +000060
Igor Laevskye0317182015-05-19 15:59:05 +000061// Cost threshold measuring when it is profitable to rematerialize value instead
62// of relocating it
63static cl::opt<unsigned>
64RematerializationThreshold("spp-rematerialization-threshold", cl::Hidden,
65 cl::init(6));
66
Philip Reamese73300b2015-04-13 16:41:32 +000067#ifdef XDEBUG
68static bool ClobberNonLive = true;
69#else
70static bool ClobberNonLive = false;
71#endif
72static cl::opt<bool, true> ClobberNonLiveOverride("rs4gc-clobber-non-live",
73 cl::location(ClobberNonLive),
74 cl::Hidden);
75
Benjamin Kramer6f665452015-02-20 14:00:58 +000076namespace {
Sanjoy Dasea45f0e2015-06-02 22:33:34 +000077struct RewriteStatepointsForGC : public ModulePass {
Philip Reamesd16a9b12015-02-20 01:06:44 +000078 static char ID; // Pass identification, replacement for typeid
79
Sanjoy Dasea45f0e2015-06-02 22:33:34 +000080 RewriteStatepointsForGC() : ModulePass(ID) {
Philip Reamesd16a9b12015-02-20 01:06:44 +000081 initializeRewriteStatepointsForGCPass(*PassRegistry::getPassRegistry());
82 }
Sanjoy Dasea45f0e2015-06-02 22:33:34 +000083 bool runOnFunction(Function &F);
84 bool runOnModule(Module &M) override {
85 bool Changed = false;
86 for (Function &F : M)
87 Changed |= runOnFunction(F);
88 return Changed;
89 }
Philip Reamesd16a9b12015-02-20 01:06:44 +000090
91 void getAnalysisUsage(AnalysisUsage &AU) const override {
92 // We add and rewrite a bunch of instructions, but don't really do much
93 // else. We could in theory preserve a lot more analyses here.
94 AU.addRequired<DominatorTreeWrapperPass>();
Igor Laevskye0317182015-05-19 15:59:05 +000095 AU.addRequired<TargetTransformInfoWrapperPass>();
Philip Reamesd16a9b12015-02-20 01:06:44 +000096 }
97};
Benjamin Kramer6f665452015-02-20 14:00:58 +000098} // namespace
Philip Reamesd16a9b12015-02-20 01:06:44 +000099
100char RewriteStatepointsForGC::ID = 0;
101
Sanjoy Dasea45f0e2015-06-02 22:33:34 +0000102ModulePass *llvm::createRewriteStatepointsForGCPass() {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000103 return new RewriteStatepointsForGC();
104}
105
106INITIALIZE_PASS_BEGIN(RewriteStatepointsForGC, "rewrite-statepoints-for-gc",
107 "Make relocations explicit at statepoints", false, false)
108INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
109INITIALIZE_PASS_END(RewriteStatepointsForGC, "rewrite-statepoints-for-gc",
110 "Make relocations explicit at statepoints", false, false)
111
112namespace {
Philip Reamesdf1ef082015-04-10 22:53:14 +0000113struct GCPtrLivenessData {
114 /// Values defined in this block.
115 DenseMap<BasicBlock *, DenseSet<Value *>> KillSet;
116 /// Values used in this block (and thus live); does not included values
117 /// killed within this block.
118 DenseMap<BasicBlock *, DenseSet<Value *>> LiveSet;
119
120 /// Values live into this basic block (i.e. used by any
121 /// instruction in this basic block or ones reachable from here)
122 DenseMap<BasicBlock *, DenseSet<Value *>> LiveIn;
123
124 /// Values live out of this basic block (i.e. live into
125 /// any successor block)
126 DenseMap<BasicBlock *, DenseSet<Value *>> LiveOut;
127};
128
Philip Reamesd16a9b12015-02-20 01:06:44 +0000129// The type of the internal cache used inside the findBasePointers family
130// of functions. From the callers perspective, this is an opaque type and
131// should not be inspected.
132//
133// In the actual implementation this caches two relations:
134// - The base relation itself (i.e. this pointer is based on that one)
135// - The base defining value relation (i.e. before base_phi insertion)
136// Generally, after the execution of a full findBasePointer call, only the
137// base relation will remain. Internally, we add a mixture of the two
138// types, then update all the second type to the first type
Philip Reamese9c3b9b2015-02-20 22:48:20 +0000139typedef DenseMap<Value *, Value *> DefiningValueMapTy;
Philip Reames1f017542015-02-20 23:16:52 +0000140typedef DenseSet<llvm::Value *> StatepointLiveSetTy;
Igor Laevskye0317182015-05-19 15:59:05 +0000141typedef DenseMap<Instruction *, Value *> RematerializedValueMapTy;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000142
Philip Reamesd16a9b12015-02-20 01:06:44 +0000143struct PartiallyConstructedSafepointRecord {
144 /// The set of values known to be live accross this safepoint
Philip Reames860660e2015-02-20 22:05:18 +0000145 StatepointLiveSetTy liveset;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000146
147 /// Mapping from live pointers to a base-defining-value
Philip Reamesf2041322015-02-20 19:26:04 +0000148 DenseMap<llvm::Value *, llvm::Value *> PointerToBase;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000149
Philip Reames0a3240f2015-02-20 21:34:11 +0000150 /// The *new* gc.statepoint instruction itself. This produces the token
151 /// that normal path gc.relocates and the gc.result are tied to.
152 Instruction *StatepointToken;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000153
Philip Reamesf2041322015-02-20 19:26:04 +0000154 /// Instruction to which exceptional gc relocates are attached
155 /// Makes it easier to iterate through them during relocationViaAlloca.
156 Instruction *UnwindToken;
Igor Laevskye0317182015-05-19 15:59:05 +0000157
158 /// Record live values we are rematerialized instead of relocating.
159 /// They are not included into 'liveset' field.
160 /// Maps rematerialized copy to it's original value.
161 RematerializedValueMapTy RematerializedValues;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000162};
163}
164
Philip Reamesdf1ef082015-04-10 22:53:14 +0000165/// Compute the live-in set for every basic block in the function
166static void computeLiveInValues(DominatorTree &DT, Function &F,
167 GCPtrLivenessData &Data);
168
169/// Given results from the dataflow liveness computation, find the set of live
170/// Values at a particular instruction.
171static void findLiveSetAtInst(Instruction *inst, GCPtrLivenessData &Data,
172 StatepointLiveSetTy &out);
173
Philip Reamesd16a9b12015-02-20 01:06:44 +0000174// TODO: Once we can get to the GCStrategy, this becomes
175// Optional<bool> isGCManagedPointer(const Value *V) const override {
176
177static bool isGCPointerType(const Type *T) {
178 if (const PointerType *PT = dyn_cast<PointerType>(T))
179 // For the sake of this example GC, we arbitrarily pick addrspace(1) as our
180 // GC managed heap. We know that a pointer into this heap needs to be
181 // updated and that no other pointer does.
182 return (1 == PT->getAddressSpace());
183 return false;
184}
185
Philip Reames8531d8c2015-04-10 21:48:25 +0000186// Return true if this type is one which a) is a gc pointer or contains a GC
187// pointer and b) is of a type this code expects to encounter as a live value.
188// (The insertion code will assert that a type which matches (a) and not (b)
Philip Reames704e78b2015-04-10 22:34:56 +0000189// is not encountered.)
Philip Reames8531d8c2015-04-10 21:48:25 +0000190static bool isHandledGCPointerType(Type *T) {
191 // We fully support gc pointers
192 if (isGCPointerType(T))
193 return true;
194 // We partially support vectors of gc pointers. The code will assert if it
195 // can't handle something.
196 if (auto VT = dyn_cast<VectorType>(T))
197 if (isGCPointerType(VT->getElementType()))
198 return true;
199 return false;
200}
201
202#ifndef NDEBUG
203/// Returns true if this type contains a gc pointer whether we know how to
204/// handle that type or not.
205static bool containsGCPtrType(Type *Ty) {
Philip Reames704e78b2015-04-10 22:34:56 +0000206 if (isGCPointerType(Ty))
Philip Reames8531d8c2015-04-10 21:48:25 +0000207 return true;
208 if (VectorType *VT = dyn_cast<VectorType>(Ty))
209 return isGCPointerType(VT->getScalarType());
210 if (ArrayType *AT = dyn_cast<ArrayType>(Ty))
211 return containsGCPtrType(AT->getElementType());
212 if (StructType *ST = dyn_cast<StructType>(Ty))
Philip Reames704e78b2015-04-10 22:34:56 +0000213 return std::any_of(
214 ST->subtypes().begin(), ST->subtypes().end(),
215 [](Type *SubType) { return containsGCPtrType(SubType); });
Philip Reames8531d8c2015-04-10 21:48:25 +0000216 return false;
217}
218
219// Returns true if this is a type which a) is a gc pointer or contains a GC
220// pointer and b) is of a type which the code doesn't expect (i.e. first class
221// aggregates). Used to trip assertions.
222static bool isUnhandledGCPointerType(Type *Ty) {
223 return containsGCPtrType(Ty) && !isHandledGCPointerType(Ty);
224}
225#endif
226
Philip Reamesd16a9b12015-02-20 01:06:44 +0000227static bool order_by_name(llvm::Value *a, llvm::Value *b) {
228 if (a->hasName() && b->hasName()) {
229 return -1 == a->getName().compare(b->getName());
230 } else if (a->hasName() && !b->hasName()) {
231 return true;
232 } else if (!a->hasName() && b->hasName()) {
233 return false;
234 } else {
235 // Better than nothing, but not stable
236 return a < b;
237 }
238}
239
Philip Reamesdf1ef082015-04-10 22:53:14 +0000240// Conservatively identifies any definitions which might be live at the
241// given instruction. The analysis is performed immediately before the
242// given instruction. Values defined by that instruction are not considered
243// live. Values used by that instruction are considered live.
244static void analyzeParsePointLiveness(
245 DominatorTree &DT, GCPtrLivenessData &OriginalLivenessData,
246 const CallSite &CS, PartiallyConstructedSafepointRecord &result) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000247 Instruction *inst = CS.getInstruction();
248
Philip Reames1f017542015-02-20 23:16:52 +0000249 StatepointLiveSetTy liveset;
Philip Reamesdf1ef082015-04-10 22:53:14 +0000250 findLiveSetAtInst(inst, OriginalLivenessData, liveset);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000251
252 if (PrintLiveSet) {
253 // Note: This output is used by several of the test cases
254 // The order of elemtns in a set is not stable, put them in a vec and sort
255 // by name
Philip Reames860660e2015-02-20 22:05:18 +0000256 SmallVector<Value *, 64> temp;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000257 temp.insert(temp.end(), liveset.begin(), liveset.end());
258 std::sort(temp.begin(), temp.end(), order_by_name);
259 errs() << "Live Variables:\n";
260 for (Value *V : temp) {
261 errs() << " " << V->getName(); // no newline
262 V->dump();
263 }
264 }
265 if (PrintLiveSetSize) {
266 errs() << "Safepoint For: " << CS.getCalledValue()->getName() << "\n";
267 errs() << "Number live values: " << liveset.size() << "\n";
268 }
269 result.liveset = liveset;
270}
271
Philip Reames311f7102015-05-12 22:19:52 +0000272static Value *findBaseDefiningValue(Value *I);
273
274/// If we can trivially determine that the index specified in the given vector
275/// is a base pointer, return it. In cases where the entire vector is known to
276/// consist of base pointers, the entire vector will be returned. This
277/// indicates that the relevant extractelement is a valid base pointer and
278/// should be used directly.
279static Value *findBaseOfVector(Value *I, Value *Index) {
Philip Reames8531d8c2015-04-10 21:48:25 +0000280 assert(I->getType()->isVectorTy() &&
281 cast<VectorType>(I->getType())->getElementType()->isPointerTy() &&
282 "Illegal to ask for the base pointer of a non-pointer type");
283
284 // Each case parallels findBaseDefiningValue below, see that code for
285 // detailed motivation.
286
287 if (isa<Argument>(I))
288 // An incoming argument to the function is a base pointer
289 return I;
290
291 // We shouldn't see the address of a global as a vector value?
292 assert(!isa<GlobalVariable>(I) &&
293 "unexpected global variable found in base of vector");
294
295 // inlining could possibly introduce phi node that contains
296 // undef if callee has multiple returns
297 if (isa<UndefValue>(I))
298 // utterly meaningless, but useful for dealing with partially optimized
299 // code.
Philip Reames704e78b2015-04-10 22:34:56 +0000300 return I;
Philip Reames8531d8c2015-04-10 21:48:25 +0000301
302 // Due to inheritance, this must be _after_ the global variable and undef
303 // checks
304 if (Constant *Con = dyn_cast<Constant>(I)) {
305 assert(!isa<GlobalVariable>(I) && !isa<UndefValue>(I) &&
306 "order of checks wrong!");
307 assert(Con->isNullValue() && "null is the only case which makes sense");
308 return Con;
309 }
310
311 if (isa<LoadInst>(I))
312 return I;
313
Philip Reames311f7102015-05-12 22:19:52 +0000314 // For an insert element, we might be able to look through it if we know
315 // something about the indexes, but if the indices are arbitrary values, we
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +0000316 // can't without much more extensive scalarization.
Philip Reames311f7102015-05-12 22:19:52 +0000317 if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(I)) {
318 Value *InsertIndex = IEI->getOperand(2);
319 // This index is inserting the value, look for it's base
320 if (InsertIndex == Index)
321 return findBaseDefiningValue(IEI->getOperand(1));
322 // Both constant, and can't be equal per above. This insert is definitely
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +0000323 // not relevant, look back at the rest of the vector and keep trying.
Philip Reames311f7102015-05-12 22:19:52 +0000324 if (isa<ConstantInt>(Index) && isa<ConstantInt>(InsertIndex))
325 return findBaseOfVector(IEI->getOperand(0), Index);
326 }
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +0000327
Philip Reames8531d8c2015-04-10 21:48:25 +0000328 // Note: This code is currently rather incomplete. We are essentially only
329 // handling cases where the vector element is trivially a base pointer. We
330 // need to update the entire base pointer construction algorithm to know how
331 // to track vector elements and potentially scalarize, but the case which
332 // would motivate the work hasn't shown up in real workloads yet.
333 llvm_unreachable("no base found for vector element");
334}
335
Philip Reamesd16a9b12015-02-20 01:06:44 +0000336/// Helper function for findBasePointer - Will return a value which either a)
337/// defines the base pointer for the input or b) blocks the simple search
338/// (i.e. a PHI or Select of two derived pointers)
339static Value *findBaseDefiningValue(Value *I) {
340 assert(I->getType()->isPointerTy() &&
341 "Illegal to ask for the base pointer of a non-pointer type");
342
Philip Reames8531d8c2015-04-10 21:48:25 +0000343 // This case is a bit of a hack - it only handles extracts from vectors which
Philip Reames311f7102015-05-12 22:19:52 +0000344 // trivially contain only base pointers or cases where we can directly match
345 // the index of the original extract element to an insertion into the vector.
346 // See note inside the function for how to improve this.
Philip Reames8531d8c2015-04-10 21:48:25 +0000347 if (auto *EEI = dyn_cast<ExtractElementInst>(I)) {
348 Value *VectorOperand = EEI->getVectorOperand();
Philip Reames311f7102015-05-12 22:19:52 +0000349 Value *Index = EEI->getIndexOperand();
350 Value *VectorBase = findBaseOfVector(VectorOperand, Index);
351 // If the result returned is a vector, we know the entire vector must
352 // contain base pointers. In that case, the extractelement is a valid base
353 // for this value.
354 if (VectorBase->getType()->isVectorTy())
355 return EEI;
356 // Otherwise, we needed to look through the vector to find the base for
357 // this particular element.
358 assert(VectorBase->getType()->isPointerTy());
359 return VectorBase;
Philip Reames8531d8c2015-04-10 21:48:25 +0000360 }
Philip Reamesd16a9b12015-02-20 01:06:44 +0000361
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000362 if (isa<Argument>(I))
Philip Reamesd16a9b12015-02-20 01:06:44 +0000363 // An incoming argument to the function is a base pointer
364 // We should have never reached here if this argument isn't an gc value
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000365 return I;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000366
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000367 if (isa<GlobalVariable>(I))
Philip Reamesd16a9b12015-02-20 01:06:44 +0000368 // base case
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000369 return I;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000370
371 // inlining could possibly introduce phi node that contains
372 // undef if callee has multiple returns
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000373 if (isa<UndefValue>(I))
374 // utterly meaningless, but useful for dealing with
375 // partially optimized code.
Philip Reames704e78b2015-04-10 22:34:56 +0000376 return I;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000377
378 // Due to inheritance, this must be _after_ the global variable and undef
379 // checks
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000380 if (Constant *Con = dyn_cast<Constant>(I)) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000381 assert(!isa<GlobalVariable>(I) && !isa<UndefValue>(I) &&
382 "order of checks wrong!");
383 // Note: Finding a constant base for something marked for relocation
384 // doesn't really make sense. The most likely case is either a) some
385 // screwed up the address space usage or b) your validating against
386 // compiled C++ code w/o the proper separation. The only real exception
387 // is a null pointer. You could have generic code written to index of
388 // off a potentially null value and have proven it null. We also use
389 // null pointers in dead paths of relocation phis (which we might later
390 // want to find a base pointer for).
Philip Reames24c6cd52015-03-27 05:47:00 +0000391 assert(isa<ConstantPointerNull>(Con) &&
392 "null is the only case which makes sense");
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000393 return Con;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000394 }
395
396 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000397 Value *Def = CI->stripPointerCasts();
David Blaikie82ad7872015-02-20 23:44:24 +0000398 // If we find a cast instruction here, it means we've found a cast which is
399 // not simply a pointer cast (i.e. an inttoptr). We don't know how to
400 // handle int->ptr conversion.
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000401 assert(!isa<CastInst>(Def) && "shouldn't find another cast here");
402 return findBaseDefiningValue(Def);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000403 }
404
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000405 if (isa<LoadInst>(I))
406 return I; // The value loaded is an gc base itself
Philip Reamesd16a9b12015-02-20 01:06:44 +0000407
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000408 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I))
409 // The base of this GEP is the base
410 return findBaseDefiningValue(GEP->getPointerOperand());
Philip Reamesd16a9b12015-02-20 01:06:44 +0000411
412 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
413 switch (II->getIntrinsicID()) {
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000414 case Intrinsic::experimental_gc_result_ptr:
Philip Reamesd16a9b12015-02-20 01:06:44 +0000415 default:
416 // fall through to general call handling
417 break;
418 case Intrinsic::experimental_gc_statepoint:
419 case Intrinsic::experimental_gc_result_float:
420 case Intrinsic::experimental_gc_result_int:
421 llvm_unreachable("these don't produce pointers");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000422 case Intrinsic::experimental_gc_relocate: {
423 // Rerunning safepoint insertion after safepoints are already
424 // inserted is not supported. It could probably be made to work,
425 // but why are you doing this? There's no good reason.
426 llvm_unreachable("repeat safepoint insertion is not supported");
427 }
428 case Intrinsic::gcroot:
429 // Currently, this mechanism hasn't been extended to work with gcroot.
430 // There's no reason it couldn't be, but I haven't thought about the
431 // implications much.
432 llvm_unreachable(
433 "interaction with the gcroot mechanism is not supported");
434 }
435 }
436 // We assume that functions in the source language only return base
437 // pointers. This should probably be generalized via attributes to support
438 // both source language and internal functions.
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000439 if (isa<CallInst>(I) || isa<InvokeInst>(I))
440 return I;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000441
442 // I have absolutely no idea how to implement this part yet. It's not
443 // neccessarily hard, I just haven't really looked at it yet.
444 assert(!isa<LandingPadInst>(I) && "Landing Pad is unimplemented");
445
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000446 if (isa<AtomicCmpXchgInst>(I))
Philip Reamesd16a9b12015-02-20 01:06:44 +0000447 // A CAS is effectively a atomic store and load combined under a
448 // predicate. From the perspective of base pointers, we just treat it
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000449 // like a load.
450 return I;
Philip Reames704e78b2015-04-10 22:34:56 +0000451
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000452 assert(!isa<AtomicRMWInst>(I) && "Xchg handled above, all others are "
Philip Reames704e78b2015-04-10 22:34:56 +0000453 "binary ops which don't apply to pointers");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000454
455 // The aggregate ops. Aggregates can either be in the heap or on the
456 // stack, but in either case, this is simply a field load. As a result,
457 // this is a defining definition of the base just like a load is.
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000458 if (isa<ExtractValueInst>(I))
459 return I;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000460
461 // We should never see an insert vector since that would require we be
462 // tracing back a struct value not a pointer value.
463 assert(!isa<InsertValueInst>(I) &&
464 "Base pointer for a struct is meaningless");
465
466 // The last two cases here don't return a base pointer. Instead, they
467 // return a value which dynamically selects from amoung several base
468 // derived pointers (each with it's own base potentially). It's the job of
469 // the caller to resolve these.
Philip Reames704e78b2015-04-10 22:34:56 +0000470 assert((isa<SelectInst>(I) || isa<PHINode>(I)) &&
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000471 "missing instruction case in findBaseDefiningValing");
472 return I;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000473}
474
475/// Returns the base defining value for this value.
Philip Reames18d0feb2015-03-27 05:39:32 +0000476static Value *findBaseDefiningValueCached(Value *I, DefiningValueMapTy &Cache) {
477 Value *&Cached = Cache[I];
Benjamin Kramer6f665452015-02-20 14:00:58 +0000478 if (!Cached) {
479 Cached = findBaseDefiningValue(I);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000480 }
Philip Reames18d0feb2015-03-27 05:39:32 +0000481 assert(Cache[I] != nullptr);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000482
483 if (TraceLSP) {
Philip Reames18d0feb2015-03-27 05:39:32 +0000484 dbgs() << "fBDV-cached: " << I->getName() << " -> " << Cached->getName()
Philip Reamesd16a9b12015-02-20 01:06:44 +0000485 << "\n";
486 }
Benjamin Kramer6f665452015-02-20 14:00:58 +0000487 return Cached;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000488}
489
490/// Return a base pointer for this value if known. Otherwise, return it's
491/// base defining value.
Philip Reames18d0feb2015-03-27 05:39:32 +0000492static Value *findBaseOrBDV(Value *I, DefiningValueMapTy &Cache) {
493 Value *Def = findBaseDefiningValueCached(I, Cache);
494 auto Found = Cache.find(Def);
495 if (Found != Cache.end()) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000496 // Either a base-of relation, or a self reference. Caller must check.
Benjamin Kramer6f665452015-02-20 14:00:58 +0000497 return Found->second;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000498 }
499 // Only a BDV available
Philip Reames18d0feb2015-03-27 05:39:32 +0000500 return Def;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000501}
502
503/// Given the result of a call to findBaseDefiningValue, or findBaseOrBDV,
504/// is it known to be a base pointer? Or do we need to continue searching.
Philip Reames18d0feb2015-03-27 05:39:32 +0000505static bool isKnownBaseResult(Value *V) {
506 if (!isa<PHINode>(V) && !isa<SelectInst>(V)) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000507 // no recursion possible
508 return true;
509 }
Philip Reames18d0feb2015-03-27 05:39:32 +0000510 if (isa<Instruction>(V) &&
511 cast<Instruction>(V)->getMetadata("is_base_value")) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000512 // This is a previously inserted base phi or select. We know
513 // that this is a base value.
514 return true;
515 }
516
517 // We need to keep searching
518 return false;
519}
520
521// TODO: find a better name for this
522namespace {
523class PhiState {
524public:
525 enum Status { Unknown, Base, Conflict };
526
527 PhiState(Status s, Value *b = nullptr) : status(s), base(b) {
528 assert(status != Base || b);
529 }
530 PhiState(Value *b) : status(Base), base(b) {}
531 PhiState() : status(Unknown), base(nullptr) {}
Philip Reamesd16a9b12015-02-20 01:06:44 +0000532
533 Status getStatus() const { return status; }
534 Value *getBase() const { return base; }
535
536 bool isBase() const { return getStatus() == Base; }
537 bool isUnknown() const { return getStatus() == Unknown; }
538 bool isConflict() const { return getStatus() == Conflict; }
539
540 bool operator==(const PhiState &other) const {
541 return base == other.base && status == other.status;
542 }
543
544 bool operator!=(const PhiState &other) const { return !(*this == other); }
545
546 void dump() {
547 errs() << status << " (" << base << " - "
548 << (base ? base->getName() : "nullptr") << "): ";
549 }
550
551private:
552 Status status;
553 Value *base; // non null only if status == base
554};
555
Philip Reamese9c3b9b2015-02-20 22:48:20 +0000556typedef DenseMap<Value *, PhiState> ConflictStateMapTy;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000557// Values of type PhiState form a lattice, and this is a helper
558// class that implementes the meet operation. The meat of the meet
559// operation is implemented in MeetPhiStates::pureMeet
560class MeetPhiStates {
561public:
562 // phiStates is a mapping from PHINodes and SelectInst's to PhiStates.
Philip Reames860660e2015-02-20 22:05:18 +0000563 explicit MeetPhiStates(const ConflictStateMapTy &phiStates)
Philip Reamesd16a9b12015-02-20 01:06:44 +0000564 : phiStates(phiStates) {}
565
566 // Destructively meet the current result with the base V. V can
567 // either be a merge instruction (SelectInst / PHINode), in which
568 // case its status is looked up in the phiStates map; or a regular
569 // SSA value, in which case it is assumed to be a base.
570 void meetWith(Value *V) {
571 PhiState otherState = getStateForBDV(V);
572 assert((MeetPhiStates::pureMeet(otherState, currentResult) ==
573 MeetPhiStates::pureMeet(currentResult, otherState)) &&
574 "math is wrong: meet does not commute!");
575 currentResult = MeetPhiStates::pureMeet(otherState, currentResult);
576 }
577
578 PhiState getResult() const { return currentResult; }
579
580private:
Philip Reames860660e2015-02-20 22:05:18 +0000581 const ConflictStateMapTy &phiStates;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000582 PhiState currentResult;
583
584 /// Return a phi state for a base defining value. We'll generate a new
585 /// base state for known bases and expect to find a cached state otherwise
586 PhiState getStateForBDV(Value *baseValue) {
587 if (isKnownBaseResult(baseValue)) {
588 return PhiState(baseValue);
589 } else {
590 return lookupFromMap(baseValue);
591 }
592 }
593
594 PhiState lookupFromMap(Value *V) {
595 auto I = phiStates.find(V);
596 assert(I != phiStates.end() && "lookup failed!");
597 return I->second;
598 }
599
600 static PhiState pureMeet(const PhiState &stateA, const PhiState &stateB) {
601 switch (stateA.getStatus()) {
602 case PhiState::Unknown:
603 return stateB;
604
605 case PhiState::Base:
606 assert(stateA.getBase() && "can't be null");
David Blaikie82ad7872015-02-20 23:44:24 +0000607 if (stateB.isUnknown())
Philip Reamesd16a9b12015-02-20 01:06:44 +0000608 return stateA;
David Blaikie82ad7872015-02-20 23:44:24 +0000609
610 if (stateB.isBase()) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000611 if (stateA.getBase() == stateB.getBase()) {
612 assert(stateA == stateB && "equality broken!");
613 return stateA;
614 }
615 return PhiState(PhiState::Conflict);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000616 }
David Blaikie82ad7872015-02-20 23:44:24 +0000617 assert(stateB.isConflict() && "only three states!");
618 return PhiState(PhiState::Conflict);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000619
620 case PhiState::Conflict:
621 return stateA;
622 }
Reid Klecknera070ee52015-02-20 19:46:02 +0000623 llvm_unreachable("only three states!");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000624 }
625};
626}
627/// For a given value or instruction, figure out what base ptr it's derived
628/// from. For gc objects, this is simply itself. On success, returns a value
629/// which is the base pointer. (This is reliable and can be used for
630/// relocation.) On failure, returns nullptr.
Philip Reamesba198492015-04-14 00:41:34 +0000631static Value *findBasePointer(Value *I, DefiningValueMapTy &cache) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000632 Value *def = findBaseOrBDV(I, cache);
633
634 if (isKnownBaseResult(def)) {
635 return def;
636 }
637
638 // Here's the rough algorithm:
639 // - For every SSA value, construct a mapping to either an actual base
640 // pointer or a PHI which obscures the base pointer.
641 // - Construct a mapping from PHI to unknown TOP state. Use an
642 // optimistic algorithm to propagate base pointer information. Lattice
643 // looks like:
644 // UNKNOWN
645 // b1 b2 b3 b4
646 // CONFLICT
647 // When algorithm terminates, all PHIs will either have a single concrete
648 // base or be in a conflict state.
649 // - For every conflict, insert a dummy PHI node without arguments. Add
650 // these to the base[Instruction] = BasePtr mapping. For every
651 // non-conflict, add the actual base.
652 // - For every conflict, add arguments for the base[a] of each input
653 // arguments.
654 //
655 // Note: A simpler form of this would be to add the conflict form of all
656 // PHIs without running the optimistic algorithm. This would be
657 // analougous to pessimistic data flow and would likely lead to an
658 // overall worse solution.
659
Philip Reames860660e2015-02-20 22:05:18 +0000660 ConflictStateMapTy states;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000661 states[def] = PhiState();
662 // Recursively fill in all phis & selects reachable from the initial one
663 // for which we don't already know a definite base value for
Philip Reamesa226e612015-02-28 00:47:50 +0000664 // TODO: This should be rewritten with a worklist
Philip Reamesd16a9b12015-02-20 01:06:44 +0000665 bool done = false;
666 while (!done) {
667 done = true;
Philip Reamesa226e612015-02-28 00:47:50 +0000668 // Since we're adding elements to 'states' as we run, we can't keep
669 // iterators into the set.
Philip Reames704e78b2015-04-10 22:34:56 +0000670 SmallVector<Value *, 16> Keys;
Philip Reamesa226e612015-02-28 00:47:50 +0000671 Keys.reserve(states.size());
Philip Reamesd16a9b12015-02-20 01:06:44 +0000672 for (auto Pair : states) {
Philip Reamesa226e612015-02-28 00:47:50 +0000673 Value *V = Pair.first;
674 Keys.push_back(V);
675 }
676 for (Value *v : Keys) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000677 assert(!isKnownBaseResult(v) && "why did it get added?");
678 if (PHINode *phi = dyn_cast<PHINode>(v)) {
David Blaikie82ad7872015-02-20 23:44:24 +0000679 assert(phi->getNumIncomingValues() > 0 &&
680 "zero input phis are illegal");
681 for (Value *InVal : phi->incoming_values()) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000682 Value *local = findBaseOrBDV(InVal, cache);
683 if (!isKnownBaseResult(local) && states.find(local) == states.end()) {
684 states[local] = PhiState();
685 done = false;
686 }
687 }
688 } else if (SelectInst *sel = dyn_cast<SelectInst>(v)) {
689 Value *local = findBaseOrBDV(sel->getTrueValue(), cache);
690 if (!isKnownBaseResult(local) && states.find(local) == states.end()) {
691 states[local] = PhiState();
692 done = false;
693 }
694 local = findBaseOrBDV(sel->getFalseValue(), cache);
695 if (!isKnownBaseResult(local) && states.find(local) == states.end()) {
696 states[local] = PhiState();
697 done = false;
698 }
699 }
700 }
701 }
702
703 if (TraceLSP) {
704 errs() << "States after initialization:\n";
705 for (auto Pair : states) {
706 Instruction *v = cast<Instruction>(Pair.first);
707 PhiState state = Pair.second;
708 state.dump();
709 v->dump();
710 }
711 }
712
713 // TODO: come back and revisit the state transitions around inputs which
714 // have reached conflict state. The current version seems too conservative.
715
716 bool progress = true;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000717 while (progress) {
Yaron Keren42a7adf2015-02-28 13:11:24 +0000718#ifndef NDEBUG
719 size_t oldSize = states.size();
720#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +0000721 progress = false;
Philip Reamesa226e612015-02-28 00:47:50 +0000722 // We're only changing keys in this loop, thus safe to keep iterators
Philip Reamesd16a9b12015-02-20 01:06:44 +0000723 for (auto Pair : states) {
724 MeetPhiStates calculateMeet(states);
725 Value *v = Pair.first;
726 assert(!isKnownBaseResult(v) && "why did it get added?");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000727 if (SelectInst *select = dyn_cast<SelectInst>(v)) {
728 calculateMeet.meetWith(findBaseOrBDV(select->getTrueValue(), cache));
729 calculateMeet.meetWith(findBaseOrBDV(select->getFalseValue(), cache));
David Blaikie82ad7872015-02-20 23:44:24 +0000730 } else
731 for (Value *Val : cast<PHINode>(v)->incoming_values())
732 calculateMeet.meetWith(findBaseOrBDV(Val, cache));
Philip Reamesd16a9b12015-02-20 01:06:44 +0000733
734 PhiState oldState = states[v];
735 PhiState newState = calculateMeet.getResult();
736 if (oldState != newState) {
737 progress = true;
738 states[v] = newState;
739 }
740 }
741
742 assert(oldSize <= states.size());
743 assert(oldSize == states.size() || progress);
744 }
745
746 if (TraceLSP) {
747 errs() << "States after meet iteration:\n";
748 for (auto Pair : states) {
749 Instruction *v = cast<Instruction>(Pair.first);
750 PhiState state = Pair.second;
751 state.dump();
752 v->dump();
753 }
754 }
755
756 // Insert Phis for all conflicts
Philip Reames2e5bcbe2015-02-28 01:52:09 +0000757 // We want to keep naming deterministic in the loop that follows, so
758 // sort the keys before iteration. This is useful in allowing us to
759 // write stable tests. Note that there is no invalidation issue here.
Philip Reames704e78b2015-04-10 22:34:56 +0000760 SmallVector<Value *, 16> Keys;
Philip Reames2e5bcbe2015-02-28 01:52:09 +0000761 Keys.reserve(states.size());
Philip Reamesd16a9b12015-02-20 01:06:44 +0000762 for (auto Pair : states) {
Philip Reames2e5bcbe2015-02-28 01:52:09 +0000763 Value *V = Pair.first;
764 Keys.push_back(V);
765 }
766 std::sort(Keys.begin(), Keys.end(), order_by_name);
767 // TODO: adjust naming patterns to avoid this order of iteration dependency
768 for (Value *V : Keys) {
769 Instruction *v = cast<Instruction>(V);
770 PhiState state = states[V];
Philip Reamesd16a9b12015-02-20 01:06:44 +0000771 assert(!isKnownBaseResult(v) && "why did it get added?");
772 assert(!state.isUnknown() && "Optimistic algorithm didn't complete!");
Philip Reamesf986d682015-02-28 00:54:41 +0000773 if (!state.isConflict())
774 continue;
Philip Reames704e78b2015-04-10 22:34:56 +0000775
Philip Reamesf986d682015-02-28 00:54:41 +0000776 if (isa<PHINode>(v)) {
777 int num_preds =
778 std::distance(pred_begin(v->getParent()), pred_end(v->getParent()));
779 assert(num_preds > 0 && "how did we reach here");
780 PHINode *phi = PHINode::Create(v->getType(), num_preds, "base_phi", v);
Philip Reamesf986d682015-02-28 00:54:41 +0000781 // Add metadata marking this as a base value
782 auto *const_1 = ConstantInt::get(
783 Type::getInt32Ty(
784 v->getParent()->getParent()->getParent()->getContext()),
785 1);
786 auto MDConst = ConstantAsMetadata::get(const_1);
787 MDNode *md = MDNode::get(
788 v->getParent()->getParent()->getParent()->getContext(), MDConst);
789 phi->setMetadata("is_base_value", md);
790 states[v] = PhiState(PhiState::Conflict, phi);
791 } else {
792 SelectInst *sel = cast<SelectInst>(v);
793 // The undef will be replaced later
794 UndefValue *undef = UndefValue::get(sel->getType());
795 SelectInst *basesel = SelectInst::Create(sel->getCondition(), undef,
796 undef, "base_select", sel);
Philip Reamesf986d682015-02-28 00:54:41 +0000797 // Add metadata marking this as a base value
798 auto *const_1 = ConstantInt::get(
799 Type::getInt32Ty(
800 v->getParent()->getParent()->getParent()->getContext()),
801 1);
802 auto MDConst = ConstantAsMetadata::get(const_1);
803 MDNode *md = MDNode::get(
804 v->getParent()->getParent()->getParent()->getContext(), MDConst);
805 basesel->setMetadata("is_base_value", md);
806 states[v] = PhiState(PhiState::Conflict, basesel);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000807 }
808 }
809
810 // Fixup all the inputs of the new PHIs
811 for (auto Pair : states) {
812 Instruction *v = cast<Instruction>(Pair.first);
813 PhiState state = Pair.second;
814
815 assert(!isKnownBaseResult(v) && "why did it get added?");
816 assert(!state.isUnknown() && "Optimistic algorithm didn't complete!");
Philip Reames28e61ce2015-02-28 01:57:44 +0000817 if (!state.isConflict())
818 continue;
Philip Reames704e78b2015-04-10 22:34:56 +0000819
Philip Reames28e61ce2015-02-28 01:57:44 +0000820 if (PHINode *basephi = dyn_cast<PHINode>(state.getBase())) {
821 PHINode *phi = cast<PHINode>(v);
822 unsigned NumPHIValues = phi->getNumIncomingValues();
823 for (unsigned i = 0; i < NumPHIValues; i++) {
824 Value *InVal = phi->getIncomingValue(i);
825 BasicBlock *InBB = phi->getIncomingBlock(i);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000826
Philip Reames28e61ce2015-02-28 01:57:44 +0000827 // If we've already seen InBB, add the same incoming value
828 // we added for it earlier. The IR verifier requires phi
829 // nodes with multiple entries from the same basic block
830 // to have the same incoming value for each of those
831 // entries. If we don't do this check here and basephi
832 // has a different type than base, we'll end up adding two
833 // bitcasts (and hence two distinct values) as incoming
834 // values for the same basic block.
Philip Reamesd16a9b12015-02-20 01:06:44 +0000835
Philip Reames28e61ce2015-02-28 01:57:44 +0000836 int blockIndex = basephi->getBasicBlockIndex(InBB);
837 if (blockIndex != -1) {
838 Value *oldBase = basephi->getIncomingValue(blockIndex);
839 basephi->addIncoming(oldBase, InBB);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000840#ifndef NDEBUG
Philip Reames28e61ce2015-02-28 01:57:44 +0000841 Value *base = findBaseOrBDV(InVal, cache);
842 if (!isKnownBaseResult(base)) {
843 // Either conflict or base.
844 assert(states.count(base));
845 base = states[base].getBase();
846 assert(base != nullptr && "unknown PhiState!");
Philip Reames28e61ce2015-02-28 01:57:44 +0000847 }
Philip Reamesd16a9b12015-02-20 01:06:44 +0000848
Philip Reames28e61ce2015-02-28 01:57:44 +0000849 // In essense this assert states: the only way two
850 // values incoming from the same basic block may be
851 // different is by being different bitcasts of the same
852 // value. A cleanup that remains TODO is changing
853 // findBaseOrBDV to return an llvm::Value of the correct
854 // type (and still remain pure). This will remove the
855 // need to add bitcasts.
856 assert(base->stripPointerCasts() == oldBase->stripPointerCasts() &&
857 "sanity -- findBaseOrBDV should be pure!");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000858#endif
Philip Reames28e61ce2015-02-28 01:57:44 +0000859 continue;
860 }
Philip Reamesd16a9b12015-02-20 01:06:44 +0000861
Philip Reames28e61ce2015-02-28 01:57:44 +0000862 // Find either the defining value for the PHI or the normal base for
863 // a non-phi node
864 Value *base = findBaseOrBDV(InVal, cache);
865 if (!isKnownBaseResult(base)) {
866 // Either conflict or base.
867 assert(states.count(base));
868 base = states[base].getBase();
869 assert(base != nullptr && "unknown PhiState!");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000870 }
Philip Reames28e61ce2015-02-28 01:57:44 +0000871 assert(base && "can't be null");
872 // Must use original input BB since base may not be Instruction
873 // The cast is needed since base traversal may strip away bitcasts
874 if (base->getType() != basephi->getType()) {
875 base = new BitCastInst(base, basephi->getType(), "cast",
876 InBB->getTerminator());
Philip Reamesd16a9b12015-02-20 01:06:44 +0000877 }
Philip Reames28e61ce2015-02-28 01:57:44 +0000878 basephi->addIncoming(base, InBB);
879 }
880 assert(basephi->getNumIncomingValues() == NumPHIValues);
881 } else {
882 SelectInst *basesel = cast<SelectInst>(state.getBase());
883 SelectInst *sel = cast<SelectInst>(v);
884 // Operand 1 & 2 are true, false path respectively. TODO: refactor to
885 // something more safe and less hacky.
886 for (int i = 1; i <= 2; i++) {
887 Value *InVal = sel->getOperand(i);
888 // Find either the defining value for the PHI or the normal base for
889 // a non-phi node
890 Value *base = findBaseOrBDV(InVal, cache);
891 if (!isKnownBaseResult(base)) {
892 // Either conflict or base.
893 assert(states.count(base));
894 base = states[base].getBase();
895 assert(base != nullptr && "unknown PhiState!");
896 }
897 assert(base && "can't be null");
898 // Must use original input BB since base may not be Instruction
899 // The cast is needed since base traversal may strip away bitcasts
900 if (base->getType() != basesel->getType()) {
901 base = new BitCastInst(base, basesel->getType(), "cast", basesel);
Philip Reames28e61ce2015-02-28 01:57:44 +0000902 }
903 basesel->setOperand(i, base);
904 }
Philip Reamesd16a9b12015-02-20 01:06:44 +0000905 }
906 }
907
908 // Cache all of our results so we can cheaply reuse them
909 // NOTE: This is actually two caches: one of the base defining value
910 // relation and one of the base pointer relation! FIXME
911 for (auto item : states) {
912 Value *v = item.first;
913 Value *base = item.second.getBase();
914 assert(v && base);
915 assert(!isKnownBaseResult(v) && "why did it get added?");
916
917 if (TraceLSP) {
918 std::string fromstr =
919 cache.count(v) ? (cache[v]->hasName() ? cache[v]->getName() : "")
920 : "none";
921 errs() << "Updating base value cache"
922 << " for: " << (v->hasName() ? v->getName() : "")
923 << " from: " << fromstr
924 << " to: " << (base->hasName() ? base->getName() : "") << "\n";
925 }
926
927 assert(isKnownBaseResult(base) &&
928 "must be something we 'know' is a base pointer");
929 if (cache.count(v)) {
930 // Once we transition from the BDV relation being store in the cache to
931 // the base relation being stored, it must be stable
932 assert((!isKnownBaseResult(cache[v]) || cache[v] == base) &&
933 "base relation should be stable");
934 }
935 cache[v] = base;
936 }
937 assert(cache.find(def) != cache.end());
938 return cache[def];
939}
940
941// For a set of live pointers (base and/or derived), identify the base
942// pointer of the object which they are derived from. This routine will
943// mutate the IR graph as needed to make the 'base' pointer live at the
944// definition site of 'derived'. This ensures that any use of 'derived' can
945// also use 'base'. This may involve the insertion of a number of
946// additional PHI nodes.
947//
948// preconditions: live is a set of pointer type Values
949//
950// side effects: may insert PHI nodes into the existing CFG, will preserve
951// CFG, will not remove or mutate any existing nodes
952//
Philip Reamesf2041322015-02-20 19:26:04 +0000953// post condition: PointerToBase contains one (derived, base) pair for every
Philip Reamesd16a9b12015-02-20 01:06:44 +0000954// pointer in live. Note that derived can be equal to base if the original
955// pointer was a base pointer.
Philip Reames704e78b2015-04-10 22:34:56 +0000956static void
957findBasePointers(const StatepointLiveSetTy &live,
958 DenseMap<llvm::Value *, llvm::Value *> &PointerToBase,
Philip Reamesba198492015-04-14 00:41:34 +0000959 DominatorTree *DT, DefiningValueMapTy &DVCache) {
Philip Reames2e5bcbe2015-02-28 01:52:09 +0000960 // For the naming of values inserted to be deterministic - which makes for
961 // much cleaner and more stable tests - we need to assign an order to the
962 // live values. DenseSets do not provide a deterministic order across runs.
Philip Reames704e78b2015-04-10 22:34:56 +0000963 SmallVector<Value *, 64> Temp;
Philip Reames2e5bcbe2015-02-28 01:52:09 +0000964 Temp.insert(Temp.end(), live.begin(), live.end());
965 std::sort(Temp.begin(), Temp.end(), order_by_name);
966 for (Value *ptr : Temp) {
Philip Reamesba198492015-04-14 00:41:34 +0000967 Value *base = findBasePointer(ptr, DVCache);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000968 assert(base && "failed to find base pointer");
Philip Reamesf2041322015-02-20 19:26:04 +0000969 PointerToBase[ptr] = base;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000970 assert((!isa<Instruction>(base) || !isa<Instruction>(ptr) ||
971 DT->dominates(cast<Instruction>(base)->getParent(),
972 cast<Instruction>(ptr)->getParent())) &&
973 "The base we found better dominate the derived pointer");
974
David Blaikie82ad7872015-02-20 23:44:24 +0000975 // If you see this trip and like to live really dangerously, the code should
976 // be correct, just with idioms the verifier can't handle. You can try
977 // disabling the verifier at your own substaintial risk.
Philip Reames704e78b2015-04-10 22:34:56 +0000978 assert(!isa<ConstantPointerNull>(base) &&
Philip Reames24c6cd52015-03-27 05:47:00 +0000979 "the relocation code needs adjustment to handle the relocation of "
980 "a null pointer constant without causing false positives in the "
981 "safepoint ir verifier.");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000982 }
983}
984
985/// Find the required based pointers (and adjust the live set) for the given
986/// parse point.
987static void findBasePointers(DominatorTree &DT, DefiningValueMapTy &DVCache,
988 const CallSite &CS,
989 PartiallyConstructedSafepointRecord &result) {
Philip Reamesf2041322015-02-20 19:26:04 +0000990 DenseMap<llvm::Value *, llvm::Value *> PointerToBase;
Philip Reamesba198492015-04-14 00:41:34 +0000991 findBasePointers(result.liveset, PointerToBase, &DT, DVCache);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000992
993 if (PrintBasePointers) {
Philip Reamesa5aeaf42015-02-28 00:20:48 +0000994 // Note: Need to print these in a stable order since this is checked in
995 // some tests.
Philip Reamesd16a9b12015-02-20 01:06:44 +0000996 errs() << "Base Pairs (w/o Relocation):\n";
Philip Reames704e78b2015-04-10 22:34:56 +0000997 SmallVector<Value *, 64> Temp;
Philip Reamesa5aeaf42015-02-28 00:20:48 +0000998 Temp.reserve(PointerToBase.size());
Philip Reamesf2041322015-02-20 19:26:04 +0000999 for (auto Pair : PointerToBase) {
Philip Reamesa5aeaf42015-02-28 00:20:48 +00001000 Temp.push_back(Pair.first);
1001 }
1002 std::sort(Temp.begin(), Temp.end(), order_by_name);
1003 for (Value *Ptr : Temp) {
1004 Value *Base = PointerToBase[Ptr];
Philip Reames704e78b2015-04-10 22:34:56 +00001005 errs() << " derived %" << Ptr->getName() << " base %" << Base->getName()
1006 << "\n";
Philip Reamesd16a9b12015-02-20 01:06:44 +00001007 }
1008 }
1009
Philip Reamesf2041322015-02-20 19:26:04 +00001010 result.PointerToBase = PointerToBase;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001011}
1012
Philip Reamesdf1ef082015-04-10 22:53:14 +00001013/// Given an updated version of the dataflow liveness results, update the
1014/// liveset and base pointer maps for the call site CS.
1015static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData,
1016 const CallSite &CS,
1017 PartiallyConstructedSafepointRecord &result);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001018
Philip Reamesdf1ef082015-04-10 22:53:14 +00001019static void recomputeLiveInValues(
1020 Function &F, DominatorTree &DT, Pass *P, ArrayRef<CallSite> toUpdate,
Philip Reamesd2b66462015-02-20 22:39:41 +00001021 MutableArrayRef<struct PartiallyConstructedSafepointRecord> records) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00001022 // TODO-PERF: reuse the original liveness, then simply run the dataflow
1023 // again. The old values are still live and will help it stablize quickly.
1024 GCPtrLivenessData RevisedLivenessData;
1025 computeLiveInValues(DT, F, RevisedLivenessData);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001026 for (size_t i = 0; i < records.size(); i++) {
1027 struct PartiallyConstructedSafepointRecord &info = records[i];
Philip Reamesd2b66462015-02-20 22:39:41 +00001028 const CallSite &CS = toUpdate[i];
Philip Reamesdf1ef082015-04-10 22:53:14 +00001029 recomputeLiveInValues(RevisedLivenessData, CS, info);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001030 }
1031}
1032
Philip Reames69e51ca2015-04-13 18:07:21 +00001033// When inserting gc.relocate calls, we need to ensure there are no uses
1034// of the original value between the gc.statepoint and the gc.relocate call.
1035// One case which can arise is a phi node starting one of the successor blocks.
1036// We also need to be able to insert the gc.relocates only on the path which
1037// goes through the statepoint. We might need to split an edge to make this
Philip Reamesf209a152015-04-13 20:00:30 +00001038// possible.
1039static BasicBlock *
Sanjoy Dasea45f0e2015-06-02 22:33:34 +00001040normalizeForInvokeSafepoint(BasicBlock *BB, BasicBlock *InvokeParent,
1041 DominatorTree &DT) {
Philip Reames69e51ca2015-04-13 18:07:21 +00001042 BasicBlock *Ret = BB;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001043 if (!BB->getUniquePredecessor()) {
Sanjoy Dasea45f0e2015-06-02 22:33:34 +00001044 Ret = SplitBlockPredecessors(BB, InvokeParent, "", nullptr, &DT);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001045 }
1046
Philip Reames69e51ca2015-04-13 18:07:21 +00001047 // Now that 'ret' has unique predecessor we can safely remove all phi nodes
1048 // from it
1049 FoldSingleEntryPHINodes(Ret);
1050 assert(!isa<PHINode>(Ret->begin()));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001051
Philip Reames69e51ca2015-04-13 18:07:21 +00001052 // At this point, we can safely insert a gc.relocate as the first instruction
1053 // in Ret if needed.
1054 return Ret;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001055}
1056
Philip Reamesd2b66462015-02-20 22:39:41 +00001057static int find_index(ArrayRef<Value *> livevec, Value *val) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001058 auto itr = std::find(livevec.begin(), livevec.end(), val);
1059 assert(livevec.end() != itr);
1060 size_t index = std::distance(livevec.begin(), itr);
1061 assert(index < livevec.size());
1062 return index;
1063}
1064
1065// Create new attribute set containing only attributes which can be transfered
1066// from original call to the safepoint.
1067static AttributeSet legalizeCallAttributes(AttributeSet AS) {
1068 AttributeSet ret;
1069
1070 for (unsigned Slot = 0; Slot < AS.getNumSlots(); Slot++) {
1071 unsigned index = AS.getSlotIndex(Slot);
1072
1073 if (index == AttributeSet::ReturnIndex ||
1074 index == AttributeSet::FunctionIndex) {
1075
1076 for (auto it = AS.begin(Slot), it_end = AS.end(Slot); it != it_end;
1077 ++it) {
1078 Attribute attr = *it;
1079
1080 // Do not allow certain attributes - just skip them
1081 // Safepoint can not be read only or read none.
1082 if (attr.hasAttribute(Attribute::ReadNone) ||
1083 attr.hasAttribute(Attribute::ReadOnly))
1084 continue;
1085
1086 ret = ret.addAttributes(
1087 AS.getContext(), index,
1088 AttributeSet::get(AS.getContext(), index, AttrBuilder(attr)));
1089 }
1090 }
1091
1092 // Just skip parameter attributes for now
1093 }
1094
1095 return ret;
1096}
1097
1098/// Helper function to place all gc relocates necessary for the given
1099/// statepoint.
1100/// Inputs:
1101/// liveVariables - list of variables to be relocated.
1102/// liveStart - index of the first live variable.
1103/// basePtrs - base pointers.
1104/// statepointToken - statepoint instruction to which relocates should be
1105/// bound.
1106/// Builder - Llvm IR builder to be used to construct new calls.
Sanjoy Das5665c992015-05-11 23:47:27 +00001107static void CreateGCRelocates(ArrayRef<llvm::Value *> LiveVariables,
1108 const int LiveStart,
1109 ArrayRef<llvm::Value *> BasePtrs,
1110 Instruction *StatepointToken,
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00001111 IRBuilder<> Builder) {
Philip Reamesd2b66462015-02-20 22:39:41 +00001112 SmallVector<Instruction *, 64> NewDefs;
Sanjoy Das5665c992015-05-11 23:47:27 +00001113 NewDefs.reserve(LiveVariables.size());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001114
Sanjoy Das5665c992015-05-11 23:47:27 +00001115 Module *M = StatepointToken->getParent()->getParent()->getParent();
Philip Reamesd16a9b12015-02-20 01:06:44 +00001116
Sanjoy Das5665c992015-05-11 23:47:27 +00001117 for (unsigned i = 0; i < LiveVariables.size(); i++) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001118 // We generate a (potentially) unique declaration for every pointer type
1119 // combination. This results is some blow up the function declarations in
1120 // the IR, but removes the need for argument bitcasts which shrinks the IR
1121 // greatly and makes it much more readable.
Sanjoy Das5665c992015-05-11 23:47:27 +00001122 SmallVector<Type *, 1> Types; // one per 'any' type
Sanjoy Das89c54912015-05-11 18:49:34 +00001123 // All gc_relocate are set to i8 addrspace(1)* type. This could help avoid
1124 // cases where the actual value's type mangling is not supported by llvm. A
1125 // bitcast is added later to convert gc_relocate to the actual value's type.
Sanjoy Das5665c992015-05-11 23:47:27 +00001126 Types.push_back(Type::getInt8PtrTy(M->getContext(), 1));
1127 Value *GCRelocateDecl = Intrinsic::getDeclaration(
1128 M, Intrinsic::experimental_gc_relocate, Types);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001129
1130 // Generate the gc.relocate call and save the result
Sanjoy Das5665c992015-05-11 23:47:27 +00001131 Value *BaseIdx =
Philip Reamesd16a9b12015-02-20 01:06:44 +00001132 ConstantInt::get(Type::getInt32Ty(M->getContext()),
Sanjoy Das5665c992015-05-11 23:47:27 +00001133 LiveStart + find_index(LiveVariables, BasePtrs[i]));
1134 Value *LiveIdx = ConstantInt::get(
Philip Reamesd16a9b12015-02-20 01:06:44 +00001135 Type::getInt32Ty(M->getContext()),
Sanjoy Das5665c992015-05-11 23:47:27 +00001136 LiveStart + find_index(LiveVariables, LiveVariables[i]));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001137
1138 // only specify a debug name if we can give a useful one
David Blaikieff6409d2015-05-18 22:13:54 +00001139 Value *Reloc = Builder.CreateCall(
1140 GCRelocateDecl, {StatepointToken, BaseIdx, LiveIdx},
Sanjoy Das5665c992015-05-11 23:47:27 +00001141 LiveVariables[i]->hasName() ? LiveVariables[i]->getName() + ".relocated"
Philip Reamesd16a9b12015-02-20 01:06:44 +00001142 : "");
1143 // Trick CodeGen into thinking there are lots of free registers at this
1144 // fake call.
Sanjoy Das5665c992015-05-11 23:47:27 +00001145 cast<CallInst>(Reloc)->setCallingConv(CallingConv::Cold);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001146
Sanjoy Das5665c992015-05-11 23:47:27 +00001147 NewDefs.push_back(cast<Instruction>(Reloc));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001148 }
Sanjoy Das5665c992015-05-11 23:47:27 +00001149 assert(NewDefs.size() == LiveVariables.size() &&
Philip Reamesd16a9b12015-02-20 01:06:44 +00001150 "missing or extra redefinition at safepoint");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001151}
1152
1153static void
1154makeStatepointExplicitImpl(const CallSite &CS, /* to replace */
1155 const SmallVectorImpl<llvm::Value *> &basePtrs,
1156 const SmallVectorImpl<llvm::Value *> &liveVariables,
1157 Pass *P,
1158 PartiallyConstructedSafepointRecord &result) {
1159 assert(basePtrs.size() == liveVariables.size());
1160 assert(isStatepoint(CS) &&
1161 "This method expects to be rewriting a statepoint");
1162
1163 BasicBlock *BB = CS.getInstruction()->getParent();
1164 assert(BB);
1165 Function *F = BB->getParent();
1166 assert(F && "must be set");
1167 Module *M = F->getParent();
Nick Lewyckyeb3231e2015-02-20 07:14:02 +00001168 (void)M;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001169 assert(M && "must be set");
1170
1171 // We're not changing the function signature of the statepoint since the gc
1172 // arguments go into the var args section.
1173 Function *gc_statepoint_decl = CS.getCalledFunction();
1174
1175 // Then go ahead and use the builder do actually do the inserts. We insert
1176 // immediately before the previous instruction under the assumption that all
1177 // arguments will be available here. We can't insert afterwards since we may
1178 // be replacing a terminator.
1179 Instruction *insertBefore = CS.getInstruction();
1180 IRBuilder<> Builder(insertBefore);
1181 // Copy all of the arguments from the original statepoint - this includes the
1182 // target, call args, and deopt args
Philip Reamesd2b66462015-02-20 22:39:41 +00001183 SmallVector<llvm::Value *, 64> args;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001184 args.insert(args.end(), CS.arg_begin(), CS.arg_end());
1185 // TODO: Clear the 'needs rewrite' flag
1186
1187 // add all the pointers to be relocated (gc arguments)
1188 // Capture the start of the live variable list for use in the gc_relocates
1189 const int live_start = args.size();
1190 args.insert(args.end(), liveVariables.begin(), liveVariables.end());
1191
1192 // Create the statepoint given all the arguments
1193 Instruction *token = nullptr;
1194 AttributeSet return_attributes;
1195 if (CS.isCall()) {
1196 CallInst *toReplace = cast<CallInst>(CS.getInstruction());
1197 CallInst *call =
1198 Builder.CreateCall(gc_statepoint_decl, args, "safepoint_token");
1199 call->setTailCall(toReplace->isTailCall());
1200 call->setCallingConv(toReplace->getCallingConv());
1201
1202 // Currently we will fail on parameter attributes and on certain
1203 // function attributes.
1204 AttributeSet new_attrs = legalizeCallAttributes(toReplace->getAttributes());
1205 // In case if we can handle this set of sttributes - set up function attrs
1206 // directly on statepoint and return attrs later for gc_result intrinsic.
1207 call->setAttributes(new_attrs.getFnAttributes());
1208 return_attributes = new_attrs.getRetAttributes();
1209
1210 token = call;
1211
1212 // Put the following gc_result and gc_relocate calls immediately after the
1213 // the old call (which we're about to delete)
1214 BasicBlock::iterator next(toReplace);
1215 assert(BB->end() != next && "not a terminator, must have next");
1216 next++;
1217 Instruction *IP = &*(next);
1218 Builder.SetInsertPoint(IP);
1219 Builder.SetCurrentDebugLocation(IP->getDebugLoc());
1220
David Blaikie82ad7872015-02-20 23:44:24 +00001221 } else {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001222 InvokeInst *toReplace = cast<InvokeInst>(CS.getInstruction());
1223
1224 // Insert the new invoke into the old block. We'll remove the old one in a
1225 // moment at which point this will become the new terminator for the
1226 // original block.
1227 InvokeInst *invoke = InvokeInst::Create(
1228 gc_statepoint_decl, toReplace->getNormalDest(),
1229 toReplace->getUnwindDest(), args, "", toReplace->getParent());
1230 invoke->setCallingConv(toReplace->getCallingConv());
1231
1232 // Currently we will fail on parameter attributes and on certain
1233 // function attributes.
1234 AttributeSet new_attrs = legalizeCallAttributes(toReplace->getAttributes());
1235 // In case if we can handle this set of sttributes - set up function attrs
1236 // directly on statepoint and return attrs later for gc_result intrinsic.
1237 invoke->setAttributes(new_attrs.getFnAttributes());
1238 return_attributes = new_attrs.getRetAttributes();
1239
1240 token = invoke;
1241
1242 // Generate gc relocates in exceptional path
Philip Reames69e51ca2015-04-13 18:07:21 +00001243 BasicBlock *unwindBlock = toReplace->getUnwindDest();
1244 assert(!isa<PHINode>(unwindBlock->begin()) &&
1245 unwindBlock->getUniquePredecessor() &&
1246 "can't safely insert in this block!");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001247
1248 Instruction *IP = &*(unwindBlock->getFirstInsertionPt());
1249 Builder.SetInsertPoint(IP);
1250 Builder.SetCurrentDebugLocation(toReplace->getDebugLoc());
1251
1252 // Extract second element from landingpad return value. We will attach
1253 // exceptional gc relocates to it.
1254 const unsigned idx = 1;
1255 Instruction *exceptional_token =
1256 cast<Instruction>(Builder.CreateExtractValue(
1257 unwindBlock->getLandingPadInst(), idx, "relocate_token"));
Philip Reamesf2041322015-02-20 19:26:04 +00001258 result.UnwindToken = exceptional_token;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001259
1260 // Just throw away return value. We will use the one we got for normal
1261 // block.
1262 (void)CreateGCRelocates(liveVariables, live_start, basePtrs,
1263 exceptional_token, Builder);
1264
1265 // Generate gc relocates and returns for normal block
Philip Reames69e51ca2015-04-13 18:07:21 +00001266 BasicBlock *normalDest = toReplace->getNormalDest();
1267 assert(!isa<PHINode>(normalDest->begin()) &&
1268 normalDest->getUniquePredecessor() &&
1269 "can't safely insert in this block!");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001270
1271 IP = &*(normalDest->getFirstInsertionPt());
1272 Builder.SetInsertPoint(IP);
1273
1274 // gc relocates will be generated later as if it were regular call
1275 // statepoint
Philip Reamesd16a9b12015-02-20 01:06:44 +00001276 }
1277 assert(token);
1278
1279 // Take the name of the original value call if it had one.
1280 token->takeName(CS.getInstruction());
1281
Philip Reames704e78b2015-04-10 22:34:56 +00001282// The GCResult is already inserted, we just need to find it
David Blaikie5e5d7842015-02-22 20:58:38 +00001283#ifndef NDEBUG
1284 Instruction *toReplace = CS.getInstruction();
1285 assert((toReplace->hasNUses(0) || toReplace->hasNUses(1)) &&
1286 "only valid use before rewrite is gc.result");
1287 assert(!toReplace->hasOneUse() ||
1288 isGCResult(cast<Instruction>(*toReplace->user_begin())));
1289#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +00001290
1291 // Update the gc.result of the original statepoint (if any) to use the newly
1292 // inserted statepoint. This is safe to do here since the token can't be
1293 // considered a live reference.
1294 CS.getInstruction()->replaceAllUsesWith(token);
1295
Philip Reames0a3240f2015-02-20 21:34:11 +00001296 result.StatepointToken = token;
1297
Philip Reamesd16a9b12015-02-20 01:06:44 +00001298 // Second, create a gc.relocate for every live variable
Philip Reames0a3240f2015-02-20 21:34:11 +00001299 CreateGCRelocates(liveVariables, live_start, basePtrs, token, Builder);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001300}
1301
1302namespace {
1303struct name_ordering {
1304 Value *base;
1305 Value *derived;
1306 bool operator()(name_ordering const &a, name_ordering const &b) {
1307 return -1 == a.derived->getName().compare(b.derived->getName());
1308 }
1309};
1310}
1311static void stablize_order(SmallVectorImpl<Value *> &basevec,
1312 SmallVectorImpl<Value *> &livevec) {
1313 assert(basevec.size() == livevec.size());
1314
Philip Reames860660e2015-02-20 22:05:18 +00001315 SmallVector<name_ordering, 64> temp;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001316 for (size_t i = 0; i < basevec.size(); i++) {
1317 name_ordering v;
1318 v.base = basevec[i];
1319 v.derived = livevec[i];
1320 temp.push_back(v);
1321 }
1322 std::sort(temp.begin(), temp.end(), name_ordering());
1323 for (size_t i = 0; i < basevec.size(); i++) {
1324 basevec[i] = temp[i].base;
1325 livevec[i] = temp[i].derived;
1326 }
1327}
1328
1329// Replace an existing gc.statepoint with a new one and a set of gc.relocates
1330// which make the relocations happening at this safepoint explicit.
Philip Reames704e78b2015-04-10 22:34:56 +00001331//
Philip Reamesd16a9b12015-02-20 01:06:44 +00001332// WARNING: Does not do any fixup to adjust users of the original live
1333// values. That's the callers responsibility.
1334static void
1335makeStatepointExplicit(DominatorTree &DT, const CallSite &CS, Pass *P,
1336 PartiallyConstructedSafepointRecord &result) {
Philip Reamesf2041322015-02-20 19:26:04 +00001337 auto liveset = result.liveset;
1338 auto PointerToBase = result.PointerToBase;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001339
1340 // Convert to vector for efficient cross referencing.
1341 SmallVector<Value *, 64> basevec, livevec;
1342 livevec.reserve(liveset.size());
1343 basevec.reserve(liveset.size());
1344 for (Value *L : liveset) {
1345 livevec.push_back(L);
1346
Philip Reamesf2041322015-02-20 19:26:04 +00001347 assert(PointerToBase.find(L) != PointerToBase.end());
1348 Value *base = PointerToBase[L];
Philip Reamesd16a9b12015-02-20 01:06:44 +00001349 basevec.push_back(base);
1350 }
1351 assert(livevec.size() == basevec.size());
1352
1353 // To make the output IR slightly more stable (for use in diffs), ensure a
1354 // fixed order of the values in the safepoint (by sorting the value name).
1355 // The order is otherwise meaningless.
1356 stablize_order(basevec, livevec);
1357
1358 // Do the actual rewriting and delete the old statepoint
1359 makeStatepointExplicitImpl(CS, basevec, livevec, P, result);
1360 CS.getInstruction()->eraseFromParent();
1361}
1362
1363// Helper function for the relocationViaAlloca.
1364// It receives iterator to the statepoint gc relocates and emits store to the
1365// assigned
1366// location (via allocaMap) for the each one of them.
1367// Add visited values into the visitedLiveValues set we will later use them
1368// for sanity check.
1369static void
Sanjoy Das5665c992015-05-11 23:47:27 +00001370insertRelocationStores(iterator_range<Value::user_iterator> GCRelocs,
1371 DenseMap<Value *, Value *> &AllocaMap,
1372 DenseSet<Value *> &VisitedLiveValues) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001373
Sanjoy Das5665c992015-05-11 23:47:27 +00001374 for (User *U : GCRelocs) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001375 if (!isa<IntrinsicInst>(U))
1376 continue;
1377
Sanjoy Das5665c992015-05-11 23:47:27 +00001378 IntrinsicInst *RelocatedValue = cast<IntrinsicInst>(U);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001379
1380 // We only care about relocates
Sanjoy Das5665c992015-05-11 23:47:27 +00001381 if (RelocatedValue->getIntrinsicID() !=
Philip Reamesd16a9b12015-02-20 01:06:44 +00001382 Intrinsic::experimental_gc_relocate) {
1383 continue;
1384 }
1385
Sanjoy Das5665c992015-05-11 23:47:27 +00001386 GCRelocateOperands RelocateOperands(RelocatedValue);
1387 Value *OriginalValue =
1388 const_cast<Value *>(RelocateOperands.getDerivedPtr());
1389 assert(AllocaMap.count(OriginalValue));
1390 Value *Alloca = AllocaMap[OriginalValue];
Philip Reamesd16a9b12015-02-20 01:06:44 +00001391
1392 // Emit store into the related alloca
Sanjoy Das89c54912015-05-11 18:49:34 +00001393 // All gc_relocate are i8 addrspace(1)* typed, and it must be bitcasted to
1394 // the correct type according to alloca.
Sanjoy Das5665c992015-05-11 23:47:27 +00001395 assert(RelocatedValue->getNextNode() && "Should always have one since it's not a terminator");
1396 IRBuilder<> Builder(RelocatedValue->getNextNode());
Sanjoy Das89c54912015-05-11 18:49:34 +00001397 Value *CastedRelocatedValue =
Sanjoy Das5665c992015-05-11 23:47:27 +00001398 Builder.CreateBitCast(RelocatedValue, cast<AllocaInst>(Alloca)->getAllocatedType(),
1399 RelocatedValue->hasName() ? RelocatedValue->getName() + ".casted" : "");
Sanjoy Das89c54912015-05-11 18:49:34 +00001400
Sanjoy Das5665c992015-05-11 23:47:27 +00001401 StoreInst *Store = new StoreInst(CastedRelocatedValue, Alloca);
1402 Store->insertAfter(cast<Instruction>(CastedRelocatedValue));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001403
1404#ifndef NDEBUG
Sanjoy Das5665c992015-05-11 23:47:27 +00001405 VisitedLiveValues.insert(OriginalValue);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001406#endif
1407 }
1408}
1409
Igor Laevskye0317182015-05-19 15:59:05 +00001410// Helper function for the "relocationViaAlloca". Similar to the
1411// "insertRelocationStores" but works for rematerialized values.
1412static void
1413insertRematerializationStores(
1414 RematerializedValueMapTy RematerializedValues,
1415 DenseMap<Value *, Value *> &AllocaMap,
1416 DenseSet<Value *> &VisitedLiveValues) {
1417
1418 for (auto RematerializedValuePair: RematerializedValues) {
1419 Instruction *RematerializedValue = RematerializedValuePair.first;
1420 Value *OriginalValue = RematerializedValuePair.second;
1421
1422 assert(AllocaMap.count(OriginalValue) &&
1423 "Can not find alloca for rematerialized value");
1424 Value *Alloca = AllocaMap[OriginalValue];
1425
1426 StoreInst *Store = new StoreInst(RematerializedValue, Alloca);
1427 Store->insertAfter(RematerializedValue);
1428
1429#ifndef NDEBUG
1430 VisitedLiveValues.insert(OriginalValue);
1431#endif
1432 }
1433}
1434
Philip Reamesd16a9b12015-02-20 01:06:44 +00001435/// do all the relocation update via allocas and mem2reg
1436static void relocationViaAlloca(
Igor Laevsky285fe842015-05-19 16:29:43 +00001437 Function &F, DominatorTree &DT, ArrayRef<Value *> Live,
1438 ArrayRef<struct PartiallyConstructedSafepointRecord> Records) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001439#ifndef NDEBUG
Philip Reamesa6ebf072015-03-27 05:53:16 +00001440 // record initial number of (static) allocas; we'll check we have the same
1441 // number when we get done.
1442 int InitialAllocaNum = 0;
Philip Reames704e78b2015-04-10 22:34:56 +00001443 for (auto I = F.getEntryBlock().begin(), E = F.getEntryBlock().end(); I != E;
1444 I++)
Philip Reamesa6ebf072015-03-27 05:53:16 +00001445 if (isa<AllocaInst>(*I))
1446 InitialAllocaNum++;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001447#endif
1448
1449 // TODO-PERF: change data structures, reserve
Igor Laevsky285fe842015-05-19 16:29:43 +00001450 DenseMap<Value *, Value *> AllocaMap;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001451 SmallVector<AllocaInst *, 200> PromotableAllocas;
Igor Laevskye0317182015-05-19 15:59:05 +00001452 // Used later to chack that we have enough allocas to store all values
1453 std::size_t NumRematerializedValues = 0;
Igor Laevsky285fe842015-05-19 16:29:43 +00001454 PromotableAllocas.reserve(Live.size());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001455
Igor Laevskye0317182015-05-19 15:59:05 +00001456 // Emit alloca for "LiveValue" and record it in "allocaMap" and
1457 // "PromotableAllocas"
1458 auto emitAllocaFor = [&](Value *LiveValue) {
1459 AllocaInst *Alloca = new AllocaInst(LiveValue->getType(), "",
1460 F.getEntryBlock().getFirstNonPHI());
Igor Laevsky285fe842015-05-19 16:29:43 +00001461 AllocaMap[LiveValue] = Alloca;
Igor Laevskye0317182015-05-19 15:59:05 +00001462 PromotableAllocas.push_back(Alloca);
1463 };
1464
Philip Reamesd16a9b12015-02-20 01:06:44 +00001465 // emit alloca for each live gc pointer
Igor Laevsky285fe842015-05-19 16:29:43 +00001466 for (unsigned i = 0; i < Live.size(); i++) {
1467 emitAllocaFor(Live[i]);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001468 }
1469
Igor Laevskye0317182015-05-19 15:59:05 +00001470 // emit allocas for rematerialized values
Igor Laevsky285fe842015-05-19 16:29:43 +00001471 for (size_t i = 0; i < Records.size(); i++) {
1472 const struct PartiallyConstructedSafepointRecord &Info = Records[i];
Igor Laevskye0317182015-05-19 15:59:05 +00001473
Igor Laevsky285fe842015-05-19 16:29:43 +00001474 for (auto RematerializedValuePair : Info.RematerializedValues) {
Igor Laevskye0317182015-05-19 15:59:05 +00001475 Value *OriginalValue = RematerializedValuePair.second;
Igor Laevsky285fe842015-05-19 16:29:43 +00001476 if (AllocaMap.count(OriginalValue) != 0)
Igor Laevskye0317182015-05-19 15:59:05 +00001477 continue;
1478
1479 emitAllocaFor(OriginalValue);
1480 ++NumRematerializedValues;
1481 }
1482 }
Igor Laevsky285fe842015-05-19 16:29:43 +00001483
Philip Reamesd16a9b12015-02-20 01:06:44 +00001484 // The next two loops are part of the same conceptual operation. We need to
1485 // insert a store to the alloca after the original def and at each
1486 // redefinition. We need to insert a load before each use. These are split
1487 // into distinct loops for performance reasons.
1488
1489 // update gc pointer after each statepoint
1490 // either store a relocated value or null (if no relocated value found for
1491 // this gc pointer and it is not a gc_result)
1492 // this must happen before we update the statepoint with load of alloca
1493 // otherwise we lose the link between statepoint and old def
Igor Laevsky285fe842015-05-19 16:29:43 +00001494 for (size_t i = 0; i < Records.size(); i++) {
1495 const struct PartiallyConstructedSafepointRecord &Info = Records[i];
1496 Value *Statepoint = Info.StatepointToken;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001497
1498 // This will be used for consistency check
Igor Laevsky285fe842015-05-19 16:29:43 +00001499 DenseSet<Value *> VisitedLiveValues;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001500
1501 // Insert stores for normal statepoint gc relocates
Igor Laevsky285fe842015-05-19 16:29:43 +00001502 insertRelocationStores(Statepoint->users(), AllocaMap, VisitedLiveValues);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001503
1504 // In case if it was invoke statepoint
1505 // we will insert stores for exceptional path gc relocates.
Philip Reames0a3240f2015-02-20 21:34:11 +00001506 if (isa<InvokeInst>(Statepoint)) {
Igor Laevsky285fe842015-05-19 16:29:43 +00001507 insertRelocationStores(Info.UnwindToken->users(), AllocaMap,
1508 VisitedLiveValues);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001509 }
1510
Igor Laevskye0317182015-05-19 15:59:05 +00001511 // Do similar thing with rematerialized values
Igor Laevsky285fe842015-05-19 16:29:43 +00001512 insertRematerializationStores(Info.RematerializedValues, AllocaMap,
1513 VisitedLiveValues);
Igor Laevskye0317182015-05-19 15:59:05 +00001514
Philip Reamese73300b2015-04-13 16:41:32 +00001515 if (ClobberNonLive) {
1516 // As a debuging aid, pretend that an unrelocated pointer becomes null at
1517 // the gc.statepoint. This will turn some subtle GC problems into
1518 // slightly easier to debug SEGVs. Note that on large IR files with
1519 // lots of gc.statepoints this is extremely costly both memory and time
1520 // wise.
1521 SmallVector<AllocaInst *, 64> ToClobber;
Igor Laevsky285fe842015-05-19 16:29:43 +00001522 for (auto Pair : AllocaMap) {
Philip Reamese73300b2015-04-13 16:41:32 +00001523 Value *Def = Pair.first;
1524 AllocaInst *Alloca = cast<AllocaInst>(Pair.second);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001525
Philip Reamese73300b2015-04-13 16:41:32 +00001526 // This value was relocated
Igor Laevsky285fe842015-05-19 16:29:43 +00001527 if (VisitedLiveValues.count(Def)) {
Philip Reamese73300b2015-04-13 16:41:32 +00001528 continue;
1529 }
1530 ToClobber.push_back(Alloca);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001531 }
Philip Reamesfa2fcf172015-02-20 19:51:56 +00001532
Philip Reamese73300b2015-04-13 16:41:32 +00001533 auto InsertClobbersAt = [&](Instruction *IP) {
1534 for (auto *AI : ToClobber) {
1535 auto AIType = cast<PointerType>(AI->getType());
1536 auto PT = cast<PointerType>(AIType->getElementType());
1537 Constant *CPN = ConstantPointerNull::get(PT);
Igor Laevsky285fe842015-05-19 16:29:43 +00001538 StoreInst *Store = new StoreInst(CPN, AI);
1539 Store->insertBefore(IP);
Philip Reamese73300b2015-04-13 16:41:32 +00001540 }
1541 };
1542
1543 // Insert the clobbering stores. These may get intermixed with the
1544 // gc.results and gc.relocates, but that's fine.
1545 if (auto II = dyn_cast<InvokeInst>(Statepoint)) {
1546 InsertClobbersAt(II->getNormalDest()->getFirstInsertionPt());
1547 InsertClobbersAt(II->getUnwindDest()->getFirstInsertionPt());
1548 } else {
1549 BasicBlock::iterator Next(cast<CallInst>(Statepoint));
1550 Next++;
1551 InsertClobbersAt(Next);
Philip Reamesfa2fcf172015-02-20 19:51:56 +00001552 }
David Blaikie82ad7872015-02-20 23:44:24 +00001553 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00001554 }
1555 // update use with load allocas and add store for gc_relocated
Igor Laevsky285fe842015-05-19 16:29:43 +00001556 for (auto Pair : AllocaMap) {
1557 Value *Def = Pair.first;
1558 Value *Alloca = Pair.second;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001559
1560 // we pre-record the uses of allocas so that we dont have to worry about
1561 // later update
1562 // that change the user information.
Igor Laevsky285fe842015-05-19 16:29:43 +00001563 SmallVector<Instruction *, 20> Uses;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001564 // PERF: trade a linear scan for repeated reallocation
Igor Laevsky285fe842015-05-19 16:29:43 +00001565 Uses.reserve(std::distance(Def->user_begin(), Def->user_end()));
1566 for (User *U : Def->users()) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001567 if (!isa<ConstantExpr>(U)) {
1568 // If the def has a ConstantExpr use, then the def is either a
1569 // ConstantExpr use itself or null. In either case
1570 // (recursively in the first, directly in the second), the oop
1571 // it is ultimately dependent on is null and this particular
1572 // use does not need to be fixed up.
Igor Laevsky285fe842015-05-19 16:29:43 +00001573 Uses.push_back(cast<Instruction>(U));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001574 }
1575 }
1576
Igor Laevsky285fe842015-05-19 16:29:43 +00001577 std::sort(Uses.begin(), Uses.end());
1578 auto Last = std::unique(Uses.begin(), Uses.end());
1579 Uses.erase(Last, Uses.end());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001580
Igor Laevsky285fe842015-05-19 16:29:43 +00001581 for (Instruction *Use : Uses) {
1582 if (isa<PHINode>(Use)) {
1583 PHINode *Phi = cast<PHINode>(Use);
1584 for (unsigned i = 0; i < Phi->getNumIncomingValues(); i++) {
1585 if (Def == Phi->getIncomingValue(i)) {
1586 LoadInst *Load = new LoadInst(
1587 Alloca, "", Phi->getIncomingBlock(i)->getTerminator());
1588 Phi->setIncomingValue(i, Load);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001589 }
1590 }
1591 } else {
Igor Laevsky285fe842015-05-19 16:29:43 +00001592 LoadInst *Load = new LoadInst(Alloca, "", Use);
1593 Use->replaceUsesOfWith(Def, Load);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001594 }
1595 }
1596
1597 // emit store for the initial gc value
1598 // store must be inserted after load, otherwise store will be in alloca's
1599 // use list and an extra load will be inserted before it
Igor Laevsky285fe842015-05-19 16:29:43 +00001600 StoreInst *Store = new StoreInst(Def, Alloca);
1601 if (Instruction *Inst = dyn_cast<Instruction>(Def)) {
1602 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(Inst)) {
Philip Reames6da37852015-03-04 00:13:52 +00001603 // InvokeInst is a TerminatorInst so the store need to be inserted
1604 // into its normal destination block.
Igor Laevsky285fe842015-05-19 16:29:43 +00001605 BasicBlock *NormalDest = Invoke->getNormalDest();
1606 Store->insertBefore(NormalDest->getFirstNonPHI());
Philip Reames6da37852015-03-04 00:13:52 +00001607 } else {
Igor Laevsky285fe842015-05-19 16:29:43 +00001608 assert(!Inst->isTerminator() &&
Philip Reames6da37852015-03-04 00:13:52 +00001609 "The only TerminatorInst that can produce a value is "
1610 "InvokeInst which is handled above.");
Igor Laevsky285fe842015-05-19 16:29:43 +00001611 Store->insertAfter(Inst);
Philip Reames6da37852015-03-04 00:13:52 +00001612 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00001613 } else {
Igor Laevsky285fe842015-05-19 16:29:43 +00001614 assert(isa<Argument>(Def));
1615 Store->insertAfter(cast<Instruction>(Alloca));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001616 }
1617 }
1618
Igor Laevsky285fe842015-05-19 16:29:43 +00001619 assert(PromotableAllocas.size() == Live.size() + NumRematerializedValues &&
Philip Reamesd16a9b12015-02-20 01:06:44 +00001620 "we must have the same allocas with lives");
1621 if (!PromotableAllocas.empty()) {
1622 // apply mem2reg to promote alloca to SSA
1623 PromoteMemToReg(PromotableAllocas, DT);
1624 }
1625
1626#ifndef NDEBUG
Philip Reames704e78b2015-04-10 22:34:56 +00001627 for (auto I = F.getEntryBlock().begin(), E = F.getEntryBlock().end(); I != E;
1628 I++)
Philip Reamesa6ebf072015-03-27 05:53:16 +00001629 if (isa<AllocaInst>(*I))
1630 InitialAllocaNum--;
1631 assert(InitialAllocaNum == 0 && "We must not introduce any extra allocas");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001632#endif
1633}
1634
1635/// Implement a unique function which doesn't require we sort the input
1636/// vector. Doing so has the effect of changing the output of a couple of
1637/// tests in ways which make them less useful in testing fused safepoints.
Philip Reamesd2b66462015-02-20 22:39:41 +00001638template <typename T> static void unique_unsorted(SmallVectorImpl<T> &Vec) {
1639 DenseSet<T> Seen;
1640 SmallVector<T, 128> TempVec;
1641 TempVec.reserve(Vec.size());
1642 for (auto Element : Vec)
1643 TempVec.push_back(Element);
1644 Vec.clear();
1645 for (auto V : TempVec) {
1646 if (Seen.insert(V).second) {
1647 Vec.push_back(V);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001648 }
1649 }
1650}
1651
Philip Reamesd16a9b12015-02-20 01:06:44 +00001652/// Insert holders so that each Value is obviously live through the entire
Philip Reamesf209a152015-04-13 20:00:30 +00001653/// lifetime of the call.
Philip Reamesd16a9b12015-02-20 01:06:44 +00001654static void insertUseHolderAfter(CallSite &CS, const ArrayRef<Value *> Values,
Philip Reamesf209a152015-04-13 20:00:30 +00001655 SmallVectorImpl<CallInst *> &Holders) {
Philip Reames21142752015-04-13 19:07:47 +00001656 if (Values.empty())
1657 // No values to hold live, might as well not insert the empty holder
1658 return;
1659
Philip Reamesd16a9b12015-02-20 01:06:44 +00001660 Module *M = CS.getInstruction()->getParent()->getParent()->getParent();
Philip Reamesf209a152015-04-13 20:00:30 +00001661 // Use a dummy vararg function to actually hold the values live
1662 Function *Func = cast<Function>(M->getOrInsertFunction(
1663 "__tmp_use", FunctionType::get(Type::getVoidTy(M->getContext()), true)));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001664 if (CS.isCall()) {
1665 // For call safepoints insert dummy calls right after safepoint
Philip Reamesf209a152015-04-13 20:00:30 +00001666 BasicBlock::iterator Next(CS.getInstruction());
1667 Next++;
1668 Holders.push_back(CallInst::Create(Func, Values, "", Next));
1669 return;
1670 }
1671 // For invoke safepooints insert dummy calls both in normal and
1672 // exceptional destination blocks
1673 auto *II = cast<InvokeInst>(CS.getInstruction());
1674 Holders.push_back(CallInst::Create(
1675 Func, Values, "", II->getNormalDest()->getFirstInsertionPt()));
1676 Holders.push_back(CallInst::Create(
1677 Func, Values, "", II->getUnwindDest()->getFirstInsertionPt()));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001678}
1679
1680static void findLiveReferences(
Philip Reamesd2b66462015-02-20 22:39:41 +00001681 Function &F, DominatorTree &DT, Pass *P, ArrayRef<CallSite> toUpdate,
1682 MutableArrayRef<struct PartiallyConstructedSafepointRecord> records) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00001683 GCPtrLivenessData OriginalLivenessData;
1684 computeLiveInValues(DT, F, OriginalLivenessData);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001685 for (size_t i = 0; i < records.size(); i++) {
1686 struct PartiallyConstructedSafepointRecord &info = records[i];
Philip Reamesd2b66462015-02-20 22:39:41 +00001687 const CallSite &CS = toUpdate[i];
Philip Reamesdf1ef082015-04-10 22:53:14 +00001688 analyzeParsePointLiveness(DT, OriginalLivenessData, CS, info);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001689 }
1690}
1691
Philip Reames8531d8c2015-04-10 21:48:25 +00001692/// Remove any vector of pointers from the liveset by scalarizing them over the
1693/// statepoint instruction. Adds the scalarized pieces to the liveset. It
1694/// would be preferrable to include the vector in the statepoint itself, but
1695/// the lowering code currently does not handle that. Extending it would be
1696/// slightly non-trivial since it requires a format change. Given how rare
1697/// such cases are (for the moment?) scalarizing is an acceptable comprimise.
1698static void splitVectorValues(Instruction *StatepointInst,
Philip Reames704e78b2015-04-10 22:34:56 +00001699 StatepointLiveSetTy &LiveSet, DominatorTree &DT) {
Philip Reames8531d8c2015-04-10 21:48:25 +00001700 SmallVector<Value *, 16> ToSplit;
1701 for (Value *V : LiveSet)
1702 if (isa<VectorType>(V->getType()))
1703 ToSplit.push_back(V);
1704
1705 if (ToSplit.empty())
1706 return;
1707
1708 Function &F = *(StatepointInst->getParent()->getParent());
1709
Philip Reames704e78b2015-04-10 22:34:56 +00001710 DenseMap<Value *, AllocaInst *> AllocaMap;
Philip Reames8531d8c2015-04-10 21:48:25 +00001711 // First is normal return, second is exceptional return (invoke only)
Philip Reames704e78b2015-04-10 22:34:56 +00001712 DenseMap<Value *, std::pair<Value *, Value *>> Replacements;
Philip Reames8531d8c2015-04-10 21:48:25 +00001713 for (Value *V : ToSplit) {
1714 LiveSet.erase(V);
1715
Philip Reames704e78b2015-04-10 22:34:56 +00001716 AllocaInst *Alloca =
1717 new AllocaInst(V->getType(), "", F.getEntryBlock().getFirstNonPHI());
Philip Reames8531d8c2015-04-10 21:48:25 +00001718 AllocaMap[V] = Alloca;
1719
1720 VectorType *VT = cast<VectorType>(V->getType());
1721 IRBuilder<> Builder(StatepointInst);
Philip Reames704e78b2015-04-10 22:34:56 +00001722 SmallVector<Value *, 16> Elements;
Philip Reames8531d8c2015-04-10 21:48:25 +00001723 for (unsigned i = 0; i < VT->getNumElements(); i++)
1724 Elements.push_back(Builder.CreateExtractElement(V, Builder.getInt32(i)));
1725 LiveSet.insert(Elements.begin(), Elements.end());
1726
1727 auto InsertVectorReform = [&](Instruction *IP) {
1728 Builder.SetInsertPoint(IP);
1729 Builder.SetCurrentDebugLocation(IP->getDebugLoc());
1730 Value *ResultVec = UndefValue::get(VT);
1731 for (unsigned i = 0; i < VT->getNumElements(); i++)
1732 ResultVec = Builder.CreateInsertElement(ResultVec, Elements[i],
1733 Builder.getInt32(i));
1734 return ResultVec;
1735 };
1736
1737 if (isa<CallInst>(StatepointInst)) {
1738 BasicBlock::iterator Next(StatepointInst);
1739 Next++;
1740 Instruction *IP = &*(Next);
1741 Replacements[V].first = InsertVectorReform(IP);
1742 Replacements[V].second = nullptr;
1743 } else {
1744 InvokeInst *Invoke = cast<InvokeInst>(StatepointInst);
1745 // We've already normalized - check that we don't have shared destination
Philip Reames704e78b2015-04-10 22:34:56 +00001746 // blocks
Philip Reames8531d8c2015-04-10 21:48:25 +00001747 BasicBlock *NormalDest = Invoke->getNormalDest();
1748 assert(!isa<PHINode>(NormalDest->begin()));
1749 BasicBlock *UnwindDest = Invoke->getUnwindDest();
1750 assert(!isa<PHINode>(UnwindDest->begin()));
1751 // Insert insert element sequences in both successors
1752 Instruction *IP = &*(NormalDest->getFirstInsertionPt());
1753 Replacements[V].first = InsertVectorReform(IP);
1754 IP = &*(UnwindDest->getFirstInsertionPt());
1755 Replacements[V].second = InsertVectorReform(IP);
1756 }
1757 }
1758 for (Value *V : ToSplit) {
1759 AllocaInst *Alloca = AllocaMap[V];
1760
1761 // Capture all users before we start mutating use lists
Philip Reames704e78b2015-04-10 22:34:56 +00001762 SmallVector<Instruction *, 16> Users;
Philip Reames8531d8c2015-04-10 21:48:25 +00001763 for (User *U : V->users())
1764 Users.push_back(cast<Instruction>(U));
1765
1766 for (Instruction *I : Users) {
1767 if (auto Phi = dyn_cast<PHINode>(I)) {
1768 for (unsigned i = 0; i < Phi->getNumIncomingValues(); i++)
1769 if (V == Phi->getIncomingValue(i)) {
Philip Reames704e78b2015-04-10 22:34:56 +00001770 LoadInst *Load = new LoadInst(
1771 Alloca, "", Phi->getIncomingBlock(i)->getTerminator());
Philip Reames8531d8c2015-04-10 21:48:25 +00001772 Phi->setIncomingValue(i, Load);
1773 }
1774 } else {
1775 LoadInst *Load = new LoadInst(Alloca, "", I);
1776 I->replaceUsesOfWith(V, Load);
1777 }
1778 }
1779
1780 // Store the original value and the replacement value into the alloca
1781 StoreInst *Store = new StoreInst(V, Alloca);
1782 if (auto I = dyn_cast<Instruction>(V))
1783 Store->insertAfter(I);
1784 else
1785 Store->insertAfter(Alloca);
Philip Reames704e78b2015-04-10 22:34:56 +00001786
Philip Reames8531d8c2015-04-10 21:48:25 +00001787 // Normal return for invoke, or call return
1788 Instruction *Replacement = cast<Instruction>(Replacements[V].first);
1789 (new StoreInst(Replacement, Alloca))->insertAfter(Replacement);
1790 // Unwind return for invoke only
1791 Replacement = cast_or_null<Instruction>(Replacements[V].second);
1792 if (Replacement)
1793 (new StoreInst(Replacement, Alloca))->insertAfter(Replacement);
1794 }
1795
1796 // apply mem2reg to promote alloca to SSA
Philip Reames704e78b2015-04-10 22:34:56 +00001797 SmallVector<AllocaInst *, 16> Allocas;
Philip Reames8531d8c2015-04-10 21:48:25 +00001798 for (Value *V : ToSplit)
1799 Allocas.push_back(AllocaMap[V]);
1800 PromoteMemToReg(Allocas, DT);
1801}
1802
Igor Laevskye0317182015-05-19 15:59:05 +00001803// Helper function for the "rematerializeLiveValues". It walks use chain
1804// starting from the "CurrentValue" until it meets "BaseValue". Only "simple"
1805// values are visited (currently it is GEP's and casts). Returns true if it
1806// sucessfully reached "BaseValue" and false otherwise.
1807// Fills "ChainToBase" array with all visited values. "BaseValue" is not
1808// recorded.
1809static bool findRematerializableChainToBasePointer(
1810 SmallVectorImpl<Instruction*> &ChainToBase,
1811 Value *CurrentValue, Value *BaseValue) {
1812
1813 // We have found a base value
1814 if (CurrentValue == BaseValue) {
1815 return true;
1816 }
1817
1818 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurrentValue)) {
1819 ChainToBase.push_back(GEP);
1820 return findRematerializableChainToBasePointer(ChainToBase,
1821 GEP->getPointerOperand(),
1822 BaseValue);
1823 }
1824
1825 if (CastInst *CI = dyn_cast<CastInst>(CurrentValue)) {
1826 Value *Def = CI->stripPointerCasts();
1827
1828 // This two checks are basically similar. First one is here for the
1829 // consistency with findBasePointers logic.
1830 assert(!isa<CastInst>(Def) && "not a pointer cast found");
1831 if (!CI->isNoopCast(CI->getModule()->getDataLayout()))
1832 return false;
1833
1834 ChainToBase.push_back(CI);
1835 return findRematerializableChainToBasePointer(ChainToBase, Def, BaseValue);
1836 }
1837
1838 // Not supported instruction in the chain
1839 return false;
1840}
1841
1842// Helper function for the "rematerializeLiveValues". Compute cost of the use
1843// chain we are going to rematerialize.
1844static unsigned
1845chainToBasePointerCost(SmallVectorImpl<Instruction*> &Chain,
1846 TargetTransformInfo &TTI) {
1847 unsigned Cost = 0;
1848
1849 for (Instruction *Instr : Chain) {
1850 if (CastInst *CI = dyn_cast<CastInst>(Instr)) {
1851 assert(CI->isNoopCast(CI->getModule()->getDataLayout()) &&
1852 "non noop cast is found during rematerialization");
1853
1854 Type *SrcTy = CI->getOperand(0)->getType();
1855 Cost += TTI.getCastInstrCost(CI->getOpcode(), CI->getType(), SrcTy);
1856
1857 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Instr)) {
1858 // Cost of the address calculation
1859 Type *ValTy = GEP->getPointerOperandType()->getPointerElementType();
1860 Cost += TTI.getAddressComputationCost(ValTy);
1861
1862 // And cost of the GEP itself
1863 // TODO: Use TTI->getGEPCost here (it exists, but appears to be not
1864 // allowed for the external usage)
1865 if (!GEP->hasAllConstantIndices())
1866 Cost += 2;
1867
1868 } else {
1869 llvm_unreachable("unsupported instruciton type during rematerialization");
1870 }
1871 }
1872
1873 return Cost;
1874}
1875
1876// From the statepoint liveset pick values that are cheaper to recompute then to
1877// relocate. Remove this values from the liveset, rematerialize them after
1878// statepoint and record them in "Info" structure. Note that similar to
1879// relocated values we don't do any user adjustments here.
1880static void rematerializeLiveValues(CallSite CS,
1881 PartiallyConstructedSafepointRecord &Info,
1882 TargetTransformInfo &TTI) {
Aaron Ballmanff7d4fa2015-05-20 14:53:50 +00001883 const unsigned int ChainLengthThreshold = 10;
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +00001884
Igor Laevskye0317182015-05-19 15:59:05 +00001885 // Record values we are going to delete from this statepoint live set.
1886 // We can not di this in following loop due to iterator invalidation.
1887 SmallVector<Value *, 32> LiveValuesToBeDeleted;
1888
1889 for (Value *LiveValue: Info.liveset) {
1890 // For each live pointer find it's defining chain
1891 SmallVector<Instruction *, 3> ChainToBase;
1892 assert(Info.PointerToBase.find(LiveValue) != Info.PointerToBase.end());
1893 bool FoundChain =
1894 findRematerializableChainToBasePointer(ChainToBase,
1895 LiveValue,
1896 Info.PointerToBase[LiveValue]);
1897 // Nothing to do, or chain is too long
1898 if (!FoundChain ||
1899 ChainToBase.size() == 0 ||
1900 ChainToBase.size() > ChainLengthThreshold)
1901 continue;
1902
1903 // Compute cost of this chain
1904 unsigned Cost = chainToBasePointerCost(ChainToBase, TTI);
1905 // TODO: We can also account for cases when we will be able to remove some
1906 // of the rematerialized values by later optimization passes. I.e if
1907 // we rematerialized several intersecting chains. Or if original values
1908 // don't have any uses besides this statepoint.
1909
1910 // For invokes we need to rematerialize each chain twice - for normal and
1911 // for unwind basic blocks. Model this by multiplying cost by two.
1912 if (CS.isInvoke()) {
1913 Cost *= 2;
1914 }
1915 // If it's too expensive - skip it
1916 if (Cost >= RematerializationThreshold)
1917 continue;
1918
1919 // Remove value from the live set
1920 LiveValuesToBeDeleted.push_back(LiveValue);
1921
1922 // Clone instructions and record them inside "Info" structure
1923
1924 // Walk backwards to visit top-most instructions first
1925 std::reverse(ChainToBase.begin(), ChainToBase.end());
1926
1927 // Utility function which clones all instructions from "ChainToBase"
1928 // and inserts them before "InsertBefore". Returns rematerialized value
1929 // which should be used after statepoint.
1930 auto rematerializeChain = [&ChainToBase](Instruction *InsertBefore) {
1931 Instruction *LastClonedValue = nullptr;
1932 Instruction *LastValue = nullptr;
1933 for (Instruction *Instr: ChainToBase) {
1934 // Only GEP's and casts are suported as we need to be careful to not
1935 // introduce any new uses of pointers not in the liveset.
1936 // Note that it's fine to introduce new uses of pointers which were
1937 // otherwise not used after this statepoint.
1938 assert(isa<GetElementPtrInst>(Instr) || isa<CastInst>(Instr));
1939
1940 Instruction *ClonedValue = Instr->clone();
1941 ClonedValue->insertBefore(InsertBefore);
1942 ClonedValue->setName(Instr->getName() + ".remat");
1943
1944 // If it is not first instruction in the chain then it uses previously
1945 // cloned value. We should update it to use cloned value.
1946 if (LastClonedValue) {
1947 assert(LastValue);
1948 ClonedValue->replaceUsesOfWith(LastValue, LastClonedValue);
1949#ifndef NDEBUG
Igor Laevskyd83f6972015-05-21 13:02:14 +00001950 // Assert that cloned instruction does not use any instructions from
1951 // this chain other than LastClonedValue
1952 for (auto OpValue : ClonedValue->operand_values()) {
1953 assert(std::find(ChainToBase.begin(), ChainToBase.end(), OpValue) ==
1954 ChainToBase.end() &&
1955 "incorrect use in rematerialization chain");
Igor Laevskye0317182015-05-19 15:59:05 +00001956 }
1957#endif
1958 }
1959
1960 LastClonedValue = ClonedValue;
1961 LastValue = Instr;
1962 }
1963 assert(LastClonedValue);
1964 return LastClonedValue;
1965 };
1966
1967 // Different cases for calls and invokes. For invokes we need to clone
1968 // instructions both on normal and unwind path.
1969 if (CS.isCall()) {
1970 Instruction *InsertBefore = CS.getInstruction()->getNextNode();
1971 assert(InsertBefore);
1972 Instruction *RematerializedValue = rematerializeChain(InsertBefore);
1973 Info.RematerializedValues[RematerializedValue] = LiveValue;
1974 } else {
1975 InvokeInst *Invoke = cast<InvokeInst>(CS.getInstruction());
1976
1977 Instruction *NormalInsertBefore =
1978 Invoke->getNormalDest()->getFirstInsertionPt();
1979 Instruction *UnwindInsertBefore =
1980 Invoke->getUnwindDest()->getFirstInsertionPt();
1981
1982 Instruction *NormalRematerializedValue =
1983 rematerializeChain(NormalInsertBefore);
1984 Instruction *UnwindRematerializedValue =
1985 rematerializeChain(UnwindInsertBefore);
1986
1987 Info.RematerializedValues[NormalRematerializedValue] = LiveValue;
1988 Info.RematerializedValues[UnwindRematerializedValue] = LiveValue;
1989 }
1990 }
1991
1992 // Remove rematerializaed values from the live set
1993 for (auto LiveValue: LiveValuesToBeDeleted) {
1994 Info.liveset.erase(LiveValue);
1995 }
1996}
1997
Philip Reamesd16a9b12015-02-20 01:06:44 +00001998static bool insertParsePoints(Function &F, DominatorTree &DT, Pass *P,
Philip Reamesd2b66462015-02-20 22:39:41 +00001999 SmallVectorImpl<CallSite> &toUpdate) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00002000#ifndef NDEBUG
2001 // sanity check the input
2002 std::set<CallSite> uniqued;
2003 uniqued.insert(toUpdate.begin(), toUpdate.end());
2004 assert(uniqued.size() == toUpdate.size() && "no duplicates please!");
2005
2006 for (size_t i = 0; i < toUpdate.size(); i++) {
2007 CallSite &CS = toUpdate[i];
2008 assert(CS.getInstruction()->getParent()->getParent() == &F);
2009 assert(isStatepoint(CS) && "expected to already be a deopt statepoint");
2010 }
2011#endif
2012
Philip Reames69e51ca2015-04-13 18:07:21 +00002013 // When inserting gc.relocates for invokes, we need to be able to insert at
2014 // the top of the successor blocks. See the comment on
2015 // normalForInvokeSafepoint on exactly what is needed. Note that this step
Philip Reamesf209a152015-04-13 20:00:30 +00002016 // may restructure the CFG.
2017 for (CallSite CS : toUpdate) {
2018 if (!CS.isInvoke())
2019 continue;
2020 InvokeInst *invoke = cast<InvokeInst>(CS.getInstruction());
2021 normalizeForInvokeSafepoint(invoke->getNormalDest(), invoke->getParent(),
Sanjoy Dasea45f0e2015-06-02 22:33:34 +00002022 DT);
Philip Reamesf209a152015-04-13 20:00:30 +00002023 normalizeForInvokeSafepoint(invoke->getUnwindDest(), invoke->getParent(),
Sanjoy Dasea45f0e2015-06-02 22:33:34 +00002024 DT);
Philip Reamesf209a152015-04-13 20:00:30 +00002025 }
Philip Reames69e51ca2015-04-13 18:07:21 +00002026
Philip Reamesd16a9b12015-02-20 01:06:44 +00002027 // A list of dummy calls added to the IR to keep various values obviously
2028 // live in the IR. We'll remove all of these when done.
Philip Reamesd2b66462015-02-20 22:39:41 +00002029 SmallVector<CallInst *, 64> holders;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002030
2031 // Insert a dummy call with all of the arguments to the vm_state we'll need
2032 // for the actual safepoint insertion. This ensures reference arguments in
2033 // the deopt argument list are considered live through the safepoint (and
2034 // thus makes sure they get relocated.)
2035 for (size_t i = 0; i < toUpdate.size(); i++) {
2036 CallSite &CS = toUpdate[i];
2037 Statepoint StatepointCS(CS);
2038
2039 SmallVector<Value *, 64> DeoptValues;
2040 for (Use &U : StatepointCS.vm_state_args()) {
2041 Value *Arg = cast<Value>(&U);
Philip Reames8531d8c2015-04-10 21:48:25 +00002042 assert(!isUnhandledGCPointerType(Arg->getType()) &&
2043 "support for FCA unimplemented");
2044 if (isHandledGCPointerType(Arg->getType()))
Philip Reamesd16a9b12015-02-20 01:06:44 +00002045 DeoptValues.push_back(Arg);
2046 }
2047 insertUseHolderAfter(CS, DeoptValues, holders);
2048 }
2049
Philip Reamesd2b66462015-02-20 22:39:41 +00002050 SmallVector<struct PartiallyConstructedSafepointRecord, 64> records;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002051 records.reserve(toUpdate.size());
2052 for (size_t i = 0; i < toUpdate.size(); i++) {
2053 struct PartiallyConstructedSafepointRecord info;
2054 records.push_back(info);
2055 }
2056 assert(records.size() == toUpdate.size());
2057
2058 // A) Identify all gc pointers which are staticly live at the given call
2059 // site.
2060 findLiveReferences(F, DT, P, toUpdate, records);
2061
Philip Reames8531d8c2015-04-10 21:48:25 +00002062 // Do a limited scalarization of any live at safepoint vector values which
2063 // contain pointers. This enables this pass to run after vectorization at
2064 // the cost of some possible performance loss. TODO: it would be nice to
2065 // natively support vectors all the way through the backend so we don't need
2066 // to scalarize here.
2067 for (size_t i = 0; i < records.size(); i++) {
2068 struct PartiallyConstructedSafepointRecord &info = records[i];
2069 Instruction *statepoint = toUpdate[i].getInstruction();
2070 splitVectorValues(cast<Instruction>(statepoint), info.liveset, DT);
2071 }
2072
Philip Reamesd16a9b12015-02-20 01:06:44 +00002073 // B) Find the base pointers for each live pointer
2074 /* scope for caching */ {
2075 // Cache the 'defining value' relation used in the computation and
2076 // insertion of base phis and selects. This ensures that we don't insert
2077 // large numbers of duplicate base_phis.
2078 DefiningValueMapTy DVCache;
2079
2080 for (size_t i = 0; i < records.size(); i++) {
2081 struct PartiallyConstructedSafepointRecord &info = records[i];
2082 CallSite &CS = toUpdate[i];
2083 findBasePointers(DT, DVCache, CS, info);
2084 }
2085 } // end of cache scope
2086
2087 // The base phi insertion logic (for any safepoint) may have inserted new
2088 // instructions which are now live at some safepoint. The simplest such
2089 // example is:
2090 // loop:
2091 // phi a <-- will be a new base_phi here
2092 // safepoint 1 <-- that needs to be live here
2093 // gep a + 1
2094 // safepoint 2
2095 // br loop
Philip Reamesd16a9b12015-02-20 01:06:44 +00002096 // We insert some dummy calls after each safepoint to definitely hold live
2097 // the base pointers which were identified for that safepoint. We'll then
2098 // ask liveness for _every_ base inserted to see what is now live. Then we
2099 // remove the dummy calls.
2100 holders.reserve(holders.size() + records.size());
2101 for (size_t i = 0; i < records.size(); i++) {
2102 struct PartiallyConstructedSafepointRecord &info = records[i];
2103 CallSite &CS = toUpdate[i];
2104
2105 SmallVector<Value *, 128> Bases;
Philip Reamesf2041322015-02-20 19:26:04 +00002106 for (auto Pair : info.PointerToBase) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00002107 Bases.push_back(Pair.second);
2108 }
2109 insertUseHolderAfter(CS, Bases, holders);
2110 }
2111
Philip Reamesdf1ef082015-04-10 22:53:14 +00002112 // By selecting base pointers, we've effectively inserted new uses. Thus, we
2113 // need to rerun liveness. We may *also* have inserted new defs, but that's
2114 // not the key issue.
2115 recomputeLiveInValues(F, DT, P, toUpdate, records);
Philip Reamesd16a9b12015-02-20 01:06:44 +00002116
Philip Reamesd16a9b12015-02-20 01:06:44 +00002117 if (PrintBasePointers) {
2118 for (size_t i = 0; i < records.size(); i++) {
2119 struct PartiallyConstructedSafepointRecord &info = records[i];
2120 errs() << "Base Pairs: (w/Relocation)\n";
Philip Reamesf2041322015-02-20 19:26:04 +00002121 for (auto Pair : info.PointerToBase) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00002122 errs() << " derived %" << Pair.first->getName() << " base %"
2123 << Pair.second->getName() << "\n";
2124 }
2125 }
2126 }
2127 for (size_t i = 0; i < holders.size(); i++) {
2128 holders[i]->eraseFromParent();
2129 holders[i] = nullptr;
2130 }
2131 holders.clear();
2132
Igor Laevskye0317182015-05-19 15:59:05 +00002133 // In order to reduce live set of statepoint we might choose to rematerialize
2134 // some values instead of relocating them. This is purelly an optimization and
2135 // does not influence correctness.
2136 TargetTransformInfo &TTI =
2137 P->getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
2138
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +00002139 for (size_t i = 0; i < records.size(); i++) {
Igor Laevskye0317182015-05-19 15:59:05 +00002140 struct PartiallyConstructedSafepointRecord &info = records[i];
2141 CallSite &CS = toUpdate[i];
2142
2143 rematerializeLiveValues(CS, info, TTI);
2144 }
2145
Philip Reamesd16a9b12015-02-20 01:06:44 +00002146 // Now run through and replace the existing statepoints with new ones with
2147 // the live variables listed. We do not yet update uses of the values being
2148 // relocated. We have references to live variables that need to
2149 // survive to the last iteration of this loop. (By construction, the
2150 // previous statepoint can not be a live variable, thus we can and remove
2151 // the old statepoint calls as we go.)
2152 for (size_t i = 0; i < records.size(); i++) {
2153 struct PartiallyConstructedSafepointRecord &info = records[i];
2154 CallSite &CS = toUpdate[i];
2155 makeStatepointExplicit(DT, CS, P, info);
2156 }
2157 toUpdate.clear(); // prevent accident use of invalid CallSites
2158
Philip Reamesd16a9b12015-02-20 01:06:44 +00002159 // Do all the fixups of the original live variables to their relocated selves
Philip Reamesd2b66462015-02-20 22:39:41 +00002160 SmallVector<Value *, 128> live;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002161 for (size_t i = 0; i < records.size(); i++) {
2162 struct PartiallyConstructedSafepointRecord &info = records[i];
2163 // We can't simply save the live set from the original insertion. One of
2164 // the live values might be the result of a call which needs a safepoint.
2165 // That Value* no longer exists and we need to use the new gc_result.
2166 // Thankfully, the liveset is embedded in the statepoint (and updated), so
2167 // we just grab that.
Philip Reames0a3240f2015-02-20 21:34:11 +00002168 Statepoint statepoint(info.StatepointToken);
Philip Reamesd16a9b12015-02-20 01:06:44 +00002169 live.insert(live.end(), statepoint.gc_args_begin(),
2170 statepoint.gc_args_end());
Philip Reames9a2e01d2015-04-13 17:35:55 +00002171#ifndef NDEBUG
2172 // Do some basic sanity checks on our liveness results before performing
2173 // relocation. Relocation can and will turn mistakes in liveness results
2174 // into non-sensical code which is must harder to debug.
2175 // TODO: It would be nice to test consistency as well
2176 assert(DT.isReachableFromEntry(info.StatepointToken->getParent()) &&
2177 "statepoint must be reachable or liveness is meaningless");
2178 for (Value *V : statepoint.gc_args()) {
2179 if (!isa<Instruction>(V))
2180 // Non-instruction values trivial dominate all possible uses
2181 continue;
2182 auto LiveInst = cast<Instruction>(V);
2183 assert(DT.isReachableFromEntry(LiveInst->getParent()) &&
2184 "unreachable values should never be live");
2185 assert(DT.dominates(LiveInst, info.StatepointToken) &&
2186 "basic SSA liveness expectation violated by liveness analysis");
2187 }
2188#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +00002189 }
2190 unique_unsorted(live);
2191
Nick Lewyckyeb3231e2015-02-20 07:14:02 +00002192#ifndef NDEBUG
Philip Reamesd16a9b12015-02-20 01:06:44 +00002193 // sanity check
2194 for (auto ptr : live) {
2195 assert(isGCPointerType(ptr->getType()) && "must be a gc pointer type");
2196 }
Nick Lewyckyeb3231e2015-02-20 07:14:02 +00002197#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +00002198
2199 relocationViaAlloca(F, DT, live, records);
2200 return !records.empty();
2201}
2202
2203/// Returns true if this function should be rewritten by this pass. The main
2204/// point of this function is as an extension point for custom logic.
2205static bool shouldRewriteStatepointsIn(Function &F) {
2206 // TODO: This should check the GCStrategy
Philip Reames2ef029c2015-02-20 18:56:14 +00002207 if (F.hasGC()) {
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +00002208 const char *FunctionGCName = F.getGC();
2209 const StringRef StatepointExampleName("statepoint-example");
2210 const StringRef CoreCLRName("coreclr");
2211 return (StatepointExampleName == FunctionGCName) ||
NAKAMURA Takumi5582a6a2015-05-25 01:43:34 +00002212 (CoreCLRName == FunctionGCName);
2213 } else
Philip Reames2ef029c2015-02-20 18:56:14 +00002214 return false;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002215}
2216
2217bool RewriteStatepointsForGC::runOnFunction(Function &F) {
2218 // Nothing to do for declarations.
2219 if (F.isDeclaration() || F.empty())
2220 return false;
2221
2222 // Policy choice says not to rewrite - the most common reason is that we're
2223 // compiling code without a GCStrategy.
2224 if (!shouldRewriteStatepointsIn(F))
2225 return false;
2226
Sanjoy Dasea45f0e2015-06-02 22:33:34 +00002227 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
Philip Reames704e78b2015-04-10 22:34:56 +00002228
Philip Reames85b36a82015-04-10 22:07:04 +00002229 // Gather all the statepoints which need rewritten. Be careful to only
2230 // consider those in reachable code since we need to ask dominance queries
2231 // when rewriting. We'll delete the unreachable ones in a moment.
Philip Reamesd2b66462015-02-20 22:39:41 +00002232 SmallVector<CallSite, 64> ParsePointNeeded;
Philip Reamesf66d7372015-04-10 22:16:58 +00002233 bool HasUnreachableStatepoint = false;
Philip Reamesd2b66462015-02-20 22:39:41 +00002234 for (Instruction &I : inst_range(F)) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00002235 // TODO: only the ones with the flag set!
Philip Reames85b36a82015-04-10 22:07:04 +00002236 if (isStatepoint(I)) {
2237 if (DT.isReachableFromEntry(I.getParent()))
2238 ParsePointNeeded.push_back(CallSite(&I));
2239 else
Philip Reamesf66d7372015-04-10 22:16:58 +00002240 HasUnreachableStatepoint = true;
Philip Reames85b36a82015-04-10 22:07:04 +00002241 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00002242 }
2243
Philip Reames85b36a82015-04-10 22:07:04 +00002244 bool MadeChange = false;
Philip Reames704e78b2015-04-10 22:34:56 +00002245
Philip Reames85b36a82015-04-10 22:07:04 +00002246 // Delete any unreachable statepoints so that we don't have unrewritten
2247 // statepoints surviving this pass. This makes testing easier and the
2248 // resulting IR less confusing to human readers. Rather than be fancy, we
2249 // just reuse a utility function which removes the unreachable blocks.
Philip Reamesf66d7372015-04-10 22:16:58 +00002250 if (HasUnreachableStatepoint)
Philip Reames85b36a82015-04-10 22:07:04 +00002251 MadeChange |= removeUnreachableBlocks(F);
2252
Philip Reamesd16a9b12015-02-20 01:06:44 +00002253 // Return early if no work to do.
2254 if (ParsePointNeeded.empty())
Philip Reames85b36a82015-04-10 22:07:04 +00002255 return MadeChange;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002256
Philip Reames85b36a82015-04-10 22:07:04 +00002257 // As a prepass, go ahead and aggressively destroy single entry phi nodes.
2258 // These are created by LCSSA. They have the effect of increasing the size
2259 // of liveness sets for no good reason. It may be harder to do this post
2260 // insertion since relocations and base phis can confuse things.
2261 for (BasicBlock &BB : F)
2262 if (BB.getUniquePredecessor()) {
2263 MadeChange = true;
2264 FoldSingleEntryPHINodes(&BB);
2265 }
2266
2267 MadeChange |= insertParsePoints(F, DT, this, ParsePointNeeded);
2268 return MadeChange;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002269}
Philip Reamesdf1ef082015-04-10 22:53:14 +00002270
2271// liveness computation via standard dataflow
2272// -------------------------------------------------------------------
2273
2274// TODO: Consider using bitvectors for liveness, the set of potentially
2275// interesting values should be small and easy to pre-compute.
2276
Philip Reamesdf1ef082015-04-10 22:53:14 +00002277/// Compute the live-in set for the location rbegin starting from
2278/// the live-out set of the basic block
2279static void computeLiveInValues(BasicBlock::reverse_iterator rbegin,
2280 BasicBlock::reverse_iterator rend,
2281 DenseSet<Value *> &LiveTmp) {
2282
2283 for (BasicBlock::reverse_iterator ritr = rbegin; ritr != rend; ritr++) {
2284 Instruction *I = &*ritr;
2285
2286 // KILL/Def - Remove this definition from LiveIn
2287 LiveTmp.erase(I);
2288
2289 // Don't consider *uses* in PHI nodes, we handle their contribution to
2290 // predecessor blocks when we seed the LiveOut sets
2291 if (isa<PHINode>(I))
2292 continue;
2293
2294 // USE - Add to the LiveIn set for this instruction
2295 for (Value *V : I->operands()) {
2296 assert(!isUnhandledGCPointerType(V->getType()) &&
2297 "support for FCA unimplemented");
Philip Reames63294cb2015-04-26 19:48:03 +00002298 if (isHandledGCPointerType(V->getType()) && !isa<Constant>(V)) {
2299 // The choice to exclude all things constant here is slightly subtle.
2300 // There are two idependent reasons:
2301 // - We assume that things which are constant (from LLVM's definition)
2302 // do not move at runtime. For example, the address of a global
2303 // variable is fixed, even though it's contents may not be.
2304 // - Second, we can't disallow arbitrary inttoptr constants even
2305 // if the language frontend does. Optimization passes are free to
2306 // locally exploit facts without respect to global reachability. This
2307 // can create sections of code which are dynamically unreachable and
2308 // contain just about anything. (see constants.ll in tests)
Philip Reamesdf1ef082015-04-10 22:53:14 +00002309 LiveTmp.insert(V);
2310 }
2311 }
2312 }
2313}
2314
2315static void computeLiveOutSeed(BasicBlock *BB, DenseSet<Value *> &LiveTmp) {
2316
2317 for (BasicBlock *Succ : successors(BB)) {
2318 const BasicBlock::iterator E(Succ->getFirstNonPHI());
2319 for (BasicBlock::iterator I = Succ->begin(); I != E; I++) {
2320 PHINode *Phi = cast<PHINode>(&*I);
2321 Value *V = Phi->getIncomingValueForBlock(BB);
2322 assert(!isUnhandledGCPointerType(V->getType()) &&
2323 "support for FCA unimplemented");
Philip Reames63294cb2015-04-26 19:48:03 +00002324 if (isHandledGCPointerType(V->getType()) && !isa<Constant>(V)) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00002325 LiveTmp.insert(V);
2326 }
2327 }
2328 }
2329}
2330
2331static DenseSet<Value *> computeKillSet(BasicBlock *BB) {
2332 DenseSet<Value *> KillSet;
2333 for (Instruction &I : *BB)
2334 if (isHandledGCPointerType(I.getType()))
2335 KillSet.insert(&I);
2336 return KillSet;
2337}
2338
Philip Reames9638ff92015-04-11 00:06:47 +00002339#ifndef NDEBUG
Philip Reamesdf1ef082015-04-10 22:53:14 +00002340/// Check that the items in 'Live' dominate 'TI'. This is used as a basic
2341/// sanity check for the liveness computation.
2342static void checkBasicSSA(DominatorTree &DT, DenseSet<Value *> &Live,
2343 TerminatorInst *TI, bool TermOkay = false) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00002344 for (Value *V : Live) {
2345 if (auto *I = dyn_cast<Instruction>(V)) {
2346 // The terminator can be a member of the LiveOut set. LLVM's definition
2347 // of instruction dominance states that V does not dominate itself. As
2348 // such, we need to special case this to allow it.
2349 if (TermOkay && TI == I)
2350 continue;
2351 assert(DT.dominates(I, TI) &&
2352 "basic SSA liveness expectation violated by liveness analysis");
2353 }
2354 }
Philip Reamesdf1ef082015-04-10 22:53:14 +00002355}
2356
2357/// Check that all the liveness sets used during the computation of liveness
2358/// obey basic SSA properties. This is useful for finding cases where we miss
2359/// a def.
2360static void checkBasicSSA(DominatorTree &DT, GCPtrLivenessData &Data,
2361 BasicBlock &BB) {
2362 checkBasicSSA(DT, Data.LiveSet[&BB], BB.getTerminator());
2363 checkBasicSSA(DT, Data.LiveOut[&BB], BB.getTerminator(), true);
2364 checkBasicSSA(DT, Data.LiveIn[&BB], BB.getTerminator());
2365}
Philip Reames9638ff92015-04-11 00:06:47 +00002366#endif
Philip Reamesdf1ef082015-04-10 22:53:14 +00002367
2368static void computeLiveInValues(DominatorTree &DT, Function &F,
2369 GCPtrLivenessData &Data) {
2370
Philip Reames4d80ede2015-04-10 23:11:26 +00002371 SmallSetVector<BasicBlock *, 200> Worklist;
Philip Reamesdf1ef082015-04-10 22:53:14 +00002372 auto AddPredsToWorklist = [&](BasicBlock *BB) {
Philip Reames4d80ede2015-04-10 23:11:26 +00002373 // We use a SetVector so that we don't have duplicates in the worklist.
2374 Worklist.insert(pred_begin(BB), pred_end(BB));
Philip Reamesdf1ef082015-04-10 22:53:14 +00002375 };
2376 auto NextItem = [&]() {
2377 BasicBlock *BB = Worklist.back();
2378 Worklist.pop_back();
Philip Reamesdf1ef082015-04-10 22:53:14 +00002379 return BB;
2380 };
2381
2382 // Seed the liveness for each individual block
2383 for (BasicBlock &BB : F) {
2384 Data.KillSet[&BB] = computeKillSet(&BB);
2385 Data.LiveSet[&BB].clear();
2386 computeLiveInValues(BB.rbegin(), BB.rend(), Data.LiveSet[&BB]);
2387
2388#ifndef NDEBUG
2389 for (Value *Kill : Data.KillSet[&BB])
2390 assert(!Data.LiveSet[&BB].count(Kill) && "live set contains kill");
2391#endif
2392
2393 Data.LiveOut[&BB] = DenseSet<Value *>();
2394 computeLiveOutSeed(&BB, Data.LiveOut[&BB]);
2395 Data.LiveIn[&BB] = Data.LiveSet[&BB];
2396 set_union(Data.LiveIn[&BB], Data.LiveOut[&BB]);
2397 set_subtract(Data.LiveIn[&BB], Data.KillSet[&BB]);
2398 if (!Data.LiveIn[&BB].empty())
2399 AddPredsToWorklist(&BB);
2400 }
2401
2402 // Propagate that liveness until stable
2403 while (!Worklist.empty()) {
2404 BasicBlock *BB = NextItem();
2405
2406 // Compute our new liveout set, then exit early if it hasn't changed
2407 // despite the contribution of our successor.
2408 DenseSet<Value *> LiveOut = Data.LiveOut[BB];
2409 const auto OldLiveOutSize = LiveOut.size();
2410 for (BasicBlock *Succ : successors(BB)) {
2411 assert(Data.LiveIn.count(Succ));
2412 set_union(LiveOut, Data.LiveIn[Succ]);
2413 }
2414 // assert OutLiveOut is a subset of LiveOut
2415 if (OldLiveOutSize == LiveOut.size()) {
2416 // If the sets are the same size, then we didn't actually add anything
2417 // when unioning our successors LiveIn Thus, the LiveIn of this block
2418 // hasn't changed.
2419 continue;
2420 }
2421 Data.LiveOut[BB] = LiveOut;
2422
2423 // Apply the effects of this basic block
2424 DenseSet<Value *> LiveTmp = LiveOut;
2425 set_union(LiveTmp, Data.LiveSet[BB]);
2426 set_subtract(LiveTmp, Data.KillSet[BB]);
2427
2428 assert(Data.LiveIn.count(BB));
2429 const DenseSet<Value *> &OldLiveIn = Data.LiveIn[BB];
2430 // assert: OldLiveIn is a subset of LiveTmp
2431 if (OldLiveIn.size() != LiveTmp.size()) {
2432 Data.LiveIn[BB] = LiveTmp;
2433 AddPredsToWorklist(BB);
2434 }
2435 } // while( !worklist.empty() )
2436
2437#ifndef NDEBUG
2438 // Sanity check our ouput against SSA properties. This helps catch any
2439 // missing kills during the above iteration.
2440 for (BasicBlock &BB : F) {
2441 checkBasicSSA(DT, Data, BB);
2442 }
2443#endif
2444}
2445
2446static void findLiveSetAtInst(Instruction *Inst, GCPtrLivenessData &Data,
2447 StatepointLiveSetTy &Out) {
2448
2449 BasicBlock *BB = Inst->getParent();
2450
2451 // Note: The copy is intentional and required
2452 assert(Data.LiveOut.count(BB));
2453 DenseSet<Value *> LiveOut = Data.LiveOut[BB];
2454
2455 // We want to handle the statepoint itself oddly. It's
2456 // call result is not live (normal), nor are it's arguments
2457 // (unless they're used again later). This adjustment is
2458 // specifically what we need to relocate
2459 BasicBlock::reverse_iterator rend(Inst);
2460 computeLiveInValues(BB->rbegin(), rend, LiveOut);
2461 LiveOut.erase(Inst);
2462 Out.insert(LiveOut.begin(), LiveOut.end());
2463}
2464
2465static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData,
2466 const CallSite &CS,
2467 PartiallyConstructedSafepointRecord &Info) {
2468 Instruction *Inst = CS.getInstruction();
2469 StatepointLiveSetTy Updated;
2470 findLiveSetAtInst(Inst, RevisedLivenessData, Updated);
2471
2472#ifndef NDEBUG
2473 DenseSet<Value *> Bases;
2474 for (auto KVPair : Info.PointerToBase) {
2475 Bases.insert(KVPair.second);
2476 }
2477#endif
2478 // We may have base pointers which are now live that weren't before. We need
2479 // to update the PointerToBase structure to reflect this.
2480 for (auto V : Updated)
2481 if (!Info.PointerToBase.count(V)) {
2482 assert(Bases.count(V) && "can't find base for unexpected live value");
2483 Info.PointerToBase[V] = V;
2484 continue;
2485 }
2486
2487#ifndef NDEBUG
2488 for (auto V : Updated) {
2489 assert(Info.PointerToBase.count(V) &&
2490 "must be able to find base for live value");
2491 }
2492#endif
2493
2494 // Remove any stale base mappings - this can happen since our liveness is
2495 // more precise then the one inherent in the base pointer analysis
2496 DenseSet<Value *> ToErase;
2497 for (auto KVPair : Info.PointerToBase)
2498 if (!Updated.count(KVPair.first))
2499 ToErase.insert(KVPair.first);
2500 for (auto V : ToErase)
2501 Info.PointerToBase.erase(V);
2502
2503#ifndef NDEBUG
2504 for (auto KVPair : Info.PointerToBase)
2505 assert(Updated.count(KVPair.first) && "record for non-live value");
2506#endif
2507
2508 Info.liveset = Updated;
2509}