blob: ba48e0a74b0b510acac0f3c28664b7caed2a039f [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"
17#include "llvm/ADT/SetOperations.h"
18#include "llvm/ADT/Statistic.h"
19#include "llvm/ADT/DenseSet.h"
Philip Reames4d80ede2015-04-10 23:11:26 +000020#include "llvm/ADT/SetVector.h"
Philip Reamesd16a9b12015-02-20 01:06:44 +000021#include "llvm/IR/BasicBlock.h"
22#include "llvm/IR/CallSite.h"
23#include "llvm/IR/Dominators.h"
24#include "llvm/IR/Function.h"
25#include "llvm/IR/IRBuilder.h"
26#include "llvm/IR/InstIterator.h"
27#include "llvm/IR/Instructions.h"
28#include "llvm/IR/Intrinsics.h"
29#include "llvm/IR/IntrinsicInst.h"
30#include "llvm/IR/Module.h"
31#include "llvm/IR/Statepoint.h"
32#include "llvm/IR/Value.h"
33#include "llvm/IR/Verifier.h"
34#include "llvm/Support/Debug.h"
35#include "llvm/Support/CommandLine.h"
36#include "llvm/Transforms/Scalar.h"
37#include "llvm/Transforms/Utils/BasicBlockUtils.h"
38#include "llvm/Transforms/Utils/Cloning.h"
39#include "llvm/Transforms/Utils/Local.h"
40#include "llvm/Transforms/Utils/PromoteMemToReg.h"
41
42#define DEBUG_TYPE "rewrite-statepoints-for-gc"
43
44using namespace llvm;
45
46// Print tracing output
47static cl::opt<bool> TraceLSP("trace-rewrite-statepoints", cl::Hidden,
48 cl::init(false));
49
50// Print the liveset found at the insert location
51static cl::opt<bool> PrintLiveSet("spp-print-liveset", cl::Hidden,
52 cl::init(false));
Philip Reames704e78b2015-04-10 22:34:56 +000053static cl::opt<bool> PrintLiveSetSize("spp-print-liveset-size", cl::Hidden,
54 cl::init(false));
Philip Reamesd16a9b12015-02-20 01:06:44 +000055// Print out the base pointers for debugging
Philip Reames704e78b2015-04-10 22:34:56 +000056static cl::opt<bool> PrintBasePointers("spp-print-base-pointers", cl::Hidden,
57 cl::init(false));
Philip Reamesd16a9b12015-02-20 01:06:44 +000058
Philip Reamese73300b2015-04-13 16:41:32 +000059#ifdef XDEBUG
60static bool ClobberNonLive = true;
61#else
62static bool ClobberNonLive = false;
63#endif
64static cl::opt<bool, true> ClobberNonLiveOverride("rs4gc-clobber-non-live",
65 cl::location(ClobberNonLive),
66 cl::Hidden);
67
Benjamin Kramer6f665452015-02-20 14:00:58 +000068namespace {
Philip Reamesd16a9b12015-02-20 01:06:44 +000069struct RewriteStatepointsForGC : public FunctionPass {
70 static char ID; // Pass identification, replacement for typeid
71
72 RewriteStatepointsForGC() : FunctionPass(ID) {
73 initializeRewriteStatepointsForGCPass(*PassRegistry::getPassRegistry());
74 }
75 bool runOnFunction(Function &F) override;
76
77 void getAnalysisUsage(AnalysisUsage &AU) const override {
78 // We add and rewrite a bunch of instructions, but don't really do much
79 // else. We could in theory preserve a lot more analyses here.
80 AU.addRequired<DominatorTreeWrapperPass>();
81 }
82};
Benjamin Kramer6f665452015-02-20 14:00:58 +000083} // namespace
Philip Reamesd16a9b12015-02-20 01:06:44 +000084
85char RewriteStatepointsForGC::ID = 0;
86
87FunctionPass *llvm::createRewriteStatepointsForGCPass() {
88 return new RewriteStatepointsForGC();
89}
90
91INITIALIZE_PASS_BEGIN(RewriteStatepointsForGC, "rewrite-statepoints-for-gc",
92 "Make relocations explicit at statepoints", false, false)
93INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
94INITIALIZE_PASS_END(RewriteStatepointsForGC, "rewrite-statepoints-for-gc",
95 "Make relocations explicit at statepoints", false, false)
96
97namespace {
Philip Reamesdf1ef082015-04-10 22:53:14 +000098struct GCPtrLivenessData {
99 /// Values defined in this block.
100 DenseMap<BasicBlock *, DenseSet<Value *>> KillSet;
101 /// Values used in this block (and thus live); does not included values
102 /// killed within this block.
103 DenseMap<BasicBlock *, DenseSet<Value *>> LiveSet;
104
105 /// Values live into this basic block (i.e. used by any
106 /// instruction in this basic block or ones reachable from here)
107 DenseMap<BasicBlock *, DenseSet<Value *>> LiveIn;
108
109 /// Values live out of this basic block (i.e. live into
110 /// any successor block)
111 DenseMap<BasicBlock *, DenseSet<Value *>> LiveOut;
112};
113
Philip Reamesd16a9b12015-02-20 01:06:44 +0000114// The type of the internal cache used inside the findBasePointers family
115// of functions. From the callers perspective, this is an opaque type and
116// should not be inspected.
117//
118// In the actual implementation this caches two relations:
119// - The base relation itself (i.e. this pointer is based on that one)
120// - The base defining value relation (i.e. before base_phi insertion)
121// Generally, after the execution of a full findBasePointer call, only the
122// base relation will remain. Internally, we add a mixture of the two
123// types, then update all the second type to the first type
Philip Reamese9c3b9b2015-02-20 22:48:20 +0000124typedef DenseMap<Value *, Value *> DefiningValueMapTy;
Philip Reames1f017542015-02-20 23:16:52 +0000125typedef DenseSet<llvm::Value *> StatepointLiveSetTy;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000126
Philip Reamesd16a9b12015-02-20 01:06:44 +0000127struct PartiallyConstructedSafepointRecord {
128 /// The set of values known to be live accross this safepoint
Philip Reames860660e2015-02-20 22:05:18 +0000129 StatepointLiveSetTy liveset;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000130
131 /// Mapping from live pointers to a base-defining-value
Philip Reamesf2041322015-02-20 19:26:04 +0000132 DenseMap<llvm::Value *, llvm::Value *> PointerToBase;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000133
Philip Reames0a3240f2015-02-20 21:34:11 +0000134 /// The *new* gc.statepoint instruction itself. This produces the token
135 /// that normal path gc.relocates and the gc.result are tied to.
136 Instruction *StatepointToken;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000137
Philip Reamesf2041322015-02-20 19:26:04 +0000138 /// Instruction to which exceptional gc relocates are attached
139 /// Makes it easier to iterate through them during relocationViaAlloca.
140 Instruction *UnwindToken;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000141};
142}
143
Philip Reamesdf1ef082015-04-10 22:53:14 +0000144/// Compute the live-in set for every basic block in the function
145static void computeLiveInValues(DominatorTree &DT, Function &F,
146 GCPtrLivenessData &Data);
147
148/// Given results from the dataflow liveness computation, find the set of live
149/// Values at a particular instruction.
150static void findLiveSetAtInst(Instruction *inst, GCPtrLivenessData &Data,
151 StatepointLiveSetTy &out);
152
Philip Reamesd16a9b12015-02-20 01:06:44 +0000153// TODO: Once we can get to the GCStrategy, this becomes
154// Optional<bool> isGCManagedPointer(const Value *V) const override {
155
156static bool isGCPointerType(const Type *T) {
157 if (const PointerType *PT = dyn_cast<PointerType>(T))
158 // For the sake of this example GC, we arbitrarily pick addrspace(1) as our
159 // GC managed heap. We know that a pointer into this heap needs to be
160 // updated and that no other pointer does.
161 return (1 == PT->getAddressSpace());
162 return false;
163}
164
Philip Reames8531d8c2015-04-10 21:48:25 +0000165// Return true if this type is one which a) is a gc pointer or contains a GC
166// pointer and b) is of a type this code expects to encounter as a live value.
167// (The insertion code will assert that a type which matches (a) and not (b)
Philip Reames704e78b2015-04-10 22:34:56 +0000168// is not encountered.)
Philip Reames8531d8c2015-04-10 21:48:25 +0000169static bool isHandledGCPointerType(Type *T) {
170 // We fully support gc pointers
171 if (isGCPointerType(T))
172 return true;
173 // We partially support vectors of gc pointers. The code will assert if it
174 // can't handle something.
175 if (auto VT = dyn_cast<VectorType>(T))
176 if (isGCPointerType(VT->getElementType()))
177 return true;
178 return false;
179}
180
181#ifndef NDEBUG
182/// Returns true if this type contains a gc pointer whether we know how to
183/// handle that type or not.
184static bool containsGCPtrType(Type *Ty) {
Philip Reames704e78b2015-04-10 22:34:56 +0000185 if (isGCPointerType(Ty))
Philip Reames8531d8c2015-04-10 21:48:25 +0000186 return true;
187 if (VectorType *VT = dyn_cast<VectorType>(Ty))
188 return isGCPointerType(VT->getScalarType());
189 if (ArrayType *AT = dyn_cast<ArrayType>(Ty))
190 return containsGCPtrType(AT->getElementType());
191 if (StructType *ST = dyn_cast<StructType>(Ty))
Philip Reames704e78b2015-04-10 22:34:56 +0000192 return std::any_of(
193 ST->subtypes().begin(), ST->subtypes().end(),
194 [](Type *SubType) { return containsGCPtrType(SubType); });
Philip Reames8531d8c2015-04-10 21:48:25 +0000195 return false;
196}
197
198// Returns true if this is a type which a) is a gc pointer or contains a GC
199// pointer and b) is of a type which the code doesn't expect (i.e. first class
200// aggregates). Used to trip assertions.
201static bool isUnhandledGCPointerType(Type *Ty) {
202 return containsGCPtrType(Ty) && !isHandledGCPointerType(Ty);
203}
204#endif
205
Philip Reamesd16a9b12015-02-20 01:06:44 +0000206static bool order_by_name(llvm::Value *a, llvm::Value *b) {
207 if (a->hasName() && b->hasName()) {
208 return -1 == a->getName().compare(b->getName());
209 } else if (a->hasName() && !b->hasName()) {
210 return true;
211 } else if (!a->hasName() && b->hasName()) {
212 return false;
213 } else {
214 // Better than nothing, but not stable
215 return a < b;
216 }
217}
218
Philip Reamesdf1ef082015-04-10 22:53:14 +0000219// Conservatively identifies any definitions which might be live at the
220// given instruction. The analysis is performed immediately before the
221// given instruction. Values defined by that instruction are not considered
222// live. Values used by that instruction are considered live.
223static void analyzeParsePointLiveness(
224 DominatorTree &DT, GCPtrLivenessData &OriginalLivenessData,
225 const CallSite &CS, PartiallyConstructedSafepointRecord &result) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000226 Instruction *inst = CS.getInstruction();
227
Philip Reames1f017542015-02-20 23:16:52 +0000228 StatepointLiveSetTy liveset;
Philip Reamesdf1ef082015-04-10 22:53:14 +0000229 findLiveSetAtInst(inst, OriginalLivenessData, liveset);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000230
231 if (PrintLiveSet) {
232 // Note: This output is used by several of the test cases
233 // The order of elemtns in a set is not stable, put them in a vec and sort
234 // by name
Philip Reames860660e2015-02-20 22:05:18 +0000235 SmallVector<Value *, 64> temp;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000236 temp.insert(temp.end(), liveset.begin(), liveset.end());
237 std::sort(temp.begin(), temp.end(), order_by_name);
238 errs() << "Live Variables:\n";
239 for (Value *V : temp) {
240 errs() << " " << V->getName(); // no newline
241 V->dump();
242 }
243 }
244 if (PrintLiveSetSize) {
245 errs() << "Safepoint For: " << CS.getCalledValue()->getName() << "\n";
246 errs() << "Number live values: " << liveset.size() << "\n";
247 }
248 result.liveset = liveset;
249}
250
Philip Reames8531d8c2015-04-10 21:48:25 +0000251/// If we can trivially determine that this vector contains only base pointers,
Philip Reames704e78b2015-04-10 22:34:56 +0000252/// return the base instruction.
Philip Reames8531d8c2015-04-10 21:48:25 +0000253static Value *findBaseOfVector(Value *I) {
254 assert(I->getType()->isVectorTy() &&
255 cast<VectorType>(I->getType())->getElementType()->isPointerTy() &&
256 "Illegal to ask for the base pointer of a non-pointer type");
257
258 // Each case parallels findBaseDefiningValue below, see that code for
259 // detailed motivation.
260
261 if (isa<Argument>(I))
262 // An incoming argument to the function is a base pointer
263 return I;
264
265 // We shouldn't see the address of a global as a vector value?
266 assert(!isa<GlobalVariable>(I) &&
267 "unexpected global variable found in base of vector");
268
269 // inlining could possibly introduce phi node that contains
270 // undef if callee has multiple returns
271 if (isa<UndefValue>(I))
272 // utterly meaningless, but useful for dealing with partially optimized
273 // code.
Philip Reames704e78b2015-04-10 22:34:56 +0000274 return I;
Philip Reames8531d8c2015-04-10 21:48:25 +0000275
276 // Due to inheritance, this must be _after_ the global variable and undef
277 // checks
278 if (Constant *Con = dyn_cast<Constant>(I)) {
279 assert(!isa<GlobalVariable>(I) && !isa<UndefValue>(I) &&
280 "order of checks wrong!");
281 assert(Con->isNullValue() && "null is the only case which makes sense");
282 return Con;
283 }
284
285 if (isa<LoadInst>(I))
286 return I;
287
288 // Note: This code is currently rather incomplete. We are essentially only
289 // handling cases where the vector element is trivially a base pointer. We
290 // need to update the entire base pointer construction algorithm to know how
291 // to track vector elements and potentially scalarize, but the case which
292 // would motivate the work hasn't shown up in real workloads yet.
293 llvm_unreachable("no base found for vector element");
294}
295
Philip Reamesd16a9b12015-02-20 01:06:44 +0000296/// Helper function for findBasePointer - Will return a value which either a)
297/// defines the base pointer for the input or b) blocks the simple search
298/// (i.e. a PHI or Select of two derived pointers)
299static Value *findBaseDefiningValue(Value *I) {
300 assert(I->getType()->isPointerTy() &&
301 "Illegal to ask for the base pointer of a non-pointer type");
302
Philip Reames8531d8c2015-04-10 21:48:25 +0000303 // This case is a bit of a hack - it only handles extracts from vectors which
304 // trivially contain only base pointers. See note inside the function for
305 // how to improve this.
306 if (auto *EEI = dyn_cast<ExtractElementInst>(I)) {
307 Value *VectorOperand = EEI->getVectorOperand();
308 Value *VectorBase = findBaseOfVector(VectorOperand);
Philip Reamesf66d7372015-04-10 22:16:58 +0000309 (void)VectorBase;
Philip Reames8531d8c2015-04-10 21:48:25 +0000310 assert(VectorBase && "extract element not known to be a trivial base");
311 return EEI;
312 }
Philip Reamesd16a9b12015-02-20 01:06:44 +0000313
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000314 if (isa<Argument>(I))
Philip Reamesd16a9b12015-02-20 01:06:44 +0000315 // An incoming argument to the function is a base pointer
316 // We should have never reached here if this argument isn't an gc value
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000317 return I;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000318
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000319 if (isa<GlobalVariable>(I))
Philip Reamesd16a9b12015-02-20 01:06:44 +0000320 // base case
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000321 return I;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000322
323 // inlining could possibly introduce phi node that contains
324 // undef if callee has multiple returns
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000325 if (isa<UndefValue>(I))
326 // utterly meaningless, but useful for dealing with
327 // partially optimized code.
Philip Reames704e78b2015-04-10 22:34:56 +0000328 return I;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000329
330 // Due to inheritance, this must be _after_ the global variable and undef
331 // checks
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000332 if (Constant *Con = dyn_cast<Constant>(I)) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000333 assert(!isa<GlobalVariable>(I) && !isa<UndefValue>(I) &&
334 "order of checks wrong!");
335 // Note: Finding a constant base for something marked for relocation
336 // doesn't really make sense. The most likely case is either a) some
337 // screwed up the address space usage or b) your validating against
338 // compiled C++ code w/o the proper separation. The only real exception
339 // is a null pointer. You could have generic code written to index of
340 // off a potentially null value and have proven it null. We also use
341 // null pointers in dead paths of relocation phis (which we might later
342 // want to find a base pointer for).
Philip Reames24c6cd52015-03-27 05:47:00 +0000343 assert(isa<ConstantPointerNull>(Con) &&
344 "null is the only case which makes sense");
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000345 return Con;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000346 }
347
348 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000349 Value *Def = CI->stripPointerCasts();
David Blaikie82ad7872015-02-20 23:44:24 +0000350 // If we find a cast instruction here, it means we've found a cast which is
351 // not simply a pointer cast (i.e. an inttoptr). We don't know how to
352 // handle int->ptr conversion.
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000353 assert(!isa<CastInst>(Def) && "shouldn't find another cast here");
354 return findBaseDefiningValue(Def);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000355 }
356
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000357 if (isa<LoadInst>(I))
358 return I; // The value loaded is an gc base itself
Philip Reamesd16a9b12015-02-20 01:06:44 +0000359
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000360 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I))
361 // The base of this GEP is the base
362 return findBaseDefiningValue(GEP->getPointerOperand());
Philip Reamesd16a9b12015-02-20 01:06:44 +0000363
364 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
365 switch (II->getIntrinsicID()) {
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000366 case Intrinsic::experimental_gc_result_ptr:
Philip Reamesd16a9b12015-02-20 01:06:44 +0000367 default:
368 // fall through to general call handling
369 break;
370 case Intrinsic::experimental_gc_statepoint:
371 case Intrinsic::experimental_gc_result_float:
372 case Intrinsic::experimental_gc_result_int:
373 llvm_unreachable("these don't produce pointers");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000374 case Intrinsic::experimental_gc_relocate: {
375 // Rerunning safepoint insertion after safepoints are already
376 // inserted is not supported. It could probably be made to work,
377 // but why are you doing this? There's no good reason.
378 llvm_unreachable("repeat safepoint insertion is not supported");
379 }
380 case Intrinsic::gcroot:
381 // Currently, this mechanism hasn't been extended to work with gcroot.
382 // There's no reason it couldn't be, but I haven't thought about the
383 // implications much.
384 llvm_unreachable(
385 "interaction with the gcroot mechanism is not supported");
386 }
387 }
388 // We assume that functions in the source language only return base
389 // pointers. This should probably be generalized via attributes to support
390 // both source language and internal functions.
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000391 if (isa<CallInst>(I) || isa<InvokeInst>(I))
392 return I;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000393
394 // I have absolutely no idea how to implement this part yet. It's not
395 // neccessarily hard, I just haven't really looked at it yet.
396 assert(!isa<LandingPadInst>(I) && "Landing Pad is unimplemented");
397
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000398 if (isa<AtomicCmpXchgInst>(I))
Philip Reamesd16a9b12015-02-20 01:06:44 +0000399 // A CAS is effectively a atomic store and load combined under a
400 // predicate. From the perspective of base pointers, we just treat it
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000401 // like a load.
402 return I;
Philip Reames704e78b2015-04-10 22:34:56 +0000403
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000404 assert(!isa<AtomicRMWInst>(I) && "Xchg handled above, all others are "
Philip Reames704e78b2015-04-10 22:34:56 +0000405 "binary ops which don't apply to pointers");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000406
407 // The aggregate ops. Aggregates can either be in the heap or on the
408 // stack, but in either case, this is simply a field load. As a result,
409 // this is a defining definition of the base just like a load is.
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000410 if (isa<ExtractValueInst>(I))
411 return I;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000412
413 // We should never see an insert vector since that would require we be
414 // tracing back a struct value not a pointer value.
415 assert(!isa<InsertValueInst>(I) &&
416 "Base pointer for a struct is meaningless");
417
418 // The last two cases here don't return a base pointer. Instead, they
419 // return a value which dynamically selects from amoung several base
420 // derived pointers (each with it's own base potentially). It's the job of
421 // the caller to resolve these.
Philip Reames704e78b2015-04-10 22:34:56 +0000422 assert((isa<SelectInst>(I) || isa<PHINode>(I)) &&
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000423 "missing instruction case in findBaseDefiningValing");
424 return I;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000425}
426
427/// Returns the base defining value for this value.
Philip Reames18d0feb2015-03-27 05:39:32 +0000428static Value *findBaseDefiningValueCached(Value *I, DefiningValueMapTy &Cache) {
429 Value *&Cached = Cache[I];
Benjamin Kramer6f665452015-02-20 14:00:58 +0000430 if (!Cached) {
431 Cached = findBaseDefiningValue(I);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000432 }
Philip Reames18d0feb2015-03-27 05:39:32 +0000433 assert(Cache[I] != nullptr);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000434
435 if (TraceLSP) {
Philip Reames18d0feb2015-03-27 05:39:32 +0000436 dbgs() << "fBDV-cached: " << I->getName() << " -> " << Cached->getName()
Philip Reamesd16a9b12015-02-20 01:06:44 +0000437 << "\n";
438 }
Benjamin Kramer6f665452015-02-20 14:00:58 +0000439 return Cached;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000440}
441
442/// Return a base pointer for this value if known. Otherwise, return it's
443/// base defining value.
Philip Reames18d0feb2015-03-27 05:39:32 +0000444static Value *findBaseOrBDV(Value *I, DefiningValueMapTy &Cache) {
445 Value *Def = findBaseDefiningValueCached(I, Cache);
446 auto Found = Cache.find(Def);
447 if (Found != Cache.end()) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000448 // Either a base-of relation, or a self reference. Caller must check.
Benjamin Kramer6f665452015-02-20 14:00:58 +0000449 return Found->second;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000450 }
451 // Only a BDV available
Philip Reames18d0feb2015-03-27 05:39:32 +0000452 return Def;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000453}
454
455/// Given the result of a call to findBaseDefiningValue, or findBaseOrBDV,
456/// is it known to be a base pointer? Or do we need to continue searching.
Philip Reames18d0feb2015-03-27 05:39:32 +0000457static bool isKnownBaseResult(Value *V) {
458 if (!isa<PHINode>(V) && !isa<SelectInst>(V)) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000459 // no recursion possible
460 return true;
461 }
Philip Reames18d0feb2015-03-27 05:39:32 +0000462 if (isa<Instruction>(V) &&
463 cast<Instruction>(V)->getMetadata("is_base_value")) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000464 // This is a previously inserted base phi or select. We know
465 // that this is a base value.
466 return true;
467 }
468
469 // We need to keep searching
470 return false;
471}
472
473// TODO: find a better name for this
474namespace {
475class PhiState {
476public:
477 enum Status { Unknown, Base, Conflict };
478
479 PhiState(Status s, Value *b = nullptr) : status(s), base(b) {
480 assert(status != Base || b);
481 }
482 PhiState(Value *b) : status(Base), base(b) {}
483 PhiState() : status(Unknown), base(nullptr) {}
Philip Reamesd16a9b12015-02-20 01:06:44 +0000484
485 Status getStatus() const { return status; }
486 Value *getBase() const { return base; }
487
488 bool isBase() const { return getStatus() == Base; }
489 bool isUnknown() const { return getStatus() == Unknown; }
490 bool isConflict() const { return getStatus() == Conflict; }
491
492 bool operator==(const PhiState &other) const {
493 return base == other.base && status == other.status;
494 }
495
496 bool operator!=(const PhiState &other) const { return !(*this == other); }
497
498 void dump() {
499 errs() << status << " (" << base << " - "
500 << (base ? base->getName() : "nullptr") << "): ";
501 }
502
503private:
504 Status status;
505 Value *base; // non null only if status == base
506};
507
Philip Reamese9c3b9b2015-02-20 22:48:20 +0000508typedef DenseMap<Value *, PhiState> ConflictStateMapTy;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000509// Values of type PhiState form a lattice, and this is a helper
510// class that implementes the meet operation. The meat of the meet
511// operation is implemented in MeetPhiStates::pureMeet
512class MeetPhiStates {
513public:
514 // phiStates is a mapping from PHINodes and SelectInst's to PhiStates.
Philip Reames860660e2015-02-20 22:05:18 +0000515 explicit MeetPhiStates(const ConflictStateMapTy &phiStates)
Philip Reamesd16a9b12015-02-20 01:06:44 +0000516 : phiStates(phiStates) {}
517
518 // Destructively meet the current result with the base V. V can
519 // either be a merge instruction (SelectInst / PHINode), in which
520 // case its status is looked up in the phiStates map; or a regular
521 // SSA value, in which case it is assumed to be a base.
522 void meetWith(Value *V) {
523 PhiState otherState = getStateForBDV(V);
524 assert((MeetPhiStates::pureMeet(otherState, currentResult) ==
525 MeetPhiStates::pureMeet(currentResult, otherState)) &&
526 "math is wrong: meet does not commute!");
527 currentResult = MeetPhiStates::pureMeet(otherState, currentResult);
528 }
529
530 PhiState getResult() const { return currentResult; }
531
532private:
Philip Reames860660e2015-02-20 22:05:18 +0000533 const ConflictStateMapTy &phiStates;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000534 PhiState currentResult;
535
536 /// Return a phi state for a base defining value. We'll generate a new
537 /// base state for known bases and expect to find a cached state otherwise
538 PhiState getStateForBDV(Value *baseValue) {
539 if (isKnownBaseResult(baseValue)) {
540 return PhiState(baseValue);
541 } else {
542 return lookupFromMap(baseValue);
543 }
544 }
545
546 PhiState lookupFromMap(Value *V) {
547 auto I = phiStates.find(V);
548 assert(I != phiStates.end() && "lookup failed!");
549 return I->second;
550 }
551
552 static PhiState pureMeet(const PhiState &stateA, const PhiState &stateB) {
553 switch (stateA.getStatus()) {
554 case PhiState::Unknown:
555 return stateB;
556
557 case PhiState::Base:
558 assert(stateA.getBase() && "can't be null");
David Blaikie82ad7872015-02-20 23:44:24 +0000559 if (stateB.isUnknown())
Philip Reamesd16a9b12015-02-20 01:06:44 +0000560 return stateA;
David Blaikie82ad7872015-02-20 23:44:24 +0000561
562 if (stateB.isBase()) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000563 if (stateA.getBase() == stateB.getBase()) {
564 assert(stateA == stateB && "equality broken!");
565 return stateA;
566 }
567 return PhiState(PhiState::Conflict);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000568 }
David Blaikie82ad7872015-02-20 23:44:24 +0000569 assert(stateB.isConflict() && "only three states!");
570 return PhiState(PhiState::Conflict);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000571
572 case PhiState::Conflict:
573 return stateA;
574 }
Reid Klecknera070ee52015-02-20 19:46:02 +0000575 llvm_unreachable("only three states!");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000576 }
577};
578}
579/// For a given value or instruction, figure out what base ptr it's derived
580/// from. For gc objects, this is simply itself. On success, returns a value
581/// which is the base pointer. (This is reliable and can be used for
582/// relocation.) On failure, returns nullptr.
Philip Reamesba198492015-04-14 00:41:34 +0000583static Value *findBasePointer(Value *I, DefiningValueMapTy &cache) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000584 Value *def = findBaseOrBDV(I, cache);
585
586 if (isKnownBaseResult(def)) {
587 return def;
588 }
589
590 // Here's the rough algorithm:
591 // - For every SSA value, construct a mapping to either an actual base
592 // pointer or a PHI which obscures the base pointer.
593 // - Construct a mapping from PHI to unknown TOP state. Use an
594 // optimistic algorithm to propagate base pointer information. Lattice
595 // looks like:
596 // UNKNOWN
597 // b1 b2 b3 b4
598 // CONFLICT
599 // When algorithm terminates, all PHIs will either have a single concrete
600 // base or be in a conflict state.
601 // - For every conflict, insert a dummy PHI node without arguments. Add
602 // these to the base[Instruction] = BasePtr mapping. For every
603 // non-conflict, add the actual base.
604 // - For every conflict, add arguments for the base[a] of each input
605 // arguments.
606 //
607 // Note: A simpler form of this would be to add the conflict form of all
608 // PHIs without running the optimistic algorithm. This would be
609 // analougous to pessimistic data flow and would likely lead to an
610 // overall worse solution.
611
Philip Reames860660e2015-02-20 22:05:18 +0000612 ConflictStateMapTy states;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000613 states[def] = PhiState();
614 // Recursively fill in all phis & selects reachable from the initial one
615 // for which we don't already know a definite base value for
Philip Reamesa226e612015-02-28 00:47:50 +0000616 // TODO: This should be rewritten with a worklist
Philip Reamesd16a9b12015-02-20 01:06:44 +0000617 bool done = false;
618 while (!done) {
619 done = true;
Philip Reamesa226e612015-02-28 00:47:50 +0000620 // Since we're adding elements to 'states' as we run, we can't keep
621 // iterators into the set.
Philip Reames704e78b2015-04-10 22:34:56 +0000622 SmallVector<Value *, 16> Keys;
Philip Reamesa226e612015-02-28 00:47:50 +0000623 Keys.reserve(states.size());
Philip Reamesd16a9b12015-02-20 01:06:44 +0000624 for (auto Pair : states) {
Philip Reamesa226e612015-02-28 00:47:50 +0000625 Value *V = Pair.first;
626 Keys.push_back(V);
627 }
628 for (Value *v : Keys) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000629 assert(!isKnownBaseResult(v) && "why did it get added?");
630 if (PHINode *phi = dyn_cast<PHINode>(v)) {
David Blaikie82ad7872015-02-20 23:44:24 +0000631 assert(phi->getNumIncomingValues() > 0 &&
632 "zero input phis are illegal");
633 for (Value *InVal : phi->incoming_values()) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000634 Value *local = findBaseOrBDV(InVal, cache);
635 if (!isKnownBaseResult(local) && states.find(local) == states.end()) {
636 states[local] = PhiState();
637 done = false;
638 }
639 }
640 } else if (SelectInst *sel = dyn_cast<SelectInst>(v)) {
641 Value *local = findBaseOrBDV(sel->getTrueValue(), cache);
642 if (!isKnownBaseResult(local) && states.find(local) == states.end()) {
643 states[local] = PhiState();
644 done = false;
645 }
646 local = findBaseOrBDV(sel->getFalseValue(), cache);
647 if (!isKnownBaseResult(local) && states.find(local) == states.end()) {
648 states[local] = PhiState();
649 done = false;
650 }
651 }
652 }
653 }
654
655 if (TraceLSP) {
656 errs() << "States after initialization:\n";
657 for (auto Pair : states) {
658 Instruction *v = cast<Instruction>(Pair.first);
659 PhiState state = Pair.second;
660 state.dump();
661 v->dump();
662 }
663 }
664
665 // TODO: come back and revisit the state transitions around inputs which
666 // have reached conflict state. The current version seems too conservative.
667
668 bool progress = true;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000669 while (progress) {
Yaron Keren42a7adf2015-02-28 13:11:24 +0000670#ifndef NDEBUG
671 size_t oldSize = states.size();
672#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +0000673 progress = false;
Philip Reamesa226e612015-02-28 00:47:50 +0000674 // We're only changing keys in this loop, thus safe to keep iterators
Philip Reamesd16a9b12015-02-20 01:06:44 +0000675 for (auto Pair : states) {
676 MeetPhiStates calculateMeet(states);
677 Value *v = Pair.first;
678 assert(!isKnownBaseResult(v) && "why did it get added?");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000679 if (SelectInst *select = dyn_cast<SelectInst>(v)) {
680 calculateMeet.meetWith(findBaseOrBDV(select->getTrueValue(), cache));
681 calculateMeet.meetWith(findBaseOrBDV(select->getFalseValue(), cache));
David Blaikie82ad7872015-02-20 23:44:24 +0000682 } else
683 for (Value *Val : cast<PHINode>(v)->incoming_values())
684 calculateMeet.meetWith(findBaseOrBDV(Val, cache));
Philip Reamesd16a9b12015-02-20 01:06:44 +0000685
686 PhiState oldState = states[v];
687 PhiState newState = calculateMeet.getResult();
688 if (oldState != newState) {
689 progress = true;
690 states[v] = newState;
691 }
692 }
693
694 assert(oldSize <= states.size());
695 assert(oldSize == states.size() || progress);
696 }
697
698 if (TraceLSP) {
699 errs() << "States after meet iteration:\n";
700 for (auto Pair : states) {
701 Instruction *v = cast<Instruction>(Pair.first);
702 PhiState state = Pair.second;
703 state.dump();
704 v->dump();
705 }
706 }
707
708 // Insert Phis for all conflicts
Philip Reames2e5bcbe2015-02-28 01:52:09 +0000709 // We want to keep naming deterministic in the loop that follows, so
710 // sort the keys before iteration. This is useful in allowing us to
711 // write stable tests. Note that there is no invalidation issue here.
Philip Reames704e78b2015-04-10 22:34:56 +0000712 SmallVector<Value *, 16> Keys;
Philip Reames2e5bcbe2015-02-28 01:52:09 +0000713 Keys.reserve(states.size());
Philip Reamesd16a9b12015-02-20 01:06:44 +0000714 for (auto Pair : states) {
Philip Reames2e5bcbe2015-02-28 01:52:09 +0000715 Value *V = Pair.first;
716 Keys.push_back(V);
717 }
718 std::sort(Keys.begin(), Keys.end(), order_by_name);
719 // TODO: adjust naming patterns to avoid this order of iteration dependency
720 for (Value *V : Keys) {
721 Instruction *v = cast<Instruction>(V);
722 PhiState state = states[V];
Philip Reamesd16a9b12015-02-20 01:06:44 +0000723 assert(!isKnownBaseResult(v) && "why did it get added?");
724 assert(!state.isUnknown() && "Optimistic algorithm didn't complete!");
Philip Reamesf986d682015-02-28 00:54:41 +0000725 if (!state.isConflict())
726 continue;
Philip Reames704e78b2015-04-10 22:34:56 +0000727
Philip Reamesf986d682015-02-28 00:54:41 +0000728 if (isa<PHINode>(v)) {
729 int num_preds =
730 std::distance(pred_begin(v->getParent()), pred_end(v->getParent()));
731 assert(num_preds > 0 && "how did we reach here");
732 PHINode *phi = PHINode::Create(v->getType(), num_preds, "base_phi", v);
Philip Reamesf986d682015-02-28 00:54:41 +0000733 // Add metadata marking this as a base value
734 auto *const_1 = ConstantInt::get(
735 Type::getInt32Ty(
736 v->getParent()->getParent()->getParent()->getContext()),
737 1);
738 auto MDConst = ConstantAsMetadata::get(const_1);
739 MDNode *md = MDNode::get(
740 v->getParent()->getParent()->getParent()->getContext(), MDConst);
741 phi->setMetadata("is_base_value", md);
742 states[v] = PhiState(PhiState::Conflict, phi);
743 } else {
744 SelectInst *sel = cast<SelectInst>(v);
745 // The undef will be replaced later
746 UndefValue *undef = UndefValue::get(sel->getType());
747 SelectInst *basesel = SelectInst::Create(sel->getCondition(), undef,
748 undef, "base_select", sel);
Philip Reamesf986d682015-02-28 00:54:41 +0000749 // Add metadata marking this as a base value
750 auto *const_1 = ConstantInt::get(
751 Type::getInt32Ty(
752 v->getParent()->getParent()->getParent()->getContext()),
753 1);
754 auto MDConst = ConstantAsMetadata::get(const_1);
755 MDNode *md = MDNode::get(
756 v->getParent()->getParent()->getParent()->getContext(), MDConst);
757 basesel->setMetadata("is_base_value", md);
758 states[v] = PhiState(PhiState::Conflict, basesel);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000759 }
760 }
761
762 // Fixup all the inputs of the new PHIs
763 for (auto Pair : states) {
764 Instruction *v = cast<Instruction>(Pair.first);
765 PhiState state = Pair.second;
766
767 assert(!isKnownBaseResult(v) && "why did it get added?");
768 assert(!state.isUnknown() && "Optimistic algorithm didn't complete!");
Philip Reames28e61ce2015-02-28 01:57:44 +0000769 if (!state.isConflict())
770 continue;
Philip Reames704e78b2015-04-10 22:34:56 +0000771
Philip Reames28e61ce2015-02-28 01:57:44 +0000772 if (PHINode *basephi = dyn_cast<PHINode>(state.getBase())) {
773 PHINode *phi = cast<PHINode>(v);
774 unsigned NumPHIValues = phi->getNumIncomingValues();
775 for (unsigned i = 0; i < NumPHIValues; i++) {
776 Value *InVal = phi->getIncomingValue(i);
777 BasicBlock *InBB = phi->getIncomingBlock(i);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000778
Philip Reames28e61ce2015-02-28 01:57:44 +0000779 // If we've already seen InBB, add the same incoming value
780 // we added for it earlier. The IR verifier requires phi
781 // nodes with multiple entries from the same basic block
782 // to have the same incoming value for each of those
783 // entries. If we don't do this check here and basephi
784 // has a different type than base, we'll end up adding two
785 // bitcasts (and hence two distinct values) as incoming
786 // values for the same basic block.
Philip Reamesd16a9b12015-02-20 01:06:44 +0000787
Philip Reames28e61ce2015-02-28 01:57:44 +0000788 int blockIndex = basephi->getBasicBlockIndex(InBB);
789 if (blockIndex != -1) {
790 Value *oldBase = basephi->getIncomingValue(blockIndex);
791 basephi->addIncoming(oldBase, InBB);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000792#ifndef NDEBUG
Philip Reames28e61ce2015-02-28 01:57:44 +0000793 Value *base = findBaseOrBDV(InVal, cache);
794 if (!isKnownBaseResult(base)) {
795 // Either conflict or base.
796 assert(states.count(base));
797 base = states[base].getBase();
798 assert(base != nullptr && "unknown PhiState!");
Philip Reames28e61ce2015-02-28 01:57:44 +0000799 }
Philip Reamesd16a9b12015-02-20 01:06:44 +0000800
Philip Reames28e61ce2015-02-28 01:57:44 +0000801 // In essense this assert states: the only way two
802 // values incoming from the same basic block may be
803 // different is by being different bitcasts of the same
804 // value. A cleanup that remains TODO is changing
805 // findBaseOrBDV to return an llvm::Value of the correct
806 // type (and still remain pure). This will remove the
807 // need to add bitcasts.
808 assert(base->stripPointerCasts() == oldBase->stripPointerCasts() &&
809 "sanity -- findBaseOrBDV should be pure!");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000810#endif
Philip Reames28e61ce2015-02-28 01:57:44 +0000811 continue;
812 }
Philip Reamesd16a9b12015-02-20 01:06:44 +0000813
Philip Reames28e61ce2015-02-28 01:57:44 +0000814 // Find either the defining value for the PHI or the normal base for
815 // a non-phi node
816 Value *base = findBaseOrBDV(InVal, cache);
817 if (!isKnownBaseResult(base)) {
818 // Either conflict or base.
819 assert(states.count(base));
820 base = states[base].getBase();
821 assert(base != nullptr && "unknown PhiState!");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000822 }
Philip Reames28e61ce2015-02-28 01:57:44 +0000823 assert(base && "can't be null");
824 // Must use original input BB since base may not be Instruction
825 // The cast is needed since base traversal may strip away bitcasts
826 if (base->getType() != basephi->getType()) {
827 base = new BitCastInst(base, basephi->getType(), "cast",
828 InBB->getTerminator());
Philip Reamesd16a9b12015-02-20 01:06:44 +0000829 }
Philip Reames28e61ce2015-02-28 01:57:44 +0000830 basephi->addIncoming(base, InBB);
831 }
832 assert(basephi->getNumIncomingValues() == NumPHIValues);
833 } else {
834 SelectInst *basesel = cast<SelectInst>(state.getBase());
835 SelectInst *sel = cast<SelectInst>(v);
836 // Operand 1 & 2 are true, false path respectively. TODO: refactor to
837 // something more safe and less hacky.
838 for (int i = 1; i <= 2; i++) {
839 Value *InVal = sel->getOperand(i);
840 // Find either the defining value for the PHI or the normal base for
841 // a non-phi node
842 Value *base = findBaseOrBDV(InVal, cache);
843 if (!isKnownBaseResult(base)) {
844 // Either conflict or base.
845 assert(states.count(base));
846 base = states[base].getBase();
847 assert(base != nullptr && "unknown PhiState!");
848 }
849 assert(base && "can't be null");
850 // Must use original input BB since base may not be Instruction
851 // The cast is needed since base traversal may strip away bitcasts
852 if (base->getType() != basesel->getType()) {
853 base = new BitCastInst(base, basesel->getType(), "cast", basesel);
Philip Reames28e61ce2015-02-28 01:57:44 +0000854 }
855 basesel->setOperand(i, base);
856 }
Philip Reamesd16a9b12015-02-20 01:06:44 +0000857 }
858 }
859
860 // Cache all of our results so we can cheaply reuse them
861 // NOTE: This is actually two caches: one of the base defining value
862 // relation and one of the base pointer relation! FIXME
863 for (auto item : states) {
864 Value *v = item.first;
865 Value *base = item.second.getBase();
866 assert(v && base);
867 assert(!isKnownBaseResult(v) && "why did it get added?");
868
869 if (TraceLSP) {
870 std::string fromstr =
871 cache.count(v) ? (cache[v]->hasName() ? cache[v]->getName() : "")
872 : "none";
873 errs() << "Updating base value cache"
874 << " for: " << (v->hasName() ? v->getName() : "")
875 << " from: " << fromstr
876 << " to: " << (base->hasName() ? base->getName() : "") << "\n";
877 }
878
879 assert(isKnownBaseResult(base) &&
880 "must be something we 'know' is a base pointer");
881 if (cache.count(v)) {
882 // Once we transition from the BDV relation being store in the cache to
883 // the base relation being stored, it must be stable
884 assert((!isKnownBaseResult(cache[v]) || cache[v] == base) &&
885 "base relation should be stable");
886 }
887 cache[v] = base;
888 }
889 assert(cache.find(def) != cache.end());
890 return cache[def];
891}
892
893// For a set of live pointers (base and/or derived), identify the base
894// pointer of the object which they are derived from. This routine will
895// mutate the IR graph as needed to make the 'base' pointer live at the
896// definition site of 'derived'. This ensures that any use of 'derived' can
897// also use 'base'. This may involve the insertion of a number of
898// additional PHI nodes.
899//
900// preconditions: live is a set of pointer type Values
901//
902// side effects: may insert PHI nodes into the existing CFG, will preserve
903// CFG, will not remove or mutate any existing nodes
904//
Philip Reamesf2041322015-02-20 19:26:04 +0000905// post condition: PointerToBase contains one (derived, base) pair for every
Philip Reamesd16a9b12015-02-20 01:06:44 +0000906// pointer in live. Note that derived can be equal to base if the original
907// pointer was a base pointer.
Philip Reames704e78b2015-04-10 22:34:56 +0000908static void
909findBasePointers(const StatepointLiveSetTy &live,
910 DenseMap<llvm::Value *, llvm::Value *> &PointerToBase,
Philip Reamesba198492015-04-14 00:41:34 +0000911 DominatorTree *DT, DefiningValueMapTy &DVCache) {
Philip Reames2e5bcbe2015-02-28 01:52:09 +0000912 // For the naming of values inserted to be deterministic - which makes for
913 // much cleaner and more stable tests - we need to assign an order to the
914 // live values. DenseSets do not provide a deterministic order across runs.
Philip Reames704e78b2015-04-10 22:34:56 +0000915 SmallVector<Value *, 64> Temp;
Philip Reames2e5bcbe2015-02-28 01:52:09 +0000916 Temp.insert(Temp.end(), live.begin(), live.end());
917 std::sort(Temp.begin(), Temp.end(), order_by_name);
918 for (Value *ptr : Temp) {
Philip Reamesba198492015-04-14 00:41:34 +0000919 Value *base = findBasePointer(ptr, DVCache);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000920 assert(base && "failed to find base pointer");
Philip Reamesf2041322015-02-20 19:26:04 +0000921 PointerToBase[ptr] = base;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000922 assert((!isa<Instruction>(base) || !isa<Instruction>(ptr) ||
923 DT->dominates(cast<Instruction>(base)->getParent(),
924 cast<Instruction>(ptr)->getParent())) &&
925 "The base we found better dominate the derived pointer");
926
David Blaikie82ad7872015-02-20 23:44:24 +0000927 // If you see this trip and like to live really dangerously, the code should
928 // be correct, just with idioms the verifier can't handle. You can try
929 // disabling the verifier at your own substaintial risk.
Philip Reames704e78b2015-04-10 22:34:56 +0000930 assert(!isa<ConstantPointerNull>(base) &&
Philip Reames24c6cd52015-03-27 05:47:00 +0000931 "the relocation code needs adjustment to handle the relocation of "
932 "a null pointer constant without causing false positives in the "
933 "safepoint ir verifier.");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000934 }
935}
936
937/// Find the required based pointers (and adjust the live set) for the given
938/// parse point.
939static void findBasePointers(DominatorTree &DT, DefiningValueMapTy &DVCache,
940 const CallSite &CS,
941 PartiallyConstructedSafepointRecord &result) {
Philip Reamesf2041322015-02-20 19:26:04 +0000942 DenseMap<llvm::Value *, llvm::Value *> PointerToBase;
Philip Reamesba198492015-04-14 00:41:34 +0000943 findBasePointers(result.liveset, PointerToBase, &DT, DVCache);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000944
945 if (PrintBasePointers) {
Philip Reamesa5aeaf42015-02-28 00:20:48 +0000946 // Note: Need to print these in a stable order since this is checked in
947 // some tests.
Philip Reamesd16a9b12015-02-20 01:06:44 +0000948 errs() << "Base Pairs (w/o Relocation):\n";
Philip Reames704e78b2015-04-10 22:34:56 +0000949 SmallVector<Value *, 64> Temp;
Philip Reamesa5aeaf42015-02-28 00:20:48 +0000950 Temp.reserve(PointerToBase.size());
Philip Reamesf2041322015-02-20 19:26:04 +0000951 for (auto Pair : PointerToBase) {
Philip Reamesa5aeaf42015-02-28 00:20:48 +0000952 Temp.push_back(Pair.first);
953 }
954 std::sort(Temp.begin(), Temp.end(), order_by_name);
955 for (Value *Ptr : Temp) {
956 Value *Base = PointerToBase[Ptr];
Philip Reames704e78b2015-04-10 22:34:56 +0000957 errs() << " derived %" << Ptr->getName() << " base %" << Base->getName()
958 << "\n";
Philip Reamesd16a9b12015-02-20 01:06:44 +0000959 }
960 }
961
Philip Reamesf2041322015-02-20 19:26:04 +0000962 result.PointerToBase = PointerToBase;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000963}
964
Philip Reamesdf1ef082015-04-10 22:53:14 +0000965/// Given an updated version of the dataflow liveness results, update the
966/// liveset and base pointer maps for the call site CS.
967static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData,
968 const CallSite &CS,
969 PartiallyConstructedSafepointRecord &result);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000970
Philip Reamesdf1ef082015-04-10 22:53:14 +0000971static void recomputeLiveInValues(
972 Function &F, DominatorTree &DT, Pass *P, ArrayRef<CallSite> toUpdate,
Philip Reamesd2b66462015-02-20 22:39:41 +0000973 MutableArrayRef<struct PartiallyConstructedSafepointRecord> records) {
Philip Reamesdf1ef082015-04-10 22:53:14 +0000974 // TODO-PERF: reuse the original liveness, then simply run the dataflow
975 // again. The old values are still live and will help it stablize quickly.
976 GCPtrLivenessData RevisedLivenessData;
977 computeLiveInValues(DT, F, RevisedLivenessData);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000978 for (size_t i = 0; i < records.size(); i++) {
979 struct PartiallyConstructedSafepointRecord &info = records[i];
Philip Reamesd2b66462015-02-20 22:39:41 +0000980 const CallSite &CS = toUpdate[i];
Philip Reamesdf1ef082015-04-10 22:53:14 +0000981 recomputeLiveInValues(RevisedLivenessData, CS, info);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000982 }
983}
984
Philip Reames69e51ca2015-04-13 18:07:21 +0000985// When inserting gc.relocate calls, we need to ensure there are no uses
986// of the original value between the gc.statepoint and the gc.relocate call.
987// One case which can arise is a phi node starting one of the successor blocks.
988// We also need to be able to insert the gc.relocates only on the path which
989// goes through the statepoint. We might need to split an edge to make this
Philip Reamesf209a152015-04-13 20:00:30 +0000990// possible.
991static BasicBlock *
992normalizeForInvokeSafepoint(BasicBlock *BB, BasicBlock *InvokeParent, Pass *P) {
Philip Reames69e51ca2015-04-13 18:07:21 +0000993 DominatorTree *DT = nullptr;
994 if (auto *DTP = P->getAnalysisIfAvailable<DominatorTreeWrapperPass>())
995 DT = &DTP->getDomTree();
Philip Reamesd16a9b12015-02-20 01:06:44 +0000996
Philip Reames69e51ca2015-04-13 18:07:21 +0000997 BasicBlock *Ret = BB;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000998 if (!BB->getUniquePredecessor()) {
Philip Reames69e51ca2015-04-13 18:07:21 +0000999 Ret = SplitBlockPredecessors(BB, InvokeParent, "", nullptr, DT);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001000 }
1001
Philip Reames69e51ca2015-04-13 18:07:21 +00001002 // Now that 'ret' has unique predecessor we can safely remove all phi nodes
1003 // from it
1004 FoldSingleEntryPHINodes(Ret);
1005 assert(!isa<PHINode>(Ret->begin()));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001006
Philip Reames69e51ca2015-04-13 18:07:21 +00001007 // At this point, we can safely insert a gc.relocate as the first instruction
1008 // in Ret if needed.
1009 return Ret;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001010}
1011
Philip Reamesd2b66462015-02-20 22:39:41 +00001012static int find_index(ArrayRef<Value *> livevec, Value *val) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001013 auto itr = std::find(livevec.begin(), livevec.end(), val);
1014 assert(livevec.end() != itr);
1015 size_t index = std::distance(livevec.begin(), itr);
1016 assert(index < livevec.size());
1017 return index;
1018}
1019
1020// Create new attribute set containing only attributes which can be transfered
1021// from original call to the safepoint.
1022static AttributeSet legalizeCallAttributes(AttributeSet AS) {
1023 AttributeSet ret;
1024
1025 for (unsigned Slot = 0; Slot < AS.getNumSlots(); Slot++) {
1026 unsigned index = AS.getSlotIndex(Slot);
1027
1028 if (index == AttributeSet::ReturnIndex ||
1029 index == AttributeSet::FunctionIndex) {
1030
1031 for (auto it = AS.begin(Slot), it_end = AS.end(Slot); it != it_end;
1032 ++it) {
1033 Attribute attr = *it;
1034
1035 // Do not allow certain attributes - just skip them
1036 // Safepoint can not be read only or read none.
1037 if (attr.hasAttribute(Attribute::ReadNone) ||
1038 attr.hasAttribute(Attribute::ReadOnly))
1039 continue;
1040
1041 ret = ret.addAttributes(
1042 AS.getContext(), index,
1043 AttributeSet::get(AS.getContext(), index, AttrBuilder(attr)));
1044 }
1045 }
1046
1047 // Just skip parameter attributes for now
1048 }
1049
1050 return ret;
1051}
1052
1053/// Helper function to place all gc relocates necessary for the given
1054/// statepoint.
1055/// Inputs:
1056/// liveVariables - list of variables to be relocated.
1057/// liveStart - index of the first live variable.
1058/// basePtrs - base pointers.
1059/// statepointToken - statepoint instruction to which relocates should be
1060/// bound.
1061/// Builder - Llvm IR builder to be used to construct new calls.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00001062static void CreateGCRelocates(ArrayRef<llvm::Value *> liveVariables,
1063 const int liveStart,
1064 ArrayRef<llvm::Value *> basePtrs,
1065 Instruction *statepointToken,
1066 IRBuilder<> Builder) {
Philip Reamesd2b66462015-02-20 22:39:41 +00001067 SmallVector<Instruction *, 64> NewDefs;
1068 NewDefs.reserve(liveVariables.size());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001069
1070 Module *M = statepointToken->getParent()->getParent()->getParent();
1071
1072 for (unsigned i = 0; i < liveVariables.size(); i++) {
1073 // We generate a (potentially) unique declaration for every pointer type
1074 // combination. This results is some blow up the function declarations in
1075 // the IR, but removes the need for argument bitcasts which shrinks the IR
1076 // greatly and makes it much more readable.
Philip Reames704e78b2015-04-10 22:34:56 +00001077 SmallVector<Type *, 1> types; // one per 'any' type
Philip Reamesd16a9b12015-02-20 01:06:44 +00001078 types.push_back(liveVariables[i]->getType()); // result type
1079 Value *gc_relocate_decl = Intrinsic::getDeclaration(
1080 M, Intrinsic::experimental_gc_relocate, types);
1081
1082 // Generate the gc.relocate call and save the result
1083 Value *baseIdx =
1084 ConstantInt::get(Type::getInt32Ty(M->getContext()),
1085 liveStart + find_index(liveVariables, basePtrs[i]));
1086 Value *liveIdx = ConstantInt::get(
1087 Type::getInt32Ty(M->getContext()),
1088 liveStart + find_index(liveVariables, liveVariables[i]));
1089
1090 // only specify a debug name if we can give a useful one
1091 Value *reloc = Builder.CreateCall3(
1092 gc_relocate_decl, statepointToken, baseIdx, liveIdx,
1093 liveVariables[i]->hasName() ? liveVariables[i]->getName() + ".relocated"
1094 : "");
1095 // Trick CodeGen into thinking there are lots of free registers at this
1096 // fake call.
1097 cast<CallInst>(reloc)->setCallingConv(CallingConv::Cold);
1098
Philip Reamesd2b66462015-02-20 22:39:41 +00001099 NewDefs.push_back(cast<Instruction>(reloc));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001100 }
Philip Reamesd2b66462015-02-20 22:39:41 +00001101 assert(NewDefs.size() == liveVariables.size() &&
Philip Reamesd16a9b12015-02-20 01:06:44 +00001102 "missing or extra redefinition at safepoint");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001103}
1104
1105static void
1106makeStatepointExplicitImpl(const CallSite &CS, /* to replace */
1107 const SmallVectorImpl<llvm::Value *> &basePtrs,
1108 const SmallVectorImpl<llvm::Value *> &liveVariables,
1109 Pass *P,
1110 PartiallyConstructedSafepointRecord &result) {
1111 assert(basePtrs.size() == liveVariables.size());
1112 assert(isStatepoint(CS) &&
1113 "This method expects to be rewriting a statepoint");
1114
1115 BasicBlock *BB = CS.getInstruction()->getParent();
1116 assert(BB);
1117 Function *F = BB->getParent();
1118 assert(F && "must be set");
1119 Module *M = F->getParent();
Nick Lewyckyeb3231e2015-02-20 07:14:02 +00001120 (void)M;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001121 assert(M && "must be set");
1122
1123 // We're not changing the function signature of the statepoint since the gc
1124 // arguments go into the var args section.
1125 Function *gc_statepoint_decl = CS.getCalledFunction();
1126
1127 // Then go ahead and use the builder do actually do the inserts. We insert
1128 // immediately before the previous instruction under the assumption that all
1129 // arguments will be available here. We can't insert afterwards since we may
1130 // be replacing a terminator.
1131 Instruction *insertBefore = CS.getInstruction();
1132 IRBuilder<> Builder(insertBefore);
1133 // Copy all of the arguments from the original statepoint - this includes the
1134 // target, call args, and deopt args
Philip Reamesd2b66462015-02-20 22:39:41 +00001135 SmallVector<llvm::Value *, 64> args;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001136 args.insert(args.end(), CS.arg_begin(), CS.arg_end());
1137 // TODO: Clear the 'needs rewrite' flag
1138
1139 // add all the pointers to be relocated (gc arguments)
1140 // Capture the start of the live variable list for use in the gc_relocates
1141 const int live_start = args.size();
1142 args.insert(args.end(), liveVariables.begin(), liveVariables.end());
1143
1144 // Create the statepoint given all the arguments
1145 Instruction *token = nullptr;
1146 AttributeSet return_attributes;
1147 if (CS.isCall()) {
1148 CallInst *toReplace = cast<CallInst>(CS.getInstruction());
1149 CallInst *call =
1150 Builder.CreateCall(gc_statepoint_decl, args, "safepoint_token");
1151 call->setTailCall(toReplace->isTailCall());
1152 call->setCallingConv(toReplace->getCallingConv());
1153
1154 // Currently we will fail on parameter attributes and on certain
1155 // function attributes.
1156 AttributeSet new_attrs = legalizeCallAttributes(toReplace->getAttributes());
1157 // In case if we can handle this set of sttributes - set up function attrs
1158 // directly on statepoint and return attrs later for gc_result intrinsic.
1159 call->setAttributes(new_attrs.getFnAttributes());
1160 return_attributes = new_attrs.getRetAttributes();
1161
1162 token = call;
1163
1164 // Put the following gc_result and gc_relocate calls immediately after the
1165 // the old call (which we're about to delete)
1166 BasicBlock::iterator next(toReplace);
1167 assert(BB->end() != next && "not a terminator, must have next");
1168 next++;
1169 Instruction *IP = &*(next);
1170 Builder.SetInsertPoint(IP);
1171 Builder.SetCurrentDebugLocation(IP->getDebugLoc());
1172
David Blaikie82ad7872015-02-20 23:44:24 +00001173 } else {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001174 InvokeInst *toReplace = cast<InvokeInst>(CS.getInstruction());
1175
1176 // Insert the new invoke into the old block. We'll remove the old one in a
1177 // moment at which point this will become the new terminator for the
1178 // original block.
1179 InvokeInst *invoke = InvokeInst::Create(
1180 gc_statepoint_decl, toReplace->getNormalDest(),
1181 toReplace->getUnwindDest(), args, "", toReplace->getParent());
1182 invoke->setCallingConv(toReplace->getCallingConv());
1183
1184 // Currently we will fail on parameter attributes and on certain
1185 // function attributes.
1186 AttributeSet new_attrs = legalizeCallAttributes(toReplace->getAttributes());
1187 // In case if we can handle this set of sttributes - set up function attrs
1188 // directly on statepoint and return attrs later for gc_result intrinsic.
1189 invoke->setAttributes(new_attrs.getFnAttributes());
1190 return_attributes = new_attrs.getRetAttributes();
1191
1192 token = invoke;
1193
1194 // Generate gc relocates in exceptional path
Philip Reames69e51ca2015-04-13 18:07:21 +00001195 BasicBlock *unwindBlock = toReplace->getUnwindDest();
1196 assert(!isa<PHINode>(unwindBlock->begin()) &&
1197 unwindBlock->getUniquePredecessor() &&
1198 "can't safely insert in this block!");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001199
1200 Instruction *IP = &*(unwindBlock->getFirstInsertionPt());
1201 Builder.SetInsertPoint(IP);
1202 Builder.SetCurrentDebugLocation(toReplace->getDebugLoc());
1203
1204 // Extract second element from landingpad return value. We will attach
1205 // exceptional gc relocates to it.
1206 const unsigned idx = 1;
1207 Instruction *exceptional_token =
1208 cast<Instruction>(Builder.CreateExtractValue(
1209 unwindBlock->getLandingPadInst(), idx, "relocate_token"));
Philip Reamesf2041322015-02-20 19:26:04 +00001210 result.UnwindToken = exceptional_token;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001211
1212 // Just throw away return value. We will use the one we got for normal
1213 // block.
1214 (void)CreateGCRelocates(liveVariables, live_start, basePtrs,
1215 exceptional_token, Builder);
1216
1217 // Generate gc relocates and returns for normal block
Philip Reames69e51ca2015-04-13 18:07:21 +00001218 BasicBlock *normalDest = toReplace->getNormalDest();
1219 assert(!isa<PHINode>(normalDest->begin()) &&
1220 normalDest->getUniquePredecessor() &&
1221 "can't safely insert in this block!");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001222
1223 IP = &*(normalDest->getFirstInsertionPt());
1224 Builder.SetInsertPoint(IP);
1225
1226 // gc relocates will be generated later as if it were regular call
1227 // statepoint
Philip Reamesd16a9b12015-02-20 01:06:44 +00001228 }
1229 assert(token);
1230
1231 // Take the name of the original value call if it had one.
1232 token->takeName(CS.getInstruction());
1233
Philip Reames704e78b2015-04-10 22:34:56 +00001234// The GCResult is already inserted, we just need to find it
David Blaikie5e5d7842015-02-22 20:58:38 +00001235#ifndef NDEBUG
1236 Instruction *toReplace = CS.getInstruction();
1237 assert((toReplace->hasNUses(0) || toReplace->hasNUses(1)) &&
1238 "only valid use before rewrite is gc.result");
1239 assert(!toReplace->hasOneUse() ||
1240 isGCResult(cast<Instruction>(*toReplace->user_begin())));
1241#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +00001242
1243 // Update the gc.result of the original statepoint (if any) to use the newly
1244 // inserted statepoint. This is safe to do here since the token can't be
1245 // considered a live reference.
1246 CS.getInstruction()->replaceAllUsesWith(token);
1247
Philip Reames0a3240f2015-02-20 21:34:11 +00001248 result.StatepointToken = token;
1249
Philip Reamesd16a9b12015-02-20 01:06:44 +00001250 // Second, create a gc.relocate for every live variable
Philip Reames0a3240f2015-02-20 21:34:11 +00001251 CreateGCRelocates(liveVariables, live_start, basePtrs, token, Builder);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001252}
1253
1254namespace {
1255struct name_ordering {
1256 Value *base;
1257 Value *derived;
1258 bool operator()(name_ordering const &a, name_ordering const &b) {
1259 return -1 == a.derived->getName().compare(b.derived->getName());
1260 }
1261};
1262}
1263static void stablize_order(SmallVectorImpl<Value *> &basevec,
1264 SmallVectorImpl<Value *> &livevec) {
1265 assert(basevec.size() == livevec.size());
1266
Philip Reames860660e2015-02-20 22:05:18 +00001267 SmallVector<name_ordering, 64> temp;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001268 for (size_t i = 0; i < basevec.size(); i++) {
1269 name_ordering v;
1270 v.base = basevec[i];
1271 v.derived = livevec[i];
1272 temp.push_back(v);
1273 }
1274 std::sort(temp.begin(), temp.end(), name_ordering());
1275 for (size_t i = 0; i < basevec.size(); i++) {
1276 basevec[i] = temp[i].base;
1277 livevec[i] = temp[i].derived;
1278 }
1279}
1280
1281// Replace an existing gc.statepoint with a new one and a set of gc.relocates
1282// which make the relocations happening at this safepoint explicit.
Philip Reames704e78b2015-04-10 22:34:56 +00001283//
Philip Reamesd16a9b12015-02-20 01:06:44 +00001284// WARNING: Does not do any fixup to adjust users of the original live
1285// values. That's the callers responsibility.
1286static void
1287makeStatepointExplicit(DominatorTree &DT, const CallSite &CS, Pass *P,
1288 PartiallyConstructedSafepointRecord &result) {
Philip Reamesf2041322015-02-20 19:26:04 +00001289 auto liveset = result.liveset;
1290 auto PointerToBase = result.PointerToBase;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001291
1292 // Convert to vector for efficient cross referencing.
1293 SmallVector<Value *, 64> basevec, livevec;
1294 livevec.reserve(liveset.size());
1295 basevec.reserve(liveset.size());
1296 for (Value *L : liveset) {
1297 livevec.push_back(L);
1298
Philip Reamesf2041322015-02-20 19:26:04 +00001299 assert(PointerToBase.find(L) != PointerToBase.end());
1300 Value *base = PointerToBase[L];
Philip Reamesd16a9b12015-02-20 01:06:44 +00001301 basevec.push_back(base);
1302 }
1303 assert(livevec.size() == basevec.size());
1304
1305 // To make the output IR slightly more stable (for use in diffs), ensure a
1306 // fixed order of the values in the safepoint (by sorting the value name).
1307 // The order is otherwise meaningless.
1308 stablize_order(basevec, livevec);
1309
1310 // Do the actual rewriting and delete the old statepoint
1311 makeStatepointExplicitImpl(CS, basevec, livevec, P, result);
1312 CS.getInstruction()->eraseFromParent();
1313}
1314
1315// Helper function for the relocationViaAlloca.
1316// It receives iterator to the statepoint gc relocates and emits store to the
1317// assigned
1318// location (via allocaMap) for the each one of them.
1319// Add visited values into the visitedLiveValues set we will later use them
1320// for sanity check.
1321static void
1322insertRelocationStores(iterator_range<Value::user_iterator> gcRelocs,
1323 DenseMap<Value *, Value *> &allocaMap,
1324 DenseSet<Value *> &visitedLiveValues) {
1325
1326 for (User *U : gcRelocs) {
1327 if (!isa<IntrinsicInst>(U))
1328 continue;
1329
1330 IntrinsicInst *relocatedValue = cast<IntrinsicInst>(U);
1331
1332 // We only care about relocates
1333 if (relocatedValue->getIntrinsicID() !=
1334 Intrinsic::experimental_gc_relocate) {
1335 continue;
1336 }
1337
1338 GCRelocateOperands relocateOperands(relocatedValue);
1339 Value *originalValue = const_cast<Value *>(relocateOperands.derivedPtr());
1340 assert(allocaMap.count(originalValue));
1341 Value *alloca = allocaMap[originalValue];
1342
1343 // Emit store into the related alloca
1344 StoreInst *store = new StoreInst(relocatedValue, alloca);
1345 store->insertAfter(relocatedValue);
1346
1347#ifndef NDEBUG
1348 visitedLiveValues.insert(originalValue);
1349#endif
1350 }
1351}
1352
1353/// do all the relocation update via allocas and mem2reg
1354static void relocationViaAlloca(
Philip Reamesd2b66462015-02-20 22:39:41 +00001355 Function &F, DominatorTree &DT, ArrayRef<Value *> live,
1356 ArrayRef<struct PartiallyConstructedSafepointRecord> records) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001357#ifndef NDEBUG
Philip Reamesa6ebf072015-03-27 05:53:16 +00001358 // record initial number of (static) allocas; we'll check we have the same
1359 // number when we get done.
1360 int InitialAllocaNum = 0;
Philip Reames704e78b2015-04-10 22:34:56 +00001361 for (auto I = F.getEntryBlock().begin(), E = F.getEntryBlock().end(); I != E;
1362 I++)
Philip Reamesa6ebf072015-03-27 05:53:16 +00001363 if (isa<AllocaInst>(*I))
1364 InitialAllocaNum++;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001365#endif
1366
1367 // TODO-PERF: change data structures, reserve
1368 DenseMap<Value *, Value *> allocaMap;
1369 SmallVector<AllocaInst *, 200> PromotableAllocas;
1370 PromotableAllocas.reserve(live.size());
1371
1372 // emit alloca for each live gc pointer
1373 for (unsigned i = 0; i < live.size(); i++) {
1374 Value *liveValue = live[i];
1375 AllocaInst *alloca = new AllocaInst(liveValue->getType(), "",
1376 F.getEntryBlock().getFirstNonPHI());
1377 allocaMap[liveValue] = alloca;
1378 PromotableAllocas.push_back(alloca);
1379 }
1380
1381 // The next two loops are part of the same conceptual operation. We need to
1382 // insert a store to the alloca after the original def and at each
1383 // redefinition. We need to insert a load before each use. These are split
1384 // into distinct loops for performance reasons.
1385
1386 // update gc pointer after each statepoint
1387 // either store a relocated value or null (if no relocated value found for
1388 // this gc pointer and it is not a gc_result)
1389 // this must happen before we update the statepoint with load of alloca
1390 // otherwise we lose the link between statepoint and old def
1391 for (size_t i = 0; i < records.size(); i++) {
1392 const struct PartiallyConstructedSafepointRecord &info = records[i];
Philip Reames0a3240f2015-02-20 21:34:11 +00001393 Value *Statepoint = info.StatepointToken;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001394
1395 // This will be used for consistency check
1396 DenseSet<Value *> visitedLiveValues;
1397
1398 // Insert stores for normal statepoint gc relocates
Philip Reames0a3240f2015-02-20 21:34:11 +00001399 insertRelocationStores(Statepoint->users(), allocaMap, visitedLiveValues);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001400
1401 // In case if it was invoke statepoint
1402 // we will insert stores for exceptional path gc relocates.
Philip Reames0a3240f2015-02-20 21:34:11 +00001403 if (isa<InvokeInst>(Statepoint)) {
Philip Reames704e78b2015-04-10 22:34:56 +00001404 insertRelocationStores(info.UnwindToken->users(), allocaMap,
1405 visitedLiveValues);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001406 }
1407
Philip Reamese73300b2015-04-13 16:41:32 +00001408 if (ClobberNonLive) {
1409 // As a debuging aid, pretend that an unrelocated pointer becomes null at
1410 // the gc.statepoint. This will turn some subtle GC problems into
1411 // slightly easier to debug SEGVs. Note that on large IR files with
1412 // lots of gc.statepoints this is extremely costly both memory and time
1413 // wise.
1414 SmallVector<AllocaInst *, 64> ToClobber;
1415 for (auto Pair : allocaMap) {
1416 Value *Def = Pair.first;
1417 AllocaInst *Alloca = cast<AllocaInst>(Pair.second);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001418
Philip Reamese73300b2015-04-13 16:41:32 +00001419 // This value was relocated
1420 if (visitedLiveValues.count(Def)) {
1421 continue;
1422 }
1423 ToClobber.push_back(Alloca);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001424 }
Philip Reamesfa2fcf172015-02-20 19:51:56 +00001425
Philip Reamese73300b2015-04-13 16:41:32 +00001426 auto InsertClobbersAt = [&](Instruction *IP) {
1427 for (auto *AI : ToClobber) {
1428 auto AIType = cast<PointerType>(AI->getType());
1429 auto PT = cast<PointerType>(AIType->getElementType());
1430 Constant *CPN = ConstantPointerNull::get(PT);
1431 StoreInst *store = new StoreInst(CPN, AI);
1432 store->insertBefore(IP);
1433 }
1434 };
1435
1436 // Insert the clobbering stores. These may get intermixed with the
1437 // gc.results and gc.relocates, but that's fine.
1438 if (auto II = dyn_cast<InvokeInst>(Statepoint)) {
1439 InsertClobbersAt(II->getNormalDest()->getFirstInsertionPt());
1440 InsertClobbersAt(II->getUnwindDest()->getFirstInsertionPt());
1441 } else {
1442 BasicBlock::iterator Next(cast<CallInst>(Statepoint));
1443 Next++;
1444 InsertClobbersAt(Next);
Philip Reamesfa2fcf172015-02-20 19:51:56 +00001445 }
David Blaikie82ad7872015-02-20 23:44:24 +00001446 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00001447 }
1448 // update use with load allocas and add store for gc_relocated
1449 for (auto Pair : allocaMap) {
1450 Value *def = Pair.first;
1451 Value *alloca = Pair.second;
1452
1453 // we pre-record the uses of allocas so that we dont have to worry about
1454 // later update
1455 // that change the user information.
1456 SmallVector<Instruction *, 20> uses;
1457 // PERF: trade a linear scan for repeated reallocation
1458 uses.reserve(std::distance(def->user_begin(), def->user_end()));
1459 for (User *U : def->users()) {
1460 if (!isa<ConstantExpr>(U)) {
1461 // If the def has a ConstantExpr use, then the def is either a
1462 // ConstantExpr use itself or null. In either case
1463 // (recursively in the first, directly in the second), the oop
1464 // it is ultimately dependent on is null and this particular
1465 // use does not need to be fixed up.
1466 uses.push_back(cast<Instruction>(U));
1467 }
1468 }
1469
1470 std::sort(uses.begin(), uses.end());
1471 auto last = std::unique(uses.begin(), uses.end());
1472 uses.erase(last, uses.end());
1473
1474 for (Instruction *use : uses) {
1475 if (isa<PHINode>(use)) {
1476 PHINode *phi = cast<PHINode>(use);
1477 for (unsigned i = 0; i < phi->getNumIncomingValues(); i++) {
1478 if (def == phi->getIncomingValue(i)) {
1479 LoadInst *load = new LoadInst(
1480 alloca, "", phi->getIncomingBlock(i)->getTerminator());
1481 phi->setIncomingValue(i, load);
1482 }
1483 }
1484 } else {
1485 LoadInst *load = new LoadInst(alloca, "", use);
1486 use->replaceUsesOfWith(def, load);
1487 }
1488 }
1489
1490 // emit store for the initial gc value
1491 // store must be inserted after load, otherwise store will be in alloca's
1492 // use list and an extra load will be inserted before it
1493 StoreInst *store = new StoreInst(def, alloca);
Philip Reames6da37852015-03-04 00:13:52 +00001494 if (Instruction *inst = dyn_cast<Instruction>(def)) {
1495 if (InvokeInst *invoke = dyn_cast<InvokeInst>(inst)) {
1496 // InvokeInst is a TerminatorInst so the store need to be inserted
1497 // into its normal destination block.
1498 BasicBlock *normalDest = invoke->getNormalDest();
1499 store->insertBefore(normalDest->getFirstNonPHI());
1500 } else {
1501 assert(!inst->isTerminator() &&
1502 "The only TerminatorInst that can produce a value is "
1503 "InvokeInst which is handled above.");
Philip Reames704e78b2015-04-10 22:34:56 +00001504 store->insertAfter(inst);
Philip Reames6da37852015-03-04 00:13:52 +00001505 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00001506 } else {
1507 assert((isa<Argument>(def) || isa<GlobalVariable>(def) ||
Philip Reames24c6cd52015-03-27 05:47:00 +00001508 isa<ConstantPointerNull>(def)) &&
Philip Reamesd16a9b12015-02-20 01:06:44 +00001509 "Must be argument or global");
1510 store->insertAfter(cast<Instruction>(alloca));
1511 }
1512 }
1513
1514 assert(PromotableAllocas.size() == live.size() &&
1515 "we must have the same allocas with lives");
1516 if (!PromotableAllocas.empty()) {
1517 // apply mem2reg to promote alloca to SSA
1518 PromoteMemToReg(PromotableAllocas, DT);
1519 }
1520
1521#ifndef NDEBUG
Philip Reames704e78b2015-04-10 22:34:56 +00001522 for (auto I = F.getEntryBlock().begin(), E = F.getEntryBlock().end(); I != E;
1523 I++)
Philip Reamesa6ebf072015-03-27 05:53:16 +00001524 if (isa<AllocaInst>(*I))
1525 InitialAllocaNum--;
1526 assert(InitialAllocaNum == 0 && "We must not introduce any extra allocas");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001527#endif
1528}
1529
1530/// Implement a unique function which doesn't require we sort the input
1531/// vector. Doing so has the effect of changing the output of a couple of
1532/// tests in ways which make them less useful in testing fused safepoints.
Philip Reamesd2b66462015-02-20 22:39:41 +00001533template <typename T> static void unique_unsorted(SmallVectorImpl<T> &Vec) {
1534 DenseSet<T> Seen;
1535 SmallVector<T, 128> TempVec;
1536 TempVec.reserve(Vec.size());
1537 for (auto Element : Vec)
1538 TempVec.push_back(Element);
1539 Vec.clear();
1540 for (auto V : TempVec) {
1541 if (Seen.insert(V).second) {
1542 Vec.push_back(V);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001543 }
1544 }
1545}
1546
Philip Reamesd16a9b12015-02-20 01:06:44 +00001547/// Insert holders so that each Value is obviously live through the entire
Philip Reamesf209a152015-04-13 20:00:30 +00001548/// lifetime of the call.
Philip Reamesd16a9b12015-02-20 01:06:44 +00001549static void insertUseHolderAfter(CallSite &CS, const ArrayRef<Value *> Values,
Philip Reamesf209a152015-04-13 20:00:30 +00001550 SmallVectorImpl<CallInst *> &Holders) {
Philip Reames21142752015-04-13 19:07:47 +00001551 if (Values.empty())
1552 // No values to hold live, might as well not insert the empty holder
1553 return;
1554
Philip Reamesd16a9b12015-02-20 01:06:44 +00001555 Module *M = CS.getInstruction()->getParent()->getParent()->getParent();
Philip Reamesf209a152015-04-13 20:00:30 +00001556 // Use a dummy vararg function to actually hold the values live
1557 Function *Func = cast<Function>(M->getOrInsertFunction(
1558 "__tmp_use", FunctionType::get(Type::getVoidTy(M->getContext()), true)));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001559 if (CS.isCall()) {
1560 // For call safepoints insert dummy calls right after safepoint
Philip Reamesf209a152015-04-13 20:00:30 +00001561 BasicBlock::iterator Next(CS.getInstruction());
1562 Next++;
1563 Holders.push_back(CallInst::Create(Func, Values, "", Next));
1564 return;
1565 }
1566 // For invoke safepooints insert dummy calls both in normal and
1567 // exceptional destination blocks
1568 auto *II = cast<InvokeInst>(CS.getInstruction());
1569 Holders.push_back(CallInst::Create(
1570 Func, Values, "", II->getNormalDest()->getFirstInsertionPt()));
1571 Holders.push_back(CallInst::Create(
1572 Func, Values, "", II->getUnwindDest()->getFirstInsertionPt()));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001573}
1574
1575static void findLiveReferences(
Philip Reamesd2b66462015-02-20 22:39:41 +00001576 Function &F, DominatorTree &DT, Pass *P, ArrayRef<CallSite> toUpdate,
1577 MutableArrayRef<struct PartiallyConstructedSafepointRecord> records) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00001578 GCPtrLivenessData OriginalLivenessData;
1579 computeLiveInValues(DT, F, OriginalLivenessData);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001580 for (size_t i = 0; i < records.size(); i++) {
1581 struct PartiallyConstructedSafepointRecord &info = records[i];
Philip Reamesd2b66462015-02-20 22:39:41 +00001582 const CallSite &CS = toUpdate[i];
Philip Reamesdf1ef082015-04-10 22:53:14 +00001583 analyzeParsePointLiveness(DT, OriginalLivenessData, CS, info);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001584 }
1585}
1586
Philip Reames8531d8c2015-04-10 21:48:25 +00001587/// Remove any vector of pointers from the liveset by scalarizing them over the
1588/// statepoint instruction. Adds the scalarized pieces to the liveset. It
1589/// would be preferrable to include the vector in the statepoint itself, but
1590/// the lowering code currently does not handle that. Extending it would be
1591/// slightly non-trivial since it requires a format change. Given how rare
1592/// such cases are (for the moment?) scalarizing is an acceptable comprimise.
1593static void splitVectorValues(Instruction *StatepointInst,
Philip Reames704e78b2015-04-10 22:34:56 +00001594 StatepointLiveSetTy &LiveSet, DominatorTree &DT) {
Philip Reames8531d8c2015-04-10 21:48:25 +00001595 SmallVector<Value *, 16> ToSplit;
1596 for (Value *V : LiveSet)
1597 if (isa<VectorType>(V->getType()))
1598 ToSplit.push_back(V);
1599
1600 if (ToSplit.empty())
1601 return;
1602
1603 Function &F = *(StatepointInst->getParent()->getParent());
1604
Philip Reames704e78b2015-04-10 22:34:56 +00001605 DenseMap<Value *, AllocaInst *> AllocaMap;
Philip Reames8531d8c2015-04-10 21:48:25 +00001606 // First is normal return, second is exceptional return (invoke only)
Philip Reames704e78b2015-04-10 22:34:56 +00001607 DenseMap<Value *, std::pair<Value *, Value *>> Replacements;
Philip Reames8531d8c2015-04-10 21:48:25 +00001608 for (Value *V : ToSplit) {
1609 LiveSet.erase(V);
1610
Philip Reames704e78b2015-04-10 22:34:56 +00001611 AllocaInst *Alloca =
1612 new AllocaInst(V->getType(), "", F.getEntryBlock().getFirstNonPHI());
Philip Reames8531d8c2015-04-10 21:48:25 +00001613 AllocaMap[V] = Alloca;
1614
1615 VectorType *VT = cast<VectorType>(V->getType());
1616 IRBuilder<> Builder(StatepointInst);
Philip Reames704e78b2015-04-10 22:34:56 +00001617 SmallVector<Value *, 16> Elements;
Philip Reames8531d8c2015-04-10 21:48:25 +00001618 for (unsigned i = 0; i < VT->getNumElements(); i++)
1619 Elements.push_back(Builder.CreateExtractElement(V, Builder.getInt32(i)));
1620 LiveSet.insert(Elements.begin(), Elements.end());
1621
1622 auto InsertVectorReform = [&](Instruction *IP) {
1623 Builder.SetInsertPoint(IP);
1624 Builder.SetCurrentDebugLocation(IP->getDebugLoc());
1625 Value *ResultVec = UndefValue::get(VT);
1626 for (unsigned i = 0; i < VT->getNumElements(); i++)
1627 ResultVec = Builder.CreateInsertElement(ResultVec, Elements[i],
1628 Builder.getInt32(i));
1629 return ResultVec;
1630 };
1631
1632 if (isa<CallInst>(StatepointInst)) {
1633 BasicBlock::iterator Next(StatepointInst);
1634 Next++;
1635 Instruction *IP = &*(Next);
1636 Replacements[V].first = InsertVectorReform(IP);
1637 Replacements[V].second = nullptr;
1638 } else {
1639 InvokeInst *Invoke = cast<InvokeInst>(StatepointInst);
1640 // We've already normalized - check that we don't have shared destination
Philip Reames704e78b2015-04-10 22:34:56 +00001641 // blocks
Philip Reames8531d8c2015-04-10 21:48:25 +00001642 BasicBlock *NormalDest = Invoke->getNormalDest();
1643 assert(!isa<PHINode>(NormalDest->begin()));
1644 BasicBlock *UnwindDest = Invoke->getUnwindDest();
1645 assert(!isa<PHINode>(UnwindDest->begin()));
1646 // Insert insert element sequences in both successors
1647 Instruction *IP = &*(NormalDest->getFirstInsertionPt());
1648 Replacements[V].first = InsertVectorReform(IP);
1649 IP = &*(UnwindDest->getFirstInsertionPt());
1650 Replacements[V].second = InsertVectorReform(IP);
1651 }
1652 }
1653 for (Value *V : ToSplit) {
1654 AllocaInst *Alloca = AllocaMap[V];
1655
1656 // Capture all users before we start mutating use lists
Philip Reames704e78b2015-04-10 22:34:56 +00001657 SmallVector<Instruction *, 16> Users;
Philip Reames8531d8c2015-04-10 21:48:25 +00001658 for (User *U : V->users())
1659 Users.push_back(cast<Instruction>(U));
1660
1661 for (Instruction *I : Users) {
1662 if (auto Phi = dyn_cast<PHINode>(I)) {
1663 for (unsigned i = 0; i < Phi->getNumIncomingValues(); i++)
1664 if (V == Phi->getIncomingValue(i)) {
Philip Reames704e78b2015-04-10 22:34:56 +00001665 LoadInst *Load = new LoadInst(
1666 Alloca, "", Phi->getIncomingBlock(i)->getTerminator());
Philip Reames8531d8c2015-04-10 21:48:25 +00001667 Phi->setIncomingValue(i, Load);
1668 }
1669 } else {
1670 LoadInst *Load = new LoadInst(Alloca, "", I);
1671 I->replaceUsesOfWith(V, Load);
1672 }
1673 }
1674
1675 // Store the original value and the replacement value into the alloca
1676 StoreInst *Store = new StoreInst(V, Alloca);
1677 if (auto I = dyn_cast<Instruction>(V))
1678 Store->insertAfter(I);
1679 else
1680 Store->insertAfter(Alloca);
Philip Reames704e78b2015-04-10 22:34:56 +00001681
Philip Reames8531d8c2015-04-10 21:48:25 +00001682 // Normal return for invoke, or call return
1683 Instruction *Replacement = cast<Instruction>(Replacements[V].first);
1684 (new StoreInst(Replacement, Alloca))->insertAfter(Replacement);
1685 // Unwind return for invoke only
1686 Replacement = cast_or_null<Instruction>(Replacements[V].second);
1687 if (Replacement)
1688 (new StoreInst(Replacement, Alloca))->insertAfter(Replacement);
1689 }
1690
1691 // apply mem2reg to promote alloca to SSA
Philip Reames704e78b2015-04-10 22:34:56 +00001692 SmallVector<AllocaInst *, 16> Allocas;
Philip Reames8531d8c2015-04-10 21:48:25 +00001693 for (Value *V : ToSplit)
1694 Allocas.push_back(AllocaMap[V]);
1695 PromoteMemToReg(Allocas, DT);
1696}
1697
Philip Reamesd16a9b12015-02-20 01:06:44 +00001698static bool insertParsePoints(Function &F, DominatorTree &DT, Pass *P,
Philip Reamesd2b66462015-02-20 22:39:41 +00001699 SmallVectorImpl<CallSite> &toUpdate) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001700#ifndef NDEBUG
1701 // sanity check the input
1702 std::set<CallSite> uniqued;
1703 uniqued.insert(toUpdate.begin(), toUpdate.end());
1704 assert(uniqued.size() == toUpdate.size() && "no duplicates please!");
1705
1706 for (size_t i = 0; i < toUpdate.size(); i++) {
1707 CallSite &CS = toUpdate[i];
1708 assert(CS.getInstruction()->getParent()->getParent() == &F);
1709 assert(isStatepoint(CS) && "expected to already be a deopt statepoint");
1710 }
1711#endif
1712
Philip Reames69e51ca2015-04-13 18:07:21 +00001713 // When inserting gc.relocates for invokes, we need to be able to insert at
1714 // the top of the successor blocks. See the comment on
1715 // normalForInvokeSafepoint on exactly what is needed. Note that this step
Philip Reamesf209a152015-04-13 20:00:30 +00001716 // may restructure the CFG.
1717 for (CallSite CS : toUpdate) {
1718 if (!CS.isInvoke())
1719 continue;
1720 InvokeInst *invoke = cast<InvokeInst>(CS.getInstruction());
1721 normalizeForInvokeSafepoint(invoke->getNormalDest(), invoke->getParent(),
1722 P);
1723 normalizeForInvokeSafepoint(invoke->getUnwindDest(), invoke->getParent(),
1724 P);
1725 }
Philip Reames69e51ca2015-04-13 18:07:21 +00001726
Philip Reamesd16a9b12015-02-20 01:06:44 +00001727 // A list of dummy calls added to the IR to keep various values obviously
1728 // live in the IR. We'll remove all of these when done.
Philip Reamesd2b66462015-02-20 22:39:41 +00001729 SmallVector<CallInst *, 64> holders;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001730
1731 // Insert a dummy call with all of the arguments to the vm_state we'll need
1732 // for the actual safepoint insertion. This ensures reference arguments in
1733 // the deopt argument list are considered live through the safepoint (and
1734 // thus makes sure they get relocated.)
1735 for (size_t i = 0; i < toUpdate.size(); i++) {
1736 CallSite &CS = toUpdate[i];
1737 Statepoint StatepointCS(CS);
1738
1739 SmallVector<Value *, 64> DeoptValues;
1740 for (Use &U : StatepointCS.vm_state_args()) {
1741 Value *Arg = cast<Value>(&U);
Philip Reames8531d8c2015-04-10 21:48:25 +00001742 assert(!isUnhandledGCPointerType(Arg->getType()) &&
1743 "support for FCA unimplemented");
1744 if (isHandledGCPointerType(Arg->getType()))
Philip Reamesd16a9b12015-02-20 01:06:44 +00001745 DeoptValues.push_back(Arg);
1746 }
1747 insertUseHolderAfter(CS, DeoptValues, holders);
1748 }
1749
Philip Reamesd2b66462015-02-20 22:39:41 +00001750 SmallVector<struct PartiallyConstructedSafepointRecord, 64> records;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001751 records.reserve(toUpdate.size());
1752 for (size_t i = 0; i < toUpdate.size(); i++) {
1753 struct PartiallyConstructedSafepointRecord info;
1754 records.push_back(info);
1755 }
1756 assert(records.size() == toUpdate.size());
1757
1758 // A) Identify all gc pointers which are staticly live at the given call
1759 // site.
1760 findLiveReferences(F, DT, P, toUpdate, records);
1761
Philip Reames8531d8c2015-04-10 21:48:25 +00001762 // Do a limited scalarization of any live at safepoint vector values which
1763 // contain pointers. This enables this pass to run after vectorization at
1764 // the cost of some possible performance loss. TODO: it would be nice to
1765 // natively support vectors all the way through the backend so we don't need
1766 // to scalarize here.
1767 for (size_t i = 0; i < records.size(); i++) {
1768 struct PartiallyConstructedSafepointRecord &info = records[i];
1769 Instruction *statepoint = toUpdate[i].getInstruction();
1770 splitVectorValues(cast<Instruction>(statepoint), info.liveset, DT);
1771 }
1772
Philip Reamesd16a9b12015-02-20 01:06:44 +00001773 // B) Find the base pointers for each live pointer
1774 /* scope for caching */ {
1775 // Cache the 'defining value' relation used in the computation and
1776 // insertion of base phis and selects. This ensures that we don't insert
1777 // large numbers of duplicate base_phis.
1778 DefiningValueMapTy DVCache;
1779
1780 for (size_t i = 0; i < records.size(); i++) {
1781 struct PartiallyConstructedSafepointRecord &info = records[i];
1782 CallSite &CS = toUpdate[i];
1783 findBasePointers(DT, DVCache, CS, info);
1784 }
1785 } // end of cache scope
1786
1787 // The base phi insertion logic (for any safepoint) may have inserted new
1788 // instructions which are now live at some safepoint. The simplest such
1789 // example is:
1790 // loop:
1791 // phi a <-- will be a new base_phi here
1792 // safepoint 1 <-- that needs to be live here
1793 // gep a + 1
1794 // safepoint 2
1795 // br loop
Philip Reamesd16a9b12015-02-20 01:06:44 +00001796 // We insert some dummy calls after each safepoint to definitely hold live
1797 // the base pointers which were identified for that safepoint. We'll then
1798 // ask liveness for _every_ base inserted to see what is now live. Then we
1799 // remove the dummy calls.
1800 holders.reserve(holders.size() + records.size());
1801 for (size_t i = 0; i < records.size(); i++) {
1802 struct PartiallyConstructedSafepointRecord &info = records[i];
1803 CallSite &CS = toUpdate[i];
1804
1805 SmallVector<Value *, 128> Bases;
Philip Reamesf2041322015-02-20 19:26:04 +00001806 for (auto Pair : info.PointerToBase) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001807 Bases.push_back(Pair.second);
1808 }
1809 insertUseHolderAfter(CS, Bases, holders);
1810 }
1811
Philip Reamesdf1ef082015-04-10 22:53:14 +00001812 // By selecting base pointers, we've effectively inserted new uses. Thus, we
1813 // need to rerun liveness. We may *also* have inserted new defs, but that's
1814 // not the key issue.
1815 recomputeLiveInValues(F, DT, P, toUpdate, records);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001816
Philip Reamesd16a9b12015-02-20 01:06:44 +00001817 if (PrintBasePointers) {
1818 for (size_t i = 0; i < records.size(); i++) {
1819 struct PartiallyConstructedSafepointRecord &info = records[i];
1820 errs() << "Base Pairs: (w/Relocation)\n";
Philip Reamesf2041322015-02-20 19:26:04 +00001821 for (auto Pair : info.PointerToBase) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001822 errs() << " derived %" << Pair.first->getName() << " base %"
1823 << Pair.second->getName() << "\n";
1824 }
1825 }
1826 }
1827 for (size_t i = 0; i < holders.size(); i++) {
1828 holders[i]->eraseFromParent();
1829 holders[i] = nullptr;
1830 }
1831 holders.clear();
1832
1833 // Now run through and replace the existing statepoints with new ones with
1834 // the live variables listed. We do not yet update uses of the values being
1835 // relocated. We have references to live variables that need to
1836 // survive to the last iteration of this loop. (By construction, the
1837 // previous statepoint can not be a live variable, thus we can and remove
1838 // the old statepoint calls as we go.)
1839 for (size_t i = 0; i < records.size(); i++) {
1840 struct PartiallyConstructedSafepointRecord &info = records[i];
1841 CallSite &CS = toUpdate[i];
1842 makeStatepointExplicit(DT, CS, P, info);
1843 }
1844 toUpdate.clear(); // prevent accident use of invalid CallSites
1845
Philip Reamesd16a9b12015-02-20 01:06:44 +00001846 // Do all the fixups of the original live variables to their relocated selves
Philip Reamesd2b66462015-02-20 22:39:41 +00001847 SmallVector<Value *, 128> live;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001848 for (size_t i = 0; i < records.size(); i++) {
1849 struct PartiallyConstructedSafepointRecord &info = records[i];
1850 // We can't simply save the live set from the original insertion. One of
1851 // the live values might be the result of a call which needs a safepoint.
1852 // That Value* no longer exists and we need to use the new gc_result.
1853 // Thankfully, the liveset is embedded in the statepoint (and updated), so
1854 // we just grab that.
Philip Reames0a3240f2015-02-20 21:34:11 +00001855 Statepoint statepoint(info.StatepointToken);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001856 live.insert(live.end(), statepoint.gc_args_begin(),
1857 statepoint.gc_args_end());
Philip Reames9a2e01d2015-04-13 17:35:55 +00001858#ifndef NDEBUG
1859 // Do some basic sanity checks on our liveness results before performing
1860 // relocation. Relocation can and will turn mistakes in liveness results
1861 // into non-sensical code which is must harder to debug.
1862 // TODO: It would be nice to test consistency as well
1863 assert(DT.isReachableFromEntry(info.StatepointToken->getParent()) &&
1864 "statepoint must be reachable or liveness is meaningless");
1865 for (Value *V : statepoint.gc_args()) {
1866 if (!isa<Instruction>(V))
1867 // Non-instruction values trivial dominate all possible uses
1868 continue;
1869 auto LiveInst = cast<Instruction>(V);
1870 assert(DT.isReachableFromEntry(LiveInst->getParent()) &&
1871 "unreachable values should never be live");
1872 assert(DT.dominates(LiveInst, info.StatepointToken) &&
1873 "basic SSA liveness expectation violated by liveness analysis");
1874 }
1875#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +00001876 }
1877 unique_unsorted(live);
1878
Nick Lewyckyeb3231e2015-02-20 07:14:02 +00001879#ifndef NDEBUG
Philip Reamesd16a9b12015-02-20 01:06:44 +00001880 // sanity check
1881 for (auto ptr : live) {
1882 assert(isGCPointerType(ptr->getType()) && "must be a gc pointer type");
1883 }
Nick Lewyckyeb3231e2015-02-20 07:14:02 +00001884#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +00001885
1886 relocationViaAlloca(F, DT, live, records);
1887 return !records.empty();
1888}
1889
1890/// Returns true if this function should be rewritten by this pass. The main
1891/// point of this function is as an extension point for custom logic.
1892static bool shouldRewriteStatepointsIn(Function &F) {
1893 // TODO: This should check the GCStrategy
Philip Reames2ef029c2015-02-20 18:56:14 +00001894 if (F.hasGC()) {
1895 const std::string StatepointExampleName("statepoint-example");
1896 return StatepointExampleName == F.getGC();
1897 } else
1898 return false;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001899}
1900
1901bool RewriteStatepointsForGC::runOnFunction(Function &F) {
1902 // Nothing to do for declarations.
1903 if (F.isDeclaration() || F.empty())
1904 return false;
1905
1906 // Policy choice says not to rewrite - the most common reason is that we're
1907 // compiling code without a GCStrategy.
1908 if (!shouldRewriteStatepointsIn(F))
1909 return false;
1910
Philip Reames85b36a82015-04-10 22:07:04 +00001911 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Philip Reames704e78b2015-04-10 22:34:56 +00001912
Philip Reames85b36a82015-04-10 22:07:04 +00001913 // Gather all the statepoints which need rewritten. Be careful to only
1914 // consider those in reachable code since we need to ask dominance queries
1915 // when rewriting. We'll delete the unreachable ones in a moment.
Philip Reamesd2b66462015-02-20 22:39:41 +00001916 SmallVector<CallSite, 64> ParsePointNeeded;
Philip Reamesf66d7372015-04-10 22:16:58 +00001917 bool HasUnreachableStatepoint = false;
Philip Reamesd2b66462015-02-20 22:39:41 +00001918 for (Instruction &I : inst_range(F)) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001919 // TODO: only the ones with the flag set!
Philip Reames85b36a82015-04-10 22:07:04 +00001920 if (isStatepoint(I)) {
1921 if (DT.isReachableFromEntry(I.getParent()))
1922 ParsePointNeeded.push_back(CallSite(&I));
1923 else
Philip Reamesf66d7372015-04-10 22:16:58 +00001924 HasUnreachableStatepoint = true;
Philip Reames85b36a82015-04-10 22:07:04 +00001925 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00001926 }
1927
Philip Reames85b36a82015-04-10 22:07:04 +00001928 bool MadeChange = false;
Philip Reames704e78b2015-04-10 22:34:56 +00001929
Philip Reames85b36a82015-04-10 22:07:04 +00001930 // Delete any unreachable statepoints so that we don't have unrewritten
1931 // statepoints surviving this pass. This makes testing easier and the
1932 // resulting IR less confusing to human readers. Rather than be fancy, we
1933 // just reuse a utility function which removes the unreachable blocks.
Philip Reamesf66d7372015-04-10 22:16:58 +00001934 if (HasUnreachableStatepoint)
Philip Reames85b36a82015-04-10 22:07:04 +00001935 MadeChange |= removeUnreachableBlocks(F);
1936
Philip Reamesd16a9b12015-02-20 01:06:44 +00001937 // Return early if no work to do.
1938 if (ParsePointNeeded.empty())
Philip Reames85b36a82015-04-10 22:07:04 +00001939 return MadeChange;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001940
Philip Reames85b36a82015-04-10 22:07:04 +00001941 // As a prepass, go ahead and aggressively destroy single entry phi nodes.
1942 // These are created by LCSSA. They have the effect of increasing the size
1943 // of liveness sets for no good reason. It may be harder to do this post
1944 // insertion since relocations and base phis can confuse things.
1945 for (BasicBlock &BB : F)
1946 if (BB.getUniquePredecessor()) {
1947 MadeChange = true;
1948 FoldSingleEntryPHINodes(&BB);
1949 }
1950
1951 MadeChange |= insertParsePoints(F, DT, this, ParsePointNeeded);
1952 return MadeChange;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001953}
Philip Reamesdf1ef082015-04-10 22:53:14 +00001954
1955// liveness computation via standard dataflow
1956// -------------------------------------------------------------------
1957
1958// TODO: Consider using bitvectors for liveness, the set of potentially
1959// interesting values should be small and easy to pre-compute.
1960
1961/// Is this value a constant consisting of entirely null values?
1962static bool isConstantNull(Value *V) {
1963 return isa<Constant>(V) && cast<Constant>(V)->isNullValue();
1964}
1965
1966/// Compute the live-in set for the location rbegin starting from
1967/// the live-out set of the basic block
1968static void computeLiveInValues(BasicBlock::reverse_iterator rbegin,
1969 BasicBlock::reverse_iterator rend,
1970 DenseSet<Value *> &LiveTmp) {
1971
1972 for (BasicBlock::reverse_iterator ritr = rbegin; ritr != rend; ritr++) {
1973 Instruction *I = &*ritr;
1974
1975 // KILL/Def - Remove this definition from LiveIn
1976 LiveTmp.erase(I);
1977
1978 // Don't consider *uses* in PHI nodes, we handle their contribution to
1979 // predecessor blocks when we seed the LiveOut sets
1980 if (isa<PHINode>(I))
1981 continue;
1982
1983 // USE - Add to the LiveIn set for this instruction
1984 for (Value *V : I->operands()) {
1985 assert(!isUnhandledGCPointerType(V->getType()) &&
1986 "support for FCA unimplemented");
1987 if (isHandledGCPointerType(V->getType()) && !isConstantNull(V) &&
1988 !isa<UndefValue>(V)) {
1989 // The choice to exclude null and undef is arbitrary here. Reconsider?
1990 LiveTmp.insert(V);
1991 }
1992 }
1993 }
1994}
1995
1996static void computeLiveOutSeed(BasicBlock *BB, DenseSet<Value *> &LiveTmp) {
1997
1998 for (BasicBlock *Succ : successors(BB)) {
1999 const BasicBlock::iterator E(Succ->getFirstNonPHI());
2000 for (BasicBlock::iterator I = Succ->begin(); I != E; I++) {
2001 PHINode *Phi = cast<PHINode>(&*I);
2002 Value *V = Phi->getIncomingValueForBlock(BB);
2003 assert(!isUnhandledGCPointerType(V->getType()) &&
2004 "support for FCA unimplemented");
2005 if (isHandledGCPointerType(V->getType()) && !isConstantNull(V) &&
2006 !isa<UndefValue>(V)) {
2007 // The choice to exclude null and undef is arbitrary here. Reconsider?
2008 LiveTmp.insert(V);
2009 }
2010 }
2011 }
2012}
2013
2014static DenseSet<Value *> computeKillSet(BasicBlock *BB) {
2015 DenseSet<Value *> KillSet;
2016 for (Instruction &I : *BB)
2017 if (isHandledGCPointerType(I.getType()))
2018 KillSet.insert(&I);
2019 return KillSet;
2020}
2021
Philip Reames9638ff92015-04-11 00:06:47 +00002022#ifndef NDEBUG
Philip Reamesdf1ef082015-04-10 22:53:14 +00002023/// Check that the items in 'Live' dominate 'TI'. This is used as a basic
2024/// sanity check for the liveness computation.
2025static void checkBasicSSA(DominatorTree &DT, DenseSet<Value *> &Live,
2026 TerminatorInst *TI, bool TermOkay = false) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00002027 for (Value *V : Live) {
2028 if (auto *I = dyn_cast<Instruction>(V)) {
2029 // The terminator can be a member of the LiveOut set. LLVM's definition
2030 // of instruction dominance states that V does not dominate itself. As
2031 // such, we need to special case this to allow it.
2032 if (TermOkay && TI == I)
2033 continue;
2034 assert(DT.dominates(I, TI) &&
2035 "basic SSA liveness expectation violated by liveness analysis");
2036 }
2037 }
Philip Reamesdf1ef082015-04-10 22:53:14 +00002038}
2039
2040/// Check that all the liveness sets used during the computation of liveness
2041/// obey basic SSA properties. This is useful for finding cases where we miss
2042/// a def.
2043static void checkBasicSSA(DominatorTree &DT, GCPtrLivenessData &Data,
2044 BasicBlock &BB) {
2045 checkBasicSSA(DT, Data.LiveSet[&BB], BB.getTerminator());
2046 checkBasicSSA(DT, Data.LiveOut[&BB], BB.getTerminator(), true);
2047 checkBasicSSA(DT, Data.LiveIn[&BB], BB.getTerminator());
2048}
Philip Reames9638ff92015-04-11 00:06:47 +00002049#endif
Philip Reamesdf1ef082015-04-10 22:53:14 +00002050
2051static void computeLiveInValues(DominatorTree &DT, Function &F,
2052 GCPtrLivenessData &Data) {
2053
Philip Reames4d80ede2015-04-10 23:11:26 +00002054 SmallSetVector<BasicBlock *, 200> Worklist;
Philip Reamesdf1ef082015-04-10 22:53:14 +00002055 auto AddPredsToWorklist = [&](BasicBlock *BB) {
Philip Reames4d80ede2015-04-10 23:11:26 +00002056 // We use a SetVector so that we don't have duplicates in the worklist.
2057 Worklist.insert(pred_begin(BB), pred_end(BB));
Philip Reamesdf1ef082015-04-10 22:53:14 +00002058 };
2059 auto NextItem = [&]() {
2060 BasicBlock *BB = Worklist.back();
2061 Worklist.pop_back();
Philip Reamesdf1ef082015-04-10 22:53:14 +00002062 return BB;
2063 };
2064
2065 // Seed the liveness for each individual block
2066 for (BasicBlock &BB : F) {
2067 Data.KillSet[&BB] = computeKillSet(&BB);
2068 Data.LiveSet[&BB].clear();
2069 computeLiveInValues(BB.rbegin(), BB.rend(), Data.LiveSet[&BB]);
2070
2071#ifndef NDEBUG
2072 for (Value *Kill : Data.KillSet[&BB])
2073 assert(!Data.LiveSet[&BB].count(Kill) && "live set contains kill");
2074#endif
2075
2076 Data.LiveOut[&BB] = DenseSet<Value *>();
2077 computeLiveOutSeed(&BB, Data.LiveOut[&BB]);
2078 Data.LiveIn[&BB] = Data.LiveSet[&BB];
2079 set_union(Data.LiveIn[&BB], Data.LiveOut[&BB]);
2080 set_subtract(Data.LiveIn[&BB], Data.KillSet[&BB]);
2081 if (!Data.LiveIn[&BB].empty())
2082 AddPredsToWorklist(&BB);
2083 }
2084
2085 // Propagate that liveness until stable
2086 while (!Worklist.empty()) {
2087 BasicBlock *BB = NextItem();
2088
2089 // Compute our new liveout set, then exit early if it hasn't changed
2090 // despite the contribution of our successor.
2091 DenseSet<Value *> LiveOut = Data.LiveOut[BB];
2092 const auto OldLiveOutSize = LiveOut.size();
2093 for (BasicBlock *Succ : successors(BB)) {
2094 assert(Data.LiveIn.count(Succ));
2095 set_union(LiveOut, Data.LiveIn[Succ]);
2096 }
2097 // assert OutLiveOut is a subset of LiveOut
2098 if (OldLiveOutSize == LiveOut.size()) {
2099 // If the sets are the same size, then we didn't actually add anything
2100 // when unioning our successors LiveIn Thus, the LiveIn of this block
2101 // hasn't changed.
2102 continue;
2103 }
2104 Data.LiveOut[BB] = LiveOut;
2105
2106 // Apply the effects of this basic block
2107 DenseSet<Value *> LiveTmp = LiveOut;
2108 set_union(LiveTmp, Data.LiveSet[BB]);
2109 set_subtract(LiveTmp, Data.KillSet[BB]);
2110
2111 assert(Data.LiveIn.count(BB));
2112 const DenseSet<Value *> &OldLiveIn = Data.LiveIn[BB];
2113 // assert: OldLiveIn is a subset of LiveTmp
2114 if (OldLiveIn.size() != LiveTmp.size()) {
2115 Data.LiveIn[BB] = LiveTmp;
2116 AddPredsToWorklist(BB);
2117 }
2118 } // while( !worklist.empty() )
2119
2120#ifndef NDEBUG
2121 // Sanity check our ouput against SSA properties. This helps catch any
2122 // missing kills during the above iteration.
2123 for (BasicBlock &BB : F) {
2124 checkBasicSSA(DT, Data, BB);
2125 }
2126#endif
2127}
2128
2129static void findLiveSetAtInst(Instruction *Inst, GCPtrLivenessData &Data,
2130 StatepointLiveSetTy &Out) {
2131
2132 BasicBlock *BB = Inst->getParent();
2133
2134 // Note: The copy is intentional and required
2135 assert(Data.LiveOut.count(BB));
2136 DenseSet<Value *> LiveOut = Data.LiveOut[BB];
2137
2138 // We want to handle the statepoint itself oddly. It's
2139 // call result is not live (normal), nor are it's arguments
2140 // (unless they're used again later). This adjustment is
2141 // specifically what we need to relocate
2142 BasicBlock::reverse_iterator rend(Inst);
2143 computeLiveInValues(BB->rbegin(), rend, LiveOut);
2144 LiveOut.erase(Inst);
2145 Out.insert(LiveOut.begin(), LiveOut.end());
2146}
2147
2148static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData,
2149 const CallSite &CS,
2150 PartiallyConstructedSafepointRecord &Info) {
2151 Instruction *Inst = CS.getInstruction();
2152 StatepointLiveSetTy Updated;
2153 findLiveSetAtInst(Inst, RevisedLivenessData, Updated);
2154
2155#ifndef NDEBUG
2156 DenseSet<Value *> Bases;
2157 for (auto KVPair : Info.PointerToBase) {
2158 Bases.insert(KVPair.second);
2159 }
2160#endif
2161 // We may have base pointers which are now live that weren't before. We need
2162 // to update the PointerToBase structure to reflect this.
2163 for (auto V : Updated)
2164 if (!Info.PointerToBase.count(V)) {
2165 assert(Bases.count(V) && "can't find base for unexpected live value");
2166 Info.PointerToBase[V] = V;
2167 continue;
2168 }
2169
2170#ifndef NDEBUG
2171 for (auto V : Updated) {
2172 assert(Info.PointerToBase.count(V) &&
2173 "must be able to find base for live value");
2174 }
2175#endif
2176
2177 // Remove any stale base mappings - this can happen since our liveness is
2178 // more precise then the one inherent in the base pointer analysis
2179 DenseSet<Value *> ToErase;
2180 for (auto KVPair : Info.PointerToBase)
2181 if (!Updated.count(KVPair.first))
2182 ToErase.insert(KVPair.first);
2183 for (auto V : ToErase)
2184 Info.PointerToBase.erase(V);
2185
2186#ifndef NDEBUG
2187 for (auto KVPair : Info.PointerToBase)
2188 assert(Updated.count(KVPair.first) && "record for non-live value");
2189#endif
2190
2191 Info.liveset = Updated;
2192}