blob: 21ff55c697e3cf169ae6813ea8cd50a555005791 [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
297/// If we can trivially determine that the index specified in the given vector
298/// is a base pointer, return it. In cases where the entire vector is known to
299/// consist of base pointers, the entire vector will be returned. This
300/// indicates that the relevant extractelement is a valid base pointer and
301/// should be used directly.
302static Value *findBaseOfVector(Value *I, Value *Index) {
Philip Reames8531d8c2015-04-10 21:48:25 +0000303 assert(I->getType()->isVectorTy() &&
304 cast<VectorType>(I->getType())->getElementType()->isPointerTy() &&
305 "Illegal to ask for the base pointer of a non-pointer type");
306
307 // Each case parallels findBaseDefiningValue below, see that code for
308 // detailed motivation.
309
310 if (isa<Argument>(I))
311 // An incoming argument to the function is a base pointer
312 return I;
313
314 // We shouldn't see the address of a global as a vector value?
315 assert(!isa<GlobalVariable>(I) &&
316 "unexpected global variable found in base of vector");
317
318 // inlining could possibly introduce phi node that contains
319 // undef if callee has multiple returns
320 if (isa<UndefValue>(I))
321 // utterly meaningless, but useful for dealing with partially optimized
322 // code.
Philip Reames704e78b2015-04-10 22:34:56 +0000323 return I;
Philip Reames8531d8c2015-04-10 21:48:25 +0000324
325 // Due to inheritance, this must be _after_ the global variable and undef
326 // checks
327 if (Constant *Con = dyn_cast<Constant>(I)) {
328 assert(!isa<GlobalVariable>(I) && !isa<UndefValue>(I) &&
329 "order of checks wrong!");
330 assert(Con->isNullValue() && "null is the only case which makes sense");
331 return Con;
332 }
333
334 if (isa<LoadInst>(I))
335 return I;
336
Philip Reames311f7102015-05-12 22:19:52 +0000337 // For an insert element, we might be able to look through it if we know
338 // something about the indexes, but if the indices are arbitrary values, we
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +0000339 // can't without much more extensive scalarization.
Philip Reames311f7102015-05-12 22:19:52 +0000340 if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(I)) {
341 Value *InsertIndex = IEI->getOperand(2);
342 // This index is inserting the value, look for it's base
343 if (InsertIndex == Index)
344 return findBaseDefiningValue(IEI->getOperand(1));
345 // Both constant, and can't be equal per above. This insert is definitely
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +0000346 // not relevant, look back at the rest of the vector and keep trying.
Philip Reames311f7102015-05-12 22:19:52 +0000347 if (isa<ConstantInt>(Index) && isa<ConstantInt>(InsertIndex))
348 return findBaseOfVector(IEI->getOperand(0), Index);
349 }
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +0000350
Philip Reames8531d8c2015-04-10 21:48:25 +0000351 // Note: This code is currently rather incomplete. We are essentially only
352 // handling cases where the vector element is trivially a base pointer. We
353 // need to update the entire base pointer construction algorithm to know how
354 // to track vector elements and potentially scalarize, but the case which
355 // would motivate the work hasn't shown up in real workloads yet.
356 llvm_unreachable("no base found for vector element");
357}
358
Philip Reamesd16a9b12015-02-20 01:06:44 +0000359/// Helper function for findBasePointer - Will return a value which either a)
360/// defines the base pointer for the input or b) blocks the simple search
361/// (i.e. a PHI or Select of two derived pointers)
362static Value *findBaseDefiningValue(Value *I) {
363 assert(I->getType()->isPointerTy() &&
364 "Illegal to ask for the base pointer of a non-pointer type");
365
Philip Reames8531d8c2015-04-10 21:48:25 +0000366 // This case is a bit of a hack - it only handles extracts from vectors which
Philip Reames311f7102015-05-12 22:19:52 +0000367 // trivially contain only base pointers or cases where we can directly match
368 // the index of the original extract element to an insertion into the vector.
369 // See note inside the function for how to improve this.
Philip Reames8531d8c2015-04-10 21:48:25 +0000370 if (auto *EEI = dyn_cast<ExtractElementInst>(I)) {
371 Value *VectorOperand = EEI->getVectorOperand();
Philip Reames311f7102015-05-12 22:19:52 +0000372 Value *Index = EEI->getIndexOperand();
373 Value *VectorBase = findBaseOfVector(VectorOperand, Index);
374 // If the result returned is a vector, we know the entire vector must
375 // contain base pointers. In that case, the extractelement is a valid base
376 // for this value.
377 if (VectorBase->getType()->isVectorTy())
378 return EEI;
379 // Otherwise, we needed to look through the vector to find the base for
380 // this particular element.
381 assert(VectorBase->getType()->isPointerTy());
382 return VectorBase;
Philip Reames8531d8c2015-04-10 21:48:25 +0000383 }
Philip Reamesd16a9b12015-02-20 01:06:44 +0000384
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000385 if (isa<Argument>(I))
Philip Reamesd16a9b12015-02-20 01:06:44 +0000386 // An incoming argument to the function is a base pointer
387 // We should have never reached here if this argument isn't an gc value
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000388 return I;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000389
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000390 if (isa<GlobalVariable>(I))
Philip Reamesd16a9b12015-02-20 01:06:44 +0000391 // base case
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000392 return I;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000393
394 // inlining could possibly introduce phi node that contains
395 // undef if callee has multiple returns
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000396 if (isa<UndefValue>(I))
397 // utterly meaningless, but useful for dealing with
398 // partially optimized code.
Philip Reames704e78b2015-04-10 22:34:56 +0000399 return I;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000400
401 // Due to inheritance, this must be _after_ the global variable and undef
402 // checks
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000403 if (Constant *Con = dyn_cast<Constant>(I)) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000404 assert(!isa<GlobalVariable>(I) && !isa<UndefValue>(I) &&
405 "order of checks wrong!");
406 // Note: Finding a constant base for something marked for relocation
407 // doesn't really make sense. The most likely case is either a) some
408 // screwed up the address space usage or b) your validating against
409 // compiled C++ code w/o the proper separation. The only real exception
410 // is a null pointer. You could have generic code written to index of
411 // off a potentially null value and have proven it null. We also use
412 // null pointers in dead paths of relocation phis (which we might later
413 // want to find a base pointer for).
Philip Reames24c6cd52015-03-27 05:47:00 +0000414 assert(isa<ConstantPointerNull>(Con) &&
415 "null is the only case which makes sense");
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000416 return Con;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000417 }
418
419 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000420 Value *Def = CI->stripPointerCasts();
David Blaikie82ad7872015-02-20 23:44:24 +0000421 // If we find a cast instruction here, it means we've found a cast which is
422 // not simply a pointer cast (i.e. an inttoptr). We don't know how to
423 // handle int->ptr conversion.
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000424 assert(!isa<CastInst>(Def) && "shouldn't find another cast here");
425 return findBaseDefiningValue(Def);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000426 }
427
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000428 if (isa<LoadInst>(I))
429 return I; // The value loaded is an gc base itself
Philip Reamesd16a9b12015-02-20 01:06:44 +0000430
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000431 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I))
432 // The base of this GEP is the base
433 return findBaseDefiningValue(GEP->getPointerOperand());
Philip Reamesd16a9b12015-02-20 01:06:44 +0000434
435 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
436 switch (II->getIntrinsicID()) {
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000437 case Intrinsic::experimental_gc_result_ptr:
Philip Reamesd16a9b12015-02-20 01:06:44 +0000438 default:
439 // fall through to general call handling
440 break;
441 case Intrinsic::experimental_gc_statepoint:
442 case Intrinsic::experimental_gc_result_float:
443 case Intrinsic::experimental_gc_result_int:
444 llvm_unreachable("these don't produce pointers");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000445 case Intrinsic::experimental_gc_relocate: {
446 // Rerunning safepoint insertion after safepoints are already
447 // inserted is not supported. It could probably be made to work,
448 // but why are you doing this? There's no good reason.
449 llvm_unreachable("repeat safepoint insertion is not supported");
450 }
451 case Intrinsic::gcroot:
452 // Currently, this mechanism hasn't been extended to work with gcroot.
453 // There's no reason it couldn't be, but I haven't thought about the
454 // implications much.
455 llvm_unreachable(
456 "interaction with the gcroot mechanism is not supported");
457 }
458 }
459 // We assume that functions in the source language only return base
460 // pointers. This should probably be generalized via attributes to support
461 // both source language and internal functions.
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000462 if (isa<CallInst>(I) || isa<InvokeInst>(I))
463 return I;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000464
465 // I have absolutely no idea how to implement this part yet. It's not
466 // neccessarily hard, I just haven't really looked at it yet.
467 assert(!isa<LandingPadInst>(I) && "Landing Pad is unimplemented");
468
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000469 if (isa<AtomicCmpXchgInst>(I))
Philip Reamesd16a9b12015-02-20 01:06:44 +0000470 // A CAS is effectively a atomic store and load combined under a
471 // predicate. From the perspective of base pointers, we just treat it
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000472 // like a load.
473 return I;
Philip Reames704e78b2015-04-10 22:34:56 +0000474
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000475 assert(!isa<AtomicRMWInst>(I) && "Xchg handled above, all others are "
Philip Reames704e78b2015-04-10 22:34:56 +0000476 "binary ops which don't apply to pointers");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000477
478 // The aggregate ops. Aggregates can either be in the heap or on the
479 // stack, but in either case, this is simply a field load. As a result,
480 // this is a defining definition of the base just like a load is.
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000481 if (isa<ExtractValueInst>(I))
482 return I;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000483
484 // We should never see an insert vector since that would require we be
485 // tracing back a struct value not a pointer value.
486 assert(!isa<InsertValueInst>(I) &&
487 "Base pointer for a struct is meaningless");
488
489 // The last two cases here don't return a base pointer. Instead, they
490 // return a value which dynamically selects from amoung several base
491 // derived pointers (each with it's own base potentially). It's the job of
492 // the caller to resolve these.
Philip Reames704e78b2015-04-10 22:34:56 +0000493 assert((isa<SelectInst>(I) || isa<PHINode>(I)) &&
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000494 "missing instruction case in findBaseDefiningValing");
495 return I;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000496}
497
498/// Returns the base defining value for this value.
Philip Reames18d0feb2015-03-27 05:39:32 +0000499static Value *findBaseDefiningValueCached(Value *I, DefiningValueMapTy &Cache) {
500 Value *&Cached = Cache[I];
Benjamin Kramer6f665452015-02-20 14:00:58 +0000501 if (!Cached) {
502 Cached = findBaseDefiningValue(I);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000503 }
Philip Reames18d0feb2015-03-27 05:39:32 +0000504 assert(Cache[I] != nullptr);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000505
506 if (TraceLSP) {
Philip Reames18d0feb2015-03-27 05:39:32 +0000507 dbgs() << "fBDV-cached: " << I->getName() << " -> " << Cached->getName()
Philip Reamesd16a9b12015-02-20 01:06:44 +0000508 << "\n";
509 }
Benjamin Kramer6f665452015-02-20 14:00:58 +0000510 return Cached;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000511}
512
513/// Return a base pointer for this value if known. Otherwise, return it's
514/// base defining value.
Philip Reames18d0feb2015-03-27 05:39:32 +0000515static Value *findBaseOrBDV(Value *I, DefiningValueMapTy &Cache) {
516 Value *Def = findBaseDefiningValueCached(I, Cache);
517 auto Found = Cache.find(Def);
518 if (Found != Cache.end()) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000519 // Either a base-of relation, or a self reference. Caller must check.
Benjamin Kramer6f665452015-02-20 14:00:58 +0000520 return Found->second;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000521 }
522 // Only a BDV available
Philip Reames18d0feb2015-03-27 05:39:32 +0000523 return Def;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000524}
525
526/// Given the result of a call to findBaseDefiningValue, or findBaseOrBDV,
527/// is it known to be a base pointer? Or do we need to continue searching.
Philip Reames18d0feb2015-03-27 05:39:32 +0000528static bool isKnownBaseResult(Value *V) {
529 if (!isa<PHINode>(V) && !isa<SelectInst>(V)) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000530 // no recursion possible
531 return true;
532 }
Philip Reames18d0feb2015-03-27 05:39:32 +0000533 if (isa<Instruction>(V) &&
534 cast<Instruction>(V)->getMetadata("is_base_value")) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000535 // This is a previously inserted base phi or select. We know
536 // that this is a base value.
537 return true;
538 }
539
540 // We need to keep searching
541 return false;
542}
543
544// TODO: find a better name for this
545namespace {
546class PhiState {
547public:
548 enum Status { Unknown, Base, Conflict };
549
550 PhiState(Status s, Value *b = nullptr) : status(s), base(b) {
551 assert(status != Base || b);
552 }
553 PhiState(Value *b) : status(Base), base(b) {}
554 PhiState() : status(Unknown), base(nullptr) {}
Philip Reamesd16a9b12015-02-20 01:06:44 +0000555
556 Status getStatus() const { return status; }
557 Value *getBase() const { return base; }
558
559 bool isBase() const { return getStatus() == Base; }
560 bool isUnknown() const { return getStatus() == Unknown; }
561 bool isConflict() const { return getStatus() == Conflict; }
562
563 bool operator==(const PhiState &other) const {
564 return base == other.base && status == other.status;
565 }
566
567 bool operator!=(const PhiState &other) const { return !(*this == other); }
568
569 void dump() {
570 errs() << status << " (" << base << " - "
571 << (base ? base->getName() : "nullptr") << "): ";
572 }
573
574private:
575 Status status;
576 Value *base; // non null only if status == base
577};
578
Philip Reamese9c3b9b2015-02-20 22:48:20 +0000579typedef DenseMap<Value *, PhiState> ConflictStateMapTy;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000580// Values of type PhiState form a lattice, and this is a helper
581// class that implementes the meet operation. The meat of the meet
582// operation is implemented in MeetPhiStates::pureMeet
583class MeetPhiStates {
584public:
585 // phiStates is a mapping from PHINodes and SelectInst's to PhiStates.
Philip Reames860660e2015-02-20 22:05:18 +0000586 explicit MeetPhiStates(const ConflictStateMapTy &phiStates)
Philip Reamesd16a9b12015-02-20 01:06:44 +0000587 : phiStates(phiStates) {}
588
589 // Destructively meet the current result with the base V. V can
590 // either be a merge instruction (SelectInst / PHINode), in which
591 // case its status is looked up in the phiStates map; or a regular
592 // SSA value, in which case it is assumed to be a base.
593 void meetWith(Value *V) {
594 PhiState otherState = getStateForBDV(V);
595 assert((MeetPhiStates::pureMeet(otherState, currentResult) ==
596 MeetPhiStates::pureMeet(currentResult, otherState)) &&
597 "math is wrong: meet does not commute!");
598 currentResult = MeetPhiStates::pureMeet(otherState, currentResult);
599 }
600
601 PhiState getResult() const { return currentResult; }
602
603private:
Philip Reames860660e2015-02-20 22:05:18 +0000604 const ConflictStateMapTy &phiStates;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000605 PhiState currentResult;
606
607 /// Return a phi state for a base defining value. We'll generate a new
608 /// base state for known bases and expect to find a cached state otherwise
609 PhiState getStateForBDV(Value *baseValue) {
610 if (isKnownBaseResult(baseValue)) {
611 return PhiState(baseValue);
612 } else {
613 return lookupFromMap(baseValue);
614 }
615 }
616
617 PhiState lookupFromMap(Value *V) {
618 auto I = phiStates.find(V);
619 assert(I != phiStates.end() && "lookup failed!");
620 return I->second;
621 }
622
623 static PhiState pureMeet(const PhiState &stateA, const PhiState &stateB) {
624 switch (stateA.getStatus()) {
625 case PhiState::Unknown:
626 return stateB;
627
628 case PhiState::Base:
629 assert(stateA.getBase() && "can't be null");
David Blaikie82ad7872015-02-20 23:44:24 +0000630 if (stateB.isUnknown())
Philip Reamesd16a9b12015-02-20 01:06:44 +0000631 return stateA;
David Blaikie82ad7872015-02-20 23:44:24 +0000632
633 if (stateB.isBase()) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000634 if (stateA.getBase() == stateB.getBase()) {
635 assert(stateA == stateB && "equality broken!");
636 return stateA;
637 }
638 return PhiState(PhiState::Conflict);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000639 }
David Blaikie82ad7872015-02-20 23:44:24 +0000640 assert(stateB.isConflict() && "only three states!");
641 return PhiState(PhiState::Conflict);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000642
643 case PhiState::Conflict:
644 return stateA;
645 }
Reid Klecknera070ee52015-02-20 19:46:02 +0000646 llvm_unreachable("only three states!");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000647 }
648};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000649}
Philip Reamesd16a9b12015-02-20 01:06:44 +0000650/// For a given value or instruction, figure out what base ptr it's derived
651/// from. For gc objects, this is simply itself. On success, returns a value
652/// which is the base pointer. (This is reliable and can be used for
653/// relocation.) On failure, returns nullptr.
Philip Reamesba198492015-04-14 00:41:34 +0000654static Value *findBasePointer(Value *I, DefiningValueMapTy &cache) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000655 Value *def = findBaseOrBDV(I, cache);
656
657 if (isKnownBaseResult(def)) {
658 return def;
659 }
660
661 // Here's the rough algorithm:
662 // - For every SSA value, construct a mapping to either an actual base
663 // pointer or a PHI which obscures the base pointer.
664 // - Construct a mapping from PHI to unknown TOP state. Use an
665 // optimistic algorithm to propagate base pointer information. Lattice
666 // looks like:
667 // UNKNOWN
668 // b1 b2 b3 b4
669 // CONFLICT
670 // When algorithm terminates, all PHIs will either have a single concrete
671 // base or be in a conflict state.
672 // - For every conflict, insert a dummy PHI node without arguments. Add
673 // these to the base[Instruction] = BasePtr mapping. For every
674 // non-conflict, add the actual base.
675 // - For every conflict, add arguments for the base[a] of each input
676 // arguments.
677 //
678 // Note: A simpler form of this would be to add the conflict form of all
679 // PHIs without running the optimistic algorithm. This would be
680 // analougous to pessimistic data flow and would likely lead to an
681 // overall worse solution.
682
Philip Reames860660e2015-02-20 22:05:18 +0000683 ConflictStateMapTy states;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000684 states[def] = PhiState();
685 // Recursively fill in all phis & selects reachable from the initial one
686 // for which we don't already know a definite base value for
Philip Reamesa226e612015-02-28 00:47:50 +0000687 // TODO: This should be rewritten with a worklist
Philip Reamesd16a9b12015-02-20 01:06:44 +0000688 bool done = false;
689 while (!done) {
690 done = true;
Philip Reamesa226e612015-02-28 00:47:50 +0000691 // Since we're adding elements to 'states' as we run, we can't keep
692 // iterators into the set.
Philip Reames704e78b2015-04-10 22:34:56 +0000693 SmallVector<Value *, 16> Keys;
Philip Reamesa226e612015-02-28 00:47:50 +0000694 Keys.reserve(states.size());
Philip Reamesd16a9b12015-02-20 01:06:44 +0000695 for (auto Pair : states) {
Philip Reamesa226e612015-02-28 00:47:50 +0000696 Value *V = Pair.first;
697 Keys.push_back(V);
698 }
699 for (Value *v : Keys) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000700 assert(!isKnownBaseResult(v) && "why did it get added?");
701 if (PHINode *phi = dyn_cast<PHINode>(v)) {
David Blaikie82ad7872015-02-20 23:44:24 +0000702 assert(phi->getNumIncomingValues() > 0 &&
703 "zero input phis are illegal");
704 for (Value *InVal : phi->incoming_values()) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000705 Value *local = findBaseOrBDV(InVal, cache);
706 if (!isKnownBaseResult(local) && states.find(local) == states.end()) {
707 states[local] = PhiState();
708 done = false;
709 }
710 }
711 } else if (SelectInst *sel = dyn_cast<SelectInst>(v)) {
712 Value *local = findBaseOrBDV(sel->getTrueValue(), cache);
713 if (!isKnownBaseResult(local) && states.find(local) == states.end()) {
714 states[local] = PhiState();
715 done = false;
716 }
717 local = findBaseOrBDV(sel->getFalseValue(), cache);
718 if (!isKnownBaseResult(local) && states.find(local) == states.end()) {
719 states[local] = PhiState();
720 done = false;
721 }
722 }
723 }
724 }
725
726 if (TraceLSP) {
727 errs() << "States after initialization:\n";
728 for (auto Pair : states) {
729 Instruction *v = cast<Instruction>(Pair.first);
730 PhiState state = Pair.second;
731 state.dump();
732 v->dump();
733 }
734 }
735
736 // TODO: come back and revisit the state transitions around inputs which
737 // have reached conflict state. The current version seems too conservative.
738
739 bool progress = true;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000740 while (progress) {
Yaron Keren42a7adf2015-02-28 13:11:24 +0000741#ifndef NDEBUG
742 size_t oldSize = states.size();
743#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +0000744 progress = false;
Philip Reamesa226e612015-02-28 00:47:50 +0000745 // We're only changing keys in this loop, thus safe to keep iterators
Philip Reamesd16a9b12015-02-20 01:06:44 +0000746 for (auto Pair : states) {
747 MeetPhiStates calculateMeet(states);
748 Value *v = Pair.first;
749 assert(!isKnownBaseResult(v) && "why did it get added?");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000750 if (SelectInst *select = dyn_cast<SelectInst>(v)) {
751 calculateMeet.meetWith(findBaseOrBDV(select->getTrueValue(), cache));
752 calculateMeet.meetWith(findBaseOrBDV(select->getFalseValue(), cache));
David Blaikie82ad7872015-02-20 23:44:24 +0000753 } else
754 for (Value *Val : cast<PHINode>(v)->incoming_values())
755 calculateMeet.meetWith(findBaseOrBDV(Val, cache));
Philip Reamesd16a9b12015-02-20 01:06:44 +0000756
757 PhiState oldState = states[v];
758 PhiState newState = calculateMeet.getResult();
759 if (oldState != newState) {
760 progress = true;
761 states[v] = newState;
762 }
763 }
764
765 assert(oldSize <= states.size());
766 assert(oldSize == states.size() || progress);
767 }
768
769 if (TraceLSP) {
770 errs() << "States after meet iteration:\n";
771 for (auto Pair : states) {
772 Instruction *v = cast<Instruction>(Pair.first);
773 PhiState state = Pair.second;
774 state.dump();
775 v->dump();
776 }
777 }
778
779 // Insert Phis for all conflicts
Philip Reames2e5bcbe2015-02-28 01:52:09 +0000780 // We want to keep naming deterministic in the loop that follows, so
781 // sort the keys before iteration. This is useful in allowing us to
782 // write stable tests. Note that there is no invalidation issue here.
Philip Reames704e78b2015-04-10 22:34:56 +0000783 SmallVector<Value *, 16> Keys;
Philip Reames2e5bcbe2015-02-28 01:52:09 +0000784 Keys.reserve(states.size());
Philip Reamesd16a9b12015-02-20 01:06:44 +0000785 for (auto Pair : states) {
Philip Reames2e5bcbe2015-02-28 01:52:09 +0000786 Value *V = Pair.first;
787 Keys.push_back(V);
788 }
789 std::sort(Keys.begin(), Keys.end(), order_by_name);
790 // TODO: adjust naming patterns to avoid this order of iteration dependency
791 for (Value *V : Keys) {
792 Instruction *v = cast<Instruction>(V);
793 PhiState state = states[V];
Philip Reamesd16a9b12015-02-20 01:06:44 +0000794 assert(!isKnownBaseResult(v) && "why did it get added?");
795 assert(!state.isUnknown() && "Optimistic algorithm didn't complete!");
Philip Reamesf986d682015-02-28 00:54:41 +0000796 if (!state.isConflict())
797 continue;
Philip Reames704e78b2015-04-10 22:34:56 +0000798
Philip Reamesf986d682015-02-28 00:54:41 +0000799 if (isa<PHINode>(v)) {
800 int num_preds =
801 std::distance(pred_begin(v->getParent()), pred_end(v->getParent()));
802 assert(num_preds > 0 && "how did we reach here");
803 PHINode *phi = PHINode::Create(v->getType(), num_preds, "base_phi", v);
Philip Reamesf986d682015-02-28 00:54:41 +0000804 // Add metadata marking this as a base value
805 auto *const_1 = ConstantInt::get(
806 Type::getInt32Ty(
807 v->getParent()->getParent()->getParent()->getContext()),
808 1);
809 auto MDConst = ConstantAsMetadata::get(const_1);
810 MDNode *md = MDNode::get(
811 v->getParent()->getParent()->getParent()->getContext(), MDConst);
812 phi->setMetadata("is_base_value", md);
813 states[v] = PhiState(PhiState::Conflict, phi);
814 } else {
815 SelectInst *sel = cast<SelectInst>(v);
816 // The undef will be replaced later
817 UndefValue *undef = UndefValue::get(sel->getType());
818 SelectInst *basesel = SelectInst::Create(sel->getCondition(), undef,
819 undef, "base_select", sel);
Philip Reamesf986d682015-02-28 00:54:41 +0000820 // Add metadata marking this as a base value
821 auto *const_1 = ConstantInt::get(
822 Type::getInt32Ty(
823 v->getParent()->getParent()->getParent()->getContext()),
824 1);
825 auto MDConst = ConstantAsMetadata::get(const_1);
826 MDNode *md = MDNode::get(
827 v->getParent()->getParent()->getParent()->getContext(), MDConst);
828 basesel->setMetadata("is_base_value", md);
829 states[v] = PhiState(PhiState::Conflict, basesel);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000830 }
831 }
832
833 // Fixup all the inputs of the new PHIs
834 for (auto Pair : states) {
835 Instruction *v = cast<Instruction>(Pair.first);
836 PhiState state = Pair.second;
837
838 assert(!isKnownBaseResult(v) && "why did it get added?");
839 assert(!state.isUnknown() && "Optimistic algorithm didn't complete!");
Philip Reames28e61ce2015-02-28 01:57:44 +0000840 if (!state.isConflict())
841 continue;
Philip Reames704e78b2015-04-10 22:34:56 +0000842
Philip Reames28e61ce2015-02-28 01:57:44 +0000843 if (PHINode *basephi = dyn_cast<PHINode>(state.getBase())) {
844 PHINode *phi = cast<PHINode>(v);
845 unsigned NumPHIValues = phi->getNumIncomingValues();
846 for (unsigned i = 0; i < NumPHIValues; i++) {
847 Value *InVal = phi->getIncomingValue(i);
848 BasicBlock *InBB = phi->getIncomingBlock(i);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000849
Philip Reames28e61ce2015-02-28 01:57:44 +0000850 // If we've already seen InBB, add the same incoming value
851 // we added for it earlier. The IR verifier requires phi
852 // nodes with multiple entries from the same basic block
853 // to have the same incoming value for each of those
854 // entries. If we don't do this check here and basephi
855 // has a different type than base, we'll end up adding two
856 // bitcasts (and hence two distinct values) as incoming
857 // values for the same basic block.
Philip Reamesd16a9b12015-02-20 01:06:44 +0000858
Philip Reames28e61ce2015-02-28 01:57:44 +0000859 int blockIndex = basephi->getBasicBlockIndex(InBB);
860 if (blockIndex != -1) {
861 Value *oldBase = basephi->getIncomingValue(blockIndex);
862 basephi->addIncoming(oldBase, InBB);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000863#ifndef NDEBUG
Philip Reames28e61ce2015-02-28 01:57:44 +0000864 Value *base = findBaseOrBDV(InVal, cache);
865 if (!isKnownBaseResult(base)) {
866 // Either conflict or base.
867 assert(states.count(base));
868 base = states[base].getBase();
869 assert(base != nullptr && "unknown PhiState!");
Philip Reames28e61ce2015-02-28 01:57:44 +0000870 }
Philip Reamesd16a9b12015-02-20 01:06:44 +0000871
Philip Reames28e61ce2015-02-28 01:57:44 +0000872 // In essense this assert states: the only way two
873 // values incoming from the same basic block may be
874 // different is by being different bitcasts of the same
875 // value. A cleanup that remains TODO is changing
876 // findBaseOrBDV to return an llvm::Value of the correct
877 // type (and still remain pure). This will remove the
878 // need to add bitcasts.
879 assert(base->stripPointerCasts() == oldBase->stripPointerCasts() &&
880 "sanity -- findBaseOrBDV should be pure!");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000881#endif
Philip Reames28e61ce2015-02-28 01:57:44 +0000882 continue;
883 }
Philip Reamesd16a9b12015-02-20 01:06:44 +0000884
Philip Reames28e61ce2015-02-28 01:57:44 +0000885 // Find either the defining value for the PHI or the normal base for
886 // a non-phi node
887 Value *base = findBaseOrBDV(InVal, cache);
888 if (!isKnownBaseResult(base)) {
889 // Either conflict or base.
890 assert(states.count(base));
891 base = states[base].getBase();
892 assert(base != nullptr && "unknown PhiState!");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000893 }
Philip Reames28e61ce2015-02-28 01:57:44 +0000894 assert(base && "can't be null");
895 // Must use original input BB since base may not be Instruction
896 // The cast is needed since base traversal may strip away bitcasts
897 if (base->getType() != basephi->getType()) {
898 base = new BitCastInst(base, basephi->getType(), "cast",
899 InBB->getTerminator());
Philip Reamesd16a9b12015-02-20 01:06:44 +0000900 }
Philip Reames28e61ce2015-02-28 01:57:44 +0000901 basephi->addIncoming(base, InBB);
902 }
903 assert(basephi->getNumIncomingValues() == NumPHIValues);
904 } else {
905 SelectInst *basesel = cast<SelectInst>(state.getBase());
906 SelectInst *sel = cast<SelectInst>(v);
907 // Operand 1 & 2 are true, false path respectively. TODO: refactor to
908 // something more safe and less hacky.
909 for (int i = 1; i <= 2; i++) {
910 Value *InVal = sel->getOperand(i);
911 // Find either the defining value for the PHI or the normal base for
912 // a non-phi node
913 Value *base = findBaseOrBDV(InVal, cache);
914 if (!isKnownBaseResult(base)) {
915 // Either conflict or base.
916 assert(states.count(base));
917 base = states[base].getBase();
918 assert(base != nullptr && "unknown PhiState!");
919 }
920 assert(base && "can't be null");
921 // Must use original input BB since base may not be Instruction
922 // The cast is needed since base traversal may strip away bitcasts
923 if (base->getType() != basesel->getType()) {
924 base = new BitCastInst(base, basesel->getType(), "cast", basesel);
Philip Reames28e61ce2015-02-28 01:57:44 +0000925 }
926 basesel->setOperand(i, base);
927 }
Philip Reamesd16a9b12015-02-20 01:06:44 +0000928 }
929 }
930
931 // Cache all of our results so we can cheaply reuse them
932 // NOTE: This is actually two caches: one of the base defining value
933 // relation and one of the base pointer relation! FIXME
934 for (auto item : states) {
935 Value *v = item.first;
936 Value *base = item.second.getBase();
937 assert(v && base);
938 assert(!isKnownBaseResult(v) && "why did it get added?");
939
940 if (TraceLSP) {
941 std::string fromstr =
942 cache.count(v) ? (cache[v]->hasName() ? cache[v]->getName() : "")
943 : "none";
944 errs() << "Updating base value cache"
945 << " for: " << (v->hasName() ? v->getName() : "")
946 << " from: " << fromstr
947 << " to: " << (base->hasName() ? base->getName() : "") << "\n";
948 }
949
950 assert(isKnownBaseResult(base) &&
951 "must be something we 'know' is a base pointer");
952 if (cache.count(v)) {
953 // Once we transition from the BDV relation being store in the cache to
954 // the base relation being stored, it must be stable
955 assert((!isKnownBaseResult(cache[v]) || cache[v] == base) &&
956 "base relation should be stable");
957 }
958 cache[v] = base;
959 }
960 assert(cache.find(def) != cache.end());
961 return cache[def];
962}
963
964// For a set of live pointers (base and/or derived), identify the base
965// pointer of the object which they are derived from. This routine will
966// mutate the IR graph as needed to make the 'base' pointer live at the
967// definition site of 'derived'. This ensures that any use of 'derived' can
968// also use 'base'. This may involve the insertion of a number of
969// additional PHI nodes.
970//
971// preconditions: live is a set of pointer type Values
972//
973// side effects: may insert PHI nodes into the existing CFG, will preserve
974// CFG, will not remove or mutate any existing nodes
975//
Philip Reamesf2041322015-02-20 19:26:04 +0000976// post condition: PointerToBase contains one (derived, base) pair for every
Philip Reamesd16a9b12015-02-20 01:06:44 +0000977// pointer in live. Note that derived can be equal to base if the original
978// pointer was a base pointer.
Philip Reames704e78b2015-04-10 22:34:56 +0000979static void
980findBasePointers(const StatepointLiveSetTy &live,
981 DenseMap<llvm::Value *, llvm::Value *> &PointerToBase,
Philip Reamesba198492015-04-14 00:41:34 +0000982 DominatorTree *DT, DefiningValueMapTy &DVCache) {
Philip Reames2e5bcbe2015-02-28 01:52:09 +0000983 // For the naming of values inserted to be deterministic - which makes for
984 // much cleaner and more stable tests - we need to assign an order to the
985 // live values. DenseSets do not provide a deterministic order across runs.
Philip Reames704e78b2015-04-10 22:34:56 +0000986 SmallVector<Value *, 64> Temp;
Philip Reames2e5bcbe2015-02-28 01:52:09 +0000987 Temp.insert(Temp.end(), live.begin(), live.end());
988 std::sort(Temp.begin(), Temp.end(), order_by_name);
989 for (Value *ptr : Temp) {
Philip Reamesba198492015-04-14 00:41:34 +0000990 Value *base = findBasePointer(ptr, DVCache);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000991 assert(base && "failed to find base pointer");
Philip Reamesf2041322015-02-20 19:26:04 +0000992 PointerToBase[ptr] = base;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000993 assert((!isa<Instruction>(base) || !isa<Instruction>(ptr) ||
994 DT->dominates(cast<Instruction>(base)->getParent(),
995 cast<Instruction>(ptr)->getParent())) &&
996 "The base we found better dominate the derived pointer");
997
David Blaikie82ad7872015-02-20 23:44:24 +0000998 // If you see this trip and like to live really dangerously, the code should
999 // be correct, just with idioms the verifier can't handle. You can try
1000 // disabling the verifier at your own substaintial risk.
Philip Reames704e78b2015-04-10 22:34:56 +00001001 assert(!isa<ConstantPointerNull>(base) &&
Philip Reames24c6cd52015-03-27 05:47:00 +00001002 "the relocation code needs adjustment to handle the relocation of "
1003 "a null pointer constant without causing false positives in the "
1004 "safepoint ir verifier.");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001005 }
1006}
1007
1008/// Find the required based pointers (and adjust the live set) for the given
1009/// parse point.
1010static void findBasePointers(DominatorTree &DT, DefiningValueMapTy &DVCache,
1011 const CallSite &CS,
1012 PartiallyConstructedSafepointRecord &result) {
Philip Reamesf2041322015-02-20 19:26:04 +00001013 DenseMap<llvm::Value *, llvm::Value *> PointerToBase;
Philip Reamesba198492015-04-14 00:41:34 +00001014 findBasePointers(result.liveset, PointerToBase, &DT, DVCache);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001015
1016 if (PrintBasePointers) {
Philip Reamesa5aeaf42015-02-28 00:20:48 +00001017 // Note: Need to print these in a stable order since this is checked in
1018 // some tests.
Philip Reamesd16a9b12015-02-20 01:06:44 +00001019 errs() << "Base Pairs (w/o Relocation):\n";
Philip Reames704e78b2015-04-10 22:34:56 +00001020 SmallVector<Value *, 64> Temp;
Philip Reamesa5aeaf42015-02-28 00:20:48 +00001021 Temp.reserve(PointerToBase.size());
Philip Reamesf2041322015-02-20 19:26:04 +00001022 for (auto Pair : PointerToBase) {
Philip Reamesa5aeaf42015-02-28 00:20:48 +00001023 Temp.push_back(Pair.first);
1024 }
1025 std::sort(Temp.begin(), Temp.end(), order_by_name);
1026 for (Value *Ptr : Temp) {
1027 Value *Base = PointerToBase[Ptr];
Philip Reames704e78b2015-04-10 22:34:56 +00001028 errs() << " derived %" << Ptr->getName() << " base %" << Base->getName()
1029 << "\n";
Philip Reamesd16a9b12015-02-20 01:06:44 +00001030 }
1031 }
1032
Philip Reamesf2041322015-02-20 19:26:04 +00001033 result.PointerToBase = PointerToBase;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001034}
1035
Philip Reamesdf1ef082015-04-10 22:53:14 +00001036/// Given an updated version of the dataflow liveness results, update the
1037/// liveset and base pointer maps for the call site CS.
1038static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData,
1039 const CallSite &CS,
1040 PartiallyConstructedSafepointRecord &result);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001041
Philip Reamesdf1ef082015-04-10 22:53:14 +00001042static void recomputeLiveInValues(
1043 Function &F, DominatorTree &DT, Pass *P, ArrayRef<CallSite> toUpdate,
Philip Reamesd2b66462015-02-20 22:39:41 +00001044 MutableArrayRef<struct PartiallyConstructedSafepointRecord> records) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00001045 // TODO-PERF: reuse the original liveness, then simply run the dataflow
1046 // again. The old values are still live and will help it stablize quickly.
1047 GCPtrLivenessData RevisedLivenessData;
1048 computeLiveInValues(DT, F, RevisedLivenessData);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001049 for (size_t i = 0; i < records.size(); i++) {
1050 struct PartiallyConstructedSafepointRecord &info = records[i];
Philip Reamesd2b66462015-02-20 22:39:41 +00001051 const CallSite &CS = toUpdate[i];
Philip Reamesdf1ef082015-04-10 22:53:14 +00001052 recomputeLiveInValues(RevisedLivenessData, CS, info);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001053 }
1054}
1055
Philip Reames69e51ca2015-04-13 18:07:21 +00001056// When inserting gc.relocate calls, we need to ensure there are no uses
1057// of the original value between the gc.statepoint and the gc.relocate call.
1058// One case which can arise is a phi node starting one of the successor blocks.
1059// We also need to be able to insert the gc.relocates only on the path which
1060// goes through the statepoint. We might need to split an edge to make this
Philip Reamesf209a152015-04-13 20:00:30 +00001061// possible.
1062static BasicBlock *
Sanjoy Dasea45f0e2015-06-02 22:33:34 +00001063normalizeForInvokeSafepoint(BasicBlock *BB, BasicBlock *InvokeParent,
1064 DominatorTree &DT) {
Philip Reames69e51ca2015-04-13 18:07:21 +00001065 BasicBlock *Ret = BB;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001066 if (!BB->getUniquePredecessor()) {
Sanjoy Dasea45f0e2015-06-02 22:33:34 +00001067 Ret = SplitBlockPredecessors(BB, InvokeParent, "", nullptr, &DT);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001068 }
1069
Philip Reames69e51ca2015-04-13 18:07:21 +00001070 // Now that 'ret' has unique predecessor we can safely remove all phi nodes
1071 // from it
1072 FoldSingleEntryPHINodes(Ret);
1073 assert(!isa<PHINode>(Ret->begin()));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001074
Philip Reames69e51ca2015-04-13 18:07:21 +00001075 // At this point, we can safely insert a gc.relocate as the first instruction
1076 // in Ret if needed.
1077 return Ret;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001078}
1079
Philip Reamesd2b66462015-02-20 22:39:41 +00001080static int find_index(ArrayRef<Value *> livevec, Value *val) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001081 auto itr = std::find(livevec.begin(), livevec.end(), val);
1082 assert(livevec.end() != itr);
1083 size_t index = std::distance(livevec.begin(), itr);
1084 assert(index < livevec.size());
1085 return index;
1086}
1087
1088// Create new attribute set containing only attributes which can be transfered
1089// from original call to the safepoint.
1090static AttributeSet legalizeCallAttributes(AttributeSet AS) {
1091 AttributeSet ret;
1092
1093 for (unsigned Slot = 0; Slot < AS.getNumSlots(); Slot++) {
1094 unsigned index = AS.getSlotIndex(Slot);
1095
1096 if (index == AttributeSet::ReturnIndex ||
1097 index == AttributeSet::FunctionIndex) {
1098
1099 for (auto it = AS.begin(Slot), it_end = AS.end(Slot); it != it_end;
1100 ++it) {
1101 Attribute attr = *it;
1102
1103 // Do not allow certain attributes - just skip them
1104 // Safepoint can not be read only or read none.
1105 if (attr.hasAttribute(Attribute::ReadNone) ||
1106 attr.hasAttribute(Attribute::ReadOnly))
1107 continue;
1108
1109 ret = ret.addAttributes(
1110 AS.getContext(), index,
1111 AttributeSet::get(AS.getContext(), index, AttrBuilder(attr)));
1112 }
1113 }
1114
1115 // Just skip parameter attributes for now
1116 }
1117
1118 return ret;
1119}
1120
1121/// Helper function to place all gc relocates necessary for the given
1122/// statepoint.
1123/// Inputs:
1124/// liveVariables - list of variables to be relocated.
1125/// liveStart - index of the first live variable.
1126/// basePtrs - base pointers.
1127/// statepointToken - statepoint instruction to which relocates should be
1128/// bound.
1129/// Builder - Llvm IR builder to be used to construct new calls.
Sanjoy Das5665c992015-05-11 23:47:27 +00001130static void CreateGCRelocates(ArrayRef<llvm::Value *> LiveVariables,
1131 const int LiveStart,
1132 ArrayRef<llvm::Value *> BasePtrs,
1133 Instruction *StatepointToken,
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00001134 IRBuilder<> Builder) {
Philip Reamesd2b66462015-02-20 22:39:41 +00001135 SmallVector<Instruction *, 64> NewDefs;
Sanjoy Das5665c992015-05-11 23:47:27 +00001136 NewDefs.reserve(LiveVariables.size());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001137
Sanjoy Das5665c992015-05-11 23:47:27 +00001138 Module *M = StatepointToken->getParent()->getParent()->getParent();
Philip Reamesd16a9b12015-02-20 01:06:44 +00001139
Sanjoy Das5665c992015-05-11 23:47:27 +00001140 for (unsigned i = 0; i < LiveVariables.size(); i++) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001141 // We generate a (potentially) unique declaration for every pointer type
1142 // combination. This results is some blow up the function declarations in
1143 // the IR, but removes the need for argument bitcasts which shrinks the IR
1144 // greatly and makes it much more readable.
Sanjoy Das5665c992015-05-11 23:47:27 +00001145 SmallVector<Type *, 1> Types; // one per 'any' type
Sanjoy Das89c54912015-05-11 18:49:34 +00001146 // All gc_relocate are set to i8 addrspace(1)* type. This could help avoid
1147 // cases where the actual value's type mangling is not supported by llvm. A
1148 // bitcast is added later to convert gc_relocate to the actual value's type.
Sanjoy Das5665c992015-05-11 23:47:27 +00001149 Types.push_back(Type::getInt8PtrTy(M->getContext(), 1));
1150 Value *GCRelocateDecl = Intrinsic::getDeclaration(
1151 M, Intrinsic::experimental_gc_relocate, Types);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001152
1153 // Generate the gc.relocate call and save the result
Sanjoy Das5665c992015-05-11 23:47:27 +00001154 Value *BaseIdx =
Philip Reamesd16a9b12015-02-20 01:06:44 +00001155 ConstantInt::get(Type::getInt32Ty(M->getContext()),
Sanjoy Das5665c992015-05-11 23:47:27 +00001156 LiveStart + find_index(LiveVariables, BasePtrs[i]));
1157 Value *LiveIdx = ConstantInt::get(
Philip Reamesd16a9b12015-02-20 01:06:44 +00001158 Type::getInt32Ty(M->getContext()),
Sanjoy Das5665c992015-05-11 23:47:27 +00001159 LiveStart + find_index(LiveVariables, LiveVariables[i]));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001160
1161 // only specify a debug name if we can give a useful one
David Blaikieff6409d2015-05-18 22:13:54 +00001162 Value *Reloc = Builder.CreateCall(
1163 GCRelocateDecl, {StatepointToken, BaseIdx, LiveIdx},
Sanjoy Das5665c992015-05-11 23:47:27 +00001164 LiveVariables[i]->hasName() ? LiveVariables[i]->getName() + ".relocated"
Philip Reamesd16a9b12015-02-20 01:06:44 +00001165 : "");
1166 // Trick CodeGen into thinking there are lots of free registers at this
1167 // fake call.
Sanjoy Das5665c992015-05-11 23:47:27 +00001168 cast<CallInst>(Reloc)->setCallingConv(CallingConv::Cold);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001169
Sanjoy Das5665c992015-05-11 23:47:27 +00001170 NewDefs.push_back(cast<Instruction>(Reloc));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001171 }
Sanjoy Das5665c992015-05-11 23:47:27 +00001172 assert(NewDefs.size() == LiveVariables.size() &&
Philip Reamesd16a9b12015-02-20 01:06:44 +00001173 "missing or extra redefinition at safepoint");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001174}
1175
1176static void
1177makeStatepointExplicitImpl(const CallSite &CS, /* to replace */
1178 const SmallVectorImpl<llvm::Value *> &basePtrs,
1179 const SmallVectorImpl<llvm::Value *> &liveVariables,
1180 Pass *P,
1181 PartiallyConstructedSafepointRecord &result) {
1182 assert(basePtrs.size() == liveVariables.size());
1183 assert(isStatepoint(CS) &&
1184 "This method expects to be rewriting a statepoint");
1185
1186 BasicBlock *BB = CS.getInstruction()->getParent();
1187 assert(BB);
1188 Function *F = BB->getParent();
1189 assert(F && "must be set");
1190 Module *M = F->getParent();
Nick Lewyckyeb3231e2015-02-20 07:14:02 +00001191 (void)M;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001192 assert(M && "must be set");
1193
1194 // We're not changing the function signature of the statepoint since the gc
1195 // arguments go into the var args section.
1196 Function *gc_statepoint_decl = CS.getCalledFunction();
1197
1198 // Then go ahead and use the builder do actually do the inserts. We insert
1199 // immediately before the previous instruction under the assumption that all
1200 // arguments will be available here. We can't insert afterwards since we may
1201 // be replacing a terminator.
1202 Instruction *insertBefore = CS.getInstruction();
1203 IRBuilder<> Builder(insertBefore);
1204 // Copy all of the arguments from the original statepoint - this includes the
1205 // target, call args, and deopt args
Philip Reamesd2b66462015-02-20 22:39:41 +00001206 SmallVector<llvm::Value *, 64> args;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001207 args.insert(args.end(), CS.arg_begin(), CS.arg_end());
1208 // TODO: Clear the 'needs rewrite' flag
1209
1210 // add all the pointers to be relocated (gc arguments)
1211 // Capture the start of the live variable list for use in the gc_relocates
1212 const int live_start = args.size();
1213 args.insert(args.end(), liveVariables.begin(), liveVariables.end());
1214
1215 // Create the statepoint given all the arguments
1216 Instruction *token = nullptr;
1217 AttributeSet return_attributes;
1218 if (CS.isCall()) {
1219 CallInst *toReplace = cast<CallInst>(CS.getInstruction());
1220 CallInst *call =
1221 Builder.CreateCall(gc_statepoint_decl, args, "safepoint_token");
1222 call->setTailCall(toReplace->isTailCall());
1223 call->setCallingConv(toReplace->getCallingConv());
1224
1225 // Currently we will fail on parameter attributes and on certain
1226 // function attributes.
1227 AttributeSet new_attrs = legalizeCallAttributes(toReplace->getAttributes());
1228 // In case if we can handle this set of sttributes - set up function attrs
1229 // directly on statepoint and return attrs later for gc_result intrinsic.
1230 call->setAttributes(new_attrs.getFnAttributes());
1231 return_attributes = new_attrs.getRetAttributes();
1232
1233 token = call;
1234
1235 // Put the following gc_result and gc_relocate calls immediately after the
1236 // the old call (which we're about to delete)
1237 BasicBlock::iterator next(toReplace);
1238 assert(BB->end() != next && "not a terminator, must have next");
1239 next++;
1240 Instruction *IP = &*(next);
1241 Builder.SetInsertPoint(IP);
1242 Builder.SetCurrentDebugLocation(IP->getDebugLoc());
1243
David Blaikie82ad7872015-02-20 23:44:24 +00001244 } else {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001245 InvokeInst *toReplace = cast<InvokeInst>(CS.getInstruction());
1246
1247 // Insert the new invoke into the old block. We'll remove the old one in a
1248 // moment at which point this will become the new terminator for the
1249 // original block.
1250 InvokeInst *invoke = InvokeInst::Create(
1251 gc_statepoint_decl, toReplace->getNormalDest(),
1252 toReplace->getUnwindDest(), args, "", toReplace->getParent());
1253 invoke->setCallingConv(toReplace->getCallingConv());
1254
1255 // Currently we will fail on parameter attributes and on certain
1256 // function attributes.
1257 AttributeSet new_attrs = legalizeCallAttributes(toReplace->getAttributes());
1258 // In case if we can handle this set of sttributes - set up function attrs
1259 // directly on statepoint and return attrs later for gc_result intrinsic.
1260 invoke->setAttributes(new_attrs.getFnAttributes());
1261 return_attributes = new_attrs.getRetAttributes();
1262
1263 token = invoke;
1264
1265 // Generate gc relocates in exceptional path
Philip Reames69e51ca2015-04-13 18:07:21 +00001266 BasicBlock *unwindBlock = toReplace->getUnwindDest();
1267 assert(!isa<PHINode>(unwindBlock->begin()) &&
1268 unwindBlock->getUniquePredecessor() &&
1269 "can't safely insert in this block!");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001270
1271 Instruction *IP = &*(unwindBlock->getFirstInsertionPt());
1272 Builder.SetInsertPoint(IP);
1273 Builder.SetCurrentDebugLocation(toReplace->getDebugLoc());
1274
1275 // Extract second element from landingpad return value. We will attach
1276 // exceptional gc relocates to it.
1277 const unsigned idx = 1;
1278 Instruction *exceptional_token =
1279 cast<Instruction>(Builder.CreateExtractValue(
1280 unwindBlock->getLandingPadInst(), idx, "relocate_token"));
Philip Reamesf2041322015-02-20 19:26:04 +00001281 result.UnwindToken = exceptional_token;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001282
1283 // Just throw away return value. We will use the one we got for normal
1284 // block.
1285 (void)CreateGCRelocates(liveVariables, live_start, basePtrs,
1286 exceptional_token, Builder);
1287
1288 // Generate gc relocates and returns for normal block
Philip Reames69e51ca2015-04-13 18:07:21 +00001289 BasicBlock *normalDest = toReplace->getNormalDest();
1290 assert(!isa<PHINode>(normalDest->begin()) &&
1291 normalDest->getUniquePredecessor() &&
1292 "can't safely insert in this block!");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001293
1294 IP = &*(normalDest->getFirstInsertionPt());
1295 Builder.SetInsertPoint(IP);
1296
1297 // gc relocates will be generated later as if it were regular call
1298 // statepoint
Philip Reamesd16a9b12015-02-20 01:06:44 +00001299 }
1300 assert(token);
1301
1302 // Take the name of the original value call if it had one.
1303 token->takeName(CS.getInstruction());
1304
Philip Reames704e78b2015-04-10 22:34:56 +00001305// The GCResult is already inserted, we just need to find it
David Blaikie5e5d7842015-02-22 20:58:38 +00001306#ifndef NDEBUG
1307 Instruction *toReplace = CS.getInstruction();
1308 assert((toReplace->hasNUses(0) || toReplace->hasNUses(1)) &&
1309 "only valid use before rewrite is gc.result");
1310 assert(!toReplace->hasOneUse() ||
1311 isGCResult(cast<Instruction>(*toReplace->user_begin())));
1312#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +00001313
1314 // Update the gc.result of the original statepoint (if any) to use the newly
1315 // inserted statepoint. This is safe to do here since the token can't be
1316 // considered a live reference.
1317 CS.getInstruction()->replaceAllUsesWith(token);
1318
Philip Reames0a3240f2015-02-20 21:34:11 +00001319 result.StatepointToken = token;
1320
Philip Reamesd16a9b12015-02-20 01:06:44 +00001321 // Second, create a gc.relocate for every live variable
Philip Reames0a3240f2015-02-20 21:34:11 +00001322 CreateGCRelocates(liveVariables, live_start, basePtrs, token, Builder);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001323}
1324
1325namespace {
1326struct name_ordering {
1327 Value *base;
1328 Value *derived;
1329 bool operator()(name_ordering const &a, name_ordering const &b) {
1330 return -1 == a.derived->getName().compare(b.derived->getName());
1331 }
1332};
1333}
1334static void stablize_order(SmallVectorImpl<Value *> &basevec,
1335 SmallVectorImpl<Value *> &livevec) {
1336 assert(basevec.size() == livevec.size());
1337
Philip Reames860660e2015-02-20 22:05:18 +00001338 SmallVector<name_ordering, 64> temp;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001339 for (size_t i = 0; i < basevec.size(); i++) {
1340 name_ordering v;
1341 v.base = basevec[i];
1342 v.derived = livevec[i];
1343 temp.push_back(v);
1344 }
1345 std::sort(temp.begin(), temp.end(), name_ordering());
1346 for (size_t i = 0; i < basevec.size(); i++) {
1347 basevec[i] = temp[i].base;
1348 livevec[i] = temp[i].derived;
1349 }
1350}
1351
1352// Replace an existing gc.statepoint with a new one and a set of gc.relocates
1353// which make the relocations happening at this safepoint explicit.
Philip Reames704e78b2015-04-10 22:34:56 +00001354//
Philip Reamesd16a9b12015-02-20 01:06:44 +00001355// WARNING: Does not do any fixup to adjust users of the original live
1356// values. That's the callers responsibility.
1357static void
1358makeStatepointExplicit(DominatorTree &DT, const CallSite &CS, Pass *P,
1359 PartiallyConstructedSafepointRecord &result) {
Philip Reamesf2041322015-02-20 19:26:04 +00001360 auto liveset = result.liveset;
1361 auto PointerToBase = result.PointerToBase;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001362
1363 // Convert to vector for efficient cross referencing.
1364 SmallVector<Value *, 64> basevec, livevec;
1365 livevec.reserve(liveset.size());
1366 basevec.reserve(liveset.size());
1367 for (Value *L : liveset) {
1368 livevec.push_back(L);
1369
Philip Reamesf2041322015-02-20 19:26:04 +00001370 assert(PointerToBase.find(L) != PointerToBase.end());
1371 Value *base = PointerToBase[L];
Philip Reamesd16a9b12015-02-20 01:06:44 +00001372 basevec.push_back(base);
1373 }
1374 assert(livevec.size() == basevec.size());
1375
1376 // To make the output IR slightly more stable (for use in diffs), ensure a
1377 // fixed order of the values in the safepoint (by sorting the value name).
1378 // The order is otherwise meaningless.
1379 stablize_order(basevec, livevec);
1380
1381 // Do the actual rewriting and delete the old statepoint
1382 makeStatepointExplicitImpl(CS, basevec, livevec, P, result);
1383 CS.getInstruction()->eraseFromParent();
1384}
1385
1386// Helper function for the relocationViaAlloca.
1387// It receives iterator to the statepoint gc relocates and emits store to the
1388// assigned
1389// location (via allocaMap) for the each one of them.
1390// Add visited values into the visitedLiveValues set we will later use them
1391// for sanity check.
1392static void
Sanjoy Das5665c992015-05-11 23:47:27 +00001393insertRelocationStores(iterator_range<Value::user_iterator> GCRelocs,
1394 DenseMap<Value *, Value *> &AllocaMap,
1395 DenseSet<Value *> &VisitedLiveValues) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001396
Sanjoy Das5665c992015-05-11 23:47:27 +00001397 for (User *U : GCRelocs) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001398 if (!isa<IntrinsicInst>(U))
1399 continue;
1400
Sanjoy Das5665c992015-05-11 23:47:27 +00001401 IntrinsicInst *RelocatedValue = cast<IntrinsicInst>(U);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001402
1403 // We only care about relocates
Sanjoy Das5665c992015-05-11 23:47:27 +00001404 if (RelocatedValue->getIntrinsicID() !=
Philip Reamesd16a9b12015-02-20 01:06:44 +00001405 Intrinsic::experimental_gc_relocate) {
1406 continue;
1407 }
1408
Sanjoy Das5665c992015-05-11 23:47:27 +00001409 GCRelocateOperands RelocateOperands(RelocatedValue);
1410 Value *OriginalValue =
1411 const_cast<Value *>(RelocateOperands.getDerivedPtr());
1412 assert(AllocaMap.count(OriginalValue));
1413 Value *Alloca = AllocaMap[OriginalValue];
Philip Reamesd16a9b12015-02-20 01:06:44 +00001414
1415 // Emit store into the related alloca
Sanjoy Das89c54912015-05-11 18:49:34 +00001416 // All gc_relocate are i8 addrspace(1)* typed, and it must be bitcasted to
1417 // the correct type according to alloca.
Sanjoy Das5665c992015-05-11 23:47:27 +00001418 assert(RelocatedValue->getNextNode() && "Should always have one since it's not a terminator");
1419 IRBuilder<> Builder(RelocatedValue->getNextNode());
Sanjoy Das89c54912015-05-11 18:49:34 +00001420 Value *CastedRelocatedValue =
Sanjoy Das5665c992015-05-11 23:47:27 +00001421 Builder.CreateBitCast(RelocatedValue, cast<AllocaInst>(Alloca)->getAllocatedType(),
1422 RelocatedValue->hasName() ? RelocatedValue->getName() + ".casted" : "");
Sanjoy Das89c54912015-05-11 18:49:34 +00001423
Sanjoy Das5665c992015-05-11 23:47:27 +00001424 StoreInst *Store = new StoreInst(CastedRelocatedValue, Alloca);
1425 Store->insertAfter(cast<Instruction>(CastedRelocatedValue));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001426
1427#ifndef NDEBUG
Sanjoy Das5665c992015-05-11 23:47:27 +00001428 VisitedLiveValues.insert(OriginalValue);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001429#endif
1430 }
1431}
1432
Igor Laevskye0317182015-05-19 15:59:05 +00001433// Helper function for the "relocationViaAlloca". Similar to the
1434// "insertRelocationStores" but works for rematerialized values.
1435static void
1436insertRematerializationStores(
1437 RematerializedValueMapTy RematerializedValues,
1438 DenseMap<Value *, Value *> &AllocaMap,
1439 DenseSet<Value *> &VisitedLiveValues) {
1440
1441 for (auto RematerializedValuePair: RematerializedValues) {
1442 Instruction *RematerializedValue = RematerializedValuePair.first;
1443 Value *OriginalValue = RematerializedValuePair.second;
1444
1445 assert(AllocaMap.count(OriginalValue) &&
1446 "Can not find alloca for rematerialized value");
1447 Value *Alloca = AllocaMap[OriginalValue];
1448
1449 StoreInst *Store = new StoreInst(RematerializedValue, Alloca);
1450 Store->insertAfter(RematerializedValue);
1451
1452#ifndef NDEBUG
1453 VisitedLiveValues.insert(OriginalValue);
1454#endif
1455 }
1456}
1457
Philip Reamesd16a9b12015-02-20 01:06:44 +00001458/// do all the relocation update via allocas and mem2reg
1459static void relocationViaAlloca(
Igor Laevsky285fe842015-05-19 16:29:43 +00001460 Function &F, DominatorTree &DT, ArrayRef<Value *> Live,
1461 ArrayRef<struct PartiallyConstructedSafepointRecord> Records) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001462#ifndef NDEBUG
Philip Reamesa6ebf072015-03-27 05:53:16 +00001463 // record initial number of (static) allocas; we'll check we have the same
1464 // number when we get done.
1465 int InitialAllocaNum = 0;
Philip Reames704e78b2015-04-10 22:34:56 +00001466 for (auto I = F.getEntryBlock().begin(), E = F.getEntryBlock().end(); I != E;
1467 I++)
Philip Reamesa6ebf072015-03-27 05:53:16 +00001468 if (isa<AllocaInst>(*I))
1469 InitialAllocaNum++;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001470#endif
1471
1472 // TODO-PERF: change data structures, reserve
Igor Laevsky285fe842015-05-19 16:29:43 +00001473 DenseMap<Value *, Value *> AllocaMap;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001474 SmallVector<AllocaInst *, 200> PromotableAllocas;
Igor Laevskye0317182015-05-19 15:59:05 +00001475 // Used later to chack that we have enough allocas to store all values
1476 std::size_t NumRematerializedValues = 0;
Igor Laevsky285fe842015-05-19 16:29:43 +00001477 PromotableAllocas.reserve(Live.size());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001478
Igor Laevskye0317182015-05-19 15:59:05 +00001479 // Emit alloca for "LiveValue" and record it in "allocaMap" and
1480 // "PromotableAllocas"
1481 auto emitAllocaFor = [&](Value *LiveValue) {
1482 AllocaInst *Alloca = new AllocaInst(LiveValue->getType(), "",
1483 F.getEntryBlock().getFirstNonPHI());
Igor Laevsky285fe842015-05-19 16:29:43 +00001484 AllocaMap[LiveValue] = Alloca;
Igor Laevskye0317182015-05-19 15:59:05 +00001485 PromotableAllocas.push_back(Alloca);
1486 };
1487
Philip Reamesd16a9b12015-02-20 01:06:44 +00001488 // emit alloca for each live gc pointer
Igor Laevsky285fe842015-05-19 16:29:43 +00001489 for (unsigned i = 0; i < Live.size(); i++) {
1490 emitAllocaFor(Live[i]);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001491 }
1492
Igor Laevskye0317182015-05-19 15:59:05 +00001493 // emit allocas for rematerialized values
Igor Laevsky285fe842015-05-19 16:29:43 +00001494 for (size_t i = 0; i < Records.size(); i++) {
1495 const struct PartiallyConstructedSafepointRecord &Info = Records[i];
Igor Laevskye0317182015-05-19 15:59:05 +00001496
Igor Laevsky285fe842015-05-19 16:29:43 +00001497 for (auto RematerializedValuePair : Info.RematerializedValues) {
Igor Laevskye0317182015-05-19 15:59:05 +00001498 Value *OriginalValue = RematerializedValuePair.second;
Igor Laevsky285fe842015-05-19 16:29:43 +00001499 if (AllocaMap.count(OriginalValue) != 0)
Igor Laevskye0317182015-05-19 15:59:05 +00001500 continue;
1501
1502 emitAllocaFor(OriginalValue);
1503 ++NumRematerializedValues;
1504 }
1505 }
Igor Laevsky285fe842015-05-19 16:29:43 +00001506
Philip Reamesd16a9b12015-02-20 01:06:44 +00001507 // The next two loops are part of the same conceptual operation. We need to
1508 // insert a store to the alloca after the original def and at each
1509 // redefinition. We need to insert a load before each use. These are split
1510 // into distinct loops for performance reasons.
1511
1512 // update gc pointer after each statepoint
1513 // either store a relocated value or null (if no relocated value found for
1514 // this gc pointer and it is not a gc_result)
1515 // this must happen before we update the statepoint with load of alloca
1516 // otherwise we lose the link between statepoint and old def
Igor Laevsky285fe842015-05-19 16:29:43 +00001517 for (size_t i = 0; i < Records.size(); i++) {
1518 const struct PartiallyConstructedSafepointRecord &Info = Records[i];
1519 Value *Statepoint = Info.StatepointToken;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001520
1521 // This will be used for consistency check
Igor Laevsky285fe842015-05-19 16:29:43 +00001522 DenseSet<Value *> VisitedLiveValues;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001523
1524 // Insert stores for normal statepoint gc relocates
Igor Laevsky285fe842015-05-19 16:29:43 +00001525 insertRelocationStores(Statepoint->users(), AllocaMap, VisitedLiveValues);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001526
1527 // In case if it was invoke statepoint
1528 // we will insert stores for exceptional path gc relocates.
Philip Reames0a3240f2015-02-20 21:34:11 +00001529 if (isa<InvokeInst>(Statepoint)) {
Igor Laevsky285fe842015-05-19 16:29:43 +00001530 insertRelocationStores(Info.UnwindToken->users(), AllocaMap,
1531 VisitedLiveValues);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001532 }
1533
Igor Laevskye0317182015-05-19 15:59:05 +00001534 // Do similar thing with rematerialized values
Igor Laevsky285fe842015-05-19 16:29:43 +00001535 insertRematerializationStores(Info.RematerializedValues, AllocaMap,
1536 VisitedLiveValues);
Igor Laevskye0317182015-05-19 15:59:05 +00001537
Philip Reamese73300b2015-04-13 16:41:32 +00001538 if (ClobberNonLive) {
1539 // As a debuging aid, pretend that an unrelocated pointer becomes null at
1540 // the gc.statepoint. This will turn some subtle GC problems into
1541 // slightly easier to debug SEGVs. Note that on large IR files with
1542 // lots of gc.statepoints this is extremely costly both memory and time
1543 // wise.
1544 SmallVector<AllocaInst *, 64> ToClobber;
Igor Laevsky285fe842015-05-19 16:29:43 +00001545 for (auto Pair : AllocaMap) {
Philip Reamese73300b2015-04-13 16:41:32 +00001546 Value *Def = Pair.first;
1547 AllocaInst *Alloca = cast<AllocaInst>(Pair.second);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001548
Philip Reamese73300b2015-04-13 16:41:32 +00001549 // This value was relocated
Igor Laevsky285fe842015-05-19 16:29:43 +00001550 if (VisitedLiveValues.count(Def)) {
Philip Reamese73300b2015-04-13 16:41:32 +00001551 continue;
1552 }
1553 ToClobber.push_back(Alloca);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001554 }
Philip Reamesfa2fcf172015-02-20 19:51:56 +00001555
Philip Reamese73300b2015-04-13 16:41:32 +00001556 auto InsertClobbersAt = [&](Instruction *IP) {
1557 for (auto *AI : ToClobber) {
1558 auto AIType = cast<PointerType>(AI->getType());
1559 auto PT = cast<PointerType>(AIType->getElementType());
1560 Constant *CPN = ConstantPointerNull::get(PT);
Igor Laevsky285fe842015-05-19 16:29:43 +00001561 StoreInst *Store = new StoreInst(CPN, AI);
1562 Store->insertBefore(IP);
Philip Reamese73300b2015-04-13 16:41:32 +00001563 }
1564 };
1565
1566 // Insert the clobbering stores. These may get intermixed with the
1567 // gc.results and gc.relocates, but that's fine.
1568 if (auto II = dyn_cast<InvokeInst>(Statepoint)) {
1569 InsertClobbersAt(II->getNormalDest()->getFirstInsertionPt());
1570 InsertClobbersAt(II->getUnwindDest()->getFirstInsertionPt());
1571 } else {
1572 BasicBlock::iterator Next(cast<CallInst>(Statepoint));
1573 Next++;
1574 InsertClobbersAt(Next);
Philip Reamesfa2fcf172015-02-20 19:51:56 +00001575 }
David Blaikie82ad7872015-02-20 23:44:24 +00001576 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00001577 }
1578 // update use with load allocas and add store for gc_relocated
Igor Laevsky285fe842015-05-19 16:29:43 +00001579 for (auto Pair : AllocaMap) {
1580 Value *Def = Pair.first;
1581 Value *Alloca = Pair.second;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001582
1583 // we pre-record the uses of allocas so that we dont have to worry about
1584 // later update
1585 // that change the user information.
Igor Laevsky285fe842015-05-19 16:29:43 +00001586 SmallVector<Instruction *, 20> Uses;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001587 // PERF: trade a linear scan for repeated reallocation
Igor Laevsky285fe842015-05-19 16:29:43 +00001588 Uses.reserve(std::distance(Def->user_begin(), Def->user_end()));
1589 for (User *U : Def->users()) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001590 if (!isa<ConstantExpr>(U)) {
1591 // If the def has a ConstantExpr use, then the def is either a
1592 // ConstantExpr use itself or null. In either case
1593 // (recursively in the first, directly in the second), the oop
1594 // it is ultimately dependent on is null and this particular
1595 // use does not need to be fixed up.
Igor Laevsky285fe842015-05-19 16:29:43 +00001596 Uses.push_back(cast<Instruction>(U));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001597 }
1598 }
1599
Igor Laevsky285fe842015-05-19 16:29:43 +00001600 std::sort(Uses.begin(), Uses.end());
1601 auto Last = std::unique(Uses.begin(), Uses.end());
1602 Uses.erase(Last, Uses.end());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001603
Igor Laevsky285fe842015-05-19 16:29:43 +00001604 for (Instruction *Use : Uses) {
1605 if (isa<PHINode>(Use)) {
1606 PHINode *Phi = cast<PHINode>(Use);
1607 for (unsigned i = 0; i < Phi->getNumIncomingValues(); i++) {
1608 if (Def == Phi->getIncomingValue(i)) {
1609 LoadInst *Load = new LoadInst(
1610 Alloca, "", Phi->getIncomingBlock(i)->getTerminator());
1611 Phi->setIncomingValue(i, Load);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001612 }
1613 }
1614 } else {
Igor Laevsky285fe842015-05-19 16:29:43 +00001615 LoadInst *Load = new LoadInst(Alloca, "", Use);
1616 Use->replaceUsesOfWith(Def, Load);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001617 }
1618 }
1619
1620 // emit store for the initial gc value
1621 // store must be inserted after load, otherwise store will be in alloca's
1622 // use list and an extra load will be inserted before it
Igor Laevsky285fe842015-05-19 16:29:43 +00001623 StoreInst *Store = new StoreInst(Def, Alloca);
1624 if (Instruction *Inst = dyn_cast<Instruction>(Def)) {
1625 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(Inst)) {
Philip Reames6da37852015-03-04 00:13:52 +00001626 // InvokeInst is a TerminatorInst so the store need to be inserted
1627 // into its normal destination block.
Igor Laevsky285fe842015-05-19 16:29:43 +00001628 BasicBlock *NormalDest = Invoke->getNormalDest();
1629 Store->insertBefore(NormalDest->getFirstNonPHI());
Philip Reames6da37852015-03-04 00:13:52 +00001630 } else {
Igor Laevsky285fe842015-05-19 16:29:43 +00001631 assert(!Inst->isTerminator() &&
Philip Reames6da37852015-03-04 00:13:52 +00001632 "The only TerminatorInst that can produce a value is "
1633 "InvokeInst which is handled above.");
Igor Laevsky285fe842015-05-19 16:29:43 +00001634 Store->insertAfter(Inst);
Philip Reames6da37852015-03-04 00:13:52 +00001635 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00001636 } else {
Igor Laevsky285fe842015-05-19 16:29:43 +00001637 assert(isa<Argument>(Def));
1638 Store->insertAfter(cast<Instruction>(Alloca));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001639 }
1640 }
1641
Igor Laevsky285fe842015-05-19 16:29:43 +00001642 assert(PromotableAllocas.size() == Live.size() + NumRematerializedValues &&
Philip Reamesd16a9b12015-02-20 01:06:44 +00001643 "we must have the same allocas with lives");
1644 if (!PromotableAllocas.empty()) {
1645 // apply mem2reg to promote alloca to SSA
1646 PromoteMemToReg(PromotableAllocas, DT);
1647 }
1648
1649#ifndef NDEBUG
Philip Reames704e78b2015-04-10 22:34:56 +00001650 for (auto I = F.getEntryBlock().begin(), E = F.getEntryBlock().end(); I != E;
1651 I++)
Philip Reamesa6ebf072015-03-27 05:53:16 +00001652 if (isa<AllocaInst>(*I))
1653 InitialAllocaNum--;
1654 assert(InitialAllocaNum == 0 && "We must not introduce any extra allocas");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001655#endif
1656}
1657
1658/// Implement a unique function which doesn't require we sort the input
1659/// vector. Doing so has the effect of changing the output of a couple of
1660/// tests in ways which make them less useful in testing fused safepoints.
Philip Reamesd2b66462015-02-20 22:39:41 +00001661template <typename T> static void unique_unsorted(SmallVectorImpl<T> &Vec) {
Benjamin Kramer258ea0d2015-06-13 19:50:38 +00001662 SmallSet<T, 8> Seen;
1663 Vec.erase(std::remove_if(Vec.begin(), Vec.end(), [&](const T &V) {
1664 return !Seen.insert(V).second;
1665 }), Vec.end());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001666}
1667
Philip Reamesd16a9b12015-02-20 01:06:44 +00001668/// Insert holders so that each Value is obviously live through the entire
Philip Reamesf209a152015-04-13 20:00:30 +00001669/// lifetime of the call.
Philip Reamesd16a9b12015-02-20 01:06:44 +00001670static void insertUseHolderAfter(CallSite &CS, const ArrayRef<Value *> Values,
Philip Reamesf209a152015-04-13 20:00:30 +00001671 SmallVectorImpl<CallInst *> &Holders) {
Philip Reames21142752015-04-13 19:07:47 +00001672 if (Values.empty())
1673 // No values to hold live, might as well not insert the empty holder
1674 return;
1675
Philip Reamesd16a9b12015-02-20 01:06:44 +00001676 Module *M = CS.getInstruction()->getParent()->getParent()->getParent();
Philip Reamesf209a152015-04-13 20:00:30 +00001677 // Use a dummy vararg function to actually hold the values live
1678 Function *Func = cast<Function>(M->getOrInsertFunction(
1679 "__tmp_use", FunctionType::get(Type::getVoidTy(M->getContext()), true)));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001680 if (CS.isCall()) {
1681 // For call safepoints insert dummy calls right after safepoint
Philip Reamesf209a152015-04-13 20:00:30 +00001682 BasicBlock::iterator Next(CS.getInstruction());
1683 Next++;
1684 Holders.push_back(CallInst::Create(Func, Values, "", Next));
1685 return;
1686 }
1687 // For invoke safepooints insert dummy calls both in normal and
1688 // exceptional destination blocks
1689 auto *II = cast<InvokeInst>(CS.getInstruction());
1690 Holders.push_back(CallInst::Create(
1691 Func, Values, "", II->getNormalDest()->getFirstInsertionPt()));
1692 Holders.push_back(CallInst::Create(
1693 Func, Values, "", II->getUnwindDest()->getFirstInsertionPt()));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001694}
1695
1696static void findLiveReferences(
Philip Reamesd2b66462015-02-20 22:39:41 +00001697 Function &F, DominatorTree &DT, Pass *P, ArrayRef<CallSite> toUpdate,
1698 MutableArrayRef<struct PartiallyConstructedSafepointRecord> records) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00001699 GCPtrLivenessData OriginalLivenessData;
1700 computeLiveInValues(DT, F, OriginalLivenessData);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001701 for (size_t i = 0; i < records.size(); i++) {
1702 struct PartiallyConstructedSafepointRecord &info = records[i];
Philip Reamesd2b66462015-02-20 22:39:41 +00001703 const CallSite &CS = toUpdate[i];
Philip Reamesdf1ef082015-04-10 22:53:14 +00001704 analyzeParsePointLiveness(DT, OriginalLivenessData, CS, info);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001705 }
1706}
1707
Philip Reames8531d8c2015-04-10 21:48:25 +00001708/// Remove any vector of pointers from the liveset by scalarizing them over the
1709/// statepoint instruction. Adds the scalarized pieces to the liveset. It
1710/// would be preferrable to include the vector in the statepoint itself, but
1711/// the lowering code currently does not handle that. Extending it would be
1712/// slightly non-trivial since it requires a format change. Given how rare
1713/// such cases are (for the moment?) scalarizing is an acceptable comprimise.
1714static void splitVectorValues(Instruction *StatepointInst,
Philip Reames704e78b2015-04-10 22:34:56 +00001715 StatepointLiveSetTy &LiveSet, DominatorTree &DT) {
Philip Reames8531d8c2015-04-10 21:48:25 +00001716 SmallVector<Value *, 16> ToSplit;
1717 for (Value *V : LiveSet)
1718 if (isa<VectorType>(V->getType()))
1719 ToSplit.push_back(V);
1720
1721 if (ToSplit.empty())
1722 return;
1723
1724 Function &F = *(StatepointInst->getParent()->getParent());
1725
Philip Reames704e78b2015-04-10 22:34:56 +00001726 DenseMap<Value *, AllocaInst *> AllocaMap;
Philip Reames8531d8c2015-04-10 21:48:25 +00001727 // First is normal return, second is exceptional return (invoke only)
Philip Reames704e78b2015-04-10 22:34:56 +00001728 DenseMap<Value *, std::pair<Value *, Value *>> Replacements;
Philip Reames8531d8c2015-04-10 21:48:25 +00001729 for (Value *V : ToSplit) {
1730 LiveSet.erase(V);
1731
Philip Reames704e78b2015-04-10 22:34:56 +00001732 AllocaInst *Alloca =
1733 new AllocaInst(V->getType(), "", F.getEntryBlock().getFirstNonPHI());
Philip Reames8531d8c2015-04-10 21:48:25 +00001734 AllocaMap[V] = Alloca;
1735
1736 VectorType *VT = cast<VectorType>(V->getType());
1737 IRBuilder<> Builder(StatepointInst);
Philip Reames704e78b2015-04-10 22:34:56 +00001738 SmallVector<Value *, 16> Elements;
Philip Reames8531d8c2015-04-10 21:48:25 +00001739 for (unsigned i = 0; i < VT->getNumElements(); i++)
1740 Elements.push_back(Builder.CreateExtractElement(V, Builder.getInt32(i)));
1741 LiveSet.insert(Elements.begin(), Elements.end());
1742
1743 auto InsertVectorReform = [&](Instruction *IP) {
1744 Builder.SetInsertPoint(IP);
1745 Builder.SetCurrentDebugLocation(IP->getDebugLoc());
1746 Value *ResultVec = UndefValue::get(VT);
1747 for (unsigned i = 0; i < VT->getNumElements(); i++)
1748 ResultVec = Builder.CreateInsertElement(ResultVec, Elements[i],
1749 Builder.getInt32(i));
1750 return ResultVec;
1751 };
1752
1753 if (isa<CallInst>(StatepointInst)) {
1754 BasicBlock::iterator Next(StatepointInst);
1755 Next++;
1756 Instruction *IP = &*(Next);
1757 Replacements[V].first = InsertVectorReform(IP);
1758 Replacements[V].second = nullptr;
1759 } else {
1760 InvokeInst *Invoke = cast<InvokeInst>(StatepointInst);
1761 // We've already normalized - check that we don't have shared destination
Philip Reames704e78b2015-04-10 22:34:56 +00001762 // blocks
Philip Reames8531d8c2015-04-10 21:48:25 +00001763 BasicBlock *NormalDest = Invoke->getNormalDest();
1764 assert(!isa<PHINode>(NormalDest->begin()));
1765 BasicBlock *UnwindDest = Invoke->getUnwindDest();
1766 assert(!isa<PHINode>(UnwindDest->begin()));
1767 // Insert insert element sequences in both successors
1768 Instruction *IP = &*(NormalDest->getFirstInsertionPt());
1769 Replacements[V].first = InsertVectorReform(IP);
1770 IP = &*(UnwindDest->getFirstInsertionPt());
1771 Replacements[V].second = InsertVectorReform(IP);
1772 }
1773 }
1774 for (Value *V : ToSplit) {
1775 AllocaInst *Alloca = AllocaMap[V];
1776
1777 // Capture all users before we start mutating use lists
Philip Reames704e78b2015-04-10 22:34:56 +00001778 SmallVector<Instruction *, 16> Users;
Philip Reames8531d8c2015-04-10 21:48:25 +00001779 for (User *U : V->users())
1780 Users.push_back(cast<Instruction>(U));
1781
1782 for (Instruction *I : Users) {
1783 if (auto Phi = dyn_cast<PHINode>(I)) {
1784 for (unsigned i = 0; i < Phi->getNumIncomingValues(); i++)
1785 if (V == Phi->getIncomingValue(i)) {
Philip Reames704e78b2015-04-10 22:34:56 +00001786 LoadInst *Load = new LoadInst(
1787 Alloca, "", Phi->getIncomingBlock(i)->getTerminator());
Philip Reames8531d8c2015-04-10 21:48:25 +00001788 Phi->setIncomingValue(i, Load);
1789 }
1790 } else {
1791 LoadInst *Load = new LoadInst(Alloca, "", I);
1792 I->replaceUsesOfWith(V, Load);
1793 }
1794 }
1795
1796 // Store the original value and the replacement value into the alloca
1797 StoreInst *Store = new StoreInst(V, Alloca);
1798 if (auto I = dyn_cast<Instruction>(V))
1799 Store->insertAfter(I);
1800 else
1801 Store->insertAfter(Alloca);
Philip Reames704e78b2015-04-10 22:34:56 +00001802
Philip Reames8531d8c2015-04-10 21:48:25 +00001803 // Normal return for invoke, or call return
1804 Instruction *Replacement = cast<Instruction>(Replacements[V].first);
1805 (new StoreInst(Replacement, Alloca))->insertAfter(Replacement);
1806 // Unwind return for invoke only
1807 Replacement = cast_or_null<Instruction>(Replacements[V].second);
1808 if (Replacement)
1809 (new StoreInst(Replacement, Alloca))->insertAfter(Replacement);
1810 }
1811
1812 // apply mem2reg to promote alloca to SSA
Philip Reames704e78b2015-04-10 22:34:56 +00001813 SmallVector<AllocaInst *, 16> Allocas;
Philip Reames8531d8c2015-04-10 21:48:25 +00001814 for (Value *V : ToSplit)
1815 Allocas.push_back(AllocaMap[V]);
1816 PromoteMemToReg(Allocas, DT);
1817}
1818
Igor Laevskye0317182015-05-19 15:59:05 +00001819// Helper function for the "rematerializeLiveValues". It walks use chain
1820// starting from the "CurrentValue" until it meets "BaseValue". Only "simple"
1821// values are visited (currently it is GEP's and casts). Returns true if it
1822// sucessfully reached "BaseValue" and false otherwise.
1823// Fills "ChainToBase" array with all visited values. "BaseValue" is not
1824// recorded.
1825static bool findRematerializableChainToBasePointer(
1826 SmallVectorImpl<Instruction*> &ChainToBase,
1827 Value *CurrentValue, Value *BaseValue) {
1828
1829 // We have found a base value
1830 if (CurrentValue == BaseValue) {
1831 return true;
1832 }
1833
1834 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurrentValue)) {
1835 ChainToBase.push_back(GEP);
1836 return findRematerializableChainToBasePointer(ChainToBase,
1837 GEP->getPointerOperand(),
1838 BaseValue);
1839 }
1840
1841 if (CastInst *CI = dyn_cast<CastInst>(CurrentValue)) {
1842 Value *Def = CI->stripPointerCasts();
1843
1844 // This two checks are basically similar. First one is here for the
1845 // consistency with findBasePointers logic.
1846 assert(!isa<CastInst>(Def) && "not a pointer cast found");
1847 if (!CI->isNoopCast(CI->getModule()->getDataLayout()))
1848 return false;
1849
1850 ChainToBase.push_back(CI);
1851 return findRematerializableChainToBasePointer(ChainToBase, Def, BaseValue);
1852 }
1853
1854 // Not supported instruction in the chain
1855 return false;
1856}
1857
1858// Helper function for the "rematerializeLiveValues". Compute cost of the use
1859// chain we are going to rematerialize.
1860static unsigned
1861chainToBasePointerCost(SmallVectorImpl<Instruction*> &Chain,
1862 TargetTransformInfo &TTI) {
1863 unsigned Cost = 0;
1864
1865 for (Instruction *Instr : Chain) {
1866 if (CastInst *CI = dyn_cast<CastInst>(Instr)) {
1867 assert(CI->isNoopCast(CI->getModule()->getDataLayout()) &&
1868 "non noop cast is found during rematerialization");
1869
1870 Type *SrcTy = CI->getOperand(0)->getType();
1871 Cost += TTI.getCastInstrCost(CI->getOpcode(), CI->getType(), SrcTy);
1872
1873 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Instr)) {
1874 // Cost of the address calculation
1875 Type *ValTy = GEP->getPointerOperandType()->getPointerElementType();
1876 Cost += TTI.getAddressComputationCost(ValTy);
1877
1878 // And cost of the GEP itself
1879 // TODO: Use TTI->getGEPCost here (it exists, but appears to be not
1880 // allowed for the external usage)
1881 if (!GEP->hasAllConstantIndices())
1882 Cost += 2;
1883
1884 } else {
1885 llvm_unreachable("unsupported instruciton type during rematerialization");
1886 }
1887 }
1888
1889 return Cost;
1890}
1891
1892// From the statepoint liveset pick values that are cheaper to recompute then to
1893// relocate. Remove this values from the liveset, rematerialize them after
1894// statepoint and record them in "Info" structure. Note that similar to
1895// relocated values we don't do any user adjustments here.
1896static void rematerializeLiveValues(CallSite CS,
1897 PartiallyConstructedSafepointRecord &Info,
1898 TargetTransformInfo &TTI) {
Aaron Ballmanff7d4fa2015-05-20 14:53:50 +00001899 const unsigned int ChainLengthThreshold = 10;
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +00001900
Igor Laevskye0317182015-05-19 15:59:05 +00001901 // Record values we are going to delete from this statepoint live set.
1902 // We can not di this in following loop due to iterator invalidation.
1903 SmallVector<Value *, 32> LiveValuesToBeDeleted;
1904
1905 for (Value *LiveValue: Info.liveset) {
1906 // For each live pointer find it's defining chain
1907 SmallVector<Instruction *, 3> ChainToBase;
1908 assert(Info.PointerToBase.find(LiveValue) != Info.PointerToBase.end());
1909 bool FoundChain =
1910 findRematerializableChainToBasePointer(ChainToBase,
1911 LiveValue,
1912 Info.PointerToBase[LiveValue]);
1913 // Nothing to do, or chain is too long
1914 if (!FoundChain ||
1915 ChainToBase.size() == 0 ||
1916 ChainToBase.size() > ChainLengthThreshold)
1917 continue;
1918
1919 // Compute cost of this chain
1920 unsigned Cost = chainToBasePointerCost(ChainToBase, TTI);
1921 // TODO: We can also account for cases when we will be able to remove some
1922 // of the rematerialized values by later optimization passes. I.e if
1923 // we rematerialized several intersecting chains. Or if original values
1924 // don't have any uses besides this statepoint.
1925
1926 // For invokes we need to rematerialize each chain twice - for normal and
1927 // for unwind basic blocks. Model this by multiplying cost by two.
1928 if (CS.isInvoke()) {
1929 Cost *= 2;
1930 }
1931 // If it's too expensive - skip it
1932 if (Cost >= RematerializationThreshold)
1933 continue;
1934
1935 // Remove value from the live set
1936 LiveValuesToBeDeleted.push_back(LiveValue);
1937
1938 // Clone instructions and record them inside "Info" structure
1939
1940 // Walk backwards to visit top-most instructions first
1941 std::reverse(ChainToBase.begin(), ChainToBase.end());
1942
1943 // Utility function which clones all instructions from "ChainToBase"
1944 // and inserts them before "InsertBefore". Returns rematerialized value
1945 // which should be used after statepoint.
1946 auto rematerializeChain = [&ChainToBase](Instruction *InsertBefore) {
1947 Instruction *LastClonedValue = nullptr;
1948 Instruction *LastValue = nullptr;
1949 for (Instruction *Instr: ChainToBase) {
1950 // Only GEP's and casts are suported as we need to be careful to not
1951 // introduce any new uses of pointers not in the liveset.
1952 // Note that it's fine to introduce new uses of pointers which were
1953 // otherwise not used after this statepoint.
1954 assert(isa<GetElementPtrInst>(Instr) || isa<CastInst>(Instr));
1955
1956 Instruction *ClonedValue = Instr->clone();
1957 ClonedValue->insertBefore(InsertBefore);
1958 ClonedValue->setName(Instr->getName() + ".remat");
1959
1960 // If it is not first instruction in the chain then it uses previously
1961 // cloned value. We should update it to use cloned value.
1962 if (LastClonedValue) {
1963 assert(LastValue);
1964 ClonedValue->replaceUsesOfWith(LastValue, LastClonedValue);
1965#ifndef NDEBUG
Igor Laevskyd83f6972015-05-21 13:02:14 +00001966 // Assert that cloned instruction does not use any instructions from
1967 // this chain other than LastClonedValue
1968 for (auto OpValue : ClonedValue->operand_values()) {
1969 assert(std::find(ChainToBase.begin(), ChainToBase.end(), OpValue) ==
1970 ChainToBase.end() &&
1971 "incorrect use in rematerialization chain");
Igor Laevskye0317182015-05-19 15:59:05 +00001972 }
1973#endif
1974 }
1975
1976 LastClonedValue = ClonedValue;
1977 LastValue = Instr;
1978 }
1979 assert(LastClonedValue);
1980 return LastClonedValue;
1981 };
1982
1983 // Different cases for calls and invokes. For invokes we need to clone
1984 // instructions both on normal and unwind path.
1985 if (CS.isCall()) {
1986 Instruction *InsertBefore = CS.getInstruction()->getNextNode();
1987 assert(InsertBefore);
1988 Instruction *RematerializedValue = rematerializeChain(InsertBefore);
1989 Info.RematerializedValues[RematerializedValue] = LiveValue;
1990 } else {
1991 InvokeInst *Invoke = cast<InvokeInst>(CS.getInstruction());
1992
1993 Instruction *NormalInsertBefore =
1994 Invoke->getNormalDest()->getFirstInsertionPt();
1995 Instruction *UnwindInsertBefore =
1996 Invoke->getUnwindDest()->getFirstInsertionPt();
1997
1998 Instruction *NormalRematerializedValue =
1999 rematerializeChain(NormalInsertBefore);
2000 Instruction *UnwindRematerializedValue =
2001 rematerializeChain(UnwindInsertBefore);
2002
2003 Info.RematerializedValues[NormalRematerializedValue] = LiveValue;
2004 Info.RematerializedValues[UnwindRematerializedValue] = LiveValue;
2005 }
2006 }
2007
2008 // Remove rematerializaed values from the live set
2009 for (auto LiveValue: LiveValuesToBeDeleted) {
2010 Info.liveset.erase(LiveValue);
2011 }
2012}
2013
Philip Reamesd16a9b12015-02-20 01:06:44 +00002014static bool insertParsePoints(Function &F, DominatorTree &DT, Pass *P,
Philip Reamesd2b66462015-02-20 22:39:41 +00002015 SmallVectorImpl<CallSite> &toUpdate) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00002016#ifndef NDEBUG
2017 // sanity check the input
2018 std::set<CallSite> uniqued;
2019 uniqued.insert(toUpdate.begin(), toUpdate.end());
2020 assert(uniqued.size() == toUpdate.size() && "no duplicates please!");
2021
2022 for (size_t i = 0; i < toUpdate.size(); i++) {
2023 CallSite &CS = toUpdate[i];
2024 assert(CS.getInstruction()->getParent()->getParent() == &F);
2025 assert(isStatepoint(CS) && "expected to already be a deopt statepoint");
2026 }
2027#endif
2028
Philip Reames69e51ca2015-04-13 18:07:21 +00002029 // When inserting gc.relocates for invokes, we need to be able to insert at
2030 // the top of the successor blocks. See the comment on
2031 // normalForInvokeSafepoint on exactly what is needed. Note that this step
Philip Reamesf209a152015-04-13 20:00:30 +00002032 // may restructure the CFG.
2033 for (CallSite CS : toUpdate) {
2034 if (!CS.isInvoke())
2035 continue;
2036 InvokeInst *invoke = cast<InvokeInst>(CS.getInstruction());
2037 normalizeForInvokeSafepoint(invoke->getNormalDest(), invoke->getParent(),
Sanjoy Dasea45f0e2015-06-02 22:33:34 +00002038 DT);
Philip Reamesf209a152015-04-13 20:00:30 +00002039 normalizeForInvokeSafepoint(invoke->getUnwindDest(), invoke->getParent(),
Sanjoy Dasea45f0e2015-06-02 22:33:34 +00002040 DT);
Philip Reamesf209a152015-04-13 20:00:30 +00002041 }
Philip Reames69e51ca2015-04-13 18:07:21 +00002042
Philip Reamesd16a9b12015-02-20 01:06:44 +00002043 // A list of dummy calls added to the IR to keep various values obviously
2044 // live in the IR. We'll remove all of these when done.
Philip Reamesd2b66462015-02-20 22:39:41 +00002045 SmallVector<CallInst *, 64> holders;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002046
2047 // Insert a dummy call with all of the arguments to the vm_state we'll need
2048 // for the actual safepoint insertion. This ensures reference arguments in
2049 // the deopt argument list are considered live through the safepoint (and
2050 // thus makes sure they get relocated.)
2051 for (size_t i = 0; i < toUpdate.size(); i++) {
2052 CallSite &CS = toUpdate[i];
2053 Statepoint StatepointCS(CS);
2054
2055 SmallVector<Value *, 64> DeoptValues;
2056 for (Use &U : StatepointCS.vm_state_args()) {
2057 Value *Arg = cast<Value>(&U);
Philip Reames8531d8c2015-04-10 21:48:25 +00002058 assert(!isUnhandledGCPointerType(Arg->getType()) &&
2059 "support for FCA unimplemented");
2060 if (isHandledGCPointerType(Arg->getType()))
Philip Reamesd16a9b12015-02-20 01:06:44 +00002061 DeoptValues.push_back(Arg);
2062 }
2063 insertUseHolderAfter(CS, DeoptValues, holders);
2064 }
2065
Philip Reamesd2b66462015-02-20 22:39:41 +00002066 SmallVector<struct PartiallyConstructedSafepointRecord, 64> records;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002067 records.reserve(toUpdate.size());
2068 for (size_t i = 0; i < toUpdate.size(); i++) {
2069 struct PartiallyConstructedSafepointRecord info;
2070 records.push_back(info);
2071 }
2072 assert(records.size() == toUpdate.size());
2073
2074 // A) Identify all gc pointers which are staticly live at the given call
2075 // site.
2076 findLiveReferences(F, DT, P, toUpdate, records);
2077
Philip Reames8531d8c2015-04-10 21:48:25 +00002078 // Do a limited scalarization of any live at safepoint vector values which
2079 // contain pointers. This enables this pass to run after vectorization at
2080 // the cost of some possible performance loss. TODO: it would be nice to
2081 // natively support vectors all the way through the backend so we don't need
2082 // to scalarize here.
2083 for (size_t i = 0; i < records.size(); i++) {
2084 struct PartiallyConstructedSafepointRecord &info = records[i];
2085 Instruction *statepoint = toUpdate[i].getInstruction();
2086 splitVectorValues(cast<Instruction>(statepoint), info.liveset, DT);
2087 }
2088
Philip Reamesd16a9b12015-02-20 01:06:44 +00002089 // B) Find the base pointers for each live pointer
2090 /* scope for caching */ {
2091 // Cache the 'defining value' relation used in the computation and
2092 // insertion of base phis and selects. This ensures that we don't insert
2093 // large numbers of duplicate base_phis.
2094 DefiningValueMapTy DVCache;
2095
2096 for (size_t i = 0; i < records.size(); i++) {
2097 struct PartiallyConstructedSafepointRecord &info = records[i];
2098 CallSite &CS = toUpdate[i];
2099 findBasePointers(DT, DVCache, CS, info);
2100 }
2101 } // end of cache scope
2102
2103 // The base phi insertion logic (for any safepoint) may have inserted new
2104 // instructions which are now live at some safepoint. The simplest such
2105 // example is:
2106 // loop:
2107 // phi a <-- will be a new base_phi here
2108 // safepoint 1 <-- that needs to be live here
2109 // gep a + 1
2110 // safepoint 2
2111 // br loop
Philip Reamesd16a9b12015-02-20 01:06:44 +00002112 // We insert some dummy calls after each safepoint to definitely hold live
2113 // the base pointers which were identified for that safepoint. We'll then
2114 // ask liveness for _every_ base inserted to see what is now live. Then we
2115 // remove the dummy calls.
2116 holders.reserve(holders.size() + records.size());
2117 for (size_t i = 0; i < records.size(); i++) {
2118 struct PartiallyConstructedSafepointRecord &info = records[i];
2119 CallSite &CS = toUpdate[i];
2120
2121 SmallVector<Value *, 128> Bases;
Philip Reamesf2041322015-02-20 19:26:04 +00002122 for (auto Pair : info.PointerToBase) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00002123 Bases.push_back(Pair.second);
2124 }
2125 insertUseHolderAfter(CS, Bases, holders);
2126 }
2127
Philip Reamesdf1ef082015-04-10 22:53:14 +00002128 // By selecting base pointers, we've effectively inserted new uses. Thus, we
2129 // need to rerun liveness. We may *also* have inserted new defs, but that's
2130 // not the key issue.
2131 recomputeLiveInValues(F, DT, P, toUpdate, records);
Philip Reamesd16a9b12015-02-20 01:06:44 +00002132
Philip Reamesd16a9b12015-02-20 01:06:44 +00002133 if (PrintBasePointers) {
2134 for (size_t i = 0; i < records.size(); i++) {
2135 struct PartiallyConstructedSafepointRecord &info = records[i];
2136 errs() << "Base Pairs: (w/Relocation)\n";
Philip Reamesf2041322015-02-20 19:26:04 +00002137 for (auto Pair : info.PointerToBase) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00002138 errs() << " derived %" << Pair.first->getName() << " base %"
2139 << Pair.second->getName() << "\n";
2140 }
2141 }
2142 }
2143 for (size_t i = 0; i < holders.size(); i++) {
2144 holders[i]->eraseFromParent();
2145 holders[i] = nullptr;
2146 }
2147 holders.clear();
2148
Igor Laevskye0317182015-05-19 15:59:05 +00002149 // In order to reduce live set of statepoint we might choose to rematerialize
2150 // some values instead of relocating them. This is purelly an optimization and
2151 // does not influence correctness.
2152 TargetTransformInfo &TTI =
2153 P->getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
2154
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +00002155 for (size_t i = 0; i < records.size(); i++) {
Igor Laevskye0317182015-05-19 15:59:05 +00002156 struct PartiallyConstructedSafepointRecord &info = records[i];
2157 CallSite &CS = toUpdate[i];
2158
2159 rematerializeLiveValues(CS, info, TTI);
2160 }
2161
Philip Reamesd16a9b12015-02-20 01:06:44 +00002162 // Now run through and replace the existing statepoints with new ones with
2163 // the live variables listed. We do not yet update uses of the values being
2164 // relocated. We have references to live variables that need to
2165 // survive to the last iteration of this loop. (By construction, the
2166 // previous statepoint can not be a live variable, thus we can and remove
2167 // the old statepoint calls as we go.)
2168 for (size_t i = 0; i < records.size(); i++) {
2169 struct PartiallyConstructedSafepointRecord &info = records[i];
2170 CallSite &CS = toUpdate[i];
2171 makeStatepointExplicit(DT, CS, P, info);
2172 }
2173 toUpdate.clear(); // prevent accident use of invalid CallSites
2174
Philip Reamesd16a9b12015-02-20 01:06:44 +00002175 // Do all the fixups of the original live variables to their relocated selves
Philip Reamesd2b66462015-02-20 22:39:41 +00002176 SmallVector<Value *, 128> live;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002177 for (size_t i = 0; i < records.size(); i++) {
2178 struct PartiallyConstructedSafepointRecord &info = records[i];
2179 // We can't simply save the live set from the original insertion. One of
2180 // the live values might be the result of a call which needs a safepoint.
2181 // That Value* no longer exists and we need to use the new gc_result.
2182 // Thankfully, the liveset is embedded in the statepoint (and updated), so
2183 // we just grab that.
Philip Reames0a3240f2015-02-20 21:34:11 +00002184 Statepoint statepoint(info.StatepointToken);
Philip Reamesd16a9b12015-02-20 01:06:44 +00002185 live.insert(live.end(), statepoint.gc_args_begin(),
2186 statepoint.gc_args_end());
Philip Reames9a2e01d2015-04-13 17:35:55 +00002187#ifndef NDEBUG
2188 // Do some basic sanity checks on our liveness results before performing
2189 // relocation. Relocation can and will turn mistakes in liveness results
2190 // into non-sensical code which is must harder to debug.
2191 // TODO: It would be nice to test consistency as well
2192 assert(DT.isReachableFromEntry(info.StatepointToken->getParent()) &&
2193 "statepoint must be reachable or liveness is meaningless");
2194 for (Value *V : statepoint.gc_args()) {
2195 if (!isa<Instruction>(V))
2196 // Non-instruction values trivial dominate all possible uses
2197 continue;
2198 auto LiveInst = cast<Instruction>(V);
2199 assert(DT.isReachableFromEntry(LiveInst->getParent()) &&
2200 "unreachable values should never be live");
2201 assert(DT.dominates(LiveInst, info.StatepointToken) &&
2202 "basic SSA liveness expectation violated by liveness analysis");
2203 }
2204#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +00002205 }
2206 unique_unsorted(live);
2207
Nick Lewyckyeb3231e2015-02-20 07:14:02 +00002208#ifndef NDEBUG
Philip Reamesd16a9b12015-02-20 01:06:44 +00002209 // sanity check
2210 for (auto ptr : live) {
2211 assert(isGCPointerType(ptr->getType()) && "must be a gc pointer type");
2212 }
Nick Lewyckyeb3231e2015-02-20 07:14:02 +00002213#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +00002214
2215 relocationViaAlloca(F, DT, live, records);
2216 return !records.empty();
2217}
2218
Sanjoy Das353a19e2015-06-02 22:33:37 +00002219// Handles both return values and arguments for Functions and CallSites.
2220template <typename AttrHolder>
2221static void RemoveDerefAttrAtIndex(LLVMContext &Ctx, AttrHolder &AH,
2222 unsigned Index) {
2223 AttrBuilder R;
2224 if (AH.getDereferenceableBytes(Index))
2225 R.addAttribute(Attribute::get(Ctx, Attribute::Dereferenceable,
2226 AH.getDereferenceableBytes(Index)));
2227 if (AH.getDereferenceableOrNullBytes(Index))
2228 R.addAttribute(Attribute::get(Ctx, Attribute::DereferenceableOrNull,
2229 AH.getDereferenceableOrNullBytes(Index)));
2230
2231 if (!R.empty())
2232 AH.setAttributes(AH.getAttributes().removeAttributes(
2233 Ctx, Index, AttributeSet::get(Ctx, Index, R)));
Vasileios Kalintiris9f77f612015-06-03 08:51:30 +00002234}
Sanjoy Das353a19e2015-06-02 22:33:37 +00002235
2236void
2237RewriteStatepointsForGC::stripDereferenceabilityInfoFromPrototype(Function &F) {
2238 LLVMContext &Ctx = F.getContext();
2239
2240 for (Argument &A : F.args())
2241 if (isa<PointerType>(A.getType()))
2242 RemoveDerefAttrAtIndex(Ctx, F, A.getArgNo() + 1);
2243
2244 if (isa<PointerType>(F.getReturnType()))
2245 RemoveDerefAttrAtIndex(Ctx, F, AttributeSet::ReturnIndex);
2246}
2247
2248void RewriteStatepointsForGC::stripDereferenceabilityInfoFromBody(Function &F) {
2249 if (F.empty())
2250 return;
2251
2252 LLVMContext &Ctx = F.getContext();
2253 MDBuilder Builder(Ctx);
2254
2255 for (Instruction &I : inst_range(F)) {
2256 if (const MDNode *MD = I.getMetadata(LLVMContext::MD_tbaa)) {
2257 assert(MD->getNumOperands() < 5 && "unrecognized metadata shape!");
2258 bool IsImmutableTBAA =
2259 MD->getNumOperands() == 4 &&
2260 mdconst::extract<ConstantInt>(MD->getOperand(3))->getValue() == 1;
2261
2262 if (!IsImmutableTBAA)
2263 continue; // no work to do, MD_tbaa is already marked mutable
2264
2265 MDNode *Base = cast<MDNode>(MD->getOperand(0));
2266 MDNode *Access = cast<MDNode>(MD->getOperand(1));
2267 uint64_t Offset =
2268 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue();
2269
2270 MDNode *MutableTBAA =
2271 Builder.createTBAAStructTagNode(Base, Access, Offset);
2272 I.setMetadata(LLVMContext::MD_tbaa, MutableTBAA);
2273 }
2274
2275 if (CallSite CS = CallSite(&I)) {
2276 for (int i = 0, e = CS.arg_size(); i != e; i++)
2277 if (isa<PointerType>(CS.getArgument(i)->getType()))
2278 RemoveDerefAttrAtIndex(Ctx, CS, i + 1);
2279 if (isa<PointerType>(CS.getType()))
2280 RemoveDerefAttrAtIndex(Ctx, CS, AttributeSet::ReturnIndex);
2281 }
2282 }
2283}
2284
Philip Reamesd16a9b12015-02-20 01:06:44 +00002285/// Returns true if this function should be rewritten by this pass. The main
2286/// point of this function is as an extension point for custom logic.
2287static bool shouldRewriteStatepointsIn(Function &F) {
2288 // TODO: This should check the GCStrategy
Philip Reames2ef029c2015-02-20 18:56:14 +00002289 if (F.hasGC()) {
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +00002290 const char *FunctionGCName = F.getGC();
2291 const StringRef StatepointExampleName("statepoint-example");
2292 const StringRef CoreCLRName("coreclr");
2293 return (StatepointExampleName == FunctionGCName) ||
NAKAMURA Takumi5582a6a2015-05-25 01:43:34 +00002294 (CoreCLRName == FunctionGCName);
2295 } else
Philip Reames2ef029c2015-02-20 18:56:14 +00002296 return false;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002297}
2298
Sanjoy Das353a19e2015-06-02 22:33:37 +00002299void RewriteStatepointsForGC::stripDereferenceabilityInfo(Module &M) {
2300#ifndef NDEBUG
2301 assert(std::any_of(M.begin(), M.end(), shouldRewriteStatepointsIn) &&
2302 "precondition!");
2303#endif
2304
2305 for (Function &F : M)
2306 stripDereferenceabilityInfoFromPrototype(F);
2307
2308 for (Function &F : M)
2309 stripDereferenceabilityInfoFromBody(F);
2310}
2311
Philip Reamesd16a9b12015-02-20 01:06:44 +00002312bool RewriteStatepointsForGC::runOnFunction(Function &F) {
2313 // Nothing to do for declarations.
2314 if (F.isDeclaration() || F.empty())
2315 return false;
2316
2317 // Policy choice says not to rewrite - the most common reason is that we're
2318 // compiling code without a GCStrategy.
2319 if (!shouldRewriteStatepointsIn(F))
2320 return false;
2321
Sanjoy Dasea45f0e2015-06-02 22:33:34 +00002322 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
Philip Reames704e78b2015-04-10 22:34:56 +00002323
Philip Reames85b36a82015-04-10 22:07:04 +00002324 // Gather all the statepoints which need rewritten. Be careful to only
2325 // consider those in reachable code since we need to ask dominance queries
2326 // when rewriting. We'll delete the unreachable ones in a moment.
Philip Reamesd2b66462015-02-20 22:39:41 +00002327 SmallVector<CallSite, 64> ParsePointNeeded;
Philip Reamesf66d7372015-04-10 22:16:58 +00002328 bool HasUnreachableStatepoint = false;
Philip Reamesd2b66462015-02-20 22:39:41 +00002329 for (Instruction &I : inst_range(F)) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00002330 // TODO: only the ones with the flag set!
Philip Reames85b36a82015-04-10 22:07:04 +00002331 if (isStatepoint(I)) {
2332 if (DT.isReachableFromEntry(I.getParent()))
2333 ParsePointNeeded.push_back(CallSite(&I));
2334 else
Philip Reamesf66d7372015-04-10 22:16:58 +00002335 HasUnreachableStatepoint = true;
Philip Reames85b36a82015-04-10 22:07:04 +00002336 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00002337 }
2338
Philip Reames85b36a82015-04-10 22:07:04 +00002339 bool MadeChange = false;
Philip Reames704e78b2015-04-10 22:34:56 +00002340
Philip Reames85b36a82015-04-10 22:07:04 +00002341 // Delete any unreachable statepoints so that we don't have unrewritten
2342 // statepoints surviving this pass. This makes testing easier and the
2343 // resulting IR less confusing to human readers. Rather than be fancy, we
2344 // just reuse a utility function which removes the unreachable blocks.
Philip Reamesf66d7372015-04-10 22:16:58 +00002345 if (HasUnreachableStatepoint)
Philip Reames85b36a82015-04-10 22:07:04 +00002346 MadeChange |= removeUnreachableBlocks(F);
2347
Philip Reamesd16a9b12015-02-20 01:06:44 +00002348 // Return early if no work to do.
2349 if (ParsePointNeeded.empty())
Philip Reames85b36a82015-04-10 22:07:04 +00002350 return MadeChange;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002351
Philip Reames85b36a82015-04-10 22:07:04 +00002352 // As a prepass, go ahead and aggressively destroy single entry phi nodes.
2353 // These are created by LCSSA. They have the effect of increasing the size
2354 // of liveness sets for no good reason. It may be harder to do this post
2355 // insertion since relocations and base phis can confuse things.
2356 for (BasicBlock &BB : F)
2357 if (BB.getUniquePredecessor()) {
2358 MadeChange = true;
2359 FoldSingleEntryPHINodes(&BB);
2360 }
2361
2362 MadeChange |= insertParsePoints(F, DT, this, ParsePointNeeded);
2363 return MadeChange;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002364}
Philip Reamesdf1ef082015-04-10 22:53:14 +00002365
2366// liveness computation via standard dataflow
2367// -------------------------------------------------------------------
2368
2369// TODO: Consider using bitvectors for liveness, the set of potentially
2370// interesting values should be small and easy to pre-compute.
2371
Philip Reamesdf1ef082015-04-10 22:53:14 +00002372/// Compute the live-in set for the location rbegin starting from
2373/// the live-out set of the basic block
2374static void computeLiveInValues(BasicBlock::reverse_iterator rbegin,
2375 BasicBlock::reverse_iterator rend,
2376 DenseSet<Value *> &LiveTmp) {
2377
2378 for (BasicBlock::reverse_iterator ritr = rbegin; ritr != rend; ritr++) {
2379 Instruction *I = &*ritr;
2380
2381 // KILL/Def - Remove this definition from LiveIn
2382 LiveTmp.erase(I);
2383
2384 // Don't consider *uses* in PHI nodes, we handle their contribution to
2385 // predecessor blocks when we seed the LiveOut sets
2386 if (isa<PHINode>(I))
2387 continue;
2388
2389 // USE - Add to the LiveIn set for this instruction
2390 for (Value *V : I->operands()) {
2391 assert(!isUnhandledGCPointerType(V->getType()) &&
2392 "support for FCA unimplemented");
Philip Reames63294cb2015-04-26 19:48:03 +00002393 if (isHandledGCPointerType(V->getType()) && !isa<Constant>(V)) {
2394 // The choice to exclude all things constant here is slightly subtle.
2395 // There are two idependent reasons:
2396 // - We assume that things which are constant (from LLVM's definition)
2397 // do not move at runtime. For example, the address of a global
2398 // variable is fixed, even though it's contents may not be.
2399 // - Second, we can't disallow arbitrary inttoptr constants even
2400 // if the language frontend does. Optimization passes are free to
2401 // locally exploit facts without respect to global reachability. This
2402 // can create sections of code which are dynamically unreachable and
2403 // contain just about anything. (see constants.ll in tests)
Philip Reamesdf1ef082015-04-10 22:53:14 +00002404 LiveTmp.insert(V);
2405 }
2406 }
2407 }
2408}
2409
2410static void computeLiveOutSeed(BasicBlock *BB, DenseSet<Value *> &LiveTmp) {
2411
2412 for (BasicBlock *Succ : successors(BB)) {
2413 const BasicBlock::iterator E(Succ->getFirstNonPHI());
2414 for (BasicBlock::iterator I = Succ->begin(); I != E; I++) {
2415 PHINode *Phi = cast<PHINode>(&*I);
2416 Value *V = Phi->getIncomingValueForBlock(BB);
2417 assert(!isUnhandledGCPointerType(V->getType()) &&
2418 "support for FCA unimplemented");
Philip Reames63294cb2015-04-26 19:48:03 +00002419 if (isHandledGCPointerType(V->getType()) && !isa<Constant>(V)) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00002420 LiveTmp.insert(V);
2421 }
2422 }
2423 }
2424}
2425
2426static DenseSet<Value *> computeKillSet(BasicBlock *BB) {
2427 DenseSet<Value *> KillSet;
2428 for (Instruction &I : *BB)
2429 if (isHandledGCPointerType(I.getType()))
2430 KillSet.insert(&I);
2431 return KillSet;
2432}
2433
Philip Reames9638ff92015-04-11 00:06:47 +00002434#ifndef NDEBUG
Philip Reamesdf1ef082015-04-10 22:53:14 +00002435/// Check that the items in 'Live' dominate 'TI'. This is used as a basic
2436/// sanity check for the liveness computation.
2437static void checkBasicSSA(DominatorTree &DT, DenseSet<Value *> &Live,
2438 TerminatorInst *TI, bool TermOkay = false) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00002439 for (Value *V : Live) {
2440 if (auto *I = dyn_cast<Instruction>(V)) {
2441 // The terminator can be a member of the LiveOut set. LLVM's definition
2442 // of instruction dominance states that V does not dominate itself. As
2443 // such, we need to special case this to allow it.
2444 if (TermOkay && TI == I)
2445 continue;
2446 assert(DT.dominates(I, TI) &&
2447 "basic SSA liveness expectation violated by liveness analysis");
2448 }
2449 }
Philip Reamesdf1ef082015-04-10 22:53:14 +00002450}
2451
2452/// Check that all the liveness sets used during the computation of liveness
2453/// obey basic SSA properties. This is useful for finding cases where we miss
2454/// a def.
2455static void checkBasicSSA(DominatorTree &DT, GCPtrLivenessData &Data,
2456 BasicBlock &BB) {
2457 checkBasicSSA(DT, Data.LiveSet[&BB], BB.getTerminator());
2458 checkBasicSSA(DT, Data.LiveOut[&BB], BB.getTerminator(), true);
2459 checkBasicSSA(DT, Data.LiveIn[&BB], BB.getTerminator());
2460}
Philip Reames9638ff92015-04-11 00:06:47 +00002461#endif
Philip Reamesdf1ef082015-04-10 22:53:14 +00002462
2463static void computeLiveInValues(DominatorTree &DT, Function &F,
2464 GCPtrLivenessData &Data) {
2465
Philip Reames4d80ede2015-04-10 23:11:26 +00002466 SmallSetVector<BasicBlock *, 200> Worklist;
Philip Reamesdf1ef082015-04-10 22:53:14 +00002467 auto AddPredsToWorklist = [&](BasicBlock *BB) {
Philip Reames4d80ede2015-04-10 23:11:26 +00002468 // We use a SetVector so that we don't have duplicates in the worklist.
2469 Worklist.insert(pred_begin(BB), pred_end(BB));
Philip Reamesdf1ef082015-04-10 22:53:14 +00002470 };
2471 auto NextItem = [&]() {
2472 BasicBlock *BB = Worklist.back();
2473 Worklist.pop_back();
Philip Reamesdf1ef082015-04-10 22:53:14 +00002474 return BB;
2475 };
2476
2477 // Seed the liveness for each individual block
2478 for (BasicBlock &BB : F) {
2479 Data.KillSet[&BB] = computeKillSet(&BB);
2480 Data.LiveSet[&BB].clear();
2481 computeLiveInValues(BB.rbegin(), BB.rend(), Data.LiveSet[&BB]);
2482
2483#ifndef NDEBUG
2484 for (Value *Kill : Data.KillSet[&BB])
2485 assert(!Data.LiveSet[&BB].count(Kill) && "live set contains kill");
2486#endif
2487
2488 Data.LiveOut[&BB] = DenseSet<Value *>();
2489 computeLiveOutSeed(&BB, Data.LiveOut[&BB]);
2490 Data.LiveIn[&BB] = Data.LiveSet[&BB];
2491 set_union(Data.LiveIn[&BB], Data.LiveOut[&BB]);
2492 set_subtract(Data.LiveIn[&BB], Data.KillSet[&BB]);
2493 if (!Data.LiveIn[&BB].empty())
2494 AddPredsToWorklist(&BB);
2495 }
2496
2497 // Propagate that liveness until stable
2498 while (!Worklist.empty()) {
2499 BasicBlock *BB = NextItem();
2500
2501 // Compute our new liveout set, then exit early if it hasn't changed
2502 // despite the contribution of our successor.
2503 DenseSet<Value *> LiveOut = Data.LiveOut[BB];
2504 const auto OldLiveOutSize = LiveOut.size();
2505 for (BasicBlock *Succ : successors(BB)) {
2506 assert(Data.LiveIn.count(Succ));
2507 set_union(LiveOut, Data.LiveIn[Succ]);
2508 }
2509 // assert OutLiveOut is a subset of LiveOut
2510 if (OldLiveOutSize == LiveOut.size()) {
2511 // If the sets are the same size, then we didn't actually add anything
2512 // when unioning our successors LiveIn Thus, the LiveIn of this block
2513 // hasn't changed.
2514 continue;
2515 }
2516 Data.LiveOut[BB] = LiveOut;
2517
2518 // Apply the effects of this basic block
2519 DenseSet<Value *> LiveTmp = LiveOut;
2520 set_union(LiveTmp, Data.LiveSet[BB]);
2521 set_subtract(LiveTmp, Data.KillSet[BB]);
2522
2523 assert(Data.LiveIn.count(BB));
2524 const DenseSet<Value *> &OldLiveIn = Data.LiveIn[BB];
2525 // assert: OldLiveIn is a subset of LiveTmp
2526 if (OldLiveIn.size() != LiveTmp.size()) {
2527 Data.LiveIn[BB] = LiveTmp;
2528 AddPredsToWorklist(BB);
2529 }
2530 } // while( !worklist.empty() )
2531
2532#ifndef NDEBUG
2533 // Sanity check our ouput against SSA properties. This helps catch any
2534 // missing kills during the above iteration.
2535 for (BasicBlock &BB : F) {
2536 checkBasicSSA(DT, Data, BB);
2537 }
2538#endif
2539}
2540
2541static void findLiveSetAtInst(Instruction *Inst, GCPtrLivenessData &Data,
2542 StatepointLiveSetTy &Out) {
2543
2544 BasicBlock *BB = Inst->getParent();
2545
2546 // Note: The copy is intentional and required
2547 assert(Data.LiveOut.count(BB));
2548 DenseSet<Value *> LiveOut = Data.LiveOut[BB];
2549
2550 // We want to handle the statepoint itself oddly. It's
2551 // call result is not live (normal), nor are it's arguments
2552 // (unless they're used again later). This adjustment is
2553 // specifically what we need to relocate
2554 BasicBlock::reverse_iterator rend(Inst);
2555 computeLiveInValues(BB->rbegin(), rend, LiveOut);
2556 LiveOut.erase(Inst);
2557 Out.insert(LiveOut.begin(), LiveOut.end());
2558}
2559
2560static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData,
2561 const CallSite &CS,
2562 PartiallyConstructedSafepointRecord &Info) {
2563 Instruction *Inst = CS.getInstruction();
2564 StatepointLiveSetTy Updated;
2565 findLiveSetAtInst(Inst, RevisedLivenessData, Updated);
2566
2567#ifndef NDEBUG
2568 DenseSet<Value *> Bases;
2569 for (auto KVPair : Info.PointerToBase) {
2570 Bases.insert(KVPair.second);
2571 }
2572#endif
2573 // We may have base pointers which are now live that weren't before. We need
2574 // to update the PointerToBase structure to reflect this.
2575 for (auto V : Updated)
2576 if (!Info.PointerToBase.count(V)) {
2577 assert(Bases.count(V) && "can't find base for unexpected live value");
2578 Info.PointerToBase[V] = V;
2579 continue;
2580 }
2581
2582#ifndef NDEBUG
2583 for (auto V : Updated) {
2584 assert(Info.PointerToBase.count(V) &&
2585 "must be able to find base for live value");
2586 }
2587#endif
2588
2589 // Remove any stale base mappings - this can happen since our liveness is
2590 // more precise then the one inherent in the base pointer analysis
2591 DenseSet<Value *> ToErase;
2592 for (auto KVPair : Info.PointerToBase)
2593 if (!Updated.count(KVPair.first))
2594 ToErase.insert(KVPair.first);
2595 for (auto V : ToErase)
2596 Info.PointerToBase.erase(V);
2597
2598#ifndef NDEBUG
2599 for (auto KVPair : Info.PointerToBase)
2600 assert(Updated.count(KVPair.first) && "record for non-live value");
2601#endif
2602
2603 Info.liveset = Updated;
2604}