blob: 56d53621b8aab15cf1b53f7a05c999db85cfe8a5 [file] [log] [blame]
Philip Reamesd16a9b12015-02-20 01:06:44 +00001//===- RewriteStatepointsForGC.cpp - Make GC relocations explicit ---------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Rewrite an existing set of gc.statepoints such that they make potential
11// relocations performed by the garbage collector explicit in the IR.
12//
13//===----------------------------------------------------------------------===//
14
15#include "llvm/Pass.h"
16#include "llvm/Analysis/CFG.h"
Igor Laevskye0317182015-05-19 15:59:05 +000017#include "llvm/Analysis/TargetTransformInfo.h"
Philip Reamesd16a9b12015-02-20 01:06:44 +000018#include "llvm/ADT/SetOperations.h"
19#include "llvm/ADT/Statistic.h"
20#include "llvm/ADT/DenseSet.h"
Philip Reames4d80ede2015-04-10 23:11:26 +000021#include "llvm/ADT/SetVector.h"
Swaroop Sridhar665bc9c2015-05-20 01:07:23 +000022#include "llvm/ADT/StringRef.h"
Philip Reamesd16a9b12015-02-20 01:06:44 +000023#include "llvm/IR/BasicBlock.h"
24#include "llvm/IR/CallSite.h"
25#include "llvm/IR/Dominators.h"
26#include "llvm/IR/Function.h"
27#include "llvm/IR/IRBuilder.h"
28#include "llvm/IR/InstIterator.h"
29#include "llvm/IR/Instructions.h"
30#include "llvm/IR/Intrinsics.h"
31#include "llvm/IR/IntrinsicInst.h"
32#include "llvm/IR/Module.h"
Sanjoy Das353a19e2015-06-02 22:33:37 +000033#include "llvm/IR/MDBuilder.h"
Philip Reamesd16a9b12015-02-20 01:06:44 +000034#include "llvm/IR/Statepoint.h"
35#include "llvm/IR/Value.h"
36#include "llvm/IR/Verifier.h"
37#include "llvm/Support/Debug.h"
38#include "llvm/Support/CommandLine.h"
39#include "llvm/Transforms/Scalar.h"
40#include "llvm/Transforms/Utils/BasicBlockUtils.h"
41#include "llvm/Transforms/Utils/Cloning.h"
42#include "llvm/Transforms/Utils/Local.h"
43#include "llvm/Transforms/Utils/PromoteMemToReg.h"
44
45#define DEBUG_TYPE "rewrite-statepoints-for-gc"
46
47using namespace llvm;
48
49// Print tracing output
50static cl::opt<bool> TraceLSP("trace-rewrite-statepoints", cl::Hidden,
51 cl::init(false));
52
53// Print the liveset found at the insert location
54static cl::opt<bool> PrintLiveSet("spp-print-liveset", cl::Hidden,
55 cl::init(false));
Philip Reames704e78b2015-04-10 22:34:56 +000056static cl::opt<bool> PrintLiveSetSize("spp-print-liveset-size", cl::Hidden,
57 cl::init(false));
Philip Reamesd16a9b12015-02-20 01:06:44 +000058// Print out the base pointers for debugging
Philip Reames704e78b2015-04-10 22:34:56 +000059static cl::opt<bool> PrintBasePointers("spp-print-base-pointers", cl::Hidden,
60 cl::init(false));
Philip Reamesd16a9b12015-02-20 01:06:44 +000061
Igor Laevskye0317182015-05-19 15:59:05 +000062// Cost threshold measuring when it is profitable to rematerialize value instead
63// of relocating it
64static cl::opt<unsigned>
65RematerializationThreshold("spp-rematerialization-threshold", cl::Hidden,
66 cl::init(6));
67
Philip Reamese73300b2015-04-13 16:41:32 +000068#ifdef XDEBUG
69static bool ClobberNonLive = true;
70#else
71static bool ClobberNonLive = false;
72#endif
73static cl::opt<bool, true> ClobberNonLiveOverride("rs4gc-clobber-non-live",
74 cl::location(ClobberNonLive),
75 cl::Hidden);
76
Benjamin Kramer6f665452015-02-20 14:00:58 +000077namespace {
Sanjoy Dasea45f0e2015-06-02 22:33:34 +000078struct RewriteStatepointsForGC : public ModulePass {
Philip Reamesd16a9b12015-02-20 01:06:44 +000079 static char ID; // Pass identification, replacement for typeid
80
Sanjoy Dasea45f0e2015-06-02 22:33:34 +000081 RewriteStatepointsForGC() : ModulePass(ID) {
Philip Reamesd16a9b12015-02-20 01:06:44 +000082 initializeRewriteStatepointsForGCPass(*PassRegistry::getPassRegistry());
83 }
Sanjoy Dasea45f0e2015-06-02 22:33:34 +000084 bool runOnFunction(Function &F);
85 bool runOnModule(Module &M) override {
86 bool Changed = false;
87 for (Function &F : M)
88 Changed |= runOnFunction(F);
Sanjoy Das353a19e2015-06-02 22:33:37 +000089
90 if (Changed) {
91 // stripDereferenceabilityInfo asserts that shouldRewriteStatepointsIn
92 // returns true for at least one function in the module. Since at least
93 // one function changed, we know that the precondition is satisfied.
94 stripDereferenceabilityInfo(M);
95 }
96
Sanjoy Dasea45f0e2015-06-02 22:33:34 +000097 return Changed;
98 }
Philip Reamesd16a9b12015-02-20 01:06:44 +000099
100 void getAnalysisUsage(AnalysisUsage &AU) const override {
101 // We add and rewrite a bunch of instructions, but don't really do much
102 // else. We could in theory preserve a lot more analyses here.
103 AU.addRequired<DominatorTreeWrapperPass>();
Igor Laevskye0317182015-05-19 15:59:05 +0000104 AU.addRequired<TargetTransformInfoWrapperPass>();
Philip Reamesd16a9b12015-02-20 01:06:44 +0000105 }
Sanjoy Das353a19e2015-06-02 22:33:37 +0000106
107 /// The IR fed into RewriteStatepointsForGC may have had attributes implying
108 /// dereferenceability that are no longer valid/correct after
109 /// RewriteStatepointsForGC has run. This is because semantically, after
110 /// RewriteStatepointsForGC runs, all calls to gc.statepoint "free" the entire
111 /// heap. stripDereferenceabilityInfo (conservatively) restores correctness
112 /// by erasing all attributes in the module that externally imply
113 /// dereferenceability.
114 ///
115 void stripDereferenceabilityInfo(Module &M);
116
117 // Helpers for stripDereferenceabilityInfo
118 void stripDereferenceabilityInfoFromBody(Function &F);
119 void stripDereferenceabilityInfoFromPrototype(Function &F);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000120};
Benjamin Kramer6f665452015-02-20 14:00:58 +0000121} // namespace
Philip Reamesd16a9b12015-02-20 01:06:44 +0000122
123char RewriteStatepointsForGC::ID = 0;
124
Sanjoy Dasea45f0e2015-06-02 22:33:34 +0000125ModulePass *llvm::createRewriteStatepointsForGCPass() {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000126 return new RewriteStatepointsForGC();
127}
128
129INITIALIZE_PASS_BEGIN(RewriteStatepointsForGC, "rewrite-statepoints-for-gc",
130 "Make relocations explicit at statepoints", false, false)
131INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
132INITIALIZE_PASS_END(RewriteStatepointsForGC, "rewrite-statepoints-for-gc",
133 "Make relocations explicit at statepoints", false, false)
134
135namespace {
Philip Reamesdf1ef082015-04-10 22:53:14 +0000136struct GCPtrLivenessData {
137 /// Values defined in this block.
138 DenseMap<BasicBlock *, DenseSet<Value *>> KillSet;
139 /// Values used in this block (and thus live); does not included values
140 /// killed within this block.
141 DenseMap<BasicBlock *, DenseSet<Value *>> LiveSet;
142
143 /// Values live into this basic block (i.e. used by any
144 /// instruction in this basic block or ones reachable from here)
145 DenseMap<BasicBlock *, DenseSet<Value *>> LiveIn;
146
147 /// Values live out of this basic block (i.e. live into
148 /// any successor block)
149 DenseMap<BasicBlock *, DenseSet<Value *>> LiveOut;
150};
151
Philip Reamesd16a9b12015-02-20 01:06:44 +0000152// The type of the internal cache used inside the findBasePointers family
153// of functions. From the callers perspective, this is an opaque type and
154// should not be inspected.
155//
156// In the actual implementation this caches two relations:
157// - The base relation itself (i.e. this pointer is based on that one)
158// - The base defining value relation (i.e. before base_phi insertion)
159// Generally, after the execution of a full findBasePointer call, only the
160// base relation will remain. Internally, we add a mixture of the two
161// types, then update all the second type to the first type
Philip Reamese9c3b9b2015-02-20 22:48:20 +0000162typedef DenseMap<Value *, Value *> DefiningValueMapTy;
Philip Reames1f017542015-02-20 23:16:52 +0000163typedef DenseSet<llvm::Value *> StatepointLiveSetTy;
Igor Laevskye0317182015-05-19 15:59:05 +0000164typedef DenseMap<Instruction *, Value *> RematerializedValueMapTy;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000165
Philip Reamesd16a9b12015-02-20 01:06:44 +0000166struct PartiallyConstructedSafepointRecord {
167 /// The set of values known to be live accross this safepoint
Philip Reames860660e2015-02-20 22:05:18 +0000168 StatepointLiveSetTy liveset;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000169
170 /// Mapping from live pointers to a base-defining-value
Philip Reamesf2041322015-02-20 19:26:04 +0000171 DenseMap<llvm::Value *, llvm::Value *> PointerToBase;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000172
Philip Reames0a3240f2015-02-20 21:34:11 +0000173 /// The *new* gc.statepoint instruction itself. This produces the token
174 /// that normal path gc.relocates and the gc.result are tied to.
175 Instruction *StatepointToken;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000176
Philip Reamesf2041322015-02-20 19:26:04 +0000177 /// Instruction to which exceptional gc relocates are attached
178 /// Makes it easier to iterate through them during relocationViaAlloca.
179 Instruction *UnwindToken;
Igor Laevskye0317182015-05-19 15:59:05 +0000180
181 /// Record live values we are rematerialized instead of relocating.
182 /// They are not included into 'liveset' field.
183 /// Maps rematerialized copy to it's original value.
184 RematerializedValueMapTy RematerializedValues;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000185};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000186}
Philip Reamesd16a9b12015-02-20 01:06:44 +0000187
Philip Reamesdf1ef082015-04-10 22:53:14 +0000188/// Compute the live-in set for every basic block in the function
189static void computeLiveInValues(DominatorTree &DT, Function &F,
190 GCPtrLivenessData &Data);
191
192/// Given results from the dataflow liveness computation, find the set of live
193/// Values at a particular instruction.
194static void findLiveSetAtInst(Instruction *inst, GCPtrLivenessData &Data,
195 StatepointLiveSetTy &out);
196
Philip Reamesd16a9b12015-02-20 01:06:44 +0000197// TODO: Once we can get to the GCStrategy, this becomes
198// Optional<bool> isGCManagedPointer(const Value *V) const override {
199
200static bool isGCPointerType(const Type *T) {
201 if (const PointerType *PT = dyn_cast<PointerType>(T))
202 // For the sake of this example GC, we arbitrarily pick addrspace(1) as our
203 // GC managed heap. We know that a pointer into this heap needs to be
204 // updated and that no other pointer does.
205 return (1 == PT->getAddressSpace());
206 return false;
207}
208
Philip Reames8531d8c2015-04-10 21:48:25 +0000209// Return true if this type is one which a) is a gc pointer or contains a GC
210// pointer and b) is of a type this code expects to encounter as a live value.
211// (The insertion code will assert that a type which matches (a) and not (b)
Philip Reames704e78b2015-04-10 22:34:56 +0000212// is not encountered.)
Philip Reames8531d8c2015-04-10 21:48:25 +0000213static bool isHandledGCPointerType(Type *T) {
214 // We fully support gc pointers
215 if (isGCPointerType(T))
216 return true;
217 // We partially support vectors of gc pointers. The code will assert if it
218 // can't handle something.
219 if (auto VT = dyn_cast<VectorType>(T))
220 if (isGCPointerType(VT->getElementType()))
221 return true;
222 return false;
223}
224
225#ifndef NDEBUG
226/// Returns true if this type contains a gc pointer whether we know how to
227/// handle that type or not.
228static bool containsGCPtrType(Type *Ty) {
Philip Reames704e78b2015-04-10 22:34:56 +0000229 if (isGCPointerType(Ty))
Philip Reames8531d8c2015-04-10 21:48:25 +0000230 return true;
231 if (VectorType *VT = dyn_cast<VectorType>(Ty))
232 return isGCPointerType(VT->getScalarType());
233 if (ArrayType *AT = dyn_cast<ArrayType>(Ty))
234 return containsGCPtrType(AT->getElementType());
235 if (StructType *ST = dyn_cast<StructType>(Ty))
Philip Reames704e78b2015-04-10 22:34:56 +0000236 return std::any_of(
237 ST->subtypes().begin(), ST->subtypes().end(),
238 [](Type *SubType) { return containsGCPtrType(SubType); });
Philip Reames8531d8c2015-04-10 21:48:25 +0000239 return false;
240}
241
242// Returns true if this is a type which a) is a gc pointer or contains a GC
243// pointer and b) is of a type which the code doesn't expect (i.e. first class
244// aggregates). Used to trip assertions.
245static bool isUnhandledGCPointerType(Type *Ty) {
246 return containsGCPtrType(Ty) && !isHandledGCPointerType(Ty);
247}
248#endif
249
Philip Reamesd16a9b12015-02-20 01:06:44 +0000250static bool order_by_name(llvm::Value *a, llvm::Value *b) {
251 if (a->hasName() && b->hasName()) {
252 return -1 == a->getName().compare(b->getName());
253 } else if (a->hasName() && !b->hasName()) {
254 return true;
255 } else if (!a->hasName() && b->hasName()) {
256 return false;
257 } else {
258 // Better than nothing, but not stable
259 return a < b;
260 }
261}
262
Philip Reamesdf1ef082015-04-10 22:53:14 +0000263// Conservatively identifies any definitions which might be live at the
264// given instruction. The analysis is performed immediately before the
265// given instruction. Values defined by that instruction are not considered
266// live. Values used by that instruction are considered live.
267static void analyzeParsePointLiveness(
268 DominatorTree &DT, GCPtrLivenessData &OriginalLivenessData,
269 const CallSite &CS, PartiallyConstructedSafepointRecord &result) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000270 Instruction *inst = CS.getInstruction();
271
Philip Reames1f017542015-02-20 23:16:52 +0000272 StatepointLiveSetTy liveset;
Philip Reamesdf1ef082015-04-10 22:53:14 +0000273 findLiveSetAtInst(inst, OriginalLivenessData, liveset);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000274
275 if (PrintLiveSet) {
276 // Note: This output is used by several of the test cases
277 // The order of elemtns in a set is not stable, put them in a vec and sort
278 // by name
Philip Reames860660e2015-02-20 22:05:18 +0000279 SmallVector<Value *, 64> temp;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000280 temp.insert(temp.end(), liveset.begin(), liveset.end());
281 std::sort(temp.begin(), temp.end(), order_by_name);
282 errs() << "Live Variables:\n";
283 for (Value *V : temp) {
284 errs() << " " << V->getName(); // no newline
285 V->dump();
286 }
287 }
288 if (PrintLiveSetSize) {
289 errs() << "Safepoint For: " << CS.getCalledValue()->getName() << "\n";
290 errs() << "Number live values: " << liveset.size() << "\n";
291 }
292 result.liveset = liveset;
293}
294
Philip Reames311f7102015-05-12 22:19:52 +0000295static Value *findBaseDefiningValue(Value *I);
296
Philip Reames8fe7f132015-06-26 22:47:37 +0000297/// Return a base defining value for the 'Index' element of the given vector
298/// instruction 'I'. If Index is null, returns a BDV for the entire vector
299/// 'I'. As an optimization, this method will try to determine when the
300/// element is known to already be a base pointer. If this can be established,
301/// the second value in the returned pair will be true. Note that either a
302/// vector or a pointer typed value can be returned. For the former, the
303/// vector returned is a BDV (and possibly a base) of the entire vector 'I'.
304/// If the later, the return pointer is a BDV (or possibly a base) for the
305/// particular element in 'I'.
306static std::pair<Value *, bool>
307findBaseDefiningValueOfVector(Value *I, Value *Index = nullptr) {
Philip Reames8531d8c2015-04-10 21:48:25 +0000308 assert(I->getType()->isVectorTy() &&
309 cast<VectorType>(I->getType())->getElementType()->isPointerTy() &&
310 "Illegal to ask for the base pointer of a non-pointer type");
311
312 // Each case parallels findBaseDefiningValue below, see that code for
313 // detailed motivation.
314
315 if (isa<Argument>(I))
316 // An incoming argument to the function is a base pointer
Philip Reames8fe7f132015-06-26 22:47:37 +0000317 return std::make_pair(I, true);
Philip Reames8531d8c2015-04-10 21:48:25 +0000318
319 // We shouldn't see the address of a global as a vector value?
320 assert(!isa<GlobalVariable>(I) &&
321 "unexpected global variable found in base of vector");
322
323 // inlining could possibly introduce phi node that contains
324 // undef if callee has multiple returns
325 if (isa<UndefValue>(I))
326 // utterly meaningless, but useful for dealing with partially optimized
327 // code.
Philip Reames8fe7f132015-06-26 22:47:37 +0000328 return std::make_pair(I, true);
Philip Reames8531d8c2015-04-10 21:48:25 +0000329
330 // Due to inheritance, this must be _after_ the global variable and undef
331 // checks
332 if (Constant *Con = dyn_cast<Constant>(I)) {
333 assert(!isa<GlobalVariable>(I) && !isa<UndefValue>(I) &&
334 "order of checks wrong!");
335 assert(Con->isNullValue() && "null is the only case which makes sense");
Philip Reames8fe7f132015-06-26 22:47:37 +0000336 return std::make_pair(Con, true);
Philip Reames8531d8c2015-04-10 21:48:25 +0000337 }
Philip Reames8fe7f132015-06-26 22:47:37 +0000338
Philip Reames8531d8c2015-04-10 21:48:25 +0000339 if (isa<LoadInst>(I))
Philip Reames8fe7f132015-06-26 22:47:37 +0000340 return std::make_pair(I, true);
341
Philip Reames311f7102015-05-12 22:19:52 +0000342 // For an insert element, we might be able to look through it if we know
Philip Reames8fe7f132015-06-26 22:47:37 +0000343 // something about the indexes.
Philip Reames311f7102015-05-12 22:19:52 +0000344 if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(I)) {
Philip Reames8fe7f132015-06-26 22:47:37 +0000345 if (Index) {
346 Value *InsertIndex = IEI->getOperand(2);
347 // This index is inserting the value, look for its BDV
348 if (InsertIndex == Index)
349 return std::make_pair(findBaseDefiningValue(IEI->getOperand(1)), false);
350 // Both constant, and can't be equal per above. This insert is definitely
351 // not relevant, look back at the rest of the vector and keep trying.
352 if (isa<ConstantInt>(Index) && isa<ConstantInt>(InsertIndex))
353 return findBaseDefiningValueOfVector(IEI->getOperand(0), Index);
354 }
355
356 // We don't know whether this vector contains entirely base pointers or
357 // not. To be conservatively correct, we treat it as a BDV and will
358 // duplicate code as needed to construct a parallel vector of bases.
359 return std::make_pair(IEI, false);
Philip Reames311f7102015-05-12 22:19:52 +0000360 }
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +0000361
Philip Reames8fe7f132015-06-26 22:47:37 +0000362 if (isa<ShuffleVectorInst>(I))
363 // We don't know whether this vector contains entirely base pointers or
364 // not. To be conservatively correct, we treat it as a BDV and will
365 // duplicate code as needed to construct a parallel vector of bases.
366 // TODO: There a number of local optimizations which could be applied here
367 // for particular sufflevector patterns.
368 return std::make_pair(I, false);
369
370 // A PHI or Select is a base defining value. The outer findBasePointer
371 // algorithm is responsible for constructing a base value for this BDV.
372 assert((isa<SelectInst>(I) || isa<PHINode>(I)) &&
373 "unknown vector instruction - no base found for vector element");
374 return std::make_pair(I, false);
Philip Reames8531d8c2015-04-10 21:48:25 +0000375}
376
Philip Reames8fe7f132015-06-26 22:47:37 +0000377static bool isKnownBaseResult(Value *V);
378
Philip Reamesd16a9b12015-02-20 01:06:44 +0000379/// Helper function for findBasePointer - Will return a value which either a)
380/// defines the base pointer for the input or b) blocks the simple search
381/// (i.e. a PHI or Select of two derived pointers)
382static Value *findBaseDefiningValue(Value *I) {
Philip Reames8fe7f132015-06-26 22:47:37 +0000383 if (I->getType()->isVectorTy())
384 return findBaseDefiningValueOfVector(I).first;
385
Philip Reamesd16a9b12015-02-20 01:06:44 +0000386 assert(I->getType()->isPointerTy() &&
387 "Illegal to ask for the base pointer of a non-pointer type");
388
Philip Reames8531d8c2015-04-10 21:48:25 +0000389 // This case is a bit of a hack - it only handles extracts from vectors which
Philip Reames311f7102015-05-12 22:19:52 +0000390 // trivially contain only base pointers or cases where we can directly match
391 // the index of the original extract element to an insertion into the vector.
392 // See note inside the function for how to improve this.
Philip Reames8531d8c2015-04-10 21:48:25 +0000393 if (auto *EEI = dyn_cast<ExtractElementInst>(I)) {
394 Value *VectorOperand = EEI->getVectorOperand();
Philip Reames311f7102015-05-12 22:19:52 +0000395 Value *Index = EEI->getIndexOperand();
Philip Reames8fe7f132015-06-26 22:47:37 +0000396 std::pair<Value *, bool> pair =
397 findBaseDefiningValueOfVector(VectorOperand, Index);
398 Value *VectorBase = pair.first;
399 if (VectorBase->getType()->isPointerTy())
400 // We found a BDV for this specific element with the vector. This is an
401 // optimization, but in practice it covers most of the useful cases
402 // created via scalarization.
403 return VectorBase;
404 else {
405 assert(VectorBase->getType()->isVectorTy());
406 if (pair.second)
407 // If the entire vector returned is known to be entirely base pointers,
408 // then the extractelement is valid base for this value.
409 return EEI;
410 else {
411 // Otherwise, we have an instruction which potentially produces a
412 // derived pointer and we need findBasePointers to clone code for us
413 // such that we can create an instruction which produces the
414 // accompanying base pointer.
415 // Note: This code is currently rather incomplete. We don't currently
416 // support the general form of shufflevector of insertelement.
417 // Conceptually, these are just 'base defining values' of the same
418 // variety as phi or select instructions. We need to update the
419 // findBasePointers algorithm to insert new 'base-only' versions of the
420 // original instructions. This is relative straight forward to do, but
421 // the case which would motivate the work hasn't shown up in real
422 // workloads yet.
423 assert((isa<PHINode>(VectorBase) || isa<SelectInst>(VectorBase)) &&
424 "need to extend findBasePointers for generic vector"
425 "instruction cases");
426 return VectorBase;
427 }
428 }
Philip Reames8531d8c2015-04-10 21:48:25 +0000429 }
Philip Reamesd16a9b12015-02-20 01:06:44 +0000430
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000431 if (isa<Argument>(I))
Philip Reamesd16a9b12015-02-20 01:06:44 +0000432 // An incoming argument to the function is a base pointer
433 // We should have never reached here if this argument isn't an gc value
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000434 return I;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000435
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000436 if (isa<GlobalVariable>(I))
Philip Reamesd16a9b12015-02-20 01:06:44 +0000437 // base case
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000438 return I;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000439
440 // inlining could possibly introduce phi node that contains
441 // undef if callee has multiple returns
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000442 if (isa<UndefValue>(I))
443 // utterly meaningless, but useful for dealing with
444 // partially optimized code.
Philip Reames704e78b2015-04-10 22:34:56 +0000445 return I;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000446
447 // Due to inheritance, this must be _after_ the global variable and undef
448 // checks
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000449 if (Constant *Con = dyn_cast<Constant>(I)) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000450 assert(!isa<GlobalVariable>(I) && !isa<UndefValue>(I) &&
451 "order of checks wrong!");
452 // Note: Finding a constant base for something marked for relocation
453 // doesn't really make sense. The most likely case is either a) some
454 // screwed up the address space usage or b) your validating against
455 // compiled C++ code w/o the proper separation. The only real exception
456 // is a null pointer. You could have generic code written to index of
457 // off a potentially null value and have proven it null. We also use
458 // null pointers in dead paths of relocation phis (which we might later
459 // want to find a base pointer for).
Philip Reames24c6cd52015-03-27 05:47:00 +0000460 assert(isa<ConstantPointerNull>(Con) &&
461 "null is the only case which makes sense");
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000462 return Con;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000463 }
464
465 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000466 Value *Def = CI->stripPointerCasts();
David Blaikie82ad7872015-02-20 23:44:24 +0000467 // If we find a cast instruction here, it means we've found a cast which is
468 // not simply a pointer cast (i.e. an inttoptr). We don't know how to
469 // handle int->ptr conversion.
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000470 assert(!isa<CastInst>(Def) && "shouldn't find another cast here");
471 return findBaseDefiningValue(Def);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000472 }
473
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000474 if (isa<LoadInst>(I))
475 return I; // The value loaded is an gc base itself
Philip Reamesd16a9b12015-02-20 01:06:44 +0000476
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000477 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I))
478 // The base of this GEP is the base
479 return findBaseDefiningValue(GEP->getPointerOperand());
Philip Reamesd16a9b12015-02-20 01:06:44 +0000480
481 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
482 switch (II->getIntrinsicID()) {
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000483 case Intrinsic::experimental_gc_result_ptr:
Philip Reamesd16a9b12015-02-20 01:06:44 +0000484 default:
485 // fall through to general call handling
486 break;
487 case Intrinsic::experimental_gc_statepoint:
488 case Intrinsic::experimental_gc_result_float:
489 case Intrinsic::experimental_gc_result_int:
490 llvm_unreachable("these don't produce pointers");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000491 case Intrinsic::experimental_gc_relocate: {
492 // Rerunning safepoint insertion after safepoints are already
493 // inserted is not supported. It could probably be made to work,
494 // but why are you doing this? There's no good reason.
495 llvm_unreachable("repeat safepoint insertion is not supported");
496 }
497 case Intrinsic::gcroot:
498 // Currently, this mechanism hasn't been extended to work with gcroot.
499 // There's no reason it couldn't be, but I haven't thought about the
500 // implications much.
501 llvm_unreachable(
502 "interaction with the gcroot mechanism is not supported");
503 }
504 }
505 // We assume that functions in the source language only return base
506 // pointers. This should probably be generalized via attributes to support
507 // both source language and internal functions.
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000508 if (isa<CallInst>(I) || isa<InvokeInst>(I))
509 return I;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000510
511 // I have absolutely no idea how to implement this part yet. It's not
512 // neccessarily hard, I just haven't really looked at it yet.
513 assert(!isa<LandingPadInst>(I) && "Landing Pad is unimplemented");
514
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000515 if (isa<AtomicCmpXchgInst>(I))
Philip Reamesd16a9b12015-02-20 01:06:44 +0000516 // A CAS is effectively a atomic store and load combined under a
517 // predicate. From the perspective of base pointers, we just treat it
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000518 // like a load.
519 return I;
Philip Reames704e78b2015-04-10 22:34:56 +0000520
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000521 assert(!isa<AtomicRMWInst>(I) && "Xchg handled above, all others are "
Philip Reames704e78b2015-04-10 22:34:56 +0000522 "binary ops which don't apply to pointers");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000523
524 // The aggregate ops. Aggregates can either be in the heap or on the
525 // stack, but in either case, this is simply a field load. As a result,
526 // this is a defining definition of the base just like a load is.
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000527 if (isa<ExtractValueInst>(I))
528 return I;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000529
530 // We should never see an insert vector since that would require we be
531 // tracing back a struct value not a pointer value.
532 assert(!isa<InsertValueInst>(I) &&
533 "Base pointer for a struct is meaningless");
534
535 // The last two cases here don't return a base pointer. Instead, they
536 // return a value which dynamically selects from amoung several base
537 // derived pointers (each with it's own base potentially). It's the job of
538 // the caller to resolve these.
Philip Reames704e78b2015-04-10 22:34:56 +0000539 assert((isa<SelectInst>(I) || isa<PHINode>(I)) &&
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000540 "missing instruction case in findBaseDefiningValing");
541 return I;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000542}
543
544/// Returns the base defining value for this value.
Philip Reames18d0feb2015-03-27 05:39:32 +0000545static Value *findBaseDefiningValueCached(Value *I, DefiningValueMapTy &Cache) {
546 Value *&Cached = Cache[I];
Benjamin Kramer6f665452015-02-20 14:00:58 +0000547 if (!Cached) {
548 Cached = findBaseDefiningValue(I);
Philip Reames2a892a62015-07-23 22:25:26 +0000549 DEBUG(dbgs() << "fBDV-cached: " << I->getName() << " -> "
550 << Cached->getName() << "\n");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000551 }
Philip Reames18d0feb2015-03-27 05:39:32 +0000552 assert(Cache[I] != nullptr);
Benjamin Kramer6f665452015-02-20 14:00:58 +0000553 return Cached;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000554}
555
556/// Return a base pointer for this value if known. Otherwise, return it's
557/// base defining value.
Philip Reames18d0feb2015-03-27 05:39:32 +0000558static Value *findBaseOrBDV(Value *I, DefiningValueMapTy &Cache) {
559 Value *Def = findBaseDefiningValueCached(I, Cache);
560 auto Found = Cache.find(Def);
561 if (Found != Cache.end()) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000562 // Either a base-of relation, or a self reference. Caller must check.
Benjamin Kramer6f665452015-02-20 14:00:58 +0000563 return Found->second;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000564 }
565 // Only a BDV available
Philip Reames18d0feb2015-03-27 05:39:32 +0000566 return Def;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000567}
568
569/// Given the result of a call to findBaseDefiningValue, or findBaseOrBDV,
570/// is it known to be a base pointer? Or do we need to continue searching.
Philip Reames18d0feb2015-03-27 05:39:32 +0000571static bool isKnownBaseResult(Value *V) {
572 if (!isa<PHINode>(V) && !isa<SelectInst>(V)) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000573 // no recursion possible
574 return true;
575 }
Philip Reames18d0feb2015-03-27 05:39:32 +0000576 if (isa<Instruction>(V) &&
577 cast<Instruction>(V)->getMetadata("is_base_value")) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000578 // This is a previously inserted base phi or select. We know
579 // that this is a base value.
580 return true;
581 }
582
583 // We need to keep searching
584 return false;
585}
586
Philip Reamesd16a9b12015-02-20 01:06:44 +0000587namespace {
Philip Reames9b141ed2015-07-23 22:49:14 +0000588/// Models the state of a single base defining value in the findBasePointer
589/// algorithm for determining where a new instruction is needed to propagate
590/// the base of this BDV.
591class BDVState {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000592public:
593 enum Status { Unknown, Base, Conflict };
594
Philip Reames9b141ed2015-07-23 22:49:14 +0000595 BDVState(Status s, Value *b = nullptr) : status(s), base(b) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000596 assert(status != Base || b);
597 }
Philip Reames9b141ed2015-07-23 22:49:14 +0000598 explicit BDVState(Value *b) : status(Base), base(b) {}
599 BDVState() : status(Unknown), base(nullptr) {}
Philip Reamesd16a9b12015-02-20 01:06:44 +0000600
601 Status getStatus() const { return status; }
602 Value *getBase() const { return base; }
603
604 bool isBase() const { return getStatus() == Base; }
605 bool isUnknown() const { return getStatus() == Unknown; }
606 bool isConflict() const { return getStatus() == Conflict; }
607
Philip Reames9b141ed2015-07-23 22:49:14 +0000608 bool operator==(const BDVState &other) const {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000609 return base == other.base && status == other.status;
610 }
611
Philip Reames9b141ed2015-07-23 22:49:14 +0000612 bool operator!=(const BDVState &other) const { return !(*this == other); }
Philip Reamesd16a9b12015-02-20 01:06:44 +0000613
Philip Reames2a892a62015-07-23 22:25:26 +0000614 LLVM_DUMP_METHOD
615 void dump() const { print(dbgs()); dbgs() << '\n'; }
616
617 void print(raw_ostream &OS) const {
618 OS << status << " (" << base << " - "
619 << (base ? base->getName() : "nullptr") << "): ";
Philip Reamesd16a9b12015-02-20 01:06:44 +0000620 }
621
622private:
623 Status status;
624 Value *base; // non null only if status == base
625};
626
Philip Reames9b141ed2015-07-23 22:49:14 +0000627inline raw_ostream &operator<<(raw_ostream &OS, const BDVState &State) {
Philip Reames2a892a62015-07-23 22:25:26 +0000628 State.print(OS);
629 return OS;
630}
631
632
Philip Reames9b141ed2015-07-23 22:49:14 +0000633typedef DenseMap<Value *, BDVState> ConflictStateMapTy;
634// Values of type BDVState form a lattice, and this is a helper
Philip Reamesd16a9b12015-02-20 01:06:44 +0000635// class that implementes the meet operation. The meat of the meet
Philip Reames9b141ed2015-07-23 22:49:14 +0000636// operation is implemented in MeetBDVStates::pureMeet
637class MeetBDVStates {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000638public:
Philip Reames273e6bb2015-07-23 21:41:27 +0000639 /// Initializes the currentResult to the TOP state so that if can be met with
640 /// any other state to produce that state.
Philip Reames9b141ed2015-07-23 22:49:14 +0000641 MeetBDVStates() {}
Philip Reamesd16a9b12015-02-20 01:06:44 +0000642
Philip Reames9b141ed2015-07-23 22:49:14 +0000643 // Destructively meet the current result with the given BDVState
644 void meetWith(BDVState otherState) {
Philip Reames273e6bb2015-07-23 21:41:27 +0000645 currentResult = meet(otherState, currentResult);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000646 }
647
Philip Reames9b141ed2015-07-23 22:49:14 +0000648 BDVState getResult() const { return currentResult; }
Philip Reamesd16a9b12015-02-20 01:06:44 +0000649
650private:
Philip Reames9b141ed2015-07-23 22:49:14 +0000651 BDVState currentResult;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000652
Philip Reames9b141ed2015-07-23 22:49:14 +0000653 /// Perform a meet operation on two elements of the BDVState lattice.
654 static BDVState meet(BDVState LHS, BDVState RHS) {
Philip Reames273e6bb2015-07-23 21:41:27 +0000655 assert((pureMeet(LHS, RHS) == pureMeet(RHS, LHS)) &&
656 "math is wrong: meet does not commute!");
Philip Reames9b141ed2015-07-23 22:49:14 +0000657 BDVState Result = pureMeet(LHS, RHS);
Philip Reames2a892a62015-07-23 22:25:26 +0000658 DEBUG(dbgs() << "meet of " << LHS << " with " << RHS
659 << " produced " << Result << "\n");
660 return Result;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000661 }
662
Philip Reames9b141ed2015-07-23 22:49:14 +0000663 static BDVState pureMeet(const BDVState &stateA, const BDVState &stateB) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000664 switch (stateA.getStatus()) {
Philip Reames9b141ed2015-07-23 22:49:14 +0000665 case BDVState::Unknown:
Philip Reamesd16a9b12015-02-20 01:06:44 +0000666 return stateB;
667
Philip Reames9b141ed2015-07-23 22:49:14 +0000668 case BDVState::Base:
Philip Reamesd16a9b12015-02-20 01:06:44 +0000669 assert(stateA.getBase() && "can't be null");
David Blaikie82ad7872015-02-20 23:44:24 +0000670 if (stateB.isUnknown())
Philip Reamesd16a9b12015-02-20 01:06:44 +0000671 return stateA;
David Blaikie82ad7872015-02-20 23:44:24 +0000672
673 if (stateB.isBase()) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000674 if (stateA.getBase() == stateB.getBase()) {
675 assert(stateA == stateB && "equality broken!");
676 return stateA;
677 }
Philip Reames9b141ed2015-07-23 22:49:14 +0000678 return BDVState(BDVState::Conflict);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000679 }
David Blaikie82ad7872015-02-20 23:44:24 +0000680 assert(stateB.isConflict() && "only three states!");
Philip Reames9b141ed2015-07-23 22:49:14 +0000681 return BDVState(BDVState::Conflict);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000682
Philip Reames9b141ed2015-07-23 22:49:14 +0000683 case BDVState::Conflict:
Philip Reamesd16a9b12015-02-20 01:06:44 +0000684 return stateA;
685 }
Reid Klecknera070ee52015-02-20 19:46:02 +0000686 llvm_unreachable("only three states!");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000687 }
688};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000689}
Philip Reamesd16a9b12015-02-20 01:06:44 +0000690/// For a given value or instruction, figure out what base ptr it's derived
691/// from. For gc objects, this is simply itself. On success, returns a value
692/// which is the base pointer. (This is reliable and can be used for
693/// relocation.) On failure, returns nullptr.
Philip Reamesba198492015-04-14 00:41:34 +0000694static Value *findBasePointer(Value *I, DefiningValueMapTy &cache) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000695 Value *def = findBaseOrBDV(I, cache);
696
697 if (isKnownBaseResult(def)) {
698 return def;
699 }
700
701 // Here's the rough algorithm:
702 // - For every SSA value, construct a mapping to either an actual base
703 // pointer or a PHI which obscures the base pointer.
704 // - Construct a mapping from PHI to unknown TOP state. Use an
705 // optimistic algorithm to propagate base pointer information. Lattice
706 // looks like:
707 // UNKNOWN
708 // b1 b2 b3 b4
709 // CONFLICT
710 // When algorithm terminates, all PHIs will either have a single concrete
711 // base or be in a conflict state.
712 // - For every conflict, insert a dummy PHI node without arguments. Add
713 // these to the base[Instruction] = BasePtr mapping. For every
714 // non-conflict, add the actual base.
715 // - For every conflict, add arguments for the base[a] of each input
716 // arguments.
717 //
718 // Note: A simpler form of this would be to add the conflict form of all
719 // PHIs without running the optimistic algorithm. This would be
720 // analougous to pessimistic data flow and would likely lead to an
721 // overall worse solution.
722
Philip Reames860660e2015-02-20 22:05:18 +0000723 ConflictStateMapTy states;
Philip Reames9b141ed2015-07-23 22:49:14 +0000724 states[def] = BDVState();
Philip Reamesd16a9b12015-02-20 01:06:44 +0000725 // Recursively fill in all phis & selects reachable from the initial one
726 // for which we don't already know a definite base value for
Philip Reamesa226e612015-02-28 00:47:50 +0000727 // TODO: This should be rewritten with a worklist
Philip Reamesd16a9b12015-02-20 01:06:44 +0000728 bool done = false;
729 while (!done) {
730 done = true;
Philip Reamesa226e612015-02-28 00:47:50 +0000731 // Since we're adding elements to 'states' as we run, we can't keep
732 // iterators into the set.
Philip Reames704e78b2015-04-10 22:34:56 +0000733 SmallVector<Value *, 16> Keys;
Philip Reamesa226e612015-02-28 00:47:50 +0000734 Keys.reserve(states.size());
Philip Reamesd16a9b12015-02-20 01:06:44 +0000735 for (auto Pair : states) {
Philip Reamesa226e612015-02-28 00:47:50 +0000736 Value *V = Pair.first;
737 Keys.push_back(V);
738 }
739 for (Value *v : Keys) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000740 assert(!isKnownBaseResult(v) && "why did it get added?");
741 if (PHINode *phi = dyn_cast<PHINode>(v)) {
David Blaikie82ad7872015-02-20 23:44:24 +0000742 assert(phi->getNumIncomingValues() > 0 &&
743 "zero input phis are illegal");
744 for (Value *InVal : phi->incoming_values()) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000745 Value *local = findBaseOrBDV(InVal, cache);
746 if (!isKnownBaseResult(local) && states.find(local) == states.end()) {
Philip Reames9b141ed2015-07-23 22:49:14 +0000747 states[local] = BDVState();
Philip Reamesd16a9b12015-02-20 01:06:44 +0000748 done = false;
749 }
750 }
751 } else if (SelectInst *sel = dyn_cast<SelectInst>(v)) {
752 Value *local = findBaseOrBDV(sel->getTrueValue(), cache);
753 if (!isKnownBaseResult(local) && states.find(local) == states.end()) {
Philip Reames9b141ed2015-07-23 22:49:14 +0000754 states[local] = BDVState();
Philip Reamesd16a9b12015-02-20 01:06:44 +0000755 done = false;
756 }
757 local = findBaseOrBDV(sel->getFalseValue(), cache);
758 if (!isKnownBaseResult(local) && states.find(local) == states.end()) {
Philip Reames9b141ed2015-07-23 22:49:14 +0000759 states[local] = BDVState();
Philip Reamesd16a9b12015-02-20 01:06:44 +0000760 done = false;
761 }
762 }
763 }
764 }
765
766 if (TraceLSP) {
767 errs() << "States after initialization:\n";
Philip Reames2a892a62015-07-23 22:25:26 +0000768 for (auto Pair : states)
769 dbgs() << " " << Pair.second << " for " << Pair.first << "\n";
Philip Reamesd16a9b12015-02-20 01:06:44 +0000770 }
771
772 // TODO: come back and revisit the state transitions around inputs which
773 // have reached conflict state. The current version seems too conservative.
774
Philip Reames273e6bb2015-07-23 21:41:27 +0000775 // Return a phi state for a base defining value. We'll generate a new
776 // base state for known bases and expect to find a cached state otherwise.
777 auto getStateForBDV = [&](Value *baseValue) {
778 if (isKnownBaseResult(baseValue))
Philip Reames9b141ed2015-07-23 22:49:14 +0000779 return BDVState(baseValue);
Philip Reames273e6bb2015-07-23 21:41:27 +0000780 auto I = states.find(baseValue);
781 assert(I != states.end() && "lookup failed!");
782 return I->second;
783 };
784
Philip Reamesd16a9b12015-02-20 01:06:44 +0000785 bool progress = true;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000786 while (progress) {
Yaron Keren42a7adf2015-02-28 13:11:24 +0000787#ifndef NDEBUG
788 size_t oldSize = states.size();
789#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +0000790 progress = false;
Philip Reamesa226e612015-02-28 00:47:50 +0000791 // We're only changing keys in this loop, thus safe to keep iterators
Philip Reamesd16a9b12015-02-20 01:06:44 +0000792 for (auto Pair : states) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000793 Value *v = Pair.first;
794 assert(!isKnownBaseResult(v) && "why did it get added?");
Philip Reames273e6bb2015-07-23 21:41:27 +0000795
Philip Reames9b141ed2015-07-23 22:49:14 +0000796 // Given an input value for the current instruction, return a BDVState
Philip Reames273e6bb2015-07-23 21:41:27 +0000797 // instance which represents the BDV of that value.
798 auto getStateForInput = [&](Value *V) mutable {
799 Value *BDV = findBaseOrBDV(V, cache);
800 return getStateForBDV(BDV);
801 };
802
Philip Reames9b141ed2015-07-23 22:49:14 +0000803 MeetBDVStates calculateMeet;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000804 if (SelectInst *select = dyn_cast<SelectInst>(v)) {
Philip Reames273e6bb2015-07-23 21:41:27 +0000805 calculateMeet.meetWith(getStateForInput(select->getTrueValue()));
806 calculateMeet.meetWith(getStateForInput(select->getFalseValue()));
David Blaikie82ad7872015-02-20 23:44:24 +0000807 } else
808 for (Value *Val : cast<PHINode>(v)->incoming_values())
Philip Reames273e6bb2015-07-23 21:41:27 +0000809 calculateMeet.meetWith(getStateForInput(Val));
Philip Reamesd16a9b12015-02-20 01:06:44 +0000810
Philip Reames9b141ed2015-07-23 22:49:14 +0000811 BDVState oldState = states[v];
812 BDVState newState = calculateMeet.getResult();
Philip Reamesd16a9b12015-02-20 01:06:44 +0000813 if (oldState != newState) {
814 progress = true;
815 states[v] = newState;
816 }
817 }
818
819 assert(oldSize <= states.size());
820 assert(oldSize == states.size() || progress);
821 }
822
823 if (TraceLSP) {
824 errs() << "States after meet iteration:\n";
Philip Reames2a892a62015-07-23 22:25:26 +0000825 for (auto Pair : states)
826 dbgs() << " " << Pair.second << " for " << Pair.first << "\n";
Philip Reamesd16a9b12015-02-20 01:06:44 +0000827 }
828
829 // Insert Phis for all conflicts
Philip Reames2e5bcbe2015-02-28 01:52:09 +0000830 // We want to keep naming deterministic in the loop that follows, so
831 // sort the keys before iteration. This is useful in allowing us to
832 // write stable tests. Note that there is no invalidation issue here.
Philip Reames704e78b2015-04-10 22:34:56 +0000833 SmallVector<Value *, 16> Keys;
Philip Reames2e5bcbe2015-02-28 01:52:09 +0000834 Keys.reserve(states.size());
Philip Reamesd16a9b12015-02-20 01:06:44 +0000835 for (auto Pair : states) {
Philip Reames2e5bcbe2015-02-28 01:52:09 +0000836 Value *V = Pair.first;
837 Keys.push_back(V);
838 }
839 std::sort(Keys.begin(), Keys.end(), order_by_name);
840 // TODO: adjust naming patterns to avoid this order of iteration dependency
841 for (Value *V : Keys) {
Philip Reames6ff1a1e32015-07-21 19:04:38 +0000842 Instruction *I = cast<Instruction>(V);
Philip Reames9b141ed2015-07-23 22:49:14 +0000843 BDVState State = states[I];
Philip Reames6ff1a1e32015-07-21 19:04:38 +0000844 assert(!isKnownBaseResult(I) && "why did it get added?");
845 assert(!State.isUnknown() && "Optimistic algorithm didn't complete!");
846 if (!State.isConflict())
Philip Reamesf986d682015-02-28 00:54:41 +0000847 continue;
Philip Reames704e78b2015-04-10 22:34:56 +0000848
Philip Reames6ff1a1e32015-07-21 19:04:38 +0000849 /// Create and insert a new instruction which will represent the base of
850 /// the given instruction 'I'.
851 auto MakeBaseInstPlaceholder = [](Instruction *I) -> Instruction* {
852 if (isa<PHINode>(I)) {
853 BasicBlock *BB = I->getParent();
854 int NumPreds = std::distance(pred_begin(BB), pred_end(BB));
855 assert(NumPreds > 0 && "how did we reach here");
856 return PHINode::Create(I->getType(), NumPreds, "base_phi", I);
857 }
858 SelectInst *Sel = cast<SelectInst>(I);
Philip Reamesf986d682015-02-28 00:54:41 +0000859 // The undef will be replaced later
Philip Reames6ff1a1e32015-07-21 19:04:38 +0000860 UndefValue *Undef = UndefValue::get(Sel->getType());
861 return SelectInst::Create(Sel->getCondition(), Undef,
862 Undef, "base_select", Sel);
863 };
864 Instruction *BaseInst = MakeBaseInstPlaceholder(I);
865 // Add metadata marking this as a base value
866 BaseInst->setMetadata("is_base_value", MDNode::get(I->getContext(), {}));
Philip Reames9b141ed2015-07-23 22:49:14 +0000867 states[I] = BDVState(BDVState::Conflict, BaseInst);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000868 }
869
870 // Fixup all the inputs of the new PHIs
871 for (auto Pair : states) {
872 Instruction *v = cast<Instruction>(Pair.first);
Philip Reames9b141ed2015-07-23 22:49:14 +0000873 BDVState state = Pair.second;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000874
875 assert(!isKnownBaseResult(v) && "why did it get added?");
876 assert(!state.isUnknown() && "Optimistic algorithm didn't complete!");
Philip Reames28e61ce2015-02-28 01:57:44 +0000877 if (!state.isConflict())
878 continue;
Philip Reames704e78b2015-04-10 22:34:56 +0000879
Philip Reames28e61ce2015-02-28 01:57:44 +0000880 if (PHINode *basephi = dyn_cast<PHINode>(state.getBase())) {
881 PHINode *phi = cast<PHINode>(v);
882 unsigned NumPHIValues = phi->getNumIncomingValues();
883 for (unsigned i = 0; i < NumPHIValues; i++) {
884 Value *InVal = phi->getIncomingValue(i);
885 BasicBlock *InBB = phi->getIncomingBlock(i);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000886
Philip Reames28e61ce2015-02-28 01:57:44 +0000887 // If we've already seen InBB, add the same incoming value
888 // we added for it earlier. The IR verifier requires phi
889 // nodes with multiple entries from the same basic block
890 // to have the same incoming value for each of those
891 // entries. If we don't do this check here and basephi
892 // has a different type than base, we'll end up adding two
893 // bitcasts (and hence two distinct values) as incoming
894 // values for the same basic block.
Philip Reamesd16a9b12015-02-20 01:06:44 +0000895
Philip Reames28e61ce2015-02-28 01:57:44 +0000896 int blockIndex = basephi->getBasicBlockIndex(InBB);
897 if (blockIndex != -1) {
898 Value *oldBase = basephi->getIncomingValue(blockIndex);
899 basephi->addIncoming(oldBase, InBB);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000900#ifndef NDEBUG
Philip Reames28e61ce2015-02-28 01:57:44 +0000901 Value *base = findBaseOrBDV(InVal, cache);
902 if (!isKnownBaseResult(base)) {
903 // Either conflict or base.
904 assert(states.count(base));
905 base = states[base].getBase();
Philip Reames9b141ed2015-07-23 22:49:14 +0000906 assert(base != nullptr && "unknown BDVState!");
Philip Reames28e61ce2015-02-28 01:57:44 +0000907 }
Philip Reamesd16a9b12015-02-20 01:06:44 +0000908
Philip Reames28e61ce2015-02-28 01:57:44 +0000909 // In essense this assert states: the only way two
910 // values incoming from the same basic block may be
911 // different is by being different bitcasts of the same
912 // value. A cleanup that remains TODO is changing
913 // findBaseOrBDV to return an llvm::Value of the correct
914 // type (and still remain pure). This will remove the
915 // need to add bitcasts.
916 assert(base->stripPointerCasts() == oldBase->stripPointerCasts() &&
917 "sanity -- findBaseOrBDV should be pure!");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000918#endif
Philip Reames28e61ce2015-02-28 01:57:44 +0000919 continue;
920 }
Philip Reamesd16a9b12015-02-20 01:06:44 +0000921
Philip Reames28e61ce2015-02-28 01:57:44 +0000922 // Find either the defining value for the PHI or the normal base for
923 // a non-phi node
924 Value *base = findBaseOrBDV(InVal, cache);
925 if (!isKnownBaseResult(base)) {
926 // Either conflict or base.
927 assert(states.count(base));
928 base = states[base].getBase();
Philip Reames9b141ed2015-07-23 22:49:14 +0000929 assert(base != nullptr && "unknown BDVState!");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000930 }
Philip Reames28e61ce2015-02-28 01:57:44 +0000931 assert(base && "can't be null");
932 // Must use original input BB since base may not be Instruction
933 // The cast is needed since base traversal may strip away bitcasts
934 if (base->getType() != basephi->getType()) {
935 base = new BitCastInst(base, basephi->getType(), "cast",
936 InBB->getTerminator());
Philip Reamesd16a9b12015-02-20 01:06:44 +0000937 }
Philip Reames28e61ce2015-02-28 01:57:44 +0000938 basephi->addIncoming(base, InBB);
939 }
940 assert(basephi->getNumIncomingValues() == NumPHIValues);
941 } else {
942 SelectInst *basesel = cast<SelectInst>(state.getBase());
943 SelectInst *sel = cast<SelectInst>(v);
944 // Operand 1 & 2 are true, false path respectively. TODO: refactor to
945 // something more safe and less hacky.
946 for (int i = 1; i <= 2; i++) {
947 Value *InVal = sel->getOperand(i);
948 // Find either the defining value for the PHI or the normal base for
949 // a non-phi node
950 Value *base = findBaseOrBDV(InVal, cache);
951 if (!isKnownBaseResult(base)) {
952 // Either conflict or base.
953 assert(states.count(base));
954 base = states[base].getBase();
Philip Reames9b141ed2015-07-23 22:49:14 +0000955 assert(base != nullptr && "unknown BDVState!");
Philip Reames28e61ce2015-02-28 01:57:44 +0000956 }
957 assert(base && "can't be null");
958 // Must use original input BB since base may not be Instruction
959 // The cast is needed since base traversal may strip away bitcasts
960 if (base->getType() != basesel->getType()) {
961 base = new BitCastInst(base, basesel->getType(), "cast", basesel);
Philip Reames28e61ce2015-02-28 01:57:44 +0000962 }
963 basesel->setOperand(i, base);
964 }
Philip Reamesd16a9b12015-02-20 01:06:44 +0000965 }
966 }
967
968 // Cache all of our results so we can cheaply reuse them
969 // NOTE: This is actually two caches: one of the base defining value
970 // relation and one of the base pointer relation! FIXME
971 for (auto item : states) {
972 Value *v = item.first;
973 Value *base = item.second.getBase();
974 assert(v && base);
975 assert(!isKnownBaseResult(v) && "why did it get added?");
976
977 if (TraceLSP) {
978 std::string fromstr =
979 cache.count(v) ? (cache[v]->hasName() ? cache[v]->getName() : "")
980 : "none";
981 errs() << "Updating base value cache"
982 << " for: " << (v->hasName() ? v->getName() : "")
983 << " from: " << fromstr
984 << " to: " << (base->hasName() ? base->getName() : "") << "\n";
985 }
986
987 assert(isKnownBaseResult(base) &&
988 "must be something we 'know' is a base pointer");
989 if (cache.count(v)) {
990 // Once we transition from the BDV relation being store in the cache to
991 // the base relation being stored, it must be stable
992 assert((!isKnownBaseResult(cache[v]) || cache[v] == base) &&
993 "base relation should be stable");
994 }
995 cache[v] = base;
996 }
997 assert(cache.find(def) != cache.end());
998 return cache[def];
999}
1000
1001// For a set of live pointers (base and/or derived), identify the base
1002// pointer of the object which they are derived from. This routine will
1003// mutate the IR graph as needed to make the 'base' pointer live at the
1004// definition site of 'derived'. This ensures that any use of 'derived' can
1005// also use 'base'. This may involve the insertion of a number of
1006// additional PHI nodes.
1007//
1008// preconditions: live is a set of pointer type Values
1009//
1010// side effects: may insert PHI nodes into the existing CFG, will preserve
1011// CFG, will not remove or mutate any existing nodes
1012//
Philip Reamesf2041322015-02-20 19:26:04 +00001013// post condition: PointerToBase contains one (derived, base) pair for every
Philip Reamesd16a9b12015-02-20 01:06:44 +00001014// pointer in live. Note that derived can be equal to base if the original
1015// pointer was a base pointer.
Philip Reames704e78b2015-04-10 22:34:56 +00001016static void
1017findBasePointers(const StatepointLiveSetTy &live,
1018 DenseMap<llvm::Value *, llvm::Value *> &PointerToBase,
Philip Reamesba198492015-04-14 00:41:34 +00001019 DominatorTree *DT, DefiningValueMapTy &DVCache) {
Philip Reames2e5bcbe2015-02-28 01:52:09 +00001020 // For the naming of values inserted to be deterministic - which makes for
1021 // much cleaner and more stable tests - we need to assign an order to the
1022 // live values. DenseSets do not provide a deterministic order across runs.
Philip Reames704e78b2015-04-10 22:34:56 +00001023 SmallVector<Value *, 64> Temp;
Philip Reames2e5bcbe2015-02-28 01:52:09 +00001024 Temp.insert(Temp.end(), live.begin(), live.end());
1025 std::sort(Temp.begin(), Temp.end(), order_by_name);
1026 for (Value *ptr : Temp) {
Philip Reamesba198492015-04-14 00:41:34 +00001027 Value *base = findBasePointer(ptr, DVCache);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001028 assert(base && "failed to find base pointer");
Philip Reamesf2041322015-02-20 19:26:04 +00001029 PointerToBase[ptr] = base;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001030 assert((!isa<Instruction>(base) || !isa<Instruction>(ptr) ||
1031 DT->dominates(cast<Instruction>(base)->getParent(),
1032 cast<Instruction>(ptr)->getParent())) &&
1033 "The base we found better dominate the derived pointer");
1034
David Blaikie82ad7872015-02-20 23:44:24 +00001035 // If you see this trip and like to live really dangerously, the code should
1036 // be correct, just with idioms the verifier can't handle. You can try
1037 // disabling the verifier at your own substaintial risk.
Philip Reames704e78b2015-04-10 22:34:56 +00001038 assert(!isa<ConstantPointerNull>(base) &&
Philip Reames24c6cd52015-03-27 05:47:00 +00001039 "the relocation code needs adjustment to handle the relocation of "
1040 "a null pointer constant without causing false positives in the "
1041 "safepoint ir verifier.");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001042 }
1043}
1044
1045/// Find the required based pointers (and adjust the live set) for the given
1046/// parse point.
1047static void findBasePointers(DominatorTree &DT, DefiningValueMapTy &DVCache,
1048 const CallSite &CS,
1049 PartiallyConstructedSafepointRecord &result) {
Philip Reamesf2041322015-02-20 19:26:04 +00001050 DenseMap<llvm::Value *, llvm::Value *> PointerToBase;
Philip Reamesba198492015-04-14 00:41:34 +00001051 findBasePointers(result.liveset, PointerToBase, &DT, DVCache);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001052
1053 if (PrintBasePointers) {
Philip Reamesa5aeaf42015-02-28 00:20:48 +00001054 // Note: Need to print these in a stable order since this is checked in
1055 // some tests.
Philip Reamesd16a9b12015-02-20 01:06:44 +00001056 errs() << "Base Pairs (w/o Relocation):\n";
Philip Reames704e78b2015-04-10 22:34:56 +00001057 SmallVector<Value *, 64> Temp;
Philip Reamesa5aeaf42015-02-28 00:20:48 +00001058 Temp.reserve(PointerToBase.size());
Philip Reamesf2041322015-02-20 19:26:04 +00001059 for (auto Pair : PointerToBase) {
Philip Reamesa5aeaf42015-02-28 00:20:48 +00001060 Temp.push_back(Pair.first);
1061 }
1062 std::sort(Temp.begin(), Temp.end(), order_by_name);
1063 for (Value *Ptr : Temp) {
1064 Value *Base = PointerToBase[Ptr];
Philip Reames704e78b2015-04-10 22:34:56 +00001065 errs() << " derived %" << Ptr->getName() << " base %" << Base->getName()
1066 << "\n";
Philip Reamesd16a9b12015-02-20 01:06:44 +00001067 }
1068 }
1069
Philip Reamesf2041322015-02-20 19:26:04 +00001070 result.PointerToBase = PointerToBase;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001071}
1072
Philip Reamesdf1ef082015-04-10 22:53:14 +00001073/// Given an updated version of the dataflow liveness results, update the
1074/// liveset and base pointer maps for the call site CS.
1075static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData,
1076 const CallSite &CS,
1077 PartiallyConstructedSafepointRecord &result);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001078
Philip Reamesdf1ef082015-04-10 22:53:14 +00001079static void recomputeLiveInValues(
1080 Function &F, DominatorTree &DT, Pass *P, ArrayRef<CallSite> toUpdate,
Philip Reamesd2b66462015-02-20 22:39:41 +00001081 MutableArrayRef<struct PartiallyConstructedSafepointRecord> records) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00001082 // TODO-PERF: reuse the original liveness, then simply run the dataflow
1083 // again. The old values are still live and will help it stablize quickly.
1084 GCPtrLivenessData RevisedLivenessData;
1085 computeLiveInValues(DT, F, RevisedLivenessData);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001086 for (size_t i = 0; i < records.size(); i++) {
1087 struct PartiallyConstructedSafepointRecord &info = records[i];
Philip Reamesd2b66462015-02-20 22:39:41 +00001088 const CallSite &CS = toUpdate[i];
Philip Reamesdf1ef082015-04-10 22:53:14 +00001089 recomputeLiveInValues(RevisedLivenessData, CS, info);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001090 }
1091}
1092
Philip Reames69e51ca2015-04-13 18:07:21 +00001093// When inserting gc.relocate calls, we need to ensure there are no uses
1094// of the original value between the gc.statepoint and the gc.relocate call.
1095// One case which can arise is a phi node starting one of the successor blocks.
1096// We also need to be able to insert the gc.relocates only on the path which
1097// goes through the statepoint. We might need to split an edge to make this
Philip Reamesf209a152015-04-13 20:00:30 +00001098// possible.
1099static BasicBlock *
Sanjoy Dasea45f0e2015-06-02 22:33:34 +00001100normalizeForInvokeSafepoint(BasicBlock *BB, BasicBlock *InvokeParent,
1101 DominatorTree &DT) {
Philip Reames69e51ca2015-04-13 18:07:21 +00001102 BasicBlock *Ret = BB;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001103 if (!BB->getUniquePredecessor()) {
Chandler Carruth96ada252015-07-22 09:52:54 +00001104 Ret = SplitBlockPredecessors(BB, InvokeParent, "", &DT);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001105 }
1106
Philip Reames69e51ca2015-04-13 18:07:21 +00001107 // Now that 'ret' has unique predecessor we can safely remove all phi nodes
1108 // from it
1109 FoldSingleEntryPHINodes(Ret);
1110 assert(!isa<PHINode>(Ret->begin()));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001111
Philip Reames69e51ca2015-04-13 18:07:21 +00001112 // At this point, we can safely insert a gc.relocate as the first instruction
1113 // in Ret if needed.
1114 return Ret;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001115}
1116
Philip Reamesd2b66462015-02-20 22:39:41 +00001117static int find_index(ArrayRef<Value *> livevec, Value *val) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001118 auto itr = std::find(livevec.begin(), livevec.end(), val);
1119 assert(livevec.end() != itr);
1120 size_t index = std::distance(livevec.begin(), itr);
1121 assert(index < livevec.size());
1122 return index;
1123}
1124
1125// Create new attribute set containing only attributes which can be transfered
1126// from original call to the safepoint.
1127static AttributeSet legalizeCallAttributes(AttributeSet AS) {
1128 AttributeSet ret;
1129
1130 for (unsigned Slot = 0; Slot < AS.getNumSlots(); Slot++) {
1131 unsigned index = AS.getSlotIndex(Slot);
1132
1133 if (index == AttributeSet::ReturnIndex ||
1134 index == AttributeSet::FunctionIndex) {
1135
1136 for (auto it = AS.begin(Slot), it_end = AS.end(Slot); it != it_end;
1137 ++it) {
1138 Attribute attr = *it;
1139
1140 // Do not allow certain attributes - just skip them
1141 // Safepoint can not be read only or read none.
1142 if (attr.hasAttribute(Attribute::ReadNone) ||
1143 attr.hasAttribute(Attribute::ReadOnly))
1144 continue;
1145
1146 ret = ret.addAttributes(
1147 AS.getContext(), index,
1148 AttributeSet::get(AS.getContext(), index, AttrBuilder(attr)));
1149 }
1150 }
1151
1152 // Just skip parameter attributes for now
1153 }
1154
1155 return ret;
1156}
1157
1158/// Helper function to place all gc relocates necessary for the given
1159/// statepoint.
1160/// Inputs:
1161/// liveVariables - list of variables to be relocated.
1162/// liveStart - index of the first live variable.
1163/// basePtrs - base pointers.
1164/// statepointToken - statepoint instruction to which relocates should be
1165/// bound.
1166/// Builder - Llvm IR builder to be used to construct new calls.
Sanjoy Das5665c992015-05-11 23:47:27 +00001167static void CreateGCRelocates(ArrayRef<llvm::Value *> LiveVariables,
1168 const int LiveStart,
1169 ArrayRef<llvm::Value *> BasePtrs,
1170 Instruction *StatepointToken,
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00001171 IRBuilder<> Builder) {
Philip Reames94babb72015-07-21 17:18:03 +00001172 if (LiveVariables.empty())
1173 return;
1174
1175 // All gc_relocate are set to i8 addrspace(1)* type. We originally generated
1176 // unique declarations for each pointer type, but this proved problematic
1177 // because the intrinsic mangling code is incomplete and fragile. Since
1178 // we're moving towards a single unified pointer type anyways, we can just
1179 // cast everything to an i8* of the right address space. A bitcast is added
1180 // later to convert gc_relocate to the actual value's type.
Philip Reames74ce2e72015-07-21 16:51:17 +00001181 Module *M = StatepointToken->getModule();
Philip Reames94babb72015-07-21 17:18:03 +00001182 auto AS = cast<PointerType>(LiveVariables[0]->getType())->getAddressSpace();
1183 Type *Types[] = {Type::getInt8PtrTy(M->getContext(), AS)};
1184 Value *GCRelocateDecl =
1185 Intrinsic::getDeclaration(M, Intrinsic::experimental_gc_relocate, Types);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001186
Sanjoy Das5665c992015-05-11 23:47:27 +00001187 for (unsigned i = 0; i < LiveVariables.size(); i++) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001188 // Generate the gc.relocate call and save the result
Sanjoy Das5665c992015-05-11 23:47:27 +00001189 Value *BaseIdx =
Philip Reamesf3880502015-07-21 00:49:55 +00001190 Builder.getInt32(LiveStart + find_index(LiveVariables, BasePtrs[i]));
1191 Value *LiveIdx =
1192 Builder.getInt32(LiveStart + find_index(LiveVariables, LiveVariables[i]));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001193
1194 // only specify a debug name if we can give a useful one
Philip Reames74ce2e72015-07-21 16:51:17 +00001195 CallInst *Reloc = Builder.CreateCall(
David Blaikieff6409d2015-05-18 22:13:54 +00001196 GCRelocateDecl, {StatepointToken, BaseIdx, LiveIdx},
Sanjoy Das5665c992015-05-11 23:47:27 +00001197 LiveVariables[i]->hasName() ? LiveVariables[i]->getName() + ".relocated"
Philip Reamesd16a9b12015-02-20 01:06:44 +00001198 : "");
1199 // Trick CodeGen into thinking there are lots of free registers at this
1200 // fake call.
Philip Reames74ce2e72015-07-21 16:51:17 +00001201 Reloc->setCallingConv(CallingConv::Cold);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001202 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00001203}
1204
1205static void
1206makeStatepointExplicitImpl(const CallSite &CS, /* to replace */
1207 const SmallVectorImpl<llvm::Value *> &basePtrs,
1208 const SmallVectorImpl<llvm::Value *> &liveVariables,
1209 Pass *P,
1210 PartiallyConstructedSafepointRecord &result) {
1211 assert(basePtrs.size() == liveVariables.size());
1212 assert(isStatepoint(CS) &&
1213 "This method expects to be rewriting a statepoint");
1214
1215 BasicBlock *BB = CS.getInstruction()->getParent();
1216 assert(BB);
1217 Function *F = BB->getParent();
1218 assert(F && "must be set");
1219 Module *M = F->getParent();
Nick Lewyckyeb3231e2015-02-20 07:14:02 +00001220 (void)M;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001221 assert(M && "must be set");
1222
1223 // We're not changing the function signature of the statepoint since the gc
1224 // arguments go into the var args section.
1225 Function *gc_statepoint_decl = CS.getCalledFunction();
1226
1227 // Then go ahead and use the builder do actually do the inserts. We insert
1228 // immediately before the previous instruction under the assumption that all
1229 // arguments will be available here. We can't insert afterwards since we may
1230 // be replacing a terminator.
1231 Instruction *insertBefore = CS.getInstruction();
1232 IRBuilder<> Builder(insertBefore);
1233 // Copy all of the arguments from the original statepoint - this includes the
1234 // target, call args, and deopt args
Philip Reamesd2b66462015-02-20 22:39:41 +00001235 SmallVector<llvm::Value *, 64> args;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001236 args.insert(args.end(), CS.arg_begin(), CS.arg_end());
1237 // TODO: Clear the 'needs rewrite' flag
1238
1239 // add all the pointers to be relocated (gc arguments)
1240 // Capture the start of the live variable list for use in the gc_relocates
1241 const int live_start = args.size();
1242 args.insert(args.end(), liveVariables.begin(), liveVariables.end());
1243
1244 // Create the statepoint given all the arguments
1245 Instruction *token = nullptr;
1246 AttributeSet return_attributes;
1247 if (CS.isCall()) {
1248 CallInst *toReplace = cast<CallInst>(CS.getInstruction());
1249 CallInst *call =
1250 Builder.CreateCall(gc_statepoint_decl, args, "safepoint_token");
1251 call->setTailCall(toReplace->isTailCall());
1252 call->setCallingConv(toReplace->getCallingConv());
1253
1254 // Currently we will fail on parameter attributes and on certain
1255 // function attributes.
1256 AttributeSet new_attrs = legalizeCallAttributes(toReplace->getAttributes());
1257 // In case if we can handle this set of sttributes - set up function attrs
1258 // directly on statepoint and return attrs later for gc_result intrinsic.
1259 call->setAttributes(new_attrs.getFnAttributes());
1260 return_attributes = new_attrs.getRetAttributes();
1261
1262 token = call;
1263
1264 // Put the following gc_result and gc_relocate calls immediately after the
1265 // the old call (which we're about to delete)
1266 BasicBlock::iterator next(toReplace);
1267 assert(BB->end() != next && "not a terminator, must have next");
1268 next++;
1269 Instruction *IP = &*(next);
1270 Builder.SetInsertPoint(IP);
1271 Builder.SetCurrentDebugLocation(IP->getDebugLoc());
1272
David Blaikie82ad7872015-02-20 23:44:24 +00001273 } else {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001274 InvokeInst *toReplace = cast<InvokeInst>(CS.getInstruction());
1275
1276 // Insert the new invoke into the old block. We'll remove the old one in a
1277 // moment at which point this will become the new terminator for the
1278 // original block.
1279 InvokeInst *invoke = InvokeInst::Create(
1280 gc_statepoint_decl, toReplace->getNormalDest(),
1281 toReplace->getUnwindDest(), args, "", toReplace->getParent());
1282 invoke->setCallingConv(toReplace->getCallingConv());
1283
1284 // Currently we will fail on parameter attributes and on certain
1285 // function attributes.
1286 AttributeSet new_attrs = legalizeCallAttributes(toReplace->getAttributes());
1287 // In case if we can handle this set of sttributes - set up function attrs
1288 // directly on statepoint and return attrs later for gc_result intrinsic.
1289 invoke->setAttributes(new_attrs.getFnAttributes());
1290 return_attributes = new_attrs.getRetAttributes();
1291
1292 token = invoke;
1293
1294 // Generate gc relocates in exceptional path
Philip Reames69e51ca2015-04-13 18:07:21 +00001295 BasicBlock *unwindBlock = toReplace->getUnwindDest();
1296 assert(!isa<PHINode>(unwindBlock->begin()) &&
1297 unwindBlock->getUniquePredecessor() &&
1298 "can't safely insert in this block!");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001299
1300 Instruction *IP = &*(unwindBlock->getFirstInsertionPt());
1301 Builder.SetInsertPoint(IP);
1302 Builder.SetCurrentDebugLocation(toReplace->getDebugLoc());
1303
1304 // Extract second element from landingpad return value. We will attach
1305 // exceptional gc relocates to it.
1306 const unsigned idx = 1;
1307 Instruction *exceptional_token =
1308 cast<Instruction>(Builder.CreateExtractValue(
1309 unwindBlock->getLandingPadInst(), idx, "relocate_token"));
Philip Reamesf2041322015-02-20 19:26:04 +00001310 result.UnwindToken = exceptional_token;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001311
Philip Reames6ff1a1e32015-07-21 19:04:38 +00001312 CreateGCRelocates(liveVariables, live_start, basePtrs,
1313 exceptional_token, Builder);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001314
1315 // Generate gc relocates and returns for normal block
Philip Reames69e51ca2015-04-13 18:07:21 +00001316 BasicBlock *normalDest = toReplace->getNormalDest();
1317 assert(!isa<PHINode>(normalDest->begin()) &&
1318 normalDest->getUniquePredecessor() &&
1319 "can't safely insert in this block!");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001320
1321 IP = &*(normalDest->getFirstInsertionPt());
1322 Builder.SetInsertPoint(IP);
1323
1324 // gc relocates will be generated later as if it were regular call
1325 // statepoint
Philip Reamesd16a9b12015-02-20 01:06:44 +00001326 }
1327 assert(token);
1328
1329 // Take the name of the original value call if it had one.
1330 token->takeName(CS.getInstruction());
1331
Philip Reames704e78b2015-04-10 22:34:56 +00001332// The GCResult is already inserted, we just need to find it
David Blaikie5e5d7842015-02-22 20:58:38 +00001333#ifndef NDEBUG
1334 Instruction *toReplace = CS.getInstruction();
1335 assert((toReplace->hasNUses(0) || toReplace->hasNUses(1)) &&
1336 "only valid use before rewrite is gc.result");
1337 assert(!toReplace->hasOneUse() ||
1338 isGCResult(cast<Instruction>(*toReplace->user_begin())));
1339#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +00001340
1341 // Update the gc.result of the original statepoint (if any) to use the newly
1342 // inserted statepoint. This is safe to do here since the token can't be
1343 // considered a live reference.
1344 CS.getInstruction()->replaceAllUsesWith(token);
1345
Philip Reames0a3240f2015-02-20 21:34:11 +00001346 result.StatepointToken = token;
1347
Philip Reamesd16a9b12015-02-20 01:06:44 +00001348 // Second, create a gc.relocate for every live variable
Philip Reames0a3240f2015-02-20 21:34:11 +00001349 CreateGCRelocates(liveVariables, live_start, basePtrs, token, Builder);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001350}
1351
1352namespace {
1353struct name_ordering {
1354 Value *base;
1355 Value *derived;
1356 bool operator()(name_ordering const &a, name_ordering const &b) {
1357 return -1 == a.derived->getName().compare(b.derived->getName());
1358 }
1359};
1360}
1361static void stablize_order(SmallVectorImpl<Value *> &basevec,
1362 SmallVectorImpl<Value *> &livevec) {
1363 assert(basevec.size() == livevec.size());
1364
Philip Reames860660e2015-02-20 22:05:18 +00001365 SmallVector<name_ordering, 64> temp;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001366 for (size_t i = 0; i < basevec.size(); i++) {
1367 name_ordering v;
1368 v.base = basevec[i];
1369 v.derived = livevec[i];
1370 temp.push_back(v);
1371 }
1372 std::sort(temp.begin(), temp.end(), name_ordering());
1373 for (size_t i = 0; i < basevec.size(); i++) {
1374 basevec[i] = temp[i].base;
1375 livevec[i] = temp[i].derived;
1376 }
1377}
1378
1379// Replace an existing gc.statepoint with a new one and a set of gc.relocates
1380// which make the relocations happening at this safepoint explicit.
Philip Reames704e78b2015-04-10 22:34:56 +00001381//
Philip Reamesd16a9b12015-02-20 01:06:44 +00001382// WARNING: Does not do any fixup to adjust users of the original live
1383// values. That's the callers responsibility.
1384static void
1385makeStatepointExplicit(DominatorTree &DT, const CallSite &CS, Pass *P,
1386 PartiallyConstructedSafepointRecord &result) {
Philip Reamesf2041322015-02-20 19:26:04 +00001387 auto liveset = result.liveset;
1388 auto PointerToBase = result.PointerToBase;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001389
1390 // Convert to vector for efficient cross referencing.
1391 SmallVector<Value *, 64> basevec, livevec;
1392 livevec.reserve(liveset.size());
1393 basevec.reserve(liveset.size());
1394 for (Value *L : liveset) {
1395 livevec.push_back(L);
Philip Reames74ce2e72015-07-21 16:51:17 +00001396 assert(PointerToBase.count(L));
Philip Reamesf2041322015-02-20 19:26:04 +00001397 Value *base = PointerToBase[L];
Philip Reamesd16a9b12015-02-20 01:06:44 +00001398 basevec.push_back(base);
1399 }
1400 assert(livevec.size() == basevec.size());
1401
1402 // To make the output IR slightly more stable (for use in diffs), ensure a
1403 // fixed order of the values in the safepoint (by sorting the value name).
1404 // The order is otherwise meaningless.
1405 stablize_order(basevec, livevec);
1406
1407 // Do the actual rewriting and delete the old statepoint
1408 makeStatepointExplicitImpl(CS, basevec, livevec, P, result);
1409 CS.getInstruction()->eraseFromParent();
1410}
1411
1412// Helper function for the relocationViaAlloca.
1413// It receives iterator to the statepoint gc relocates and emits store to the
1414// assigned
1415// location (via allocaMap) for the each one of them.
1416// Add visited values into the visitedLiveValues set we will later use them
1417// for sanity check.
1418static void
Sanjoy Das5665c992015-05-11 23:47:27 +00001419insertRelocationStores(iterator_range<Value::user_iterator> GCRelocs,
1420 DenseMap<Value *, Value *> &AllocaMap,
1421 DenseSet<Value *> &VisitedLiveValues) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001422
Sanjoy Das5665c992015-05-11 23:47:27 +00001423 for (User *U : GCRelocs) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001424 if (!isa<IntrinsicInst>(U))
1425 continue;
1426
Sanjoy Das5665c992015-05-11 23:47:27 +00001427 IntrinsicInst *RelocatedValue = cast<IntrinsicInst>(U);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001428
1429 // We only care about relocates
Sanjoy Das5665c992015-05-11 23:47:27 +00001430 if (RelocatedValue->getIntrinsicID() !=
Philip Reamesd16a9b12015-02-20 01:06:44 +00001431 Intrinsic::experimental_gc_relocate) {
1432 continue;
1433 }
1434
Sanjoy Das5665c992015-05-11 23:47:27 +00001435 GCRelocateOperands RelocateOperands(RelocatedValue);
1436 Value *OriginalValue =
1437 const_cast<Value *>(RelocateOperands.getDerivedPtr());
1438 assert(AllocaMap.count(OriginalValue));
1439 Value *Alloca = AllocaMap[OriginalValue];
Philip Reamesd16a9b12015-02-20 01:06:44 +00001440
1441 // Emit store into the related alloca
Sanjoy Das89c54912015-05-11 18:49:34 +00001442 // All gc_relocate are i8 addrspace(1)* typed, and it must be bitcasted to
1443 // the correct type according to alloca.
Sanjoy Das5665c992015-05-11 23:47:27 +00001444 assert(RelocatedValue->getNextNode() && "Should always have one since it's not a terminator");
1445 IRBuilder<> Builder(RelocatedValue->getNextNode());
Sanjoy Das89c54912015-05-11 18:49:34 +00001446 Value *CastedRelocatedValue =
Sanjoy Das5665c992015-05-11 23:47:27 +00001447 Builder.CreateBitCast(RelocatedValue, cast<AllocaInst>(Alloca)->getAllocatedType(),
1448 RelocatedValue->hasName() ? RelocatedValue->getName() + ".casted" : "");
Sanjoy Das89c54912015-05-11 18:49:34 +00001449
Sanjoy Das5665c992015-05-11 23:47:27 +00001450 StoreInst *Store = new StoreInst(CastedRelocatedValue, Alloca);
1451 Store->insertAfter(cast<Instruction>(CastedRelocatedValue));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001452
1453#ifndef NDEBUG
Sanjoy Das5665c992015-05-11 23:47:27 +00001454 VisitedLiveValues.insert(OriginalValue);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001455#endif
1456 }
1457}
1458
Igor Laevskye0317182015-05-19 15:59:05 +00001459// Helper function for the "relocationViaAlloca". Similar to the
1460// "insertRelocationStores" but works for rematerialized values.
1461static void
1462insertRematerializationStores(
1463 RematerializedValueMapTy RematerializedValues,
1464 DenseMap<Value *, Value *> &AllocaMap,
1465 DenseSet<Value *> &VisitedLiveValues) {
1466
1467 for (auto RematerializedValuePair: RematerializedValues) {
1468 Instruction *RematerializedValue = RematerializedValuePair.first;
1469 Value *OriginalValue = RematerializedValuePair.second;
1470
1471 assert(AllocaMap.count(OriginalValue) &&
1472 "Can not find alloca for rematerialized value");
1473 Value *Alloca = AllocaMap[OriginalValue];
1474
1475 StoreInst *Store = new StoreInst(RematerializedValue, Alloca);
1476 Store->insertAfter(RematerializedValue);
1477
1478#ifndef NDEBUG
1479 VisitedLiveValues.insert(OriginalValue);
1480#endif
1481 }
1482}
1483
Philip Reamesd16a9b12015-02-20 01:06:44 +00001484/// do all the relocation update via allocas and mem2reg
1485static void relocationViaAlloca(
Igor Laevsky285fe842015-05-19 16:29:43 +00001486 Function &F, DominatorTree &DT, ArrayRef<Value *> Live,
1487 ArrayRef<struct PartiallyConstructedSafepointRecord> Records) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001488#ifndef NDEBUG
Philip Reamesa6ebf072015-03-27 05:53:16 +00001489 // record initial number of (static) allocas; we'll check we have the same
1490 // number when we get done.
1491 int InitialAllocaNum = 0;
Philip Reames704e78b2015-04-10 22:34:56 +00001492 for (auto I = F.getEntryBlock().begin(), E = F.getEntryBlock().end(); I != E;
1493 I++)
Philip Reamesa6ebf072015-03-27 05:53:16 +00001494 if (isa<AllocaInst>(*I))
1495 InitialAllocaNum++;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001496#endif
1497
1498 // TODO-PERF: change data structures, reserve
Igor Laevsky285fe842015-05-19 16:29:43 +00001499 DenseMap<Value *, Value *> AllocaMap;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001500 SmallVector<AllocaInst *, 200> PromotableAllocas;
Igor Laevskye0317182015-05-19 15:59:05 +00001501 // Used later to chack that we have enough allocas to store all values
1502 std::size_t NumRematerializedValues = 0;
Igor Laevsky285fe842015-05-19 16:29:43 +00001503 PromotableAllocas.reserve(Live.size());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001504
Igor Laevskye0317182015-05-19 15:59:05 +00001505 // Emit alloca for "LiveValue" and record it in "allocaMap" and
1506 // "PromotableAllocas"
1507 auto emitAllocaFor = [&](Value *LiveValue) {
1508 AllocaInst *Alloca = new AllocaInst(LiveValue->getType(), "",
1509 F.getEntryBlock().getFirstNonPHI());
Igor Laevsky285fe842015-05-19 16:29:43 +00001510 AllocaMap[LiveValue] = Alloca;
Igor Laevskye0317182015-05-19 15:59:05 +00001511 PromotableAllocas.push_back(Alloca);
1512 };
1513
Philip Reamesd16a9b12015-02-20 01:06:44 +00001514 // emit alloca for each live gc pointer
Igor Laevsky285fe842015-05-19 16:29:43 +00001515 for (unsigned i = 0; i < Live.size(); i++) {
1516 emitAllocaFor(Live[i]);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001517 }
1518
Igor Laevskye0317182015-05-19 15:59:05 +00001519 // emit allocas for rematerialized values
Igor Laevsky285fe842015-05-19 16:29:43 +00001520 for (size_t i = 0; i < Records.size(); i++) {
1521 const struct PartiallyConstructedSafepointRecord &Info = Records[i];
Igor Laevskye0317182015-05-19 15:59:05 +00001522
Igor Laevsky285fe842015-05-19 16:29:43 +00001523 for (auto RematerializedValuePair : Info.RematerializedValues) {
Igor Laevskye0317182015-05-19 15:59:05 +00001524 Value *OriginalValue = RematerializedValuePair.second;
Igor Laevsky285fe842015-05-19 16:29:43 +00001525 if (AllocaMap.count(OriginalValue) != 0)
Igor Laevskye0317182015-05-19 15:59:05 +00001526 continue;
1527
1528 emitAllocaFor(OriginalValue);
1529 ++NumRematerializedValues;
1530 }
1531 }
Igor Laevsky285fe842015-05-19 16:29:43 +00001532
Philip Reamesd16a9b12015-02-20 01:06:44 +00001533 // The next two loops are part of the same conceptual operation. We need to
1534 // insert a store to the alloca after the original def and at each
1535 // redefinition. We need to insert a load before each use. These are split
1536 // into distinct loops for performance reasons.
1537
1538 // update gc pointer after each statepoint
1539 // either store a relocated value or null (if no relocated value found for
1540 // this gc pointer and it is not a gc_result)
1541 // this must happen before we update the statepoint with load of alloca
1542 // otherwise we lose the link between statepoint and old def
Igor Laevsky285fe842015-05-19 16:29:43 +00001543 for (size_t i = 0; i < Records.size(); i++) {
1544 const struct PartiallyConstructedSafepointRecord &Info = Records[i];
1545 Value *Statepoint = Info.StatepointToken;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001546
1547 // This will be used for consistency check
Igor Laevsky285fe842015-05-19 16:29:43 +00001548 DenseSet<Value *> VisitedLiveValues;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001549
1550 // Insert stores for normal statepoint gc relocates
Igor Laevsky285fe842015-05-19 16:29:43 +00001551 insertRelocationStores(Statepoint->users(), AllocaMap, VisitedLiveValues);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001552
1553 // In case if it was invoke statepoint
1554 // we will insert stores for exceptional path gc relocates.
Philip Reames0a3240f2015-02-20 21:34:11 +00001555 if (isa<InvokeInst>(Statepoint)) {
Igor Laevsky285fe842015-05-19 16:29:43 +00001556 insertRelocationStores(Info.UnwindToken->users(), AllocaMap,
1557 VisitedLiveValues);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001558 }
1559
Igor Laevskye0317182015-05-19 15:59:05 +00001560 // Do similar thing with rematerialized values
Igor Laevsky285fe842015-05-19 16:29:43 +00001561 insertRematerializationStores(Info.RematerializedValues, AllocaMap,
1562 VisitedLiveValues);
Igor Laevskye0317182015-05-19 15:59:05 +00001563
Philip Reamese73300b2015-04-13 16:41:32 +00001564 if (ClobberNonLive) {
1565 // As a debuging aid, pretend that an unrelocated pointer becomes null at
1566 // the gc.statepoint. This will turn some subtle GC problems into
1567 // slightly easier to debug SEGVs. Note that on large IR files with
1568 // lots of gc.statepoints this is extremely costly both memory and time
1569 // wise.
1570 SmallVector<AllocaInst *, 64> ToClobber;
Igor Laevsky285fe842015-05-19 16:29:43 +00001571 for (auto Pair : AllocaMap) {
Philip Reamese73300b2015-04-13 16:41:32 +00001572 Value *Def = Pair.first;
1573 AllocaInst *Alloca = cast<AllocaInst>(Pair.second);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001574
Philip Reamese73300b2015-04-13 16:41:32 +00001575 // This value was relocated
Igor Laevsky285fe842015-05-19 16:29:43 +00001576 if (VisitedLiveValues.count(Def)) {
Philip Reamese73300b2015-04-13 16:41:32 +00001577 continue;
1578 }
1579 ToClobber.push_back(Alloca);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001580 }
Philip Reamesfa2fcf172015-02-20 19:51:56 +00001581
Philip Reamese73300b2015-04-13 16:41:32 +00001582 auto InsertClobbersAt = [&](Instruction *IP) {
1583 for (auto *AI : ToClobber) {
1584 auto AIType = cast<PointerType>(AI->getType());
1585 auto PT = cast<PointerType>(AIType->getElementType());
1586 Constant *CPN = ConstantPointerNull::get(PT);
Igor Laevsky285fe842015-05-19 16:29:43 +00001587 StoreInst *Store = new StoreInst(CPN, AI);
1588 Store->insertBefore(IP);
Philip Reamese73300b2015-04-13 16:41:32 +00001589 }
1590 };
1591
1592 // Insert the clobbering stores. These may get intermixed with the
1593 // gc.results and gc.relocates, but that's fine.
1594 if (auto II = dyn_cast<InvokeInst>(Statepoint)) {
1595 InsertClobbersAt(II->getNormalDest()->getFirstInsertionPt());
1596 InsertClobbersAt(II->getUnwindDest()->getFirstInsertionPt());
1597 } else {
1598 BasicBlock::iterator Next(cast<CallInst>(Statepoint));
1599 Next++;
1600 InsertClobbersAt(Next);
Philip Reamesfa2fcf172015-02-20 19:51:56 +00001601 }
David Blaikie82ad7872015-02-20 23:44:24 +00001602 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00001603 }
1604 // update use with load allocas and add store for gc_relocated
Igor Laevsky285fe842015-05-19 16:29:43 +00001605 for (auto Pair : AllocaMap) {
1606 Value *Def = Pair.first;
1607 Value *Alloca = Pair.second;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001608
1609 // we pre-record the uses of allocas so that we dont have to worry about
1610 // later update
1611 // that change the user information.
Igor Laevsky285fe842015-05-19 16:29:43 +00001612 SmallVector<Instruction *, 20> Uses;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001613 // PERF: trade a linear scan for repeated reallocation
Igor Laevsky285fe842015-05-19 16:29:43 +00001614 Uses.reserve(std::distance(Def->user_begin(), Def->user_end()));
1615 for (User *U : Def->users()) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001616 if (!isa<ConstantExpr>(U)) {
1617 // If the def has a ConstantExpr use, then the def is either a
1618 // ConstantExpr use itself or null. In either case
1619 // (recursively in the first, directly in the second), the oop
1620 // it is ultimately dependent on is null and this particular
1621 // use does not need to be fixed up.
Igor Laevsky285fe842015-05-19 16:29:43 +00001622 Uses.push_back(cast<Instruction>(U));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001623 }
1624 }
1625
Igor Laevsky285fe842015-05-19 16:29:43 +00001626 std::sort(Uses.begin(), Uses.end());
1627 auto Last = std::unique(Uses.begin(), Uses.end());
1628 Uses.erase(Last, Uses.end());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001629
Igor Laevsky285fe842015-05-19 16:29:43 +00001630 for (Instruction *Use : Uses) {
1631 if (isa<PHINode>(Use)) {
1632 PHINode *Phi = cast<PHINode>(Use);
1633 for (unsigned i = 0; i < Phi->getNumIncomingValues(); i++) {
1634 if (Def == Phi->getIncomingValue(i)) {
1635 LoadInst *Load = new LoadInst(
1636 Alloca, "", Phi->getIncomingBlock(i)->getTerminator());
1637 Phi->setIncomingValue(i, Load);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001638 }
1639 }
1640 } else {
Igor Laevsky285fe842015-05-19 16:29:43 +00001641 LoadInst *Load = new LoadInst(Alloca, "", Use);
1642 Use->replaceUsesOfWith(Def, Load);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001643 }
1644 }
1645
1646 // emit store for the initial gc value
1647 // store must be inserted after load, otherwise store will be in alloca's
1648 // use list and an extra load will be inserted before it
Igor Laevsky285fe842015-05-19 16:29:43 +00001649 StoreInst *Store = new StoreInst(Def, Alloca);
1650 if (Instruction *Inst = dyn_cast<Instruction>(Def)) {
1651 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(Inst)) {
Philip Reames6da37852015-03-04 00:13:52 +00001652 // InvokeInst is a TerminatorInst so the store need to be inserted
1653 // into its normal destination block.
Igor Laevsky285fe842015-05-19 16:29:43 +00001654 BasicBlock *NormalDest = Invoke->getNormalDest();
1655 Store->insertBefore(NormalDest->getFirstNonPHI());
Philip Reames6da37852015-03-04 00:13:52 +00001656 } else {
Igor Laevsky285fe842015-05-19 16:29:43 +00001657 assert(!Inst->isTerminator() &&
Philip Reames6da37852015-03-04 00:13:52 +00001658 "The only TerminatorInst that can produce a value is "
1659 "InvokeInst which is handled above.");
Igor Laevsky285fe842015-05-19 16:29:43 +00001660 Store->insertAfter(Inst);
Philip Reames6da37852015-03-04 00:13:52 +00001661 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00001662 } else {
Igor Laevsky285fe842015-05-19 16:29:43 +00001663 assert(isa<Argument>(Def));
1664 Store->insertAfter(cast<Instruction>(Alloca));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001665 }
1666 }
1667
Igor Laevsky285fe842015-05-19 16:29:43 +00001668 assert(PromotableAllocas.size() == Live.size() + NumRematerializedValues &&
Philip Reamesd16a9b12015-02-20 01:06:44 +00001669 "we must have the same allocas with lives");
1670 if (!PromotableAllocas.empty()) {
1671 // apply mem2reg to promote alloca to SSA
1672 PromoteMemToReg(PromotableAllocas, DT);
1673 }
1674
1675#ifndef NDEBUG
Philip Reames704e78b2015-04-10 22:34:56 +00001676 for (auto I = F.getEntryBlock().begin(), E = F.getEntryBlock().end(); I != E;
1677 I++)
Philip Reamesa6ebf072015-03-27 05:53:16 +00001678 if (isa<AllocaInst>(*I))
1679 InitialAllocaNum--;
1680 assert(InitialAllocaNum == 0 && "We must not introduce any extra allocas");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001681#endif
1682}
1683
1684/// Implement a unique function which doesn't require we sort the input
1685/// vector. Doing so has the effect of changing the output of a couple of
1686/// tests in ways which make them less useful in testing fused safepoints.
Philip Reamesd2b66462015-02-20 22:39:41 +00001687template <typename T> static void unique_unsorted(SmallVectorImpl<T> &Vec) {
Benjamin Kramer258ea0d2015-06-13 19:50:38 +00001688 SmallSet<T, 8> Seen;
1689 Vec.erase(std::remove_if(Vec.begin(), Vec.end(), [&](const T &V) {
1690 return !Seen.insert(V).second;
1691 }), Vec.end());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001692}
1693
Philip Reamesd16a9b12015-02-20 01:06:44 +00001694/// Insert holders so that each Value is obviously live through the entire
Philip Reamesf209a152015-04-13 20:00:30 +00001695/// lifetime of the call.
Philip Reamesd16a9b12015-02-20 01:06:44 +00001696static void insertUseHolderAfter(CallSite &CS, const ArrayRef<Value *> Values,
Philip Reamesf209a152015-04-13 20:00:30 +00001697 SmallVectorImpl<CallInst *> &Holders) {
Philip Reames21142752015-04-13 19:07:47 +00001698 if (Values.empty())
1699 // No values to hold live, might as well not insert the empty holder
1700 return;
1701
Philip Reamesd16a9b12015-02-20 01:06:44 +00001702 Module *M = CS.getInstruction()->getParent()->getParent()->getParent();
Philip Reamesf209a152015-04-13 20:00:30 +00001703 // Use a dummy vararg function to actually hold the values live
1704 Function *Func = cast<Function>(M->getOrInsertFunction(
1705 "__tmp_use", FunctionType::get(Type::getVoidTy(M->getContext()), true)));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001706 if (CS.isCall()) {
1707 // For call safepoints insert dummy calls right after safepoint
Philip Reamesf209a152015-04-13 20:00:30 +00001708 BasicBlock::iterator Next(CS.getInstruction());
1709 Next++;
1710 Holders.push_back(CallInst::Create(Func, Values, "", Next));
1711 return;
1712 }
1713 // For invoke safepooints insert dummy calls both in normal and
1714 // exceptional destination blocks
1715 auto *II = cast<InvokeInst>(CS.getInstruction());
1716 Holders.push_back(CallInst::Create(
1717 Func, Values, "", II->getNormalDest()->getFirstInsertionPt()));
1718 Holders.push_back(CallInst::Create(
1719 Func, Values, "", II->getUnwindDest()->getFirstInsertionPt()));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001720}
1721
1722static void findLiveReferences(
Philip Reamesd2b66462015-02-20 22:39:41 +00001723 Function &F, DominatorTree &DT, Pass *P, ArrayRef<CallSite> toUpdate,
1724 MutableArrayRef<struct PartiallyConstructedSafepointRecord> records) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00001725 GCPtrLivenessData OriginalLivenessData;
1726 computeLiveInValues(DT, F, OriginalLivenessData);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001727 for (size_t i = 0; i < records.size(); i++) {
1728 struct PartiallyConstructedSafepointRecord &info = records[i];
Philip Reamesd2b66462015-02-20 22:39:41 +00001729 const CallSite &CS = toUpdate[i];
Philip Reamesdf1ef082015-04-10 22:53:14 +00001730 analyzeParsePointLiveness(DT, OriginalLivenessData, CS, info);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001731 }
1732}
1733
Philip Reames8531d8c2015-04-10 21:48:25 +00001734/// Remove any vector of pointers from the liveset by scalarizing them over the
1735/// statepoint instruction. Adds the scalarized pieces to the liveset. It
1736/// would be preferrable to include the vector in the statepoint itself, but
1737/// the lowering code currently does not handle that. Extending it would be
1738/// slightly non-trivial since it requires a format change. Given how rare
1739/// such cases are (for the moment?) scalarizing is an acceptable comprimise.
1740static void splitVectorValues(Instruction *StatepointInst,
Philip Reames8fe7f132015-06-26 22:47:37 +00001741 StatepointLiveSetTy &LiveSet,
1742 DenseMap<Value *, Value *>& PointerToBase,
1743 DominatorTree &DT) {
Philip Reames8531d8c2015-04-10 21:48:25 +00001744 SmallVector<Value *, 16> ToSplit;
1745 for (Value *V : LiveSet)
1746 if (isa<VectorType>(V->getType()))
1747 ToSplit.push_back(V);
1748
1749 if (ToSplit.empty())
1750 return;
1751
Philip Reames8fe7f132015-06-26 22:47:37 +00001752 DenseMap<Value *, SmallVector<Value *, 16>> ElementMapping;
1753
Philip Reames8531d8c2015-04-10 21:48:25 +00001754 Function &F = *(StatepointInst->getParent()->getParent());
1755
Philip Reames704e78b2015-04-10 22:34:56 +00001756 DenseMap<Value *, AllocaInst *> AllocaMap;
Philip Reames8531d8c2015-04-10 21:48:25 +00001757 // First is normal return, second is exceptional return (invoke only)
Philip Reames704e78b2015-04-10 22:34:56 +00001758 DenseMap<Value *, std::pair<Value *, Value *>> Replacements;
Philip Reames8531d8c2015-04-10 21:48:25 +00001759 for (Value *V : ToSplit) {
Philip Reames704e78b2015-04-10 22:34:56 +00001760 AllocaInst *Alloca =
1761 new AllocaInst(V->getType(), "", F.getEntryBlock().getFirstNonPHI());
Philip Reames8531d8c2015-04-10 21:48:25 +00001762 AllocaMap[V] = Alloca;
1763
1764 VectorType *VT = cast<VectorType>(V->getType());
1765 IRBuilder<> Builder(StatepointInst);
Philip Reames704e78b2015-04-10 22:34:56 +00001766 SmallVector<Value *, 16> Elements;
Philip Reames8531d8c2015-04-10 21:48:25 +00001767 for (unsigned i = 0; i < VT->getNumElements(); i++)
1768 Elements.push_back(Builder.CreateExtractElement(V, Builder.getInt32(i)));
Philip Reames8fe7f132015-06-26 22:47:37 +00001769 ElementMapping[V] = Elements;
Philip Reames8531d8c2015-04-10 21:48:25 +00001770
1771 auto InsertVectorReform = [&](Instruction *IP) {
1772 Builder.SetInsertPoint(IP);
1773 Builder.SetCurrentDebugLocation(IP->getDebugLoc());
1774 Value *ResultVec = UndefValue::get(VT);
1775 for (unsigned i = 0; i < VT->getNumElements(); i++)
1776 ResultVec = Builder.CreateInsertElement(ResultVec, Elements[i],
1777 Builder.getInt32(i));
1778 return ResultVec;
1779 };
1780
1781 if (isa<CallInst>(StatepointInst)) {
1782 BasicBlock::iterator Next(StatepointInst);
1783 Next++;
1784 Instruction *IP = &*(Next);
1785 Replacements[V].first = InsertVectorReform(IP);
1786 Replacements[V].second = nullptr;
1787 } else {
1788 InvokeInst *Invoke = cast<InvokeInst>(StatepointInst);
1789 // We've already normalized - check that we don't have shared destination
Philip Reames704e78b2015-04-10 22:34:56 +00001790 // blocks
Philip Reames8531d8c2015-04-10 21:48:25 +00001791 BasicBlock *NormalDest = Invoke->getNormalDest();
1792 assert(!isa<PHINode>(NormalDest->begin()));
1793 BasicBlock *UnwindDest = Invoke->getUnwindDest();
1794 assert(!isa<PHINode>(UnwindDest->begin()));
1795 // Insert insert element sequences in both successors
1796 Instruction *IP = &*(NormalDest->getFirstInsertionPt());
1797 Replacements[V].first = InsertVectorReform(IP);
1798 IP = &*(UnwindDest->getFirstInsertionPt());
1799 Replacements[V].second = InsertVectorReform(IP);
1800 }
1801 }
Philip Reames8fe7f132015-06-26 22:47:37 +00001802
Philip Reames8531d8c2015-04-10 21:48:25 +00001803 for (Value *V : ToSplit) {
1804 AllocaInst *Alloca = AllocaMap[V];
1805
1806 // Capture all users before we start mutating use lists
Philip Reames704e78b2015-04-10 22:34:56 +00001807 SmallVector<Instruction *, 16> Users;
Philip Reames8531d8c2015-04-10 21:48:25 +00001808 for (User *U : V->users())
1809 Users.push_back(cast<Instruction>(U));
1810
1811 for (Instruction *I : Users) {
1812 if (auto Phi = dyn_cast<PHINode>(I)) {
1813 for (unsigned i = 0; i < Phi->getNumIncomingValues(); i++)
1814 if (V == Phi->getIncomingValue(i)) {
Philip Reames704e78b2015-04-10 22:34:56 +00001815 LoadInst *Load = new LoadInst(
1816 Alloca, "", Phi->getIncomingBlock(i)->getTerminator());
Philip Reames8531d8c2015-04-10 21:48:25 +00001817 Phi->setIncomingValue(i, Load);
1818 }
1819 } else {
1820 LoadInst *Load = new LoadInst(Alloca, "", I);
1821 I->replaceUsesOfWith(V, Load);
1822 }
1823 }
1824
1825 // Store the original value and the replacement value into the alloca
1826 StoreInst *Store = new StoreInst(V, Alloca);
1827 if (auto I = dyn_cast<Instruction>(V))
1828 Store->insertAfter(I);
1829 else
1830 Store->insertAfter(Alloca);
Philip Reames704e78b2015-04-10 22:34:56 +00001831
Philip Reames8531d8c2015-04-10 21:48:25 +00001832 // Normal return for invoke, or call return
1833 Instruction *Replacement = cast<Instruction>(Replacements[V].first);
1834 (new StoreInst(Replacement, Alloca))->insertAfter(Replacement);
1835 // Unwind return for invoke only
1836 Replacement = cast_or_null<Instruction>(Replacements[V].second);
1837 if (Replacement)
1838 (new StoreInst(Replacement, Alloca))->insertAfter(Replacement);
1839 }
1840
1841 // apply mem2reg to promote alloca to SSA
Philip Reames704e78b2015-04-10 22:34:56 +00001842 SmallVector<AllocaInst *, 16> Allocas;
Philip Reames8531d8c2015-04-10 21:48:25 +00001843 for (Value *V : ToSplit)
1844 Allocas.push_back(AllocaMap[V]);
1845 PromoteMemToReg(Allocas, DT);
Philip Reames8fe7f132015-06-26 22:47:37 +00001846
1847 // Update our tracking of live pointers and base mappings to account for the
1848 // changes we just made.
1849 for (Value *V : ToSplit) {
1850 auto &Elements = ElementMapping[V];
1851
1852 LiveSet.erase(V);
1853 LiveSet.insert(Elements.begin(), Elements.end());
1854 // We need to update the base mapping as well.
1855 assert(PointerToBase.count(V));
1856 Value *OldBase = PointerToBase[V];
1857 auto &BaseElements = ElementMapping[OldBase];
1858 PointerToBase.erase(V);
1859 assert(Elements.size() == BaseElements.size());
1860 for (unsigned i = 0; i < Elements.size(); i++) {
1861 Value *Elem = Elements[i];
1862 PointerToBase[Elem] = BaseElements[i];
1863 }
1864 }
Philip Reames8531d8c2015-04-10 21:48:25 +00001865}
1866
Igor Laevskye0317182015-05-19 15:59:05 +00001867// Helper function for the "rematerializeLiveValues". It walks use chain
1868// starting from the "CurrentValue" until it meets "BaseValue". Only "simple"
1869// values are visited (currently it is GEP's and casts). Returns true if it
1870// sucessfully reached "BaseValue" and false otherwise.
1871// Fills "ChainToBase" array with all visited values. "BaseValue" is not
1872// recorded.
1873static bool findRematerializableChainToBasePointer(
1874 SmallVectorImpl<Instruction*> &ChainToBase,
1875 Value *CurrentValue, Value *BaseValue) {
1876
1877 // We have found a base value
1878 if (CurrentValue == BaseValue) {
1879 return true;
1880 }
1881
1882 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurrentValue)) {
1883 ChainToBase.push_back(GEP);
1884 return findRematerializableChainToBasePointer(ChainToBase,
1885 GEP->getPointerOperand(),
1886 BaseValue);
1887 }
1888
1889 if (CastInst *CI = dyn_cast<CastInst>(CurrentValue)) {
1890 Value *Def = CI->stripPointerCasts();
1891
1892 // This two checks are basically similar. First one is here for the
1893 // consistency with findBasePointers logic.
1894 assert(!isa<CastInst>(Def) && "not a pointer cast found");
1895 if (!CI->isNoopCast(CI->getModule()->getDataLayout()))
1896 return false;
1897
1898 ChainToBase.push_back(CI);
1899 return findRematerializableChainToBasePointer(ChainToBase, Def, BaseValue);
1900 }
1901
1902 // Not supported instruction in the chain
1903 return false;
1904}
1905
1906// Helper function for the "rematerializeLiveValues". Compute cost of the use
1907// chain we are going to rematerialize.
1908static unsigned
1909chainToBasePointerCost(SmallVectorImpl<Instruction*> &Chain,
1910 TargetTransformInfo &TTI) {
1911 unsigned Cost = 0;
1912
1913 for (Instruction *Instr : Chain) {
1914 if (CastInst *CI = dyn_cast<CastInst>(Instr)) {
1915 assert(CI->isNoopCast(CI->getModule()->getDataLayout()) &&
1916 "non noop cast is found during rematerialization");
1917
1918 Type *SrcTy = CI->getOperand(0)->getType();
1919 Cost += TTI.getCastInstrCost(CI->getOpcode(), CI->getType(), SrcTy);
1920
1921 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Instr)) {
1922 // Cost of the address calculation
1923 Type *ValTy = GEP->getPointerOperandType()->getPointerElementType();
1924 Cost += TTI.getAddressComputationCost(ValTy);
1925
1926 // And cost of the GEP itself
1927 // TODO: Use TTI->getGEPCost here (it exists, but appears to be not
1928 // allowed for the external usage)
1929 if (!GEP->hasAllConstantIndices())
1930 Cost += 2;
1931
1932 } else {
1933 llvm_unreachable("unsupported instruciton type during rematerialization");
1934 }
1935 }
1936
1937 return Cost;
1938}
1939
1940// From the statepoint liveset pick values that are cheaper to recompute then to
1941// relocate. Remove this values from the liveset, rematerialize them after
1942// statepoint and record them in "Info" structure. Note that similar to
1943// relocated values we don't do any user adjustments here.
1944static void rematerializeLiveValues(CallSite CS,
1945 PartiallyConstructedSafepointRecord &Info,
1946 TargetTransformInfo &TTI) {
Aaron Ballmanff7d4fa2015-05-20 14:53:50 +00001947 const unsigned int ChainLengthThreshold = 10;
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +00001948
Igor Laevskye0317182015-05-19 15:59:05 +00001949 // Record values we are going to delete from this statepoint live set.
1950 // We can not di this in following loop due to iterator invalidation.
1951 SmallVector<Value *, 32> LiveValuesToBeDeleted;
1952
1953 for (Value *LiveValue: Info.liveset) {
1954 // For each live pointer find it's defining chain
1955 SmallVector<Instruction *, 3> ChainToBase;
Philip Reames74ce2e72015-07-21 16:51:17 +00001956 assert(Info.PointerToBase.count(LiveValue));
Igor Laevskye0317182015-05-19 15:59:05 +00001957 bool FoundChain =
1958 findRematerializableChainToBasePointer(ChainToBase,
1959 LiveValue,
1960 Info.PointerToBase[LiveValue]);
1961 // Nothing to do, or chain is too long
1962 if (!FoundChain ||
1963 ChainToBase.size() == 0 ||
1964 ChainToBase.size() > ChainLengthThreshold)
1965 continue;
1966
1967 // Compute cost of this chain
1968 unsigned Cost = chainToBasePointerCost(ChainToBase, TTI);
1969 // TODO: We can also account for cases when we will be able to remove some
1970 // of the rematerialized values by later optimization passes. I.e if
1971 // we rematerialized several intersecting chains. Or if original values
1972 // don't have any uses besides this statepoint.
1973
1974 // For invokes we need to rematerialize each chain twice - for normal and
1975 // for unwind basic blocks. Model this by multiplying cost by two.
1976 if (CS.isInvoke()) {
1977 Cost *= 2;
1978 }
1979 // If it's too expensive - skip it
1980 if (Cost >= RematerializationThreshold)
1981 continue;
1982
1983 // Remove value from the live set
1984 LiveValuesToBeDeleted.push_back(LiveValue);
1985
1986 // Clone instructions and record them inside "Info" structure
1987
1988 // Walk backwards to visit top-most instructions first
1989 std::reverse(ChainToBase.begin(), ChainToBase.end());
1990
1991 // Utility function which clones all instructions from "ChainToBase"
1992 // and inserts them before "InsertBefore". Returns rematerialized value
1993 // which should be used after statepoint.
1994 auto rematerializeChain = [&ChainToBase](Instruction *InsertBefore) {
1995 Instruction *LastClonedValue = nullptr;
1996 Instruction *LastValue = nullptr;
1997 for (Instruction *Instr: ChainToBase) {
1998 // Only GEP's and casts are suported as we need to be careful to not
1999 // introduce any new uses of pointers not in the liveset.
2000 // Note that it's fine to introduce new uses of pointers which were
2001 // otherwise not used after this statepoint.
2002 assert(isa<GetElementPtrInst>(Instr) || isa<CastInst>(Instr));
2003
2004 Instruction *ClonedValue = Instr->clone();
2005 ClonedValue->insertBefore(InsertBefore);
2006 ClonedValue->setName(Instr->getName() + ".remat");
2007
2008 // If it is not first instruction in the chain then it uses previously
2009 // cloned value. We should update it to use cloned value.
2010 if (LastClonedValue) {
2011 assert(LastValue);
2012 ClonedValue->replaceUsesOfWith(LastValue, LastClonedValue);
2013#ifndef NDEBUG
Igor Laevskyd83f6972015-05-21 13:02:14 +00002014 // Assert that cloned instruction does not use any instructions from
2015 // this chain other than LastClonedValue
2016 for (auto OpValue : ClonedValue->operand_values()) {
2017 assert(std::find(ChainToBase.begin(), ChainToBase.end(), OpValue) ==
2018 ChainToBase.end() &&
2019 "incorrect use in rematerialization chain");
Igor Laevskye0317182015-05-19 15:59:05 +00002020 }
2021#endif
2022 }
2023
2024 LastClonedValue = ClonedValue;
2025 LastValue = Instr;
2026 }
2027 assert(LastClonedValue);
2028 return LastClonedValue;
2029 };
2030
2031 // Different cases for calls and invokes. For invokes we need to clone
2032 // instructions both on normal and unwind path.
2033 if (CS.isCall()) {
2034 Instruction *InsertBefore = CS.getInstruction()->getNextNode();
2035 assert(InsertBefore);
2036 Instruction *RematerializedValue = rematerializeChain(InsertBefore);
2037 Info.RematerializedValues[RematerializedValue] = LiveValue;
2038 } else {
2039 InvokeInst *Invoke = cast<InvokeInst>(CS.getInstruction());
2040
2041 Instruction *NormalInsertBefore =
2042 Invoke->getNormalDest()->getFirstInsertionPt();
2043 Instruction *UnwindInsertBefore =
2044 Invoke->getUnwindDest()->getFirstInsertionPt();
2045
2046 Instruction *NormalRematerializedValue =
2047 rematerializeChain(NormalInsertBefore);
2048 Instruction *UnwindRematerializedValue =
2049 rematerializeChain(UnwindInsertBefore);
2050
2051 Info.RematerializedValues[NormalRematerializedValue] = LiveValue;
2052 Info.RematerializedValues[UnwindRematerializedValue] = LiveValue;
2053 }
2054 }
2055
2056 // Remove rematerializaed values from the live set
2057 for (auto LiveValue: LiveValuesToBeDeleted) {
2058 Info.liveset.erase(LiveValue);
2059 }
2060}
2061
Philip Reamesd16a9b12015-02-20 01:06:44 +00002062static bool insertParsePoints(Function &F, DominatorTree &DT, Pass *P,
Philip Reamesd2b66462015-02-20 22:39:41 +00002063 SmallVectorImpl<CallSite> &toUpdate) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00002064#ifndef NDEBUG
2065 // sanity check the input
2066 std::set<CallSite> uniqued;
2067 uniqued.insert(toUpdate.begin(), toUpdate.end());
2068 assert(uniqued.size() == toUpdate.size() && "no duplicates please!");
2069
2070 for (size_t i = 0; i < toUpdate.size(); i++) {
2071 CallSite &CS = toUpdate[i];
2072 assert(CS.getInstruction()->getParent()->getParent() == &F);
2073 assert(isStatepoint(CS) && "expected to already be a deopt statepoint");
2074 }
2075#endif
2076
Philip Reames69e51ca2015-04-13 18:07:21 +00002077 // When inserting gc.relocates for invokes, we need to be able to insert at
2078 // the top of the successor blocks. See the comment on
2079 // normalForInvokeSafepoint on exactly what is needed. Note that this step
Philip Reamesf209a152015-04-13 20:00:30 +00002080 // may restructure the CFG.
2081 for (CallSite CS : toUpdate) {
2082 if (!CS.isInvoke())
2083 continue;
2084 InvokeInst *invoke = cast<InvokeInst>(CS.getInstruction());
2085 normalizeForInvokeSafepoint(invoke->getNormalDest(), invoke->getParent(),
Sanjoy Dasea45f0e2015-06-02 22:33:34 +00002086 DT);
Philip Reamesf209a152015-04-13 20:00:30 +00002087 normalizeForInvokeSafepoint(invoke->getUnwindDest(), invoke->getParent(),
Sanjoy Dasea45f0e2015-06-02 22:33:34 +00002088 DT);
Philip Reamesf209a152015-04-13 20:00:30 +00002089 }
Philip Reames69e51ca2015-04-13 18:07:21 +00002090
Philip Reamesd16a9b12015-02-20 01:06:44 +00002091 // A list of dummy calls added to the IR to keep various values obviously
2092 // live in the IR. We'll remove all of these when done.
Philip Reamesd2b66462015-02-20 22:39:41 +00002093 SmallVector<CallInst *, 64> holders;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002094
2095 // Insert a dummy call with all of the arguments to the vm_state we'll need
2096 // for the actual safepoint insertion. This ensures reference arguments in
2097 // the deopt argument list are considered live through the safepoint (and
2098 // thus makes sure they get relocated.)
2099 for (size_t i = 0; i < toUpdate.size(); i++) {
2100 CallSite &CS = toUpdate[i];
2101 Statepoint StatepointCS(CS);
2102
2103 SmallVector<Value *, 64> DeoptValues;
2104 for (Use &U : StatepointCS.vm_state_args()) {
2105 Value *Arg = cast<Value>(&U);
Philip Reames8531d8c2015-04-10 21:48:25 +00002106 assert(!isUnhandledGCPointerType(Arg->getType()) &&
2107 "support for FCA unimplemented");
2108 if (isHandledGCPointerType(Arg->getType()))
Philip Reamesd16a9b12015-02-20 01:06:44 +00002109 DeoptValues.push_back(Arg);
2110 }
2111 insertUseHolderAfter(CS, DeoptValues, holders);
2112 }
2113
Philip Reamesd2b66462015-02-20 22:39:41 +00002114 SmallVector<struct PartiallyConstructedSafepointRecord, 64> records;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002115 records.reserve(toUpdate.size());
2116 for (size_t i = 0; i < toUpdate.size(); i++) {
2117 struct PartiallyConstructedSafepointRecord info;
2118 records.push_back(info);
2119 }
2120 assert(records.size() == toUpdate.size());
2121
2122 // A) Identify all gc pointers which are staticly live at the given call
2123 // site.
2124 findLiveReferences(F, DT, P, toUpdate, records);
2125
2126 // B) Find the base pointers for each live pointer
2127 /* scope for caching */ {
2128 // Cache the 'defining value' relation used in the computation and
2129 // insertion of base phis and selects. This ensures that we don't insert
2130 // large numbers of duplicate base_phis.
2131 DefiningValueMapTy DVCache;
2132
2133 for (size_t i = 0; i < records.size(); i++) {
2134 struct PartiallyConstructedSafepointRecord &info = records[i];
2135 CallSite &CS = toUpdate[i];
2136 findBasePointers(DT, DVCache, CS, info);
2137 }
2138 } // end of cache scope
2139
2140 // The base phi insertion logic (for any safepoint) may have inserted new
2141 // instructions which are now live at some safepoint. The simplest such
2142 // example is:
2143 // loop:
2144 // phi a <-- will be a new base_phi here
2145 // safepoint 1 <-- that needs to be live here
2146 // gep a + 1
2147 // safepoint 2
2148 // br loop
Philip Reamesd16a9b12015-02-20 01:06:44 +00002149 // We insert some dummy calls after each safepoint to definitely hold live
2150 // the base pointers which were identified for that safepoint. We'll then
2151 // ask liveness for _every_ base inserted to see what is now live. Then we
2152 // remove the dummy calls.
2153 holders.reserve(holders.size() + records.size());
2154 for (size_t i = 0; i < records.size(); i++) {
2155 struct PartiallyConstructedSafepointRecord &info = records[i];
2156 CallSite &CS = toUpdate[i];
2157
2158 SmallVector<Value *, 128> Bases;
Philip Reamesf2041322015-02-20 19:26:04 +00002159 for (auto Pair : info.PointerToBase) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00002160 Bases.push_back(Pair.second);
2161 }
2162 insertUseHolderAfter(CS, Bases, holders);
2163 }
2164
Philip Reamesdf1ef082015-04-10 22:53:14 +00002165 // By selecting base pointers, we've effectively inserted new uses. Thus, we
2166 // need to rerun liveness. We may *also* have inserted new defs, but that's
2167 // not the key issue.
2168 recomputeLiveInValues(F, DT, P, toUpdate, records);
Philip Reamesd16a9b12015-02-20 01:06:44 +00002169
Philip Reamesd16a9b12015-02-20 01:06:44 +00002170 if (PrintBasePointers) {
2171 for (size_t i = 0; i < records.size(); i++) {
2172 struct PartiallyConstructedSafepointRecord &info = records[i];
2173 errs() << "Base Pairs: (w/Relocation)\n";
Philip Reamesf2041322015-02-20 19:26:04 +00002174 for (auto Pair : info.PointerToBase) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00002175 errs() << " derived %" << Pair.first->getName() << " base %"
2176 << Pair.second->getName() << "\n";
2177 }
2178 }
2179 }
2180 for (size_t i = 0; i < holders.size(); i++) {
2181 holders[i]->eraseFromParent();
2182 holders[i] = nullptr;
2183 }
2184 holders.clear();
2185
Philip Reames8fe7f132015-06-26 22:47:37 +00002186 // Do a limited scalarization of any live at safepoint vector values which
2187 // contain pointers. This enables this pass to run after vectorization at
2188 // the cost of some possible performance loss. TODO: it would be nice to
2189 // natively support vectors all the way through the backend so we don't need
2190 // to scalarize here.
2191 for (size_t i = 0; i < records.size(); i++) {
2192 struct PartiallyConstructedSafepointRecord &info = records[i];
2193 Instruction *statepoint = toUpdate[i].getInstruction();
2194 splitVectorValues(cast<Instruction>(statepoint), info.liveset,
2195 info.PointerToBase, DT);
2196 }
2197
Igor Laevskye0317182015-05-19 15:59:05 +00002198 // In order to reduce live set of statepoint we might choose to rematerialize
2199 // some values instead of relocating them. This is purelly an optimization and
2200 // does not influence correctness.
2201 TargetTransformInfo &TTI =
2202 P->getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
2203
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +00002204 for (size_t i = 0; i < records.size(); i++) {
Igor Laevskye0317182015-05-19 15:59:05 +00002205 struct PartiallyConstructedSafepointRecord &info = records[i];
2206 CallSite &CS = toUpdate[i];
2207
2208 rematerializeLiveValues(CS, info, TTI);
2209 }
2210
Philip Reamesd16a9b12015-02-20 01:06:44 +00002211 // Now run through and replace the existing statepoints with new ones with
2212 // the live variables listed. We do not yet update uses of the values being
2213 // relocated. We have references to live variables that need to
2214 // survive to the last iteration of this loop. (By construction, the
2215 // previous statepoint can not be a live variable, thus we can and remove
2216 // the old statepoint calls as we go.)
2217 for (size_t i = 0; i < records.size(); i++) {
2218 struct PartiallyConstructedSafepointRecord &info = records[i];
2219 CallSite &CS = toUpdate[i];
2220 makeStatepointExplicit(DT, CS, P, info);
2221 }
2222 toUpdate.clear(); // prevent accident use of invalid CallSites
2223
Philip Reamesd16a9b12015-02-20 01:06:44 +00002224 // Do all the fixups of the original live variables to their relocated selves
Philip Reamesd2b66462015-02-20 22:39:41 +00002225 SmallVector<Value *, 128> live;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002226 for (size_t i = 0; i < records.size(); i++) {
2227 struct PartiallyConstructedSafepointRecord &info = records[i];
2228 // We can't simply save the live set from the original insertion. One of
2229 // the live values might be the result of a call which needs a safepoint.
2230 // That Value* no longer exists and we need to use the new gc_result.
2231 // Thankfully, the liveset is embedded in the statepoint (and updated), so
2232 // we just grab that.
Philip Reames0a3240f2015-02-20 21:34:11 +00002233 Statepoint statepoint(info.StatepointToken);
Philip Reamesd16a9b12015-02-20 01:06:44 +00002234 live.insert(live.end(), statepoint.gc_args_begin(),
2235 statepoint.gc_args_end());
Philip Reames9a2e01d2015-04-13 17:35:55 +00002236#ifndef NDEBUG
2237 // Do some basic sanity checks on our liveness results before performing
2238 // relocation. Relocation can and will turn mistakes in liveness results
2239 // into non-sensical code which is must harder to debug.
2240 // TODO: It would be nice to test consistency as well
2241 assert(DT.isReachableFromEntry(info.StatepointToken->getParent()) &&
2242 "statepoint must be reachable or liveness is meaningless");
2243 for (Value *V : statepoint.gc_args()) {
2244 if (!isa<Instruction>(V))
2245 // Non-instruction values trivial dominate all possible uses
2246 continue;
2247 auto LiveInst = cast<Instruction>(V);
2248 assert(DT.isReachableFromEntry(LiveInst->getParent()) &&
2249 "unreachable values should never be live");
2250 assert(DT.dominates(LiveInst, info.StatepointToken) &&
2251 "basic SSA liveness expectation violated by liveness analysis");
2252 }
2253#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +00002254 }
2255 unique_unsorted(live);
2256
Nick Lewyckyeb3231e2015-02-20 07:14:02 +00002257#ifndef NDEBUG
Philip Reamesd16a9b12015-02-20 01:06:44 +00002258 // sanity check
2259 for (auto ptr : live) {
2260 assert(isGCPointerType(ptr->getType()) && "must be a gc pointer type");
2261 }
Nick Lewyckyeb3231e2015-02-20 07:14:02 +00002262#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +00002263
2264 relocationViaAlloca(F, DT, live, records);
2265 return !records.empty();
2266}
2267
Sanjoy Das353a19e2015-06-02 22:33:37 +00002268// Handles both return values and arguments for Functions and CallSites.
2269template <typename AttrHolder>
2270static void RemoveDerefAttrAtIndex(LLVMContext &Ctx, AttrHolder &AH,
2271 unsigned Index) {
2272 AttrBuilder R;
2273 if (AH.getDereferenceableBytes(Index))
2274 R.addAttribute(Attribute::get(Ctx, Attribute::Dereferenceable,
2275 AH.getDereferenceableBytes(Index)));
2276 if (AH.getDereferenceableOrNullBytes(Index))
2277 R.addAttribute(Attribute::get(Ctx, Attribute::DereferenceableOrNull,
2278 AH.getDereferenceableOrNullBytes(Index)));
2279
2280 if (!R.empty())
2281 AH.setAttributes(AH.getAttributes().removeAttributes(
2282 Ctx, Index, AttributeSet::get(Ctx, Index, R)));
Vasileios Kalintiris9f77f612015-06-03 08:51:30 +00002283}
Sanjoy Das353a19e2015-06-02 22:33:37 +00002284
2285void
2286RewriteStatepointsForGC::stripDereferenceabilityInfoFromPrototype(Function &F) {
2287 LLVMContext &Ctx = F.getContext();
2288
2289 for (Argument &A : F.args())
2290 if (isa<PointerType>(A.getType()))
2291 RemoveDerefAttrAtIndex(Ctx, F, A.getArgNo() + 1);
2292
2293 if (isa<PointerType>(F.getReturnType()))
2294 RemoveDerefAttrAtIndex(Ctx, F, AttributeSet::ReturnIndex);
2295}
2296
2297void RewriteStatepointsForGC::stripDereferenceabilityInfoFromBody(Function &F) {
2298 if (F.empty())
2299 return;
2300
2301 LLVMContext &Ctx = F.getContext();
2302 MDBuilder Builder(Ctx);
2303
2304 for (Instruction &I : inst_range(F)) {
2305 if (const MDNode *MD = I.getMetadata(LLVMContext::MD_tbaa)) {
2306 assert(MD->getNumOperands() < 5 && "unrecognized metadata shape!");
2307 bool IsImmutableTBAA =
2308 MD->getNumOperands() == 4 &&
2309 mdconst::extract<ConstantInt>(MD->getOperand(3))->getValue() == 1;
2310
2311 if (!IsImmutableTBAA)
2312 continue; // no work to do, MD_tbaa is already marked mutable
2313
2314 MDNode *Base = cast<MDNode>(MD->getOperand(0));
2315 MDNode *Access = cast<MDNode>(MD->getOperand(1));
2316 uint64_t Offset =
2317 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue();
2318
2319 MDNode *MutableTBAA =
2320 Builder.createTBAAStructTagNode(Base, Access, Offset);
2321 I.setMetadata(LLVMContext::MD_tbaa, MutableTBAA);
2322 }
2323
2324 if (CallSite CS = CallSite(&I)) {
2325 for (int i = 0, e = CS.arg_size(); i != e; i++)
2326 if (isa<PointerType>(CS.getArgument(i)->getType()))
2327 RemoveDerefAttrAtIndex(Ctx, CS, i + 1);
2328 if (isa<PointerType>(CS.getType()))
2329 RemoveDerefAttrAtIndex(Ctx, CS, AttributeSet::ReturnIndex);
2330 }
2331 }
2332}
2333
Philip Reamesd16a9b12015-02-20 01:06:44 +00002334/// Returns true if this function should be rewritten by this pass. The main
2335/// point of this function is as an extension point for custom logic.
2336static bool shouldRewriteStatepointsIn(Function &F) {
2337 // TODO: This should check the GCStrategy
Philip Reames2ef029c2015-02-20 18:56:14 +00002338 if (F.hasGC()) {
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +00002339 const char *FunctionGCName = F.getGC();
2340 const StringRef StatepointExampleName("statepoint-example");
2341 const StringRef CoreCLRName("coreclr");
2342 return (StatepointExampleName == FunctionGCName) ||
NAKAMURA Takumi5582a6a2015-05-25 01:43:34 +00002343 (CoreCLRName == FunctionGCName);
2344 } else
Philip Reames2ef029c2015-02-20 18:56:14 +00002345 return false;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002346}
2347
Sanjoy Das353a19e2015-06-02 22:33:37 +00002348void RewriteStatepointsForGC::stripDereferenceabilityInfo(Module &M) {
2349#ifndef NDEBUG
2350 assert(std::any_of(M.begin(), M.end(), shouldRewriteStatepointsIn) &&
2351 "precondition!");
2352#endif
2353
2354 for (Function &F : M)
2355 stripDereferenceabilityInfoFromPrototype(F);
2356
2357 for (Function &F : M)
2358 stripDereferenceabilityInfoFromBody(F);
2359}
2360
Philip Reamesd16a9b12015-02-20 01:06:44 +00002361bool RewriteStatepointsForGC::runOnFunction(Function &F) {
2362 // Nothing to do for declarations.
2363 if (F.isDeclaration() || F.empty())
2364 return false;
2365
2366 // Policy choice says not to rewrite - the most common reason is that we're
2367 // compiling code without a GCStrategy.
2368 if (!shouldRewriteStatepointsIn(F))
2369 return false;
2370
Sanjoy Dasea45f0e2015-06-02 22:33:34 +00002371 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
Philip Reames704e78b2015-04-10 22:34:56 +00002372
Philip Reames85b36a82015-04-10 22:07:04 +00002373 // Gather all the statepoints which need rewritten. Be careful to only
2374 // consider those in reachable code since we need to ask dominance queries
2375 // when rewriting. We'll delete the unreachable ones in a moment.
Philip Reamesd2b66462015-02-20 22:39:41 +00002376 SmallVector<CallSite, 64> ParsePointNeeded;
Philip Reamesf66d7372015-04-10 22:16:58 +00002377 bool HasUnreachableStatepoint = false;
Philip Reamesd2b66462015-02-20 22:39:41 +00002378 for (Instruction &I : inst_range(F)) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00002379 // TODO: only the ones with the flag set!
Philip Reames85b36a82015-04-10 22:07:04 +00002380 if (isStatepoint(I)) {
2381 if (DT.isReachableFromEntry(I.getParent()))
2382 ParsePointNeeded.push_back(CallSite(&I));
2383 else
Philip Reamesf66d7372015-04-10 22:16:58 +00002384 HasUnreachableStatepoint = true;
Philip Reames85b36a82015-04-10 22:07:04 +00002385 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00002386 }
2387
Philip Reames85b36a82015-04-10 22:07:04 +00002388 bool MadeChange = false;
Philip Reames704e78b2015-04-10 22:34:56 +00002389
Philip Reames85b36a82015-04-10 22:07:04 +00002390 // Delete any unreachable statepoints so that we don't have unrewritten
2391 // statepoints surviving this pass. This makes testing easier and the
2392 // resulting IR less confusing to human readers. Rather than be fancy, we
2393 // just reuse a utility function which removes the unreachable blocks.
Philip Reamesf66d7372015-04-10 22:16:58 +00002394 if (HasUnreachableStatepoint)
Philip Reames85b36a82015-04-10 22:07:04 +00002395 MadeChange |= removeUnreachableBlocks(F);
2396
Philip Reamesd16a9b12015-02-20 01:06:44 +00002397 // Return early if no work to do.
2398 if (ParsePointNeeded.empty())
Philip Reames85b36a82015-04-10 22:07:04 +00002399 return MadeChange;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002400
Philip Reames85b36a82015-04-10 22:07:04 +00002401 // As a prepass, go ahead and aggressively destroy single entry phi nodes.
2402 // These are created by LCSSA. They have the effect of increasing the size
2403 // of liveness sets for no good reason. It may be harder to do this post
2404 // insertion since relocations and base phis can confuse things.
2405 for (BasicBlock &BB : F)
2406 if (BB.getUniquePredecessor()) {
2407 MadeChange = true;
2408 FoldSingleEntryPHINodes(&BB);
2409 }
2410
2411 MadeChange |= insertParsePoints(F, DT, this, ParsePointNeeded);
2412 return MadeChange;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002413}
Philip Reamesdf1ef082015-04-10 22:53:14 +00002414
2415// liveness computation via standard dataflow
2416// -------------------------------------------------------------------
2417
2418// TODO: Consider using bitvectors for liveness, the set of potentially
2419// interesting values should be small and easy to pre-compute.
2420
Philip Reamesdf1ef082015-04-10 22:53:14 +00002421/// Compute the live-in set for the location rbegin starting from
2422/// the live-out set of the basic block
2423static void computeLiveInValues(BasicBlock::reverse_iterator rbegin,
2424 BasicBlock::reverse_iterator rend,
2425 DenseSet<Value *> &LiveTmp) {
2426
2427 for (BasicBlock::reverse_iterator ritr = rbegin; ritr != rend; ritr++) {
2428 Instruction *I = &*ritr;
2429
2430 // KILL/Def - Remove this definition from LiveIn
2431 LiveTmp.erase(I);
2432
2433 // Don't consider *uses* in PHI nodes, we handle their contribution to
2434 // predecessor blocks when we seed the LiveOut sets
2435 if (isa<PHINode>(I))
2436 continue;
2437
2438 // USE - Add to the LiveIn set for this instruction
2439 for (Value *V : I->operands()) {
2440 assert(!isUnhandledGCPointerType(V->getType()) &&
2441 "support for FCA unimplemented");
Philip Reames63294cb2015-04-26 19:48:03 +00002442 if (isHandledGCPointerType(V->getType()) && !isa<Constant>(V)) {
2443 // The choice to exclude all things constant here is slightly subtle.
2444 // There are two idependent reasons:
2445 // - We assume that things which are constant (from LLVM's definition)
2446 // do not move at runtime. For example, the address of a global
2447 // variable is fixed, even though it's contents may not be.
2448 // - Second, we can't disallow arbitrary inttoptr constants even
2449 // if the language frontend does. Optimization passes are free to
2450 // locally exploit facts without respect to global reachability. This
2451 // can create sections of code which are dynamically unreachable and
2452 // contain just about anything. (see constants.ll in tests)
Philip Reamesdf1ef082015-04-10 22:53:14 +00002453 LiveTmp.insert(V);
2454 }
2455 }
2456 }
2457}
2458
2459static void computeLiveOutSeed(BasicBlock *BB, DenseSet<Value *> &LiveTmp) {
2460
2461 for (BasicBlock *Succ : successors(BB)) {
2462 const BasicBlock::iterator E(Succ->getFirstNonPHI());
2463 for (BasicBlock::iterator I = Succ->begin(); I != E; I++) {
2464 PHINode *Phi = cast<PHINode>(&*I);
2465 Value *V = Phi->getIncomingValueForBlock(BB);
2466 assert(!isUnhandledGCPointerType(V->getType()) &&
2467 "support for FCA unimplemented");
Philip Reames63294cb2015-04-26 19:48:03 +00002468 if (isHandledGCPointerType(V->getType()) && !isa<Constant>(V)) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00002469 LiveTmp.insert(V);
2470 }
2471 }
2472 }
2473}
2474
2475static DenseSet<Value *> computeKillSet(BasicBlock *BB) {
2476 DenseSet<Value *> KillSet;
2477 for (Instruction &I : *BB)
2478 if (isHandledGCPointerType(I.getType()))
2479 KillSet.insert(&I);
2480 return KillSet;
2481}
2482
Philip Reames9638ff92015-04-11 00:06:47 +00002483#ifndef NDEBUG
Philip Reamesdf1ef082015-04-10 22:53:14 +00002484/// Check that the items in 'Live' dominate 'TI'. This is used as a basic
2485/// sanity check for the liveness computation.
2486static void checkBasicSSA(DominatorTree &DT, DenseSet<Value *> &Live,
2487 TerminatorInst *TI, bool TermOkay = false) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00002488 for (Value *V : Live) {
2489 if (auto *I = dyn_cast<Instruction>(V)) {
2490 // The terminator can be a member of the LiveOut set. LLVM's definition
2491 // of instruction dominance states that V does not dominate itself. As
2492 // such, we need to special case this to allow it.
2493 if (TermOkay && TI == I)
2494 continue;
2495 assert(DT.dominates(I, TI) &&
2496 "basic SSA liveness expectation violated by liveness analysis");
2497 }
2498 }
Philip Reamesdf1ef082015-04-10 22:53:14 +00002499}
2500
2501/// Check that all the liveness sets used during the computation of liveness
2502/// obey basic SSA properties. This is useful for finding cases where we miss
2503/// a def.
2504static void checkBasicSSA(DominatorTree &DT, GCPtrLivenessData &Data,
2505 BasicBlock &BB) {
2506 checkBasicSSA(DT, Data.LiveSet[&BB], BB.getTerminator());
2507 checkBasicSSA(DT, Data.LiveOut[&BB], BB.getTerminator(), true);
2508 checkBasicSSA(DT, Data.LiveIn[&BB], BB.getTerminator());
2509}
Philip Reames9638ff92015-04-11 00:06:47 +00002510#endif
Philip Reamesdf1ef082015-04-10 22:53:14 +00002511
2512static void computeLiveInValues(DominatorTree &DT, Function &F,
2513 GCPtrLivenessData &Data) {
2514
Philip Reames4d80ede2015-04-10 23:11:26 +00002515 SmallSetVector<BasicBlock *, 200> Worklist;
Philip Reamesdf1ef082015-04-10 22:53:14 +00002516 auto AddPredsToWorklist = [&](BasicBlock *BB) {
Philip Reames4d80ede2015-04-10 23:11:26 +00002517 // We use a SetVector so that we don't have duplicates in the worklist.
2518 Worklist.insert(pred_begin(BB), pred_end(BB));
Philip Reamesdf1ef082015-04-10 22:53:14 +00002519 };
2520 auto NextItem = [&]() {
2521 BasicBlock *BB = Worklist.back();
2522 Worklist.pop_back();
Philip Reamesdf1ef082015-04-10 22:53:14 +00002523 return BB;
2524 };
2525
2526 // Seed the liveness for each individual block
2527 for (BasicBlock &BB : F) {
2528 Data.KillSet[&BB] = computeKillSet(&BB);
2529 Data.LiveSet[&BB].clear();
2530 computeLiveInValues(BB.rbegin(), BB.rend(), Data.LiveSet[&BB]);
2531
2532#ifndef NDEBUG
2533 for (Value *Kill : Data.KillSet[&BB])
2534 assert(!Data.LiveSet[&BB].count(Kill) && "live set contains kill");
2535#endif
2536
2537 Data.LiveOut[&BB] = DenseSet<Value *>();
2538 computeLiveOutSeed(&BB, Data.LiveOut[&BB]);
2539 Data.LiveIn[&BB] = Data.LiveSet[&BB];
2540 set_union(Data.LiveIn[&BB], Data.LiveOut[&BB]);
2541 set_subtract(Data.LiveIn[&BB], Data.KillSet[&BB]);
2542 if (!Data.LiveIn[&BB].empty())
2543 AddPredsToWorklist(&BB);
2544 }
2545
2546 // Propagate that liveness until stable
2547 while (!Worklist.empty()) {
2548 BasicBlock *BB = NextItem();
2549
2550 // Compute our new liveout set, then exit early if it hasn't changed
2551 // despite the contribution of our successor.
2552 DenseSet<Value *> LiveOut = Data.LiveOut[BB];
2553 const auto OldLiveOutSize = LiveOut.size();
2554 for (BasicBlock *Succ : successors(BB)) {
2555 assert(Data.LiveIn.count(Succ));
2556 set_union(LiveOut, Data.LiveIn[Succ]);
2557 }
2558 // assert OutLiveOut is a subset of LiveOut
2559 if (OldLiveOutSize == LiveOut.size()) {
2560 // If the sets are the same size, then we didn't actually add anything
2561 // when unioning our successors LiveIn Thus, the LiveIn of this block
2562 // hasn't changed.
2563 continue;
2564 }
2565 Data.LiveOut[BB] = LiveOut;
2566
2567 // Apply the effects of this basic block
2568 DenseSet<Value *> LiveTmp = LiveOut;
2569 set_union(LiveTmp, Data.LiveSet[BB]);
2570 set_subtract(LiveTmp, Data.KillSet[BB]);
2571
2572 assert(Data.LiveIn.count(BB));
2573 const DenseSet<Value *> &OldLiveIn = Data.LiveIn[BB];
2574 // assert: OldLiveIn is a subset of LiveTmp
2575 if (OldLiveIn.size() != LiveTmp.size()) {
2576 Data.LiveIn[BB] = LiveTmp;
2577 AddPredsToWorklist(BB);
2578 }
2579 } // while( !worklist.empty() )
2580
2581#ifndef NDEBUG
2582 // Sanity check our ouput against SSA properties. This helps catch any
2583 // missing kills during the above iteration.
2584 for (BasicBlock &BB : F) {
2585 checkBasicSSA(DT, Data, BB);
2586 }
2587#endif
2588}
2589
2590static void findLiveSetAtInst(Instruction *Inst, GCPtrLivenessData &Data,
2591 StatepointLiveSetTy &Out) {
2592
2593 BasicBlock *BB = Inst->getParent();
2594
2595 // Note: The copy is intentional and required
2596 assert(Data.LiveOut.count(BB));
2597 DenseSet<Value *> LiveOut = Data.LiveOut[BB];
2598
2599 // We want to handle the statepoint itself oddly. It's
2600 // call result is not live (normal), nor are it's arguments
2601 // (unless they're used again later). This adjustment is
2602 // specifically what we need to relocate
2603 BasicBlock::reverse_iterator rend(Inst);
2604 computeLiveInValues(BB->rbegin(), rend, LiveOut);
2605 LiveOut.erase(Inst);
2606 Out.insert(LiveOut.begin(), LiveOut.end());
2607}
2608
2609static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData,
2610 const CallSite &CS,
2611 PartiallyConstructedSafepointRecord &Info) {
2612 Instruction *Inst = CS.getInstruction();
2613 StatepointLiveSetTy Updated;
2614 findLiveSetAtInst(Inst, RevisedLivenessData, Updated);
2615
2616#ifndef NDEBUG
2617 DenseSet<Value *> Bases;
2618 for (auto KVPair : Info.PointerToBase) {
2619 Bases.insert(KVPair.second);
2620 }
2621#endif
2622 // We may have base pointers which are now live that weren't before. We need
2623 // to update the PointerToBase structure to reflect this.
2624 for (auto V : Updated)
2625 if (!Info.PointerToBase.count(V)) {
2626 assert(Bases.count(V) && "can't find base for unexpected live value");
2627 Info.PointerToBase[V] = V;
2628 continue;
2629 }
2630
2631#ifndef NDEBUG
2632 for (auto V : Updated) {
2633 assert(Info.PointerToBase.count(V) &&
2634 "must be able to find base for live value");
2635 }
2636#endif
2637
2638 // Remove any stale base mappings - this can happen since our liveness is
2639 // more precise then the one inherent in the base pointer analysis
2640 DenseSet<Value *> ToErase;
2641 for (auto KVPair : Info.PointerToBase)
2642 if (!Updated.count(KVPair.first))
2643 ToErase.insert(KVPair.first);
2644 for (auto V : ToErase)
2645 Info.PointerToBase.erase(V);
2646
2647#ifndef NDEBUG
2648 for (auto KVPair : Info.PointerToBase)
2649 assert(Updated.count(KVPair.first) && "record for non-live value");
2650#endif
2651
2652 Info.liveset = Updated;
2653}