blob: 8c2cb35566811bedfe7c1c7f6b015f916bc10895 [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
134 /// Any new values which were added to the IR during base pointer analysis
135 /// for this safepoint
Philip Reamesf2041322015-02-20 19:26:04 +0000136 DenseSet<llvm::Value *> NewInsertedDefs;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000137
Philip Reames0a3240f2015-02-20 21:34:11 +0000138 /// The *new* gc.statepoint instruction itself. This produces the token
139 /// that normal path gc.relocates and the gc.result are tied to.
140 Instruction *StatepointToken;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000141
Philip Reamesf2041322015-02-20 19:26:04 +0000142 /// Instruction to which exceptional gc relocates are attached
143 /// Makes it easier to iterate through them during relocationViaAlloca.
144 Instruction *UnwindToken;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000145};
146}
147
Philip Reamesdf1ef082015-04-10 22:53:14 +0000148/// Compute the live-in set for every basic block in the function
149static void computeLiveInValues(DominatorTree &DT, Function &F,
150 GCPtrLivenessData &Data);
151
152/// Given results from the dataflow liveness computation, find the set of live
153/// Values at a particular instruction.
154static void findLiveSetAtInst(Instruction *inst, GCPtrLivenessData &Data,
155 StatepointLiveSetTy &out);
156
Philip Reamesd16a9b12015-02-20 01:06:44 +0000157// TODO: Once we can get to the GCStrategy, this becomes
158// Optional<bool> isGCManagedPointer(const Value *V) const override {
159
160static bool isGCPointerType(const Type *T) {
161 if (const PointerType *PT = dyn_cast<PointerType>(T))
162 // For the sake of this example GC, we arbitrarily pick addrspace(1) as our
163 // GC managed heap. We know that a pointer into this heap needs to be
164 // updated and that no other pointer does.
165 return (1 == PT->getAddressSpace());
166 return false;
167}
168
Philip Reames8531d8c2015-04-10 21:48:25 +0000169// Return true if this type is one which a) is a gc pointer or contains a GC
170// pointer and b) is of a type this code expects to encounter as a live value.
171// (The insertion code will assert that a type which matches (a) and not (b)
Philip Reames704e78b2015-04-10 22:34:56 +0000172// is not encountered.)
Philip Reames8531d8c2015-04-10 21:48:25 +0000173static bool isHandledGCPointerType(Type *T) {
174 // We fully support gc pointers
175 if (isGCPointerType(T))
176 return true;
177 // We partially support vectors of gc pointers. The code will assert if it
178 // can't handle something.
179 if (auto VT = dyn_cast<VectorType>(T))
180 if (isGCPointerType(VT->getElementType()))
181 return true;
182 return false;
183}
184
185#ifndef NDEBUG
186/// Returns true if this type contains a gc pointer whether we know how to
187/// handle that type or not.
188static bool containsGCPtrType(Type *Ty) {
Philip Reames704e78b2015-04-10 22:34:56 +0000189 if (isGCPointerType(Ty))
Philip Reames8531d8c2015-04-10 21:48:25 +0000190 return true;
191 if (VectorType *VT = dyn_cast<VectorType>(Ty))
192 return isGCPointerType(VT->getScalarType());
193 if (ArrayType *AT = dyn_cast<ArrayType>(Ty))
194 return containsGCPtrType(AT->getElementType());
195 if (StructType *ST = dyn_cast<StructType>(Ty))
Philip Reames704e78b2015-04-10 22:34:56 +0000196 return std::any_of(
197 ST->subtypes().begin(), ST->subtypes().end(),
198 [](Type *SubType) { return containsGCPtrType(SubType); });
Philip Reames8531d8c2015-04-10 21:48:25 +0000199 return false;
200}
201
202// Returns true if this is a type which a) is a gc pointer or contains a GC
203// pointer and b) is of a type which the code doesn't expect (i.e. first class
204// aggregates). Used to trip assertions.
205static bool isUnhandledGCPointerType(Type *Ty) {
206 return containsGCPtrType(Ty) && !isHandledGCPointerType(Ty);
207}
208#endif
209
Philip Reamesd16a9b12015-02-20 01:06:44 +0000210static bool order_by_name(llvm::Value *a, llvm::Value *b) {
211 if (a->hasName() && b->hasName()) {
212 return -1 == a->getName().compare(b->getName());
213 } else if (a->hasName() && !b->hasName()) {
214 return true;
215 } else if (!a->hasName() && b->hasName()) {
216 return false;
217 } else {
218 // Better than nothing, but not stable
219 return a < b;
220 }
221}
222
Philip Reamesdf1ef082015-04-10 22:53:14 +0000223// Conservatively identifies any definitions which might be live at the
224// given instruction. The analysis is performed immediately before the
225// given instruction. Values defined by that instruction are not considered
226// live. Values used by that instruction are considered live.
227static void analyzeParsePointLiveness(
228 DominatorTree &DT, GCPtrLivenessData &OriginalLivenessData,
229 const CallSite &CS, PartiallyConstructedSafepointRecord &result) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000230 Instruction *inst = CS.getInstruction();
231
Philip Reames1f017542015-02-20 23:16:52 +0000232 StatepointLiveSetTy liveset;
Philip Reamesdf1ef082015-04-10 22:53:14 +0000233 findLiveSetAtInst(inst, OriginalLivenessData, liveset);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000234
235 if (PrintLiveSet) {
236 // Note: This output is used by several of the test cases
237 // The order of elemtns in a set is not stable, put them in a vec and sort
238 // by name
Philip Reames860660e2015-02-20 22:05:18 +0000239 SmallVector<Value *, 64> temp;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000240 temp.insert(temp.end(), liveset.begin(), liveset.end());
241 std::sort(temp.begin(), temp.end(), order_by_name);
242 errs() << "Live Variables:\n";
243 for (Value *V : temp) {
244 errs() << " " << V->getName(); // no newline
245 V->dump();
246 }
247 }
248 if (PrintLiveSetSize) {
249 errs() << "Safepoint For: " << CS.getCalledValue()->getName() << "\n";
250 errs() << "Number live values: " << liveset.size() << "\n";
251 }
252 result.liveset = liveset;
253}
254
Philip Reames8531d8c2015-04-10 21:48:25 +0000255/// If we can trivially determine that this vector contains only base pointers,
Philip Reames704e78b2015-04-10 22:34:56 +0000256/// return the base instruction.
Philip Reames8531d8c2015-04-10 21:48:25 +0000257static Value *findBaseOfVector(Value *I) {
258 assert(I->getType()->isVectorTy() &&
259 cast<VectorType>(I->getType())->getElementType()->isPointerTy() &&
260 "Illegal to ask for the base pointer of a non-pointer type");
261
262 // Each case parallels findBaseDefiningValue below, see that code for
263 // detailed motivation.
264
265 if (isa<Argument>(I))
266 // An incoming argument to the function is a base pointer
267 return I;
268
269 // We shouldn't see the address of a global as a vector value?
270 assert(!isa<GlobalVariable>(I) &&
271 "unexpected global variable found in base of vector");
272
273 // inlining could possibly introduce phi node that contains
274 // undef if callee has multiple returns
275 if (isa<UndefValue>(I))
276 // utterly meaningless, but useful for dealing with partially optimized
277 // code.
Philip Reames704e78b2015-04-10 22:34:56 +0000278 return I;
Philip Reames8531d8c2015-04-10 21:48:25 +0000279
280 // Due to inheritance, this must be _after_ the global variable and undef
281 // checks
282 if (Constant *Con = dyn_cast<Constant>(I)) {
283 assert(!isa<GlobalVariable>(I) && !isa<UndefValue>(I) &&
284 "order of checks wrong!");
285 assert(Con->isNullValue() && "null is the only case which makes sense");
286 return Con;
287 }
288
289 if (isa<LoadInst>(I))
290 return I;
291
292 // Note: This code is currently rather incomplete. We are essentially only
293 // handling cases where the vector element is trivially a base pointer. We
294 // need to update the entire base pointer construction algorithm to know how
295 // to track vector elements and potentially scalarize, but the case which
296 // would motivate the work hasn't shown up in real workloads yet.
297 llvm_unreachable("no base found for vector element");
298}
299
Philip Reamesd16a9b12015-02-20 01:06:44 +0000300/// Helper function for findBasePointer - Will return a value which either a)
301/// defines the base pointer for the input or b) blocks the simple search
302/// (i.e. a PHI or Select of two derived pointers)
303static Value *findBaseDefiningValue(Value *I) {
304 assert(I->getType()->isPointerTy() &&
305 "Illegal to ask for the base pointer of a non-pointer type");
306
Philip Reames8531d8c2015-04-10 21:48:25 +0000307 // This case is a bit of a hack - it only handles extracts from vectors which
308 // trivially contain only base pointers. See note inside the function for
309 // how to improve this.
310 if (auto *EEI = dyn_cast<ExtractElementInst>(I)) {
311 Value *VectorOperand = EEI->getVectorOperand();
312 Value *VectorBase = findBaseOfVector(VectorOperand);
Philip Reamesf66d7372015-04-10 22:16:58 +0000313 (void)VectorBase;
Philip Reames8531d8c2015-04-10 21:48:25 +0000314 assert(VectorBase && "extract element not known to be a trivial base");
315 return EEI;
316 }
Philip Reamesd16a9b12015-02-20 01:06:44 +0000317
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000318 if (isa<Argument>(I))
Philip Reamesd16a9b12015-02-20 01:06:44 +0000319 // An incoming argument to the function is a base pointer
320 // We should have never reached here if this argument isn't an gc value
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000321 return I;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000322
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000323 if (isa<GlobalVariable>(I))
Philip Reamesd16a9b12015-02-20 01:06:44 +0000324 // base case
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000325 return I;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000326
327 // inlining could possibly introduce phi node that contains
328 // undef if callee has multiple returns
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000329 if (isa<UndefValue>(I))
330 // utterly meaningless, but useful for dealing with
331 // partially optimized code.
Philip Reames704e78b2015-04-10 22:34:56 +0000332 return I;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000333
334 // Due to inheritance, this must be _after_ the global variable and undef
335 // checks
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000336 if (Constant *Con = dyn_cast<Constant>(I)) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000337 assert(!isa<GlobalVariable>(I) && !isa<UndefValue>(I) &&
338 "order of checks wrong!");
339 // Note: Finding a constant base for something marked for relocation
340 // doesn't really make sense. The most likely case is either a) some
341 // screwed up the address space usage or b) your validating against
342 // compiled C++ code w/o the proper separation. The only real exception
343 // is a null pointer. You could have generic code written to index of
344 // off a potentially null value and have proven it null. We also use
345 // null pointers in dead paths of relocation phis (which we might later
346 // want to find a base pointer for).
Philip Reames24c6cd52015-03-27 05:47:00 +0000347 assert(isa<ConstantPointerNull>(Con) &&
348 "null is the only case which makes sense");
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000349 return Con;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000350 }
351
352 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000353 Value *Def = CI->stripPointerCasts();
David Blaikie82ad7872015-02-20 23:44:24 +0000354 // If we find a cast instruction here, it means we've found a cast which is
355 // not simply a pointer cast (i.e. an inttoptr). We don't know how to
356 // handle int->ptr conversion.
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000357 assert(!isa<CastInst>(Def) && "shouldn't find another cast here");
358 return findBaseDefiningValue(Def);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000359 }
360
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000361 if (isa<LoadInst>(I))
362 return I; // The value loaded is an gc base itself
Philip Reamesd16a9b12015-02-20 01:06:44 +0000363
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000364 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I))
365 // The base of this GEP is the base
366 return findBaseDefiningValue(GEP->getPointerOperand());
Philip Reamesd16a9b12015-02-20 01:06:44 +0000367
368 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
369 switch (II->getIntrinsicID()) {
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000370 case Intrinsic::experimental_gc_result_ptr:
Philip Reamesd16a9b12015-02-20 01:06:44 +0000371 default:
372 // fall through to general call handling
373 break;
374 case Intrinsic::experimental_gc_statepoint:
375 case Intrinsic::experimental_gc_result_float:
376 case Intrinsic::experimental_gc_result_int:
377 llvm_unreachable("these don't produce pointers");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000378 case Intrinsic::experimental_gc_relocate: {
379 // Rerunning safepoint insertion after safepoints are already
380 // inserted is not supported. It could probably be made to work,
381 // but why are you doing this? There's no good reason.
382 llvm_unreachable("repeat safepoint insertion is not supported");
383 }
384 case Intrinsic::gcroot:
385 // Currently, this mechanism hasn't been extended to work with gcroot.
386 // There's no reason it couldn't be, but I haven't thought about the
387 // implications much.
388 llvm_unreachable(
389 "interaction with the gcroot mechanism is not supported");
390 }
391 }
392 // We assume that functions in the source language only return base
393 // pointers. This should probably be generalized via attributes to support
394 // both source language and internal functions.
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000395 if (isa<CallInst>(I) || isa<InvokeInst>(I))
396 return I;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000397
398 // I have absolutely no idea how to implement this part yet. It's not
399 // neccessarily hard, I just haven't really looked at it yet.
400 assert(!isa<LandingPadInst>(I) && "Landing Pad is unimplemented");
401
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000402 if (isa<AtomicCmpXchgInst>(I))
Philip Reamesd16a9b12015-02-20 01:06:44 +0000403 // A CAS is effectively a atomic store and load combined under a
404 // predicate. From the perspective of base pointers, we just treat it
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000405 // like a load.
406 return I;
Philip Reames704e78b2015-04-10 22:34:56 +0000407
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000408 assert(!isa<AtomicRMWInst>(I) && "Xchg handled above, all others are "
Philip Reames704e78b2015-04-10 22:34:56 +0000409 "binary ops which don't apply to pointers");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000410
411 // The aggregate ops. Aggregates can either be in the heap or on the
412 // stack, but in either case, this is simply a field load. As a result,
413 // this is a defining definition of the base just like a load is.
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000414 if (isa<ExtractValueInst>(I))
415 return I;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000416
417 // We should never see an insert vector since that would require we be
418 // tracing back a struct value not a pointer value.
419 assert(!isa<InsertValueInst>(I) &&
420 "Base pointer for a struct is meaningless");
421
422 // The last two cases here don't return a base pointer. Instead, they
423 // return a value which dynamically selects from amoung several base
424 // derived pointers (each with it's own base potentially). It's the job of
425 // the caller to resolve these.
Philip Reames704e78b2015-04-10 22:34:56 +0000426 assert((isa<SelectInst>(I) || isa<PHINode>(I)) &&
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000427 "missing instruction case in findBaseDefiningValing");
428 return I;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000429}
430
431/// Returns the base defining value for this value.
Philip Reames18d0feb2015-03-27 05:39:32 +0000432static Value *findBaseDefiningValueCached(Value *I, DefiningValueMapTy &Cache) {
433 Value *&Cached = Cache[I];
Benjamin Kramer6f665452015-02-20 14:00:58 +0000434 if (!Cached) {
435 Cached = findBaseDefiningValue(I);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000436 }
Philip Reames18d0feb2015-03-27 05:39:32 +0000437 assert(Cache[I] != nullptr);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000438
439 if (TraceLSP) {
Philip Reames18d0feb2015-03-27 05:39:32 +0000440 dbgs() << "fBDV-cached: " << I->getName() << " -> " << Cached->getName()
Philip Reamesd16a9b12015-02-20 01:06:44 +0000441 << "\n";
442 }
Benjamin Kramer6f665452015-02-20 14:00:58 +0000443 return Cached;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000444}
445
446/// Return a base pointer for this value if known. Otherwise, return it's
447/// base defining value.
Philip Reames18d0feb2015-03-27 05:39:32 +0000448static Value *findBaseOrBDV(Value *I, DefiningValueMapTy &Cache) {
449 Value *Def = findBaseDefiningValueCached(I, Cache);
450 auto Found = Cache.find(Def);
451 if (Found != Cache.end()) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000452 // Either a base-of relation, or a self reference. Caller must check.
Benjamin Kramer6f665452015-02-20 14:00:58 +0000453 return Found->second;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000454 }
455 // Only a BDV available
Philip Reames18d0feb2015-03-27 05:39:32 +0000456 return Def;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000457}
458
459/// Given the result of a call to findBaseDefiningValue, or findBaseOrBDV,
460/// is it known to be a base pointer? Or do we need to continue searching.
Philip Reames18d0feb2015-03-27 05:39:32 +0000461static bool isKnownBaseResult(Value *V) {
462 if (!isa<PHINode>(V) && !isa<SelectInst>(V)) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000463 // no recursion possible
464 return true;
465 }
Philip Reames18d0feb2015-03-27 05:39:32 +0000466 if (isa<Instruction>(V) &&
467 cast<Instruction>(V)->getMetadata("is_base_value")) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000468 // This is a previously inserted base phi or select. We know
469 // that this is a base value.
470 return true;
471 }
472
473 // We need to keep searching
474 return false;
475}
476
477// TODO: find a better name for this
478namespace {
479class PhiState {
480public:
481 enum Status { Unknown, Base, Conflict };
482
483 PhiState(Status s, Value *b = nullptr) : status(s), base(b) {
484 assert(status != Base || b);
485 }
486 PhiState(Value *b) : status(Base), base(b) {}
487 PhiState() : status(Unknown), base(nullptr) {}
Philip Reamesd16a9b12015-02-20 01:06:44 +0000488
489 Status getStatus() const { return status; }
490 Value *getBase() const { return base; }
491
492 bool isBase() const { return getStatus() == Base; }
493 bool isUnknown() const { return getStatus() == Unknown; }
494 bool isConflict() const { return getStatus() == Conflict; }
495
496 bool operator==(const PhiState &other) const {
497 return base == other.base && status == other.status;
498 }
499
500 bool operator!=(const PhiState &other) const { return !(*this == other); }
501
502 void dump() {
503 errs() << status << " (" << base << " - "
504 << (base ? base->getName() : "nullptr") << "): ";
505 }
506
507private:
508 Status status;
509 Value *base; // non null only if status == base
510};
511
Philip Reamese9c3b9b2015-02-20 22:48:20 +0000512typedef DenseMap<Value *, PhiState> ConflictStateMapTy;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000513// Values of type PhiState form a lattice, and this is a helper
514// class that implementes the meet operation. The meat of the meet
515// operation is implemented in MeetPhiStates::pureMeet
516class MeetPhiStates {
517public:
518 // phiStates is a mapping from PHINodes and SelectInst's to PhiStates.
Philip Reames860660e2015-02-20 22:05:18 +0000519 explicit MeetPhiStates(const ConflictStateMapTy &phiStates)
Philip Reamesd16a9b12015-02-20 01:06:44 +0000520 : phiStates(phiStates) {}
521
522 // Destructively meet the current result with the base V. V can
523 // either be a merge instruction (SelectInst / PHINode), in which
524 // case its status is looked up in the phiStates map; or a regular
525 // SSA value, in which case it is assumed to be a base.
526 void meetWith(Value *V) {
527 PhiState otherState = getStateForBDV(V);
528 assert((MeetPhiStates::pureMeet(otherState, currentResult) ==
529 MeetPhiStates::pureMeet(currentResult, otherState)) &&
530 "math is wrong: meet does not commute!");
531 currentResult = MeetPhiStates::pureMeet(otherState, currentResult);
532 }
533
534 PhiState getResult() const { return currentResult; }
535
536private:
Philip Reames860660e2015-02-20 22:05:18 +0000537 const ConflictStateMapTy &phiStates;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000538 PhiState currentResult;
539
540 /// Return a phi state for a base defining value. We'll generate a new
541 /// base state for known bases and expect to find a cached state otherwise
542 PhiState getStateForBDV(Value *baseValue) {
543 if (isKnownBaseResult(baseValue)) {
544 return PhiState(baseValue);
545 } else {
546 return lookupFromMap(baseValue);
547 }
548 }
549
550 PhiState lookupFromMap(Value *V) {
551 auto I = phiStates.find(V);
552 assert(I != phiStates.end() && "lookup failed!");
553 return I->second;
554 }
555
556 static PhiState pureMeet(const PhiState &stateA, const PhiState &stateB) {
557 switch (stateA.getStatus()) {
558 case PhiState::Unknown:
559 return stateB;
560
561 case PhiState::Base:
562 assert(stateA.getBase() && "can't be null");
David Blaikie82ad7872015-02-20 23:44:24 +0000563 if (stateB.isUnknown())
Philip Reamesd16a9b12015-02-20 01:06:44 +0000564 return stateA;
David Blaikie82ad7872015-02-20 23:44:24 +0000565
566 if (stateB.isBase()) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000567 if (stateA.getBase() == stateB.getBase()) {
568 assert(stateA == stateB && "equality broken!");
569 return stateA;
570 }
571 return PhiState(PhiState::Conflict);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000572 }
David Blaikie82ad7872015-02-20 23:44:24 +0000573 assert(stateB.isConflict() && "only three states!");
574 return PhiState(PhiState::Conflict);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000575
576 case PhiState::Conflict:
577 return stateA;
578 }
Reid Klecknera070ee52015-02-20 19:46:02 +0000579 llvm_unreachable("only three states!");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000580 }
581};
582}
583/// For a given value or instruction, figure out what base ptr it's derived
584/// from. For gc objects, this is simply itself. On success, returns a value
585/// which is the base pointer. (This is reliable and can be used for
586/// relocation.) On failure, returns nullptr.
587static Value *findBasePointer(Value *I, DefiningValueMapTy &cache,
Philip Reamesf2041322015-02-20 19:26:04 +0000588 DenseSet<llvm::Value *> &NewInsertedDefs) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000589 Value *def = findBaseOrBDV(I, cache);
590
591 if (isKnownBaseResult(def)) {
592 return def;
593 }
594
595 // Here's the rough algorithm:
596 // - For every SSA value, construct a mapping to either an actual base
597 // pointer or a PHI which obscures the base pointer.
598 // - Construct a mapping from PHI to unknown TOP state. Use an
599 // optimistic algorithm to propagate base pointer information. Lattice
600 // looks like:
601 // UNKNOWN
602 // b1 b2 b3 b4
603 // CONFLICT
604 // When algorithm terminates, all PHIs will either have a single concrete
605 // base or be in a conflict state.
606 // - For every conflict, insert a dummy PHI node without arguments. Add
607 // these to the base[Instruction] = BasePtr mapping. For every
608 // non-conflict, add the actual base.
609 // - For every conflict, add arguments for the base[a] of each input
610 // arguments.
611 //
612 // Note: A simpler form of this would be to add the conflict form of all
613 // PHIs without running the optimistic algorithm. This would be
614 // analougous to pessimistic data flow and would likely lead to an
615 // overall worse solution.
616
Philip Reames860660e2015-02-20 22:05:18 +0000617 ConflictStateMapTy states;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000618 states[def] = PhiState();
619 // Recursively fill in all phis & selects reachable from the initial one
620 // for which we don't already know a definite base value for
Philip Reamesa226e612015-02-28 00:47:50 +0000621 // TODO: This should be rewritten with a worklist
Philip Reamesd16a9b12015-02-20 01:06:44 +0000622 bool done = false;
623 while (!done) {
624 done = true;
Philip Reamesa226e612015-02-28 00:47:50 +0000625 // Since we're adding elements to 'states' as we run, we can't keep
626 // iterators into the set.
Philip Reames704e78b2015-04-10 22:34:56 +0000627 SmallVector<Value *, 16> Keys;
Philip Reamesa226e612015-02-28 00:47:50 +0000628 Keys.reserve(states.size());
Philip Reamesd16a9b12015-02-20 01:06:44 +0000629 for (auto Pair : states) {
Philip Reamesa226e612015-02-28 00:47:50 +0000630 Value *V = Pair.first;
631 Keys.push_back(V);
632 }
633 for (Value *v : Keys) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000634 assert(!isKnownBaseResult(v) && "why did it get added?");
635 if (PHINode *phi = dyn_cast<PHINode>(v)) {
David Blaikie82ad7872015-02-20 23:44:24 +0000636 assert(phi->getNumIncomingValues() > 0 &&
637 "zero input phis are illegal");
638 for (Value *InVal : phi->incoming_values()) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000639 Value *local = findBaseOrBDV(InVal, cache);
640 if (!isKnownBaseResult(local) && states.find(local) == states.end()) {
641 states[local] = PhiState();
642 done = false;
643 }
644 }
645 } else if (SelectInst *sel = dyn_cast<SelectInst>(v)) {
646 Value *local = findBaseOrBDV(sel->getTrueValue(), cache);
647 if (!isKnownBaseResult(local) && states.find(local) == states.end()) {
648 states[local] = PhiState();
649 done = false;
650 }
651 local = findBaseOrBDV(sel->getFalseValue(), cache);
652 if (!isKnownBaseResult(local) && states.find(local) == states.end()) {
653 states[local] = PhiState();
654 done = false;
655 }
656 }
657 }
658 }
659
660 if (TraceLSP) {
661 errs() << "States after initialization:\n";
662 for (auto Pair : states) {
663 Instruction *v = cast<Instruction>(Pair.first);
664 PhiState state = Pair.second;
665 state.dump();
666 v->dump();
667 }
668 }
669
670 // TODO: come back and revisit the state transitions around inputs which
671 // have reached conflict state. The current version seems too conservative.
672
673 bool progress = true;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000674 while (progress) {
Yaron Keren42a7adf2015-02-28 13:11:24 +0000675#ifndef NDEBUG
676 size_t oldSize = states.size();
677#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +0000678 progress = false;
Philip Reamesa226e612015-02-28 00:47:50 +0000679 // We're only changing keys in this loop, thus safe to keep iterators
Philip Reamesd16a9b12015-02-20 01:06:44 +0000680 for (auto Pair : states) {
681 MeetPhiStates calculateMeet(states);
682 Value *v = Pair.first;
683 assert(!isKnownBaseResult(v) && "why did it get added?");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000684 if (SelectInst *select = dyn_cast<SelectInst>(v)) {
685 calculateMeet.meetWith(findBaseOrBDV(select->getTrueValue(), cache));
686 calculateMeet.meetWith(findBaseOrBDV(select->getFalseValue(), cache));
David Blaikie82ad7872015-02-20 23:44:24 +0000687 } else
688 for (Value *Val : cast<PHINode>(v)->incoming_values())
689 calculateMeet.meetWith(findBaseOrBDV(Val, cache));
Philip Reamesd16a9b12015-02-20 01:06:44 +0000690
691 PhiState oldState = states[v];
692 PhiState newState = calculateMeet.getResult();
693 if (oldState != newState) {
694 progress = true;
695 states[v] = newState;
696 }
697 }
698
699 assert(oldSize <= states.size());
700 assert(oldSize == states.size() || progress);
701 }
702
703 if (TraceLSP) {
704 errs() << "States after meet iteration:\n";
705 for (auto Pair : states) {
706 Instruction *v = cast<Instruction>(Pair.first);
707 PhiState state = Pair.second;
708 state.dump();
709 v->dump();
710 }
711 }
712
713 // Insert Phis for all conflicts
Philip Reames2e5bcbe2015-02-28 01:52:09 +0000714 // We want to keep naming deterministic in the loop that follows, so
715 // sort the keys before iteration. This is useful in allowing us to
716 // write stable tests. Note that there is no invalidation issue here.
Philip Reames704e78b2015-04-10 22:34:56 +0000717 SmallVector<Value *, 16> Keys;
Philip Reames2e5bcbe2015-02-28 01:52:09 +0000718 Keys.reserve(states.size());
Philip Reamesd16a9b12015-02-20 01:06:44 +0000719 for (auto Pair : states) {
Philip Reames2e5bcbe2015-02-28 01:52:09 +0000720 Value *V = Pair.first;
721 Keys.push_back(V);
722 }
723 std::sort(Keys.begin(), Keys.end(), order_by_name);
724 // TODO: adjust naming patterns to avoid this order of iteration dependency
725 for (Value *V : Keys) {
726 Instruction *v = cast<Instruction>(V);
727 PhiState state = states[V];
Philip Reamesd16a9b12015-02-20 01:06:44 +0000728 assert(!isKnownBaseResult(v) && "why did it get added?");
729 assert(!state.isUnknown() && "Optimistic algorithm didn't complete!");
Philip Reamesf986d682015-02-28 00:54:41 +0000730 if (!state.isConflict())
731 continue;
Philip Reames704e78b2015-04-10 22:34:56 +0000732
Philip Reamesf986d682015-02-28 00:54:41 +0000733 if (isa<PHINode>(v)) {
734 int num_preds =
735 std::distance(pred_begin(v->getParent()), pred_end(v->getParent()));
736 assert(num_preds > 0 && "how did we reach here");
737 PHINode *phi = PHINode::Create(v->getType(), num_preds, "base_phi", v);
738 NewInsertedDefs.insert(phi);
739 // Add metadata marking this as a base value
740 auto *const_1 = ConstantInt::get(
741 Type::getInt32Ty(
742 v->getParent()->getParent()->getParent()->getContext()),
743 1);
744 auto MDConst = ConstantAsMetadata::get(const_1);
745 MDNode *md = MDNode::get(
746 v->getParent()->getParent()->getParent()->getContext(), MDConst);
747 phi->setMetadata("is_base_value", md);
748 states[v] = PhiState(PhiState::Conflict, phi);
749 } else {
750 SelectInst *sel = cast<SelectInst>(v);
751 // The undef will be replaced later
752 UndefValue *undef = UndefValue::get(sel->getType());
753 SelectInst *basesel = SelectInst::Create(sel->getCondition(), undef,
754 undef, "base_select", sel);
755 NewInsertedDefs.insert(basesel);
756 // Add metadata marking this as a base value
757 auto *const_1 = ConstantInt::get(
758 Type::getInt32Ty(
759 v->getParent()->getParent()->getParent()->getContext()),
760 1);
761 auto MDConst = ConstantAsMetadata::get(const_1);
762 MDNode *md = MDNode::get(
763 v->getParent()->getParent()->getParent()->getContext(), MDConst);
764 basesel->setMetadata("is_base_value", md);
765 states[v] = PhiState(PhiState::Conflict, basesel);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000766 }
767 }
768
769 // Fixup all the inputs of the new PHIs
770 for (auto Pair : states) {
771 Instruction *v = cast<Instruction>(Pair.first);
772 PhiState state = Pair.second;
773
774 assert(!isKnownBaseResult(v) && "why did it get added?");
775 assert(!state.isUnknown() && "Optimistic algorithm didn't complete!");
Philip Reames28e61ce2015-02-28 01:57:44 +0000776 if (!state.isConflict())
777 continue;
Philip Reames704e78b2015-04-10 22:34:56 +0000778
Philip Reames28e61ce2015-02-28 01:57:44 +0000779 if (PHINode *basephi = dyn_cast<PHINode>(state.getBase())) {
780 PHINode *phi = cast<PHINode>(v);
781 unsigned NumPHIValues = phi->getNumIncomingValues();
782 for (unsigned i = 0; i < NumPHIValues; i++) {
783 Value *InVal = phi->getIncomingValue(i);
784 BasicBlock *InBB = phi->getIncomingBlock(i);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000785
Philip Reames28e61ce2015-02-28 01:57:44 +0000786 // If we've already seen InBB, add the same incoming value
787 // we added for it earlier. The IR verifier requires phi
788 // nodes with multiple entries from the same basic block
789 // to have the same incoming value for each of those
790 // entries. If we don't do this check here and basephi
791 // has a different type than base, we'll end up adding two
792 // bitcasts (and hence two distinct values) as incoming
793 // values for the same basic block.
Philip Reamesd16a9b12015-02-20 01:06:44 +0000794
Philip Reames28e61ce2015-02-28 01:57:44 +0000795 int blockIndex = basephi->getBasicBlockIndex(InBB);
796 if (blockIndex != -1) {
797 Value *oldBase = basephi->getIncomingValue(blockIndex);
798 basephi->addIncoming(oldBase, InBB);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000799#ifndef NDEBUG
Philip Reames28e61ce2015-02-28 01:57:44 +0000800 Value *base = findBaseOrBDV(InVal, cache);
801 if (!isKnownBaseResult(base)) {
802 // Either conflict or base.
803 assert(states.count(base));
804 base = states[base].getBase();
805 assert(base != nullptr && "unknown PhiState!");
806 assert(NewInsertedDefs.count(base) &&
807 "should have already added this in a prev. iteration!");
808 }
Philip Reamesd16a9b12015-02-20 01:06:44 +0000809
Philip Reames28e61ce2015-02-28 01:57:44 +0000810 // In essense this assert states: the only way two
811 // values incoming from the same basic block may be
812 // different is by being different bitcasts of the same
813 // value. A cleanup that remains TODO is changing
814 // findBaseOrBDV to return an llvm::Value of the correct
815 // type (and still remain pure). This will remove the
816 // need to add bitcasts.
817 assert(base->stripPointerCasts() == oldBase->stripPointerCasts() &&
818 "sanity -- findBaseOrBDV should be pure!");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000819#endif
Philip Reames28e61ce2015-02-28 01:57:44 +0000820 continue;
821 }
Philip Reamesd16a9b12015-02-20 01:06:44 +0000822
Philip Reames28e61ce2015-02-28 01:57:44 +0000823 // Find either the defining value for the PHI or the normal base for
824 // a non-phi node
825 Value *base = findBaseOrBDV(InVal, cache);
826 if (!isKnownBaseResult(base)) {
827 // Either conflict or base.
828 assert(states.count(base));
829 base = states[base].getBase();
830 assert(base != nullptr && "unknown PhiState!");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000831 }
Philip Reames28e61ce2015-02-28 01:57:44 +0000832 assert(base && "can't be null");
833 // Must use original input BB since base may not be Instruction
834 // The cast is needed since base traversal may strip away bitcasts
835 if (base->getType() != basephi->getType()) {
836 base = new BitCastInst(base, basephi->getType(), "cast",
837 InBB->getTerminator());
838 NewInsertedDefs.insert(base);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000839 }
Philip Reames28e61ce2015-02-28 01:57:44 +0000840 basephi->addIncoming(base, InBB);
841 }
842 assert(basephi->getNumIncomingValues() == NumPHIValues);
843 } else {
844 SelectInst *basesel = cast<SelectInst>(state.getBase());
845 SelectInst *sel = cast<SelectInst>(v);
846 // Operand 1 & 2 are true, false path respectively. TODO: refactor to
847 // something more safe and less hacky.
848 for (int i = 1; i <= 2; i++) {
849 Value *InVal = sel->getOperand(i);
850 // Find either the defining value for the PHI or the normal base for
851 // a non-phi node
852 Value *base = findBaseOrBDV(InVal, cache);
853 if (!isKnownBaseResult(base)) {
854 // Either conflict or base.
855 assert(states.count(base));
856 base = states[base].getBase();
857 assert(base != nullptr && "unknown PhiState!");
858 }
859 assert(base && "can't be null");
860 // Must use original input BB since base may not be Instruction
861 // The cast is needed since base traversal may strip away bitcasts
862 if (base->getType() != basesel->getType()) {
863 base = new BitCastInst(base, basesel->getType(), "cast", basesel);
864 NewInsertedDefs.insert(base);
865 }
866 basesel->setOperand(i, base);
867 }
Philip Reamesd16a9b12015-02-20 01:06:44 +0000868 }
869 }
870
871 // Cache all of our results so we can cheaply reuse them
872 // NOTE: This is actually two caches: one of the base defining value
873 // relation and one of the base pointer relation! FIXME
874 for (auto item : states) {
875 Value *v = item.first;
876 Value *base = item.second.getBase();
877 assert(v && base);
878 assert(!isKnownBaseResult(v) && "why did it get added?");
879
880 if (TraceLSP) {
881 std::string fromstr =
882 cache.count(v) ? (cache[v]->hasName() ? cache[v]->getName() : "")
883 : "none";
884 errs() << "Updating base value cache"
885 << " for: " << (v->hasName() ? v->getName() : "")
886 << " from: " << fromstr
887 << " to: " << (base->hasName() ? base->getName() : "") << "\n";
888 }
889
890 assert(isKnownBaseResult(base) &&
891 "must be something we 'know' is a base pointer");
892 if (cache.count(v)) {
893 // Once we transition from the BDV relation being store in the cache to
894 // the base relation being stored, it must be stable
895 assert((!isKnownBaseResult(cache[v]) || cache[v] == base) &&
896 "base relation should be stable");
897 }
898 cache[v] = base;
899 }
900 assert(cache.find(def) != cache.end());
901 return cache[def];
902}
903
904// For a set of live pointers (base and/or derived), identify the base
905// pointer of the object which they are derived from. This routine will
906// mutate the IR graph as needed to make the 'base' pointer live at the
907// definition site of 'derived'. This ensures that any use of 'derived' can
908// also use 'base'. This may involve the insertion of a number of
909// additional PHI nodes.
910//
911// preconditions: live is a set of pointer type Values
912//
913// side effects: may insert PHI nodes into the existing CFG, will preserve
914// CFG, will not remove or mutate any existing nodes
915//
Philip Reamesf2041322015-02-20 19:26:04 +0000916// post condition: PointerToBase contains one (derived, base) pair for every
Philip Reamesd16a9b12015-02-20 01:06:44 +0000917// pointer in live. Note that derived can be equal to base if the original
918// pointer was a base pointer.
Philip Reames704e78b2015-04-10 22:34:56 +0000919static void
920findBasePointers(const StatepointLiveSetTy &live,
921 DenseMap<llvm::Value *, llvm::Value *> &PointerToBase,
922 DominatorTree *DT, DefiningValueMapTy &DVCache,
923 DenseSet<llvm::Value *> &NewInsertedDefs) {
Philip Reames2e5bcbe2015-02-28 01:52:09 +0000924 // For the naming of values inserted to be deterministic - which makes for
925 // much cleaner and more stable tests - we need to assign an order to the
926 // live values. DenseSets do not provide a deterministic order across runs.
Philip Reames704e78b2015-04-10 22:34:56 +0000927 SmallVector<Value *, 64> Temp;
Philip Reames2e5bcbe2015-02-28 01:52:09 +0000928 Temp.insert(Temp.end(), live.begin(), live.end());
929 std::sort(Temp.begin(), Temp.end(), order_by_name);
930 for (Value *ptr : Temp) {
Philip Reamesf2041322015-02-20 19:26:04 +0000931 Value *base = findBasePointer(ptr, DVCache, NewInsertedDefs);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000932 assert(base && "failed to find base pointer");
Philip Reamesf2041322015-02-20 19:26:04 +0000933 PointerToBase[ptr] = base;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000934 assert((!isa<Instruction>(base) || !isa<Instruction>(ptr) ||
935 DT->dominates(cast<Instruction>(base)->getParent(),
936 cast<Instruction>(ptr)->getParent())) &&
937 "The base we found better dominate the derived pointer");
938
David Blaikie82ad7872015-02-20 23:44:24 +0000939 // If you see this trip and like to live really dangerously, the code should
940 // be correct, just with idioms the verifier can't handle. You can try
941 // disabling the verifier at your own substaintial risk.
Philip Reames704e78b2015-04-10 22:34:56 +0000942 assert(!isa<ConstantPointerNull>(base) &&
Philip Reames24c6cd52015-03-27 05:47:00 +0000943 "the relocation code needs adjustment to handle the relocation of "
944 "a null pointer constant without causing false positives in the "
945 "safepoint ir verifier.");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000946 }
947}
948
949/// Find the required based pointers (and adjust the live set) for the given
950/// parse point.
951static void findBasePointers(DominatorTree &DT, DefiningValueMapTy &DVCache,
952 const CallSite &CS,
953 PartiallyConstructedSafepointRecord &result) {
Philip Reamesf2041322015-02-20 19:26:04 +0000954 DenseMap<llvm::Value *, llvm::Value *> PointerToBase;
955 DenseSet<llvm::Value *> NewInsertedDefs;
Philip Reames704e78b2015-04-10 22:34:56 +0000956 findBasePointers(result.liveset, PointerToBase, &DT, DVCache,
957 NewInsertedDefs);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000958
959 if (PrintBasePointers) {
Philip Reamesa5aeaf42015-02-28 00:20:48 +0000960 // Note: Need to print these in a stable order since this is checked in
961 // some tests.
Philip Reamesd16a9b12015-02-20 01:06:44 +0000962 errs() << "Base Pairs (w/o Relocation):\n";
Philip Reames704e78b2015-04-10 22:34:56 +0000963 SmallVector<Value *, 64> Temp;
Philip Reamesa5aeaf42015-02-28 00:20:48 +0000964 Temp.reserve(PointerToBase.size());
Philip Reamesf2041322015-02-20 19:26:04 +0000965 for (auto Pair : PointerToBase) {
Philip Reamesa5aeaf42015-02-28 00:20:48 +0000966 Temp.push_back(Pair.first);
967 }
968 std::sort(Temp.begin(), Temp.end(), order_by_name);
969 for (Value *Ptr : Temp) {
970 Value *Base = PointerToBase[Ptr];
Philip Reames704e78b2015-04-10 22:34:56 +0000971 errs() << " derived %" << Ptr->getName() << " base %" << Base->getName()
972 << "\n";
Philip Reamesd16a9b12015-02-20 01:06:44 +0000973 }
974 }
975
Philip Reamesf2041322015-02-20 19:26:04 +0000976 result.PointerToBase = PointerToBase;
977 result.NewInsertedDefs = NewInsertedDefs;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000978}
979
Philip Reamesdf1ef082015-04-10 22:53:14 +0000980/// Given an updated version of the dataflow liveness results, update the
981/// liveset and base pointer maps for the call site CS.
982static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData,
983 const CallSite &CS,
984 PartiallyConstructedSafepointRecord &result);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000985
Philip Reamesdf1ef082015-04-10 22:53:14 +0000986static void recomputeLiveInValues(
987 Function &F, DominatorTree &DT, Pass *P, ArrayRef<CallSite> toUpdate,
Philip Reamesd2b66462015-02-20 22:39:41 +0000988 MutableArrayRef<struct PartiallyConstructedSafepointRecord> records) {
Philip Reamesdf1ef082015-04-10 22:53:14 +0000989 // TODO-PERF: reuse the original liveness, then simply run the dataflow
990 // again. The old values are still live and will help it stablize quickly.
991 GCPtrLivenessData RevisedLivenessData;
992 computeLiveInValues(DT, F, RevisedLivenessData);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000993 for (size_t i = 0; i < records.size(); i++) {
994 struct PartiallyConstructedSafepointRecord &info = records[i];
Philip Reamesd2b66462015-02-20 22:39:41 +0000995 const CallSite &CS = toUpdate[i];
Philip Reamesdf1ef082015-04-10 22:53:14 +0000996 recomputeLiveInValues(RevisedLivenessData, CS, info);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000997 }
998}
999
Philip Reames69e51ca2015-04-13 18:07:21 +00001000// When inserting gc.relocate calls, we need to ensure there are no uses
1001// of the original value between the gc.statepoint and the gc.relocate call.
1002// One case which can arise is a phi node starting one of the successor blocks.
1003// We also need to be able to insert the gc.relocates only on the path which
1004// goes through the statepoint. We might need to split an edge to make this
1005// possible.
1006static BasicBlock *normalizeForInvokeSafepoint(BasicBlock *BB,
Philip Reamesd16a9b12015-02-20 01:06:44 +00001007 BasicBlock *InvokeParent,
1008 Pass *P) {
Philip Reames69e51ca2015-04-13 18:07:21 +00001009 DominatorTree *DT = nullptr;
1010 if (auto *DTP = P->getAnalysisIfAvailable<DominatorTreeWrapperPass>())
1011 DT = &DTP->getDomTree();
Philip Reamesd16a9b12015-02-20 01:06:44 +00001012
Philip Reames69e51ca2015-04-13 18:07:21 +00001013 BasicBlock *Ret = BB;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001014 if (!BB->getUniquePredecessor()) {
Philip Reames69e51ca2015-04-13 18:07:21 +00001015 Ret = SplitBlockPredecessors(BB, InvokeParent, "", nullptr, DT);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001016 }
1017
Philip Reames69e51ca2015-04-13 18:07:21 +00001018 // Now that 'ret' has unique predecessor we can safely remove all phi nodes
1019 // from it
1020 FoldSingleEntryPHINodes(Ret);
1021 assert(!isa<PHINode>(Ret->begin()));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001022
Philip Reames69e51ca2015-04-13 18:07:21 +00001023 // At this point, we can safely insert a gc.relocate as the first instruction
1024 // in Ret if needed.
1025 return Ret;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001026}
1027
Philip Reamesd2b66462015-02-20 22:39:41 +00001028static int find_index(ArrayRef<Value *> livevec, Value *val) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001029 auto itr = std::find(livevec.begin(), livevec.end(), val);
1030 assert(livevec.end() != itr);
1031 size_t index = std::distance(livevec.begin(), itr);
1032 assert(index < livevec.size());
1033 return index;
1034}
1035
1036// Create new attribute set containing only attributes which can be transfered
1037// from original call to the safepoint.
1038static AttributeSet legalizeCallAttributes(AttributeSet AS) {
1039 AttributeSet ret;
1040
1041 for (unsigned Slot = 0; Slot < AS.getNumSlots(); Slot++) {
1042 unsigned index = AS.getSlotIndex(Slot);
1043
1044 if (index == AttributeSet::ReturnIndex ||
1045 index == AttributeSet::FunctionIndex) {
1046
1047 for (auto it = AS.begin(Slot), it_end = AS.end(Slot); it != it_end;
1048 ++it) {
1049 Attribute attr = *it;
1050
1051 // Do not allow certain attributes - just skip them
1052 // Safepoint can not be read only or read none.
1053 if (attr.hasAttribute(Attribute::ReadNone) ||
1054 attr.hasAttribute(Attribute::ReadOnly))
1055 continue;
1056
1057 ret = ret.addAttributes(
1058 AS.getContext(), index,
1059 AttributeSet::get(AS.getContext(), index, AttrBuilder(attr)));
1060 }
1061 }
1062
1063 // Just skip parameter attributes for now
1064 }
1065
1066 return ret;
1067}
1068
1069/// Helper function to place all gc relocates necessary for the given
1070/// statepoint.
1071/// Inputs:
1072/// liveVariables - list of variables to be relocated.
1073/// liveStart - index of the first live variable.
1074/// basePtrs - base pointers.
1075/// statepointToken - statepoint instruction to which relocates should be
1076/// bound.
1077/// Builder - Llvm IR builder to be used to construct new calls.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00001078static void CreateGCRelocates(ArrayRef<llvm::Value *> liveVariables,
1079 const int liveStart,
1080 ArrayRef<llvm::Value *> basePtrs,
1081 Instruction *statepointToken,
1082 IRBuilder<> Builder) {
Philip Reamesd2b66462015-02-20 22:39:41 +00001083 SmallVector<Instruction *, 64> NewDefs;
1084 NewDefs.reserve(liveVariables.size());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001085
1086 Module *M = statepointToken->getParent()->getParent()->getParent();
1087
1088 for (unsigned i = 0; i < liveVariables.size(); i++) {
1089 // We generate a (potentially) unique declaration for every pointer type
1090 // combination. This results is some blow up the function declarations in
1091 // the IR, but removes the need for argument bitcasts which shrinks the IR
1092 // greatly and makes it much more readable.
Philip Reames704e78b2015-04-10 22:34:56 +00001093 SmallVector<Type *, 1> types; // one per 'any' type
Philip Reamesd16a9b12015-02-20 01:06:44 +00001094 types.push_back(liveVariables[i]->getType()); // result type
1095 Value *gc_relocate_decl = Intrinsic::getDeclaration(
1096 M, Intrinsic::experimental_gc_relocate, types);
1097
1098 // Generate the gc.relocate call and save the result
1099 Value *baseIdx =
1100 ConstantInt::get(Type::getInt32Ty(M->getContext()),
1101 liveStart + find_index(liveVariables, basePtrs[i]));
1102 Value *liveIdx = ConstantInt::get(
1103 Type::getInt32Ty(M->getContext()),
1104 liveStart + find_index(liveVariables, liveVariables[i]));
1105
1106 // only specify a debug name if we can give a useful one
1107 Value *reloc = Builder.CreateCall3(
1108 gc_relocate_decl, statepointToken, baseIdx, liveIdx,
1109 liveVariables[i]->hasName() ? liveVariables[i]->getName() + ".relocated"
1110 : "");
1111 // Trick CodeGen into thinking there are lots of free registers at this
1112 // fake call.
1113 cast<CallInst>(reloc)->setCallingConv(CallingConv::Cold);
1114
Philip Reamesd2b66462015-02-20 22:39:41 +00001115 NewDefs.push_back(cast<Instruction>(reloc));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001116 }
Philip Reamesd2b66462015-02-20 22:39:41 +00001117 assert(NewDefs.size() == liveVariables.size() &&
Philip Reamesd16a9b12015-02-20 01:06:44 +00001118 "missing or extra redefinition at safepoint");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001119}
1120
1121static void
1122makeStatepointExplicitImpl(const CallSite &CS, /* to replace */
1123 const SmallVectorImpl<llvm::Value *> &basePtrs,
1124 const SmallVectorImpl<llvm::Value *> &liveVariables,
1125 Pass *P,
1126 PartiallyConstructedSafepointRecord &result) {
1127 assert(basePtrs.size() == liveVariables.size());
1128 assert(isStatepoint(CS) &&
1129 "This method expects to be rewriting a statepoint");
1130
1131 BasicBlock *BB = CS.getInstruction()->getParent();
1132 assert(BB);
1133 Function *F = BB->getParent();
1134 assert(F && "must be set");
1135 Module *M = F->getParent();
Nick Lewyckyeb3231e2015-02-20 07:14:02 +00001136 (void)M;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001137 assert(M && "must be set");
1138
1139 // We're not changing the function signature of the statepoint since the gc
1140 // arguments go into the var args section.
1141 Function *gc_statepoint_decl = CS.getCalledFunction();
1142
1143 // Then go ahead and use the builder do actually do the inserts. We insert
1144 // immediately before the previous instruction under the assumption that all
1145 // arguments will be available here. We can't insert afterwards since we may
1146 // be replacing a terminator.
1147 Instruction *insertBefore = CS.getInstruction();
1148 IRBuilder<> Builder(insertBefore);
1149 // Copy all of the arguments from the original statepoint - this includes the
1150 // target, call args, and deopt args
Philip Reamesd2b66462015-02-20 22:39:41 +00001151 SmallVector<llvm::Value *, 64> args;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001152 args.insert(args.end(), CS.arg_begin(), CS.arg_end());
1153 // TODO: Clear the 'needs rewrite' flag
1154
1155 // add all the pointers to be relocated (gc arguments)
1156 // Capture the start of the live variable list for use in the gc_relocates
1157 const int live_start = args.size();
1158 args.insert(args.end(), liveVariables.begin(), liveVariables.end());
1159
1160 // Create the statepoint given all the arguments
1161 Instruction *token = nullptr;
1162 AttributeSet return_attributes;
1163 if (CS.isCall()) {
1164 CallInst *toReplace = cast<CallInst>(CS.getInstruction());
1165 CallInst *call =
1166 Builder.CreateCall(gc_statepoint_decl, args, "safepoint_token");
1167 call->setTailCall(toReplace->isTailCall());
1168 call->setCallingConv(toReplace->getCallingConv());
1169
1170 // Currently we will fail on parameter attributes and on certain
1171 // function attributes.
1172 AttributeSet new_attrs = legalizeCallAttributes(toReplace->getAttributes());
1173 // In case if we can handle this set of sttributes - set up function attrs
1174 // directly on statepoint and return attrs later for gc_result intrinsic.
1175 call->setAttributes(new_attrs.getFnAttributes());
1176 return_attributes = new_attrs.getRetAttributes();
1177
1178 token = call;
1179
1180 // Put the following gc_result and gc_relocate calls immediately after the
1181 // the old call (which we're about to delete)
1182 BasicBlock::iterator next(toReplace);
1183 assert(BB->end() != next && "not a terminator, must have next");
1184 next++;
1185 Instruction *IP = &*(next);
1186 Builder.SetInsertPoint(IP);
1187 Builder.SetCurrentDebugLocation(IP->getDebugLoc());
1188
David Blaikie82ad7872015-02-20 23:44:24 +00001189 } else {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001190 InvokeInst *toReplace = cast<InvokeInst>(CS.getInstruction());
1191
1192 // Insert the new invoke into the old block. We'll remove the old one in a
1193 // moment at which point this will become the new terminator for the
1194 // original block.
1195 InvokeInst *invoke = InvokeInst::Create(
1196 gc_statepoint_decl, toReplace->getNormalDest(),
1197 toReplace->getUnwindDest(), args, "", toReplace->getParent());
1198 invoke->setCallingConv(toReplace->getCallingConv());
1199
1200 // Currently we will fail on parameter attributes and on certain
1201 // function attributes.
1202 AttributeSet new_attrs = legalizeCallAttributes(toReplace->getAttributes());
1203 // In case if we can handle this set of sttributes - set up function attrs
1204 // directly on statepoint and return attrs later for gc_result intrinsic.
1205 invoke->setAttributes(new_attrs.getFnAttributes());
1206 return_attributes = new_attrs.getRetAttributes();
1207
1208 token = invoke;
1209
1210 // Generate gc relocates in exceptional path
Philip Reames69e51ca2015-04-13 18:07:21 +00001211 BasicBlock *unwindBlock = toReplace->getUnwindDest();
1212 assert(!isa<PHINode>(unwindBlock->begin()) &&
1213 unwindBlock->getUniquePredecessor() &&
1214 "can't safely insert in this block!");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001215
1216 Instruction *IP = &*(unwindBlock->getFirstInsertionPt());
1217 Builder.SetInsertPoint(IP);
1218 Builder.SetCurrentDebugLocation(toReplace->getDebugLoc());
1219
1220 // Extract second element from landingpad return value. We will attach
1221 // exceptional gc relocates to it.
1222 const unsigned idx = 1;
1223 Instruction *exceptional_token =
1224 cast<Instruction>(Builder.CreateExtractValue(
1225 unwindBlock->getLandingPadInst(), idx, "relocate_token"));
Philip Reamesf2041322015-02-20 19:26:04 +00001226 result.UnwindToken = exceptional_token;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001227
1228 // Just throw away return value. We will use the one we got for normal
1229 // block.
1230 (void)CreateGCRelocates(liveVariables, live_start, basePtrs,
1231 exceptional_token, Builder);
1232
1233 // Generate gc relocates and returns for normal block
Philip Reames69e51ca2015-04-13 18:07:21 +00001234 BasicBlock *normalDest = toReplace->getNormalDest();
1235 assert(!isa<PHINode>(normalDest->begin()) &&
1236 normalDest->getUniquePredecessor() &&
1237 "can't safely insert in this block!");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001238
1239 IP = &*(normalDest->getFirstInsertionPt());
1240 Builder.SetInsertPoint(IP);
1241
1242 // gc relocates will be generated later as if it were regular call
1243 // statepoint
Philip Reamesd16a9b12015-02-20 01:06:44 +00001244 }
1245 assert(token);
1246
1247 // Take the name of the original value call if it had one.
1248 token->takeName(CS.getInstruction());
1249
Philip Reames704e78b2015-04-10 22:34:56 +00001250// The GCResult is already inserted, we just need to find it
David Blaikie5e5d7842015-02-22 20:58:38 +00001251#ifndef NDEBUG
1252 Instruction *toReplace = CS.getInstruction();
1253 assert((toReplace->hasNUses(0) || toReplace->hasNUses(1)) &&
1254 "only valid use before rewrite is gc.result");
1255 assert(!toReplace->hasOneUse() ||
1256 isGCResult(cast<Instruction>(*toReplace->user_begin())));
1257#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +00001258
1259 // Update the gc.result of the original statepoint (if any) to use the newly
1260 // inserted statepoint. This is safe to do here since the token can't be
1261 // considered a live reference.
1262 CS.getInstruction()->replaceAllUsesWith(token);
1263
Philip Reames0a3240f2015-02-20 21:34:11 +00001264 result.StatepointToken = token;
1265
Philip Reamesd16a9b12015-02-20 01:06:44 +00001266 // Second, create a gc.relocate for every live variable
Philip Reames0a3240f2015-02-20 21:34:11 +00001267 CreateGCRelocates(liveVariables, live_start, basePtrs, token, Builder);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001268}
1269
1270namespace {
1271struct name_ordering {
1272 Value *base;
1273 Value *derived;
1274 bool operator()(name_ordering const &a, name_ordering const &b) {
1275 return -1 == a.derived->getName().compare(b.derived->getName());
1276 }
1277};
1278}
1279static void stablize_order(SmallVectorImpl<Value *> &basevec,
1280 SmallVectorImpl<Value *> &livevec) {
1281 assert(basevec.size() == livevec.size());
1282
Philip Reames860660e2015-02-20 22:05:18 +00001283 SmallVector<name_ordering, 64> temp;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001284 for (size_t i = 0; i < basevec.size(); i++) {
1285 name_ordering v;
1286 v.base = basevec[i];
1287 v.derived = livevec[i];
1288 temp.push_back(v);
1289 }
1290 std::sort(temp.begin(), temp.end(), name_ordering());
1291 for (size_t i = 0; i < basevec.size(); i++) {
1292 basevec[i] = temp[i].base;
1293 livevec[i] = temp[i].derived;
1294 }
1295}
1296
1297// Replace an existing gc.statepoint with a new one and a set of gc.relocates
1298// which make the relocations happening at this safepoint explicit.
Philip Reames704e78b2015-04-10 22:34:56 +00001299//
Philip Reamesd16a9b12015-02-20 01:06:44 +00001300// WARNING: Does not do any fixup to adjust users of the original live
1301// values. That's the callers responsibility.
1302static void
1303makeStatepointExplicit(DominatorTree &DT, const CallSite &CS, Pass *P,
1304 PartiallyConstructedSafepointRecord &result) {
Philip Reamesf2041322015-02-20 19:26:04 +00001305 auto liveset = result.liveset;
1306 auto PointerToBase = result.PointerToBase;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001307
1308 // Convert to vector for efficient cross referencing.
1309 SmallVector<Value *, 64> basevec, livevec;
1310 livevec.reserve(liveset.size());
1311 basevec.reserve(liveset.size());
1312 for (Value *L : liveset) {
1313 livevec.push_back(L);
1314
Philip Reamesf2041322015-02-20 19:26:04 +00001315 assert(PointerToBase.find(L) != PointerToBase.end());
1316 Value *base = PointerToBase[L];
Philip Reamesd16a9b12015-02-20 01:06:44 +00001317 basevec.push_back(base);
1318 }
1319 assert(livevec.size() == basevec.size());
1320
1321 // To make the output IR slightly more stable (for use in diffs), ensure a
1322 // fixed order of the values in the safepoint (by sorting the value name).
1323 // The order is otherwise meaningless.
1324 stablize_order(basevec, livevec);
1325
1326 // Do the actual rewriting and delete the old statepoint
1327 makeStatepointExplicitImpl(CS, basevec, livevec, P, result);
1328 CS.getInstruction()->eraseFromParent();
1329}
1330
1331// Helper function for the relocationViaAlloca.
1332// It receives iterator to the statepoint gc relocates and emits store to the
1333// assigned
1334// location (via allocaMap) for the each one of them.
1335// Add visited values into the visitedLiveValues set we will later use them
1336// for sanity check.
1337static void
1338insertRelocationStores(iterator_range<Value::user_iterator> gcRelocs,
1339 DenseMap<Value *, Value *> &allocaMap,
1340 DenseSet<Value *> &visitedLiveValues) {
1341
1342 for (User *U : gcRelocs) {
1343 if (!isa<IntrinsicInst>(U))
1344 continue;
1345
1346 IntrinsicInst *relocatedValue = cast<IntrinsicInst>(U);
1347
1348 // We only care about relocates
1349 if (relocatedValue->getIntrinsicID() !=
1350 Intrinsic::experimental_gc_relocate) {
1351 continue;
1352 }
1353
1354 GCRelocateOperands relocateOperands(relocatedValue);
1355 Value *originalValue = const_cast<Value *>(relocateOperands.derivedPtr());
1356 assert(allocaMap.count(originalValue));
1357 Value *alloca = allocaMap[originalValue];
1358
1359 // Emit store into the related alloca
1360 StoreInst *store = new StoreInst(relocatedValue, alloca);
1361 store->insertAfter(relocatedValue);
1362
1363#ifndef NDEBUG
1364 visitedLiveValues.insert(originalValue);
1365#endif
1366 }
1367}
1368
1369/// do all the relocation update via allocas and mem2reg
1370static void relocationViaAlloca(
Philip Reamesd2b66462015-02-20 22:39:41 +00001371 Function &F, DominatorTree &DT, ArrayRef<Value *> live,
1372 ArrayRef<struct PartiallyConstructedSafepointRecord> records) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001373#ifndef NDEBUG
Philip Reamesa6ebf072015-03-27 05:53:16 +00001374 // record initial number of (static) allocas; we'll check we have the same
1375 // number when we get done.
1376 int InitialAllocaNum = 0;
Philip Reames704e78b2015-04-10 22:34:56 +00001377 for (auto I = F.getEntryBlock().begin(), E = F.getEntryBlock().end(); I != E;
1378 I++)
Philip Reamesa6ebf072015-03-27 05:53:16 +00001379 if (isa<AllocaInst>(*I))
1380 InitialAllocaNum++;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001381#endif
1382
1383 // TODO-PERF: change data structures, reserve
1384 DenseMap<Value *, Value *> allocaMap;
1385 SmallVector<AllocaInst *, 200> PromotableAllocas;
1386 PromotableAllocas.reserve(live.size());
1387
1388 // emit alloca for each live gc pointer
1389 for (unsigned i = 0; i < live.size(); i++) {
1390 Value *liveValue = live[i];
1391 AllocaInst *alloca = new AllocaInst(liveValue->getType(), "",
1392 F.getEntryBlock().getFirstNonPHI());
1393 allocaMap[liveValue] = alloca;
1394 PromotableAllocas.push_back(alloca);
1395 }
1396
1397 // The next two loops are part of the same conceptual operation. We need to
1398 // insert a store to the alloca after the original def and at each
1399 // redefinition. We need to insert a load before each use. These are split
1400 // into distinct loops for performance reasons.
1401
1402 // update gc pointer after each statepoint
1403 // either store a relocated value or null (if no relocated value found for
1404 // this gc pointer and it is not a gc_result)
1405 // this must happen before we update the statepoint with load of alloca
1406 // otherwise we lose the link between statepoint and old def
1407 for (size_t i = 0; i < records.size(); i++) {
1408 const struct PartiallyConstructedSafepointRecord &info = records[i];
Philip Reames0a3240f2015-02-20 21:34:11 +00001409 Value *Statepoint = info.StatepointToken;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001410
1411 // This will be used for consistency check
1412 DenseSet<Value *> visitedLiveValues;
1413
1414 // Insert stores for normal statepoint gc relocates
Philip Reames0a3240f2015-02-20 21:34:11 +00001415 insertRelocationStores(Statepoint->users(), allocaMap, visitedLiveValues);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001416
1417 // In case if it was invoke statepoint
1418 // we will insert stores for exceptional path gc relocates.
Philip Reames0a3240f2015-02-20 21:34:11 +00001419 if (isa<InvokeInst>(Statepoint)) {
Philip Reames704e78b2015-04-10 22:34:56 +00001420 insertRelocationStores(info.UnwindToken->users(), allocaMap,
1421 visitedLiveValues);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001422 }
1423
Philip Reamese73300b2015-04-13 16:41:32 +00001424 if (ClobberNonLive) {
1425 // As a debuging aid, pretend that an unrelocated pointer becomes null at
1426 // the gc.statepoint. This will turn some subtle GC problems into
1427 // slightly easier to debug SEGVs. Note that on large IR files with
1428 // lots of gc.statepoints this is extremely costly both memory and time
1429 // wise.
1430 SmallVector<AllocaInst *, 64> ToClobber;
1431 for (auto Pair : allocaMap) {
1432 Value *Def = Pair.first;
1433 AllocaInst *Alloca = cast<AllocaInst>(Pair.second);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001434
Philip Reamese73300b2015-04-13 16:41:32 +00001435 // This value was relocated
1436 if (visitedLiveValues.count(Def)) {
1437 continue;
1438 }
1439 ToClobber.push_back(Alloca);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001440 }
Philip Reamesfa2fcf172015-02-20 19:51:56 +00001441
Philip Reamese73300b2015-04-13 16:41:32 +00001442 auto InsertClobbersAt = [&](Instruction *IP) {
1443 for (auto *AI : ToClobber) {
1444 auto AIType = cast<PointerType>(AI->getType());
1445 auto PT = cast<PointerType>(AIType->getElementType());
1446 Constant *CPN = ConstantPointerNull::get(PT);
1447 StoreInst *store = new StoreInst(CPN, AI);
1448 store->insertBefore(IP);
1449 }
1450 };
1451
1452 // Insert the clobbering stores. These may get intermixed with the
1453 // gc.results and gc.relocates, but that's fine.
1454 if (auto II = dyn_cast<InvokeInst>(Statepoint)) {
1455 InsertClobbersAt(II->getNormalDest()->getFirstInsertionPt());
1456 InsertClobbersAt(II->getUnwindDest()->getFirstInsertionPt());
1457 } else {
1458 BasicBlock::iterator Next(cast<CallInst>(Statepoint));
1459 Next++;
1460 InsertClobbersAt(Next);
Philip Reamesfa2fcf172015-02-20 19:51:56 +00001461 }
David Blaikie82ad7872015-02-20 23:44:24 +00001462 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00001463 }
1464 // update use with load allocas and add store for gc_relocated
1465 for (auto Pair : allocaMap) {
1466 Value *def = Pair.first;
1467 Value *alloca = Pair.second;
1468
1469 // we pre-record the uses of allocas so that we dont have to worry about
1470 // later update
1471 // that change the user information.
1472 SmallVector<Instruction *, 20> uses;
1473 // PERF: trade a linear scan for repeated reallocation
1474 uses.reserve(std::distance(def->user_begin(), def->user_end()));
1475 for (User *U : def->users()) {
1476 if (!isa<ConstantExpr>(U)) {
1477 // If the def has a ConstantExpr use, then the def is either a
1478 // ConstantExpr use itself or null. In either case
1479 // (recursively in the first, directly in the second), the oop
1480 // it is ultimately dependent on is null and this particular
1481 // use does not need to be fixed up.
1482 uses.push_back(cast<Instruction>(U));
1483 }
1484 }
1485
1486 std::sort(uses.begin(), uses.end());
1487 auto last = std::unique(uses.begin(), uses.end());
1488 uses.erase(last, uses.end());
1489
1490 for (Instruction *use : uses) {
1491 if (isa<PHINode>(use)) {
1492 PHINode *phi = cast<PHINode>(use);
1493 for (unsigned i = 0; i < phi->getNumIncomingValues(); i++) {
1494 if (def == phi->getIncomingValue(i)) {
1495 LoadInst *load = new LoadInst(
1496 alloca, "", phi->getIncomingBlock(i)->getTerminator());
1497 phi->setIncomingValue(i, load);
1498 }
1499 }
1500 } else {
1501 LoadInst *load = new LoadInst(alloca, "", use);
1502 use->replaceUsesOfWith(def, load);
1503 }
1504 }
1505
1506 // emit store for the initial gc value
1507 // store must be inserted after load, otherwise store will be in alloca's
1508 // use list and an extra load will be inserted before it
1509 StoreInst *store = new StoreInst(def, alloca);
Philip Reames6da37852015-03-04 00:13:52 +00001510 if (Instruction *inst = dyn_cast<Instruction>(def)) {
1511 if (InvokeInst *invoke = dyn_cast<InvokeInst>(inst)) {
1512 // InvokeInst is a TerminatorInst so the store need to be inserted
1513 // into its normal destination block.
1514 BasicBlock *normalDest = invoke->getNormalDest();
1515 store->insertBefore(normalDest->getFirstNonPHI());
1516 } else {
1517 assert(!inst->isTerminator() &&
1518 "The only TerminatorInst that can produce a value is "
1519 "InvokeInst which is handled above.");
Philip Reames704e78b2015-04-10 22:34:56 +00001520 store->insertAfter(inst);
Philip Reames6da37852015-03-04 00:13:52 +00001521 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00001522 } else {
1523 assert((isa<Argument>(def) || isa<GlobalVariable>(def) ||
Philip Reames24c6cd52015-03-27 05:47:00 +00001524 isa<ConstantPointerNull>(def)) &&
Philip Reamesd16a9b12015-02-20 01:06:44 +00001525 "Must be argument or global");
1526 store->insertAfter(cast<Instruction>(alloca));
1527 }
1528 }
1529
1530 assert(PromotableAllocas.size() == live.size() &&
1531 "we must have the same allocas with lives");
1532 if (!PromotableAllocas.empty()) {
1533 // apply mem2reg to promote alloca to SSA
1534 PromoteMemToReg(PromotableAllocas, DT);
1535 }
1536
1537#ifndef NDEBUG
Philip Reames704e78b2015-04-10 22:34:56 +00001538 for (auto I = F.getEntryBlock().begin(), E = F.getEntryBlock().end(); I != E;
1539 I++)
Philip Reamesa6ebf072015-03-27 05:53:16 +00001540 if (isa<AllocaInst>(*I))
1541 InitialAllocaNum--;
1542 assert(InitialAllocaNum == 0 && "We must not introduce any extra allocas");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001543#endif
1544}
1545
1546/// Implement a unique function which doesn't require we sort the input
1547/// vector. Doing so has the effect of changing the output of a couple of
1548/// tests in ways which make them less useful in testing fused safepoints.
Philip Reamesd2b66462015-02-20 22:39:41 +00001549template <typename T> static void unique_unsorted(SmallVectorImpl<T> &Vec) {
1550 DenseSet<T> Seen;
1551 SmallVector<T, 128> TempVec;
1552 TempVec.reserve(Vec.size());
1553 for (auto Element : Vec)
1554 TempVec.push_back(Element);
1555 Vec.clear();
1556 for (auto V : TempVec) {
1557 if (Seen.insert(V).second) {
1558 Vec.push_back(V);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001559 }
1560 }
1561}
1562
1563static Function *getUseHolder(Module &M) {
1564 FunctionType *ftype =
1565 FunctionType::get(Type::getVoidTy(M.getContext()), true);
1566 Function *Func = cast<Function>(M.getOrInsertFunction("__tmp_use", ftype));
1567 return Func;
1568}
1569
1570/// Insert holders so that each Value is obviously live through the entire
1571/// liftetime of the call.
1572static void insertUseHolderAfter(CallSite &CS, const ArrayRef<Value *> Values,
Philip Reamesd2b66462015-02-20 22:39:41 +00001573 SmallVectorImpl<CallInst *> &holders) {
Philip Reames21142752015-04-13 19:07:47 +00001574 if (Values.empty())
1575 // No values to hold live, might as well not insert the empty holder
1576 return;
1577
Philip Reamesd16a9b12015-02-20 01:06:44 +00001578 Module *M = CS.getInstruction()->getParent()->getParent()->getParent();
1579 Function *Func = getUseHolder(*M);
1580 if (CS.isCall()) {
1581 // For call safepoints insert dummy calls right after safepoint
1582 BasicBlock::iterator next(CS.getInstruction());
1583 next++;
1584 CallInst *base_holder = CallInst::Create(Func, Values, "", next);
1585 holders.push_back(base_holder);
1586 } else if (CS.isInvoke()) {
1587 // For invoke safepooints insert dummy calls both in normal and
1588 // exceptional destination blocks
1589 InvokeInst *invoke = cast<InvokeInst>(CS.getInstruction());
1590 CallInst *normal_holder = CallInst::Create(
1591 Func, Values, "", invoke->getNormalDest()->getFirstInsertionPt());
1592 CallInst *unwind_holder = CallInst::Create(
1593 Func, Values, "", invoke->getUnwindDest()->getFirstInsertionPt());
1594 holders.push_back(normal_holder);
1595 holders.push_back(unwind_holder);
Philip Reames860660e2015-02-20 22:05:18 +00001596 } else
1597 llvm_unreachable("unsupported call type");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001598}
1599
1600static void findLiveReferences(
Philip Reamesd2b66462015-02-20 22:39:41 +00001601 Function &F, DominatorTree &DT, Pass *P, ArrayRef<CallSite> toUpdate,
1602 MutableArrayRef<struct PartiallyConstructedSafepointRecord> records) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00001603 GCPtrLivenessData OriginalLivenessData;
1604 computeLiveInValues(DT, F, OriginalLivenessData);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001605 for (size_t i = 0; i < records.size(); i++) {
1606 struct PartiallyConstructedSafepointRecord &info = records[i];
Philip Reamesd2b66462015-02-20 22:39:41 +00001607 const CallSite &CS = toUpdate[i];
Philip Reamesdf1ef082015-04-10 22:53:14 +00001608 analyzeParsePointLiveness(DT, OriginalLivenessData, CS, info);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001609 }
1610}
1611
Philip Reames8531d8c2015-04-10 21:48:25 +00001612/// Remove any vector of pointers from the liveset by scalarizing them over the
1613/// statepoint instruction. Adds the scalarized pieces to the liveset. It
1614/// would be preferrable to include the vector in the statepoint itself, but
1615/// the lowering code currently does not handle that. Extending it would be
1616/// slightly non-trivial since it requires a format change. Given how rare
1617/// such cases are (for the moment?) scalarizing is an acceptable comprimise.
1618static void splitVectorValues(Instruction *StatepointInst,
Philip Reames704e78b2015-04-10 22:34:56 +00001619 StatepointLiveSetTy &LiveSet, DominatorTree &DT) {
Philip Reames8531d8c2015-04-10 21:48:25 +00001620 SmallVector<Value *, 16> ToSplit;
1621 for (Value *V : LiveSet)
1622 if (isa<VectorType>(V->getType()))
1623 ToSplit.push_back(V);
1624
1625 if (ToSplit.empty())
1626 return;
1627
1628 Function &F = *(StatepointInst->getParent()->getParent());
1629
Philip Reames704e78b2015-04-10 22:34:56 +00001630 DenseMap<Value *, AllocaInst *> AllocaMap;
Philip Reames8531d8c2015-04-10 21:48:25 +00001631 // First is normal return, second is exceptional return (invoke only)
Philip Reames704e78b2015-04-10 22:34:56 +00001632 DenseMap<Value *, std::pair<Value *, Value *>> Replacements;
Philip Reames8531d8c2015-04-10 21:48:25 +00001633 for (Value *V : ToSplit) {
1634 LiveSet.erase(V);
1635
Philip Reames704e78b2015-04-10 22:34:56 +00001636 AllocaInst *Alloca =
1637 new AllocaInst(V->getType(), "", F.getEntryBlock().getFirstNonPHI());
Philip Reames8531d8c2015-04-10 21:48:25 +00001638 AllocaMap[V] = Alloca;
1639
1640 VectorType *VT = cast<VectorType>(V->getType());
1641 IRBuilder<> Builder(StatepointInst);
Philip Reames704e78b2015-04-10 22:34:56 +00001642 SmallVector<Value *, 16> Elements;
Philip Reames8531d8c2015-04-10 21:48:25 +00001643 for (unsigned i = 0; i < VT->getNumElements(); i++)
1644 Elements.push_back(Builder.CreateExtractElement(V, Builder.getInt32(i)));
1645 LiveSet.insert(Elements.begin(), Elements.end());
1646
1647 auto InsertVectorReform = [&](Instruction *IP) {
1648 Builder.SetInsertPoint(IP);
1649 Builder.SetCurrentDebugLocation(IP->getDebugLoc());
1650 Value *ResultVec = UndefValue::get(VT);
1651 for (unsigned i = 0; i < VT->getNumElements(); i++)
1652 ResultVec = Builder.CreateInsertElement(ResultVec, Elements[i],
1653 Builder.getInt32(i));
1654 return ResultVec;
1655 };
1656
1657 if (isa<CallInst>(StatepointInst)) {
1658 BasicBlock::iterator Next(StatepointInst);
1659 Next++;
1660 Instruction *IP = &*(Next);
1661 Replacements[V].first = InsertVectorReform(IP);
1662 Replacements[V].second = nullptr;
1663 } else {
1664 InvokeInst *Invoke = cast<InvokeInst>(StatepointInst);
1665 // We've already normalized - check that we don't have shared destination
Philip Reames704e78b2015-04-10 22:34:56 +00001666 // blocks
Philip Reames8531d8c2015-04-10 21:48:25 +00001667 BasicBlock *NormalDest = Invoke->getNormalDest();
1668 assert(!isa<PHINode>(NormalDest->begin()));
1669 BasicBlock *UnwindDest = Invoke->getUnwindDest();
1670 assert(!isa<PHINode>(UnwindDest->begin()));
1671 // Insert insert element sequences in both successors
1672 Instruction *IP = &*(NormalDest->getFirstInsertionPt());
1673 Replacements[V].first = InsertVectorReform(IP);
1674 IP = &*(UnwindDest->getFirstInsertionPt());
1675 Replacements[V].second = InsertVectorReform(IP);
1676 }
1677 }
1678 for (Value *V : ToSplit) {
1679 AllocaInst *Alloca = AllocaMap[V];
1680
1681 // Capture all users before we start mutating use lists
Philip Reames704e78b2015-04-10 22:34:56 +00001682 SmallVector<Instruction *, 16> Users;
Philip Reames8531d8c2015-04-10 21:48:25 +00001683 for (User *U : V->users())
1684 Users.push_back(cast<Instruction>(U));
1685
1686 for (Instruction *I : Users) {
1687 if (auto Phi = dyn_cast<PHINode>(I)) {
1688 for (unsigned i = 0; i < Phi->getNumIncomingValues(); i++)
1689 if (V == Phi->getIncomingValue(i)) {
Philip Reames704e78b2015-04-10 22:34:56 +00001690 LoadInst *Load = new LoadInst(
1691 Alloca, "", Phi->getIncomingBlock(i)->getTerminator());
Philip Reames8531d8c2015-04-10 21:48:25 +00001692 Phi->setIncomingValue(i, Load);
1693 }
1694 } else {
1695 LoadInst *Load = new LoadInst(Alloca, "", I);
1696 I->replaceUsesOfWith(V, Load);
1697 }
1698 }
1699
1700 // Store the original value and the replacement value into the alloca
1701 StoreInst *Store = new StoreInst(V, Alloca);
1702 if (auto I = dyn_cast<Instruction>(V))
1703 Store->insertAfter(I);
1704 else
1705 Store->insertAfter(Alloca);
Philip Reames704e78b2015-04-10 22:34:56 +00001706
Philip Reames8531d8c2015-04-10 21:48:25 +00001707 // Normal return for invoke, or call return
1708 Instruction *Replacement = cast<Instruction>(Replacements[V].first);
1709 (new StoreInst(Replacement, Alloca))->insertAfter(Replacement);
1710 // Unwind return for invoke only
1711 Replacement = cast_or_null<Instruction>(Replacements[V].second);
1712 if (Replacement)
1713 (new StoreInst(Replacement, Alloca))->insertAfter(Replacement);
1714 }
1715
1716 // apply mem2reg to promote alloca to SSA
Philip Reames704e78b2015-04-10 22:34:56 +00001717 SmallVector<AllocaInst *, 16> Allocas;
Philip Reames8531d8c2015-04-10 21:48:25 +00001718 for (Value *V : ToSplit)
1719 Allocas.push_back(AllocaMap[V]);
1720 PromoteMemToReg(Allocas, DT);
1721}
1722
Philip Reamesd16a9b12015-02-20 01:06:44 +00001723static bool insertParsePoints(Function &F, DominatorTree &DT, Pass *P,
Philip Reamesd2b66462015-02-20 22:39:41 +00001724 SmallVectorImpl<CallSite> &toUpdate) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001725#ifndef NDEBUG
1726 // sanity check the input
1727 std::set<CallSite> uniqued;
1728 uniqued.insert(toUpdate.begin(), toUpdate.end());
1729 assert(uniqued.size() == toUpdate.size() && "no duplicates please!");
1730
1731 for (size_t i = 0; i < toUpdate.size(); i++) {
1732 CallSite &CS = toUpdate[i];
1733 assert(CS.getInstruction()->getParent()->getParent() == &F);
1734 assert(isStatepoint(CS) && "expected to already be a deopt statepoint");
1735 }
1736#endif
1737
Philip Reames69e51ca2015-04-13 18:07:21 +00001738 // When inserting gc.relocates for invokes, we need to be able to insert at
1739 // the top of the successor blocks. See the comment on
1740 // normalForInvokeSafepoint on exactly what is needed. Note that this step
1741 // may restructure the CFG.
1742 for (CallSite CS : toUpdate)
1743 if (CS.isInvoke()) {
1744 InvokeInst *invoke = cast<InvokeInst>(CS.getInstruction());
1745 normalizeForInvokeSafepoint(invoke->getNormalDest(),
1746 invoke->getParent(), P);
1747 normalizeForInvokeSafepoint(invoke->getUnwindDest(),
1748 invoke->getParent(), P);
1749 }
1750
Philip Reamesd16a9b12015-02-20 01:06:44 +00001751 // A list of dummy calls added to the IR to keep various values obviously
1752 // live in the IR. We'll remove all of these when done.
Philip Reamesd2b66462015-02-20 22:39:41 +00001753 SmallVector<CallInst *, 64> holders;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001754
1755 // Insert a dummy call with all of the arguments to the vm_state we'll need
1756 // for the actual safepoint insertion. This ensures reference arguments in
1757 // the deopt argument list are considered live through the safepoint (and
1758 // thus makes sure they get relocated.)
1759 for (size_t i = 0; i < toUpdate.size(); i++) {
1760 CallSite &CS = toUpdate[i];
1761 Statepoint StatepointCS(CS);
1762
1763 SmallVector<Value *, 64> DeoptValues;
1764 for (Use &U : StatepointCS.vm_state_args()) {
1765 Value *Arg = cast<Value>(&U);
Philip Reames8531d8c2015-04-10 21:48:25 +00001766 assert(!isUnhandledGCPointerType(Arg->getType()) &&
1767 "support for FCA unimplemented");
1768 if (isHandledGCPointerType(Arg->getType()))
Philip Reamesd16a9b12015-02-20 01:06:44 +00001769 DeoptValues.push_back(Arg);
1770 }
1771 insertUseHolderAfter(CS, DeoptValues, holders);
1772 }
1773
Philip Reamesd2b66462015-02-20 22:39:41 +00001774 SmallVector<struct PartiallyConstructedSafepointRecord, 64> records;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001775 records.reserve(toUpdate.size());
1776 for (size_t i = 0; i < toUpdate.size(); i++) {
1777 struct PartiallyConstructedSafepointRecord info;
1778 records.push_back(info);
1779 }
1780 assert(records.size() == toUpdate.size());
1781
1782 // A) Identify all gc pointers which are staticly live at the given call
1783 // site.
1784 findLiveReferences(F, DT, P, toUpdate, records);
1785
Philip Reames8531d8c2015-04-10 21:48:25 +00001786 // Do a limited scalarization of any live at safepoint vector values which
1787 // contain pointers. This enables this pass to run after vectorization at
1788 // the cost of some possible performance loss. TODO: it would be nice to
1789 // natively support vectors all the way through the backend so we don't need
1790 // to scalarize here.
1791 for (size_t i = 0; i < records.size(); i++) {
1792 struct PartiallyConstructedSafepointRecord &info = records[i];
1793 Instruction *statepoint = toUpdate[i].getInstruction();
1794 splitVectorValues(cast<Instruction>(statepoint), info.liveset, DT);
1795 }
1796
Philip Reamesd16a9b12015-02-20 01:06:44 +00001797 // B) Find the base pointers for each live pointer
1798 /* scope for caching */ {
1799 // Cache the 'defining value' relation used in the computation and
1800 // insertion of base phis and selects. This ensures that we don't insert
1801 // large numbers of duplicate base_phis.
1802 DefiningValueMapTy DVCache;
1803
1804 for (size_t i = 0; i < records.size(); i++) {
1805 struct PartiallyConstructedSafepointRecord &info = records[i];
1806 CallSite &CS = toUpdate[i];
1807 findBasePointers(DT, DVCache, CS, info);
1808 }
1809 } // end of cache scope
1810
1811 // The base phi insertion logic (for any safepoint) may have inserted new
1812 // instructions which are now live at some safepoint. The simplest such
1813 // example is:
1814 // loop:
1815 // phi a <-- will be a new base_phi here
1816 // safepoint 1 <-- that needs to be live here
1817 // gep a + 1
1818 // safepoint 2
1819 // br loop
Philip Reames1f017542015-02-20 23:16:52 +00001820 DenseSet<llvm::Value *> allInsertedDefs;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001821 for (size_t i = 0; i < records.size(); i++) {
1822 struct PartiallyConstructedSafepointRecord &info = records[i];
Philip Reamesf2041322015-02-20 19:26:04 +00001823 allInsertedDefs.insert(info.NewInsertedDefs.begin(),
1824 info.NewInsertedDefs.end());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001825 }
1826
1827 // We insert some dummy calls after each safepoint to definitely hold live
1828 // the base pointers which were identified for that safepoint. We'll then
1829 // ask liveness for _every_ base inserted to see what is now live. Then we
1830 // remove the dummy calls.
1831 holders.reserve(holders.size() + records.size());
1832 for (size_t i = 0; i < records.size(); i++) {
1833 struct PartiallyConstructedSafepointRecord &info = records[i];
1834 CallSite &CS = toUpdate[i];
1835
1836 SmallVector<Value *, 128> Bases;
Philip Reamesf2041322015-02-20 19:26:04 +00001837 for (auto Pair : info.PointerToBase) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001838 Bases.push_back(Pair.second);
1839 }
1840 insertUseHolderAfter(CS, Bases, holders);
1841 }
1842
Philip Reamesdf1ef082015-04-10 22:53:14 +00001843 // By selecting base pointers, we've effectively inserted new uses. Thus, we
1844 // need to rerun liveness. We may *also* have inserted new defs, but that's
1845 // not the key issue.
1846 recomputeLiveInValues(F, DT, P, toUpdate, records);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001847
Philip Reamesd16a9b12015-02-20 01:06:44 +00001848 if (PrintBasePointers) {
1849 for (size_t i = 0; i < records.size(); i++) {
1850 struct PartiallyConstructedSafepointRecord &info = records[i];
1851 errs() << "Base Pairs: (w/Relocation)\n";
Philip Reamesf2041322015-02-20 19:26:04 +00001852 for (auto Pair : info.PointerToBase) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001853 errs() << " derived %" << Pair.first->getName() << " base %"
1854 << Pair.second->getName() << "\n";
1855 }
1856 }
1857 }
1858 for (size_t i = 0; i < holders.size(); i++) {
1859 holders[i]->eraseFromParent();
1860 holders[i] = nullptr;
1861 }
1862 holders.clear();
1863
1864 // Now run through and replace the existing statepoints with new ones with
1865 // the live variables listed. We do not yet update uses of the values being
1866 // relocated. We have references to live variables that need to
1867 // survive to the last iteration of this loop. (By construction, the
1868 // previous statepoint can not be a live variable, thus we can and remove
1869 // the old statepoint calls as we go.)
1870 for (size_t i = 0; i < records.size(); i++) {
1871 struct PartiallyConstructedSafepointRecord &info = records[i];
1872 CallSite &CS = toUpdate[i];
1873 makeStatepointExplicit(DT, CS, P, info);
1874 }
1875 toUpdate.clear(); // prevent accident use of invalid CallSites
1876
Philip Reamesd16a9b12015-02-20 01:06:44 +00001877 // Do all the fixups of the original live variables to their relocated selves
Philip Reamesd2b66462015-02-20 22:39:41 +00001878 SmallVector<Value *, 128> live;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001879 for (size_t i = 0; i < records.size(); i++) {
1880 struct PartiallyConstructedSafepointRecord &info = records[i];
1881 // We can't simply save the live set from the original insertion. One of
1882 // the live values might be the result of a call which needs a safepoint.
1883 // That Value* no longer exists and we need to use the new gc_result.
1884 // Thankfully, the liveset is embedded in the statepoint (and updated), so
1885 // we just grab that.
Philip Reames0a3240f2015-02-20 21:34:11 +00001886 Statepoint statepoint(info.StatepointToken);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001887 live.insert(live.end(), statepoint.gc_args_begin(),
1888 statepoint.gc_args_end());
Philip Reames9a2e01d2015-04-13 17:35:55 +00001889#ifndef NDEBUG
1890 // Do some basic sanity checks on our liveness results before performing
1891 // relocation. Relocation can and will turn mistakes in liveness results
1892 // into non-sensical code which is must harder to debug.
1893 // TODO: It would be nice to test consistency as well
1894 assert(DT.isReachableFromEntry(info.StatepointToken->getParent()) &&
1895 "statepoint must be reachable or liveness is meaningless");
1896 for (Value *V : statepoint.gc_args()) {
1897 if (!isa<Instruction>(V))
1898 // Non-instruction values trivial dominate all possible uses
1899 continue;
1900 auto LiveInst = cast<Instruction>(V);
1901 assert(DT.isReachableFromEntry(LiveInst->getParent()) &&
1902 "unreachable values should never be live");
1903 assert(DT.dominates(LiveInst, info.StatepointToken) &&
1904 "basic SSA liveness expectation violated by liveness analysis");
1905 }
1906#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +00001907 }
1908 unique_unsorted(live);
1909
Nick Lewyckyeb3231e2015-02-20 07:14:02 +00001910#ifndef NDEBUG
Philip Reamesd16a9b12015-02-20 01:06:44 +00001911 // sanity check
1912 for (auto ptr : live) {
1913 assert(isGCPointerType(ptr->getType()) && "must be a gc pointer type");
1914 }
Nick Lewyckyeb3231e2015-02-20 07:14:02 +00001915#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +00001916
1917 relocationViaAlloca(F, DT, live, records);
1918 return !records.empty();
1919}
1920
1921/// Returns true if this function should be rewritten by this pass. The main
1922/// point of this function is as an extension point for custom logic.
1923static bool shouldRewriteStatepointsIn(Function &F) {
1924 // TODO: This should check the GCStrategy
Philip Reames2ef029c2015-02-20 18:56:14 +00001925 if (F.hasGC()) {
1926 const std::string StatepointExampleName("statepoint-example");
1927 return StatepointExampleName == F.getGC();
1928 } else
1929 return false;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001930}
1931
1932bool RewriteStatepointsForGC::runOnFunction(Function &F) {
1933 // Nothing to do for declarations.
1934 if (F.isDeclaration() || F.empty())
1935 return false;
1936
1937 // Policy choice says not to rewrite - the most common reason is that we're
1938 // compiling code without a GCStrategy.
1939 if (!shouldRewriteStatepointsIn(F))
1940 return false;
1941
Philip Reames85b36a82015-04-10 22:07:04 +00001942 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Philip Reames704e78b2015-04-10 22:34:56 +00001943
Philip Reames85b36a82015-04-10 22:07:04 +00001944 // Gather all the statepoints which need rewritten. Be careful to only
1945 // consider those in reachable code since we need to ask dominance queries
1946 // when rewriting. We'll delete the unreachable ones in a moment.
Philip Reamesd2b66462015-02-20 22:39:41 +00001947 SmallVector<CallSite, 64> ParsePointNeeded;
Philip Reamesf66d7372015-04-10 22:16:58 +00001948 bool HasUnreachableStatepoint = false;
Philip Reamesd2b66462015-02-20 22:39:41 +00001949 for (Instruction &I : inst_range(F)) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001950 // TODO: only the ones with the flag set!
Philip Reames85b36a82015-04-10 22:07:04 +00001951 if (isStatepoint(I)) {
1952 if (DT.isReachableFromEntry(I.getParent()))
1953 ParsePointNeeded.push_back(CallSite(&I));
1954 else
Philip Reamesf66d7372015-04-10 22:16:58 +00001955 HasUnreachableStatepoint = true;
Philip Reames85b36a82015-04-10 22:07:04 +00001956 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00001957 }
1958
Philip Reames85b36a82015-04-10 22:07:04 +00001959 bool MadeChange = false;
Philip Reames704e78b2015-04-10 22:34:56 +00001960
Philip Reames85b36a82015-04-10 22:07:04 +00001961 // Delete any unreachable statepoints so that we don't have unrewritten
1962 // statepoints surviving this pass. This makes testing easier and the
1963 // resulting IR less confusing to human readers. Rather than be fancy, we
1964 // just reuse a utility function which removes the unreachable blocks.
Philip Reamesf66d7372015-04-10 22:16:58 +00001965 if (HasUnreachableStatepoint)
Philip Reames85b36a82015-04-10 22:07:04 +00001966 MadeChange |= removeUnreachableBlocks(F);
1967
Philip Reamesd16a9b12015-02-20 01:06:44 +00001968 // Return early if no work to do.
1969 if (ParsePointNeeded.empty())
Philip Reames85b36a82015-04-10 22:07:04 +00001970 return MadeChange;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001971
Philip Reames85b36a82015-04-10 22:07:04 +00001972 // As a prepass, go ahead and aggressively destroy single entry phi nodes.
1973 // These are created by LCSSA. They have the effect of increasing the size
1974 // of liveness sets for no good reason. It may be harder to do this post
1975 // insertion since relocations and base phis can confuse things.
1976 for (BasicBlock &BB : F)
1977 if (BB.getUniquePredecessor()) {
1978 MadeChange = true;
1979 FoldSingleEntryPHINodes(&BB);
1980 }
1981
1982 MadeChange |= insertParsePoints(F, DT, this, ParsePointNeeded);
1983 return MadeChange;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001984}
Philip Reamesdf1ef082015-04-10 22:53:14 +00001985
1986// liveness computation via standard dataflow
1987// -------------------------------------------------------------------
1988
1989// TODO: Consider using bitvectors for liveness, the set of potentially
1990// interesting values should be small and easy to pre-compute.
1991
1992/// Is this value a constant consisting of entirely null values?
1993static bool isConstantNull(Value *V) {
1994 return isa<Constant>(V) && cast<Constant>(V)->isNullValue();
1995}
1996
1997/// Compute the live-in set for the location rbegin starting from
1998/// the live-out set of the basic block
1999static void computeLiveInValues(BasicBlock::reverse_iterator rbegin,
2000 BasicBlock::reverse_iterator rend,
2001 DenseSet<Value *> &LiveTmp) {
2002
2003 for (BasicBlock::reverse_iterator ritr = rbegin; ritr != rend; ritr++) {
2004 Instruction *I = &*ritr;
2005
2006 // KILL/Def - Remove this definition from LiveIn
2007 LiveTmp.erase(I);
2008
2009 // Don't consider *uses* in PHI nodes, we handle their contribution to
2010 // predecessor blocks when we seed the LiveOut sets
2011 if (isa<PHINode>(I))
2012 continue;
2013
2014 // USE - Add to the LiveIn set for this instruction
2015 for (Value *V : I->operands()) {
2016 assert(!isUnhandledGCPointerType(V->getType()) &&
2017 "support for FCA unimplemented");
2018 if (isHandledGCPointerType(V->getType()) && !isConstantNull(V) &&
2019 !isa<UndefValue>(V)) {
2020 // The choice to exclude null and undef is arbitrary here. Reconsider?
2021 LiveTmp.insert(V);
2022 }
2023 }
2024 }
2025}
2026
2027static void computeLiveOutSeed(BasicBlock *BB, DenseSet<Value *> &LiveTmp) {
2028
2029 for (BasicBlock *Succ : successors(BB)) {
2030 const BasicBlock::iterator E(Succ->getFirstNonPHI());
2031 for (BasicBlock::iterator I = Succ->begin(); I != E; I++) {
2032 PHINode *Phi = cast<PHINode>(&*I);
2033 Value *V = Phi->getIncomingValueForBlock(BB);
2034 assert(!isUnhandledGCPointerType(V->getType()) &&
2035 "support for FCA unimplemented");
2036 if (isHandledGCPointerType(V->getType()) && !isConstantNull(V) &&
2037 !isa<UndefValue>(V)) {
2038 // The choice to exclude null and undef is arbitrary here. Reconsider?
2039 LiveTmp.insert(V);
2040 }
2041 }
2042 }
2043}
2044
2045static DenseSet<Value *> computeKillSet(BasicBlock *BB) {
2046 DenseSet<Value *> KillSet;
2047 for (Instruction &I : *BB)
2048 if (isHandledGCPointerType(I.getType()))
2049 KillSet.insert(&I);
2050 return KillSet;
2051}
2052
Philip Reames9638ff92015-04-11 00:06:47 +00002053#ifndef NDEBUG
Philip Reamesdf1ef082015-04-10 22:53:14 +00002054/// Check that the items in 'Live' dominate 'TI'. This is used as a basic
2055/// sanity check for the liveness computation.
2056static void checkBasicSSA(DominatorTree &DT, DenseSet<Value *> &Live,
2057 TerminatorInst *TI, bool TermOkay = false) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00002058 for (Value *V : Live) {
2059 if (auto *I = dyn_cast<Instruction>(V)) {
2060 // The terminator can be a member of the LiveOut set. LLVM's definition
2061 // of instruction dominance states that V does not dominate itself. As
2062 // such, we need to special case this to allow it.
2063 if (TermOkay && TI == I)
2064 continue;
2065 assert(DT.dominates(I, TI) &&
2066 "basic SSA liveness expectation violated by liveness analysis");
2067 }
2068 }
Philip Reamesdf1ef082015-04-10 22:53:14 +00002069}
2070
2071/// Check that all the liveness sets used during the computation of liveness
2072/// obey basic SSA properties. This is useful for finding cases where we miss
2073/// a def.
2074static void checkBasicSSA(DominatorTree &DT, GCPtrLivenessData &Data,
2075 BasicBlock &BB) {
2076 checkBasicSSA(DT, Data.LiveSet[&BB], BB.getTerminator());
2077 checkBasicSSA(DT, Data.LiveOut[&BB], BB.getTerminator(), true);
2078 checkBasicSSA(DT, Data.LiveIn[&BB], BB.getTerminator());
2079}
Philip Reames9638ff92015-04-11 00:06:47 +00002080#endif
Philip Reamesdf1ef082015-04-10 22:53:14 +00002081
2082static void computeLiveInValues(DominatorTree &DT, Function &F,
2083 GCPtrLivenessData &Data) {
2084
Philip Reames4d80ede2015-04-10 23:11:26 +00002085 SmallSetVector<BasicBlock *, 200> Worklist;
Philip Reamesdf1ef082015-04-10 22:53:14 +00002086 auto AddPredsToWorklist = [&](BasicBlock *BB) {
Philip Reames4d80ede2015-04-10 23:11:26 +00002087 // We use a SetVector so that we don't have duplicates in the worklist.
2088 Worklist.insert(pred_begin(BB), pred_end(BB));
Philip Reamesdf1ef082015-04-10 22:53:14 +00002089 };
2090 auto NextItem = [&]() {
2091 BasicBlock *BB = Worklist.back();
2092 Worklist.pop_back();
Philip Reamesdf1ef082015-04-10 22:53:14 +00002093 return BB;
2094 };
2095
2096 // Seed the liveness for each individual block
2097 for (BasicBlock &BB : F) {
2098 Data.KillSet[&BB] = computeKillSet(&BB);
2099 Data.LiveSet[&BB].clear();
2100 computeLiveInValues(BB.rbegin(), BB.rend(), Data.LiveSet[&BB]);
2101
2102#ifndef NDEBUG
2103 for (Value *Kill : Data.KillSet[&BB])
2104 assert(!Data.LiveSet[&BB].count(Kill) && "live set contains kill");
2105#endif
2106
2107 Data.LiveOut[&BB] = DenseSet<Value *>();
2108 computeLiveOutSeed(&BB, Data.LiveOut[&BB]);
2109 Data.LiveIn[&BB] = Data.LiveSet[&BB];
2110 set_union(Data.LiveIn[&BB], Data.LiveOut[&BB]);
2111 set_subtract(Data.LiveIn[&BB], Data.KillSet[&BB]);
2112 if (!Data.LiveIn[&BB].empty())
2113 AddPredsToWorklist(&BB);
2114 }
2115
2116 // Propagate that liveness until stable
2117 while (!Worklist.empty()) {
2118 BasicBlock *BB = NextItem();
2119
2120 // Compute our new liveout set, then exit early if it hasn't changed
2121 // despite the contribution of our successor.
2122 DenseSet<Value *> LiveOut = Data.LiveOut[BB];
2123 const auto OldLiveOutSize = LiveOut.size();
2124 for (BasicBlock *Succ : successors(BB)) {
2125 assert(Data.LiveIn.count(Succ));
2126 set_union(LiveOut, Data.LiveIn[Succ]);
2127 }
2128 // assert OutLiveOut is a subset of LiveOut
2129 if (OldLiveOutSize == LiveOut.size()) {
2130 // If the sets are the same size, then we didn't actually add anything
2131 // when unioning our successors LiveIn Thus, the LiveIn of this block
2132 // hasn't changed.
2133 continue;
2134 }
2135 Data.LiveOut[BB] = LiveOut;
2136
2137 // Apply the effects of this basic block
2138 DenseSet<Value *> LiveTmp = LiveOut;
2139 set_union(LiveTmp, Data.LiveSet[BB]);
2140 set_subtract(LiveTmp, Data.KillSet[BB]);
2141
2142 assert(Data.LiveIn.count(BB));
2143 const DenseSet<Value *> &OldLiveIn = Data.LiveIn[BB];
2144 // assert: OldLiveIn is a subset of LiveTmp
2145 if (OldLiveIn.size() != LiveTmp.size()) {
2146 Data.LiveIn[BB] = LiveTmp;
2147 AddPredsToWorklist(BB);
2148 }
2149 } // while( !worklist.empty() )
2150
2151#ifndef NDEBUG
2152 // Sanity check our ouput against SSA properties. This helps catch any
2153 // missing kills during the above iteration.
2154 for (BasicBlock &BB : F) {
2155 checkBasicSSA(DT, Data, BB);
2156 }
2157#endif
2158}
2159
2160static void findLiveSetAtInst(Instruction *Inst, GCPtrLivenessData &Data,
2161 StatepointLiveSetTy &Out) {
2162
2163 BasicBlock *BB = Inst->getParent();
2164
2165 // Note: The copy is intentional and required
2166 assert(Data.LiveOut.count(BB));
2167 DenseSet<Value *> LiveOut = Data.LiveOut[BB];
2168
2169 // We want to handle the statepoint itself oddly. It's
2170 // call result is not live (normal), nor are it's arguments
2171 // (unless they're used again later). This adjustment is
2172 // specifically what we need to relocate
2173 BasicBlock::reverse_iterator rend(Inst);
2174 computeLiveInValues(BB->rbegin(), rend, LiveOut);
2175 LiveOut.erase(Inst);
2176 Out.insert(LiveOut.begin(), LiveOut.end());
2177}
2178
2179static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData,
2180 const CallSite &CS,
2181 PartiallyConstructedSafepointRecord &Info) {
2182 Instruction *Inst = CS.getInstruction();
2183 StatepointLiveSetTy Updated;
2184 findLiveSetAtInst(Inst, RevisedLivenessData, Updated);
2185
2186#ifndef NDEBUG
2187 DenseSet<Value *> Bases;
2188 for (auto KVPair : Info.PointerToBase) {
2189 Bases.insert(KVPair.second);
2190 }
2191#endif
2192 // We may have base pointers which are now live that weren't before. We need
2193 // to update the PointerToBase structure to reflect this.
2194 for (auto V : Updated)
2195 if (!Info.PointerToBase.count(V)) {
2196 assert(Bases.count(V) && "can't find base for unexpected live value");
2197 Info.PointerToBase[V] = V;
2198 continue;
2199 }
2200
2201#ifndef NDEBUG
2202 for (auto V : Updated) {
2203 assert(Info.PointerToBase.count(V) &&
2204 "must be able to find base for live value");
2205 }
2206#endif
2207
2208 // Remove any stale base mappings - this can happen since our liveness is
2209 // more precise then the one inherent in the base pointer analysis
2210 DenseSet<Value *> ToErase;
2211 for (auto KVPair : Info.PointerToBase)
2212 if (!Updated.count(KVPair.first))
2213 ToErase.insert(KVPair.first);
2214 for (auto V : ToErase)
2215 Info.PointerToBase.erase(V);
2216
2217#ifndef NDEBUG
2218 for (auto KVPair : Info.PointerToBase)
2219 assert(Updated.count(KVPair.first) && "record for non-live value");
2220#endif
2221
2222 Info.liveset = Updated;
2223}