blob: 6cf765a8438cec178499355c2449c43aef8e530c [file] [log] [blame]
Philip Reamesd16a9b12015-02-20 01:06:44 +00001//===- RewriteStatepointsForGC.cpp - Make GC relocations explicit ---------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Rewrite an existing set of gc.statepoints such that they make potential
11// relocations performed by the garbage collector explicit in the IR.
12//
13//===----------------------------------------------------------------------===//
14
15#include "llvm/Pass.h"
16#include "llvm/Analysis/CFG.h"
Igor Laevskye0317182015-05-19 15:59:05 +000017#include "llvm/Analysis/TargetTransformInfo.h"
Philip Reamesd16a9b12015-02-20 01:06:44 +000018#include "llvm/ADT/SetOperations.h"
19#include "llvm/ADT/Statistic.h"
20#include "llvm/ADT/DenseSet.h"
Philip Reames4d80ede2015-04-10 23:11:26 +000021#include "llvm/ADT/SetVector.h"
Swaroop Sridhar665bc9c2015-05-20 01:07:23 +000022#include "llvm/ADT/StringRef.h"
Philip Reamesd16a9b12015-02-20 01:06:44 +000023#include "llvm/IR/BasicBlock.h"
24#include "llvm/IR/CallSite.h"
25#include "llvm/IR/Dominators.h"
26#include "llvm/IR/Function.h"
27#include "llvm/IR/IRBuilder.h"
28#include "llvm/IR/InstIterator.h"
29#include "llvm/IR/Instructions.h"
30#include "llvm/IR/Intrinsics.h"
31#include "llvm/IR/IntrinsicInst.h"
32#include "llvm/IR/Module.h"
33#include "llvm/IR/Statepoint.h"
34#include "llvm/IR/Value.h"
35#include "llvm/IR/Verifier.h"
36#include "llvm/Support/Debug.h"
37#include "llvm/Support/CommandLine.h"
38#include "llvm/Transforms/Scalar.h"
39#include "llvm/Transforms/Utils/BasicBlockUtils.h"
40#include "llvm/Transforms/Utils/Cloning.h"
41#include "llvm/Transforms/Utils/Local.h"
42#include "llvm/Transforms/Utils/PromoteMemToReg.h"
43
44#define DEBUG_TYPE "rewrite-statepoints-for-gc"
45
46using namespace llvm;
47
48// Print tracing output
49static cl::opt<bool> TraceLSP("trace-rewrite-statepoints", cl::Hidden,
50 cl::init(false));
51
52// Print the liveset found at the insert location
53static cl::opt<bool> PrintLiveSet("spp-print-liveset", cl::Hidden,
54 cl::init(false));
Philip Reames704e78b2015-04-10 22:34:56 +000055static cl::opt<bool> PrintLiveSetSize("spp-print-liveset-size", cl::Hidden,
56 cl::init(false));
Philip Reamesd16a9b12015-02-20 01:06:44 +000057// Print out the base pointers for debugging
Philip Reames704e78b2015-04-10 22:34:56 +000058static cl::opt<bool> PrintBasePointers("spp-print-base-pointers", cl::Hidden,
59 cl::init(false));
Philip Reamesd16a9b12015-02-20 01:06:44 +000060
Igor Laevskye0317182015-05-19 15:59:05 +000061// Cost threshold measuring when it is profitable to rematerialize value instead
62// of relocating it
63static cl::opt<unsigned>
64RematerializationThreshold("spp-rematerialization-threshold", cl::Hidden,
65 cl::init(6));
66
Philip Reamese73300b2015-04-13 16:41:32 +000067#ifdef XDEBUG
68static bool ClobberNonLive = true;
69#else
70static bool ClobberNonLive = false;
71#endif
72static cl::opt<bool, true> ClobberNonLiveOverride("rs4gc-clobber-non-live",
73 cl::location(ClobberNonLive),
74 cl::Hidden);
75
Benjamin Kramer6f665452015-02-20 14:00:58 +000076namespace {
Philip Reamesd16a9b12015-02-20 01:06:44 +000077struct RewriteStatepointsForGC : public FunctionPass {
78 static char ID; // Pass identification, replacement for typeid
79
80 RewriteStatepointsForGC() : FunctionPass(ID) {
81 initializeRewriteStatepointsForGCPass(*PassRegistry::getPassRegistry());
82 }
83 bool runOnFunction(Function &F) override;
84
85 void getAnalysisUsage(AnalysisUsage &AU) const override {
86 // We add and rewrite a bunch of instructions, but don't really do much
87 // else. We could in theory preserve a lot more analyses here.
88 AU.addRequired<DominatorTreeWrapperPass>();
Igor Laevskye0317182015-05-19 15:59:05 +000089 AU.addRequired<TargetTransformInfoWrapperPass>();
Philip Reamesd16a9b12015-02-20 01:06:44 +000090 }
91};
Benjamin Kramer6f665452015-02-20 14:00:58 +000092} // namespace
Philip Reamesd16a9b12015-02-20 01:06:44 +000093
94char RewriteStatepointsForGC::ID = 0;
95
96FunctionPass *llvm::createRewriteStatepointsForGCPass() {
97 return new RewriteStatepointsForGC();
98}
99
100INITIALIZE_PASS_BEGIN(RewriteStatepointsForGC, "rewrite-statepoints-for-gc",
101 "Make relocations explicit at statepoints", false, false)
102INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
103INITIALIZE_PASS_END(RewriteStatepointsForGC, "rewrite-statepoints-for-gc",
104 "Make relocations explicit at statepoints", false, false)
105
106namespace {
Philip Reamesdf1ef082015-04-10 22:53:14 +0000107struct GCPtrLivenessData {
108 /// Values defined in this block.
109 DenseMap<BasicBlock *, DenseSet<Value *>> KillSet;
110 /// Values used in this block (and thus live); does not included values
111 /// killed within this block.
112 DenseMap<BasicBlock *, DenseSet<Value *>> LiveSet;
113
114 /// Values live into this basic block (i.e. used by any
115 /// instruction in this basic block or ones reachable from here)
116 DenseMap<BasicBlock *, DenseSet<Value *>> LiveIn;
117
118 /// Values live out of this basic block (i.e. live into
119 /// any successor block)
120 DenseMap<BasicBlock *, DenseSet<Value *>> LiveOut;
121};
122
Philip Reamesd16a9b12015-02-20 01:06:44 +0000123// The type of the internal cache used inside the findBasePointers family
124// of functions. From the callers perspective, this is an opaque type and
125// should not be inspected.
126//
127// In the actual implementation this caches two relations:
128// - The base relation itself (i.e. this pointer is based on that one)
129// - The base defining value relation (i.e. before base_phi insertion)
130// Generally, after the execution of a full findBasePointer call, only the
131// base relation will remain. Internally, we add a mixture of the two
132// types, then update all the second type to the first type
Philip Reamese9c3b9b2015-02-20 22:48:20 +0000133typedef DenseMap<Value *, Value *> DefiningValueMapTy;
Philip Reames1f017542015-02-20 23:16:52 +0000134typedef DenseSet<llvm::Value *> StatepointLiveSetTy;
Igor Laevskye0317182015-05-19 15:59:05 +0000135typedef DenseMap<Instruction *, Value *> RematerializedValueMapTy;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000136
Philip Reamesd16a9b12015-02-20 01:06:44 +0000137struct PartiallyConstructedSafepointRecord {
138 /// The set of values known to be live accross this safepoint
Philip Reames860660e2015-02-20 22:05:18 +0000139 StatepointLiveSetTy liveset;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000140
141 /// Mapping from live pointers to a base-defining-value
Philip Reamesf2041322015-02-20 19:26:04 +0000142 DenseMap<llvm::Value *, llvm::Value *> PointerToBase;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000143
Philip Reames0a3240f2015-02-20 21:34:11 +0000144 /// The *new* gc.statepoint instruction itself. This produces the token
145 /// that normal path gc.relocates and the gc.result are tied to.
146 Instruction *StatepointToken;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000147
Philip Reamesf2041322015-02-20 19:26:04 +0000148 /// Instruction to which exceptional gc relocates are attached
149 /// Makes it easier to iterate through them during relocationViaAlloca.
150 Instruction *UnwindToken;
Igor Laevskye0317182015-05-19 15:59:05 +0000151
152 /// Record live values we are rematerialized instead of relocating.
153 /// They are not included into 'liveset' field.
154 /// Maps rematerialized copy to it's original value.
155 RematerializedValueMapTy RematerializedValues;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000156};
157}
158
Philip Reamesdf1ef082015-04-10 22:53:14 +0000159/// Compute the live-in set for every basic block in the function
160static void computeLiveInValues(DominatorTree &DT, Function &F,
161 GCPtrLivenessData &Data);
162
163/// Given results from the dataflow liveness computation, find the set of live
164/// Values at a particular instruction.
165static void findLiveSetAtInst(Instruction *inst, GCPtrLivenessData &Data,
166 StatepointLiveSetTy &out);
167
Philip Reamesd16a9b12015-02-20 01:06:44 +0000168// TODO: Once we can get to the GCStrategy, this becomes
169// Optional<bool> isGCManagedPointer(const Value *V) const override {
170
171static bool isGCPointerType(const Type *T) {
172 if (const PointerType *PT = dyn_cast<PointerType>(T))
173 // For the sake of this example GC, we arbitrarily pick addrspace(1) as our
174 // GC managed heap. We know that a pointer into this heap needs to be
175 // updated and that no other pointer does.
176 return (1 == PT->getAddressSpace());
177 return false;
178}
179
Philip Reames8531d8c2015-04-10 21:48:25 +0000180// Return true if this type is one which a) is a gc pointer or contains a GC
181// pointer and b) is of a type this code expects to encounter as a live value.
182// (The insertion code will assert that a type which matches (a) and not (b)
Philip Reames704e78b2015-04-10 22:34:56 +0000183// is not encountered.)
Philip Reames8531d8c2015-04-10 21:48:25 +0000184static bool isHandledGCPointerType(Type *T) {
185 // We fully support gc pointers
186 if (isGCPointerType(T))
187 return true;
188 // We partially support vectors of gc pointers. The code will assert if it
189 // can't handle something.
190 if (auto VT = dyn_cast<VectorType>(T))
191 if (isGCPointerType(VT->getElementType()))
192 return true;
193 return false;
194}
195
196#ifndef NDEBUG
197/// Returns true if this type contains a gc pointer whether we know how to
198/// handle that type or not.
199static bool containsGCPtrType(Type *Ty) {
Philip Reames704e78b2015-04-10 22:34:56 +0000200 if (isGCPointerType(Ty))
Philip Reames8531d8c2015-04-10 21:48:25 +0000201 return true;
202 if (VectorType *VT = dyn_cast<VectorType>(Ty))
203 return isGCPointerType(VT->getScalarType());
204 if (ArrayType *AT = dyn_cast<ArrayType>(Ty))
205 return containsGCPtrType(AT->getElementType());
206 if (StructType *ST = dyn_cast<StructType>(Ty))
Philip Reames704e78b2015-04-10 22:34:56 +0000207 return std::any_of(
208 ST->subtypes().begin(), ST->subtypes().end(),
209 [](Type *SubType) { return containsGCPtrType(SubType); });
Philip Reames8531d8c2015-04-10 21:48:25 +0000210 return false;
211}
212
213// Returns true if this is a type which a) is a gc pointer or contains a GC
214// pointer and b) is of a type which the code doesn't expect (i.e. first class
215// aggregates). Used to trip assertions.
216static bool isUnhandledGCPointerType(Type *Ty) {
217 return containsGCPtrType(Ty) && !isHandledGCPointerType(Ty);
218}
219#endif
220
Philip Reamesd16a9b12015-02-20 01:06:44 +0000221static bool order_by_name(llvm::Value *a, llvm::Value *b) {
222 if (a->hasName() && b->hasName()) {
223 return -1 == a->getName().compare(b->getName());
224 } else if (a->hasName() && !b->hasName()) {
225 return true;
226 } else if (!a->hasName() && b->hasName()) {
227 return false;
228 } else {
229 // Better than nothing, but not stable
230 return a < b;
231 }
232}
233
Philip Reamesdf1ef082015-04-10 22:53:14 +0000234// Conservatively identifies any definitions which might be live at the
235// given instruction. The analysis is performed immediately before the
236// given instruction. Values defined by that instruction are not considered
237// live. Values used by that instruction are considered live.
238static void analyzeParsePointLiveness(
239 DominatorTree &DT, GCPtrLivenessData &OriginalLivenessData,
240 const CallSite &CS, PartiallyConstructedSafepointRecord &result) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000241 Instruction *inst = CS.getInstruction();
242
Philip Reames1f017542015-02-20 23:16:52 +0000243 StatepointLiveSetTy liveset;
Philip Reamesdf1ef082015-04-10 22:53:14 +0000244 findLiveSetAtInst(inst, OriginalLivenessData, liveset);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000245
246 if (PrintLiveSet) {
247 // Note: This output is used by several of the test cases
248 // The order of elemtns in a set is not stable, put them in a vec and sort
249 // by name
Philip Reames860660e2015-02-20 22:05:18 +0000250 SmallVector<Value *, 64> temp;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000251 temp.insert(temp.end(), liveset.begin(), liveset.end());
252 std::sort(temp.begin(), temp.end(), order_by_name);
253 errs() << "Live Variables:\n";
254 for (Value *V : temp) {
255 errs() << " " << V->getName(); // no newline
256 V->dump();
257 }
258 }
259 if (PrintLiveSetSize) {
260 errs() << "Safepoint For: " << CS.getCalledValue()->getName() << "\n";
261 errs() << "Number live values: " << liveset.size() << "\n";
262 }
263 result.liveset = liveset;
264}
265
Philip Reames311f7102015-05-12 22:19:52 +0000266static Value *findBaseDefiningValue(Value *I);
267
268/// If we can trivially determine that the index specified in the given vector
269/// is a base pointer, return it. In cases where the entire vector is known to
270/// consist of base pointers, the entire vector will be returned. This
271/// indicates that the relevant extractelement is a valid base pointer and
272/// should be used directly.
273static Value *findBaseOfVector(Value *I, Value *Index) {
Philip Reames8531d8c2015-04-10 21:48:25 +0000274 assert(I->getType()->isVectorTy() &&
275 cast<VectorType>(I->getType())->getElementType()->isPointerTy() &&
276 "Illegal to ask for the base pointer of a non-pointer type");
277
278 // Each case parallels findBaseDefiningValue below, see that code for
279 // detailed motivation.
280
281 if (isa<Argument>(I))
282 // An incoming argument to the function is a base pointer
283 return I;
284
285 // We shouldn't see the address of a global as a vector value?
286 assert(!isa<GlobalVariable>(I) &&
287 "unexpected global variable found in base of vector");
288
289 // inlining could possibly introduce phi node that contains
290 // undef if callee has multiple returns
291 if (isa<UndefValue>(I))
292 // utterly meaningless, but useful for dealing with partially optimized
293 // code.
Philip Reames704e78b2015-04-10 22:34:56 +0000294 return I;
Philip Reames8531d8c2015-04-10 21:48:25 +0000295
296 // Due to inheritance, this must be _after_ the global variable and undef
297 // checks
298 if (Constant *Con = dyn_cast<Constant>(I)) {
299 assert(!isa<GlobalVariable>(I) && !isa<UndefValue>(I) &&
300 "order of checks wrong!");
301 assert(Con->isNullValue() && "null is the only case which makes sense");
302 return Con;
303 }
304
305 if (isa<LoadInst>(I))
306 return I;
307
Philip Reames311f7102015-05-12 22:19:52 +0000308 // For an insert element, we might be able to look through it if we know
309 // something about the indexes, but if the indices are arbitrary values, we
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +0000310 // can't without much more extensive scalarization.
Philip Reames311f7102015-05-12 22:19:52 +0000311 if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(I)) {
312 Value *InsertIndex = IEI->getOperand(2);
313 // This index is inserting the value, look for it's base
314 if (InsertIndex == Index)
315 return findBaseDefiningValue(IEI->getOperand(1));
316 // Both constant, and can't be equal per above. This insert is definitely
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +0000317 // not relevant, look back at the rest of the vector and keep trying.
Philip Reames311f7102015-05-12 22:19:52 +0000318 if (isa<ConstantInt>(Index) && isa<ConstantInt>(InsertIndex))
319 return findBaseOfVector(IEI->getOperand(0), Index);
320 }
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +0000321
Philip Reames8531d8c2015-04-10 21:48:25 +0000322 // Note: This code is currently rather incomplete. We are essentially only
323 // handling cases where the vector element is trivially a base pointer. We
324 // need to update the entire base pointer construction algorithm to know how
325 // to track vector elements and potentially scalarize, but the case which
326 // would motivate the work hasn't shown up in real workloads yet.
327 llvm_unreachable("no base found for vector element");
328}
329
Philip Reamesd16a9b12015-02-20 01:06:44 +0000330/// Helper function for findBasePointer - Will return a value which either a)
331/// defines the base pointer for the input or b) blocks the simple search
332/// (i.e. a PHI or Select of two derived pointers)
333static Value *findBaseDefiningValue(Value *I) {
334 assert(I->getType()->isPointerTy() &&
335 "Illegal to ask for the base pointer of a non-pointer type");
336
Philip Reames8531d8c2015-04-10 21:48:25 +0000337 // This case is a bit of a hack - it only handles extracts from vectors which
Philip Reames311f7102015-05-12 22:19:52 +0000338 // trivially contain only base pointers or cases where we can directly match
339 // the index of the original extract element to an insertion into the vector.
340 // See note inside the function for how to improve this.
Philip Reames8531d8c2015-04-10 21:48:25 +0000341 if (auto *EEI = dyn_cast<ExtractElementInst>(I)) {
342 Value *VectorOperand = EEI->getVectorOperand();
Philip Reames311f7102015-05-12 22:19:52 +0000343 Value *Index = EEI->getIndexOperand();
344 Value *VectorBase = findBaseOfVector(VectorOperand, Index);
345 // If the result returned is a vector, we know the entire vector must
346 // contain base pointers. In that case, the extractelement is a valid base
347 // for this value.
348 if (VectorBase->getType()->isVectorTy())
349 return EEI;
350 // Otherwise, we needed to look through the vector to find the base for
351 // this particular element.
352 assert(VectorBase->getType()->isPointerTy());
353 return VectorBase;
Philip Reames8531d8c2015-04-10 21:48:25 +0000354 }
Philip Reamesd16a9b12015-02-20 01:06:44 +0000355
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000356 if (isa<Argument>(I))
Philip Reamesd16a9b12015-02-20 01:06:44 +0000357 // An incoming argument to the function is a base pointer
358 // We should have never reached here if this argument isn't an gc value
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000359 return I;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000360
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000361 if (isa<GlobalVariable>(I))
Philip Reamesd16a9b12015-02-20 01:06:44 +0000362 // base case
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000363 return I;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000364
365 // inlining could possibly introduce phi node that contains
366 // undef if callee has multiple returns
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000367 if (isa<UndefValue>(I))
368 // utterly meaningless, but useful for dealing with
369 // partially optimized code.
Philip Reames704e78b2015-04-10 22:34:56 +0000370 return I;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000371
372 // Due to inheritance, this must be _after_ the global variable and undef
373 // checks
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000374 if (Constant *Con = dyn_cast<Constant>(I)) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000375 assert(!isa<GlobalVariable>(I) && !isa<UndefValue>(I) &&
376 "order of checks wrong!");
377 // Note: Finding a constant base for something marked for relocation
378 // doesn't really make sense. The most likely case is either a) some
379 // screwed up the address space usage or b) your validating against
380 // compiled C++ code w/o the proper separation. The only real exception
381 // is a null pointer. You could have generic code written to index of
382 // off a potentially null value and have proven it null. We also use
383 // null pointers in dead paths of relocation phis (which we might later
384 // want to find a base pointer for).
Philip Reames24c6cd52015-03-27 05:47:00 +0000385 assert(isa<ConstantPointerNull>(Con) &&
386 "null is the only case which makes sense");
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000387 return Con;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000388 }
389
390 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000391 Value *Def = CI->stripPointerCasts();
David Blaikie82ad7872015-02-20 23:44:24 +0000392 // If we find a cast instruction here, it means we've found a cast which is
393 // not simply a pointer cast (i.e. an inttoptr). We don't know how to
394 // handle int->ptr conversion.
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000395 assert(!isa<CastInst>(Def) && "shouldn't find another cast here");
396 return findBaseDefiningValue(Def);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000397 }
398
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000399 if (isa<LoadInst>(I))
400 return I; // The value loaded is an gc base itself
Philip Reamesd16a9b12015-02-20 01:06:44 +0000401
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000402 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I))
403 // The base of this GEP is the base
404 return findBaseDefiningValue(GEP->getPointerOperand());
Philip Reamesd16a9b12015-02-20 01:06:44 +0000405
406 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
407 switch (II->getIntrinsicID()) {
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000408 case Intrinsic::experimental_gc_result_ptr:
Philip Reamesd16a9b12015-02-20 01:06:44 +0000409 default:
410 // fall through to general call handling
411 break;
412 case Intrinsic::experimental_gc_statepoint:
413 case Intrinsic::experimental_gc_result_float:
414 case Intrinsic::experimental_gc_result_int:
415 llvm_unreachable("these don't produce pointers");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000416 case Intrinsic::experimental_gc_relocate: {
417 // Rerunning safepoint insertion after safepoints are already
418 // inserted is not supported. It could probably be made to work,
419 // but why are you doing this? There's no good reason.
420 llvm_unreachable("repeat safepoint insertion is not supported");
421 }
422 case Intrinsic::gcroot:
423 // Currently, this mechanism hasn't been extended to work with gcroot.
424 // There's no reason it couldn't be, but I haven't thought about the
425 // implications much.
426 llvm_unreachable(
427 "interaction with the gcroot mechanism is not supported");
428 }
429 }
430 // We assume that functions in the source language only return base
431 // pointers. This should probably be generalized via attributes to support
432 // both source language and internal functions.
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000433 if (isa<CallInst>(I) || isa<InvokeInst>(I))
434 return I;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000435
436 // I have absolutely no idea how to implement this part yet. It's not
437 // neccessarily hard, I just haven't really looked at it yet.
438 assert(!isa<LandingPadInst>(I) && "Landing Pad is unimplemented");
439
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000440 if (isa<AtomicCmpXchgInst>(I))
Philip Reamesd16a9b12015-02-20 01:06:44 +0000441 // A CAS is effectively a atomic store and load combined under a
442 // predicate. From the perspective of base pointers, we just treat it
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000443 // like a load.
444 return I;
Philip Reames704e78b2015-04-10 22:34:56 +0000445
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000446 assert(!isa<AtomicRMWInst>(I) && "Xchg handled above, all others are "
Philip Reames704e78b2015-04-10 22:34:56 +0000447 "binary ops which don't apply to pointers");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000448
449 // The aggregate ops. Aggregates can either be in the heap or on the
450 // stack, but in either case, this is simply a field load. As a result,
451 // this is a defining definition of the base just like a load is.
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000452 if (isa<ExtractValueInst>(I))
453 return I;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000454
455 // We should never see an insert vector since that would require we be
456 // tracing back a struct value not a pointer value.
457 assert(!isa<InsertValueInst>(I) &&
458 "Base pointer for a struct is meaningless");
459
460 // The last two cases here don't return a base pointer. Instead, they
461 // return a value which dynamically selects from amoung several base
462 // derived pointers (each with it's own base potentially). It's the job of
463 // the caller to resolve these.
Philip Reames704e78b2015-04-10 22:34:56 +0000464 assert((isa<SelectInst>(I) || isa<PHINode>(I)) &&
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000465 "missing instruction case in findBaseDefiningValing");
466 return I;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000467}
468
469/// Returns the base defining value for this value.
Philip Reames18d0feb2015-03-27 05:39:32 +0000470static Value *findBaseDefiningValueCached(Value *I, DefiningValueMapTy &Cache) {
471 Value *&Cached = Cache[I];
Benjamin Kramer6f665452015-02-20 14:00:58 +0000472 if (!Cached) {
473 Cached = findBaseDefiningValue(I);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000474 }
Philip Reames18d0feb2015-03-27 05:39:32 +0000475 assert(Cache[I] != nullptr);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000476
477 if (TraceLSP) {
Philip Reames18d0feb2015-03-27 05:39:32 +0000478 dbgs() << "fBDV-cached: " << I->getName() << " -> " << Cached->getName()
Philip Reamesd16a9b12015-02-20 01:06:44 +0000479 << "\n";
480 }
Benjamin Kramer6f665452015-02-20 14:00:58 +0000481 return Cached;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000482}
483
484/// Return a base pointer for this value if known. Otherwise, return it's
485/// base defining value.
Philip Reames18d0feb2015-03-27 05:39:32 +0000486static Value *findBaseOrBDV(Value *I, DefiningValueMapTy &Cache) {
487 Value *Def = findBaseDefiningValueCached(I, Cache);
488 auto Found = Cache.find(Def);
489 if (Found != Cache.end()) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000490 // Either a base-of relation, or a self reference. Caller must check.
Benjamin Kramer6f665452015-02-20 14:00:58 +0000491 return Found->second;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000492 }
493 // Only a BDV available
Philip Reames18d0feb2015-03-27 05:39:32 +0000494 return Def;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000495}
496
497/// Given the result of a call to findBaseDefiningValue, or findBaseOrBDV,
498/// is it known to be a base pointer? Or do we need to continue searching.
Philip Reames18d0feb2015-03-27 05:39:32 +0000499static bool isKnownBaseResult(Value *V) {
500 if (!isa<PHINode>(V) && !isa<SelectInst>(V)) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000501 // no recursion possible
502 return true;
503 }
Philip Reames18d0feb2015-03-27 05:39:32 +0000504 if (isa<Instruction>(V) &&
505 cast<Instruction>(V)->getMetadata("is_base_value")) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000506 // This is a previously inserted base phi or select. We know
507 // that this is a base value.
508 return true;
509 }
510
511 // We need to keep searching
512 return false;
513}
514
515// TODO: find a better name for this
516namespace {
517class PhiState {
518public:
519 enum Status { Unknown, Base, Conflict };
520
521 PhiState(Status s, Value *b = nullptr) : status(s), base(b) {
522 assert(status != Base || b);
523 }
524 PhiState(Value *b) : status(Base), base(b) {}
525 PhiState() : status(Unknown), base(nullptr) {}
Philip Reamesd16a9b12015-02-20 01:06:44 +0000526
527 Status getStatus() const { return status; }
528 Value *getBase() const { return base; }
529
530 bool isBase() const { return getStatus() == Base; }
531 bool isUnknown() const { return getStatus() == Unknown; }
532 bool isConflict() const { return getStatus() == Conflict; }
533
534 bool operator==(const PhiState &other) const {
535 return base == other.base && status == other.status;
536 }
537
538 bool operator!=(const PhiState &other) const { return !(*this == other); }
539
540 void dump() {
541 errs() << status << " (" << base << " - "
542 << (base ? base->getName() : "nullptr") << "): ";
543 }
544
545private:
546 Status status;
547 Value *base; // non null only if status == base
548};
549
Philip Reamese9c3b9b2015-02-20 22:48:20 +0000550typedef DenseMap<Value *, PhiState> ConflictStateMapTy;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000551// Values of type PhiState form a lattice, and this is a helper
552// class that implementes the meet operation. The meat of the meet
553// operation is implemented in MeetPhiStates::pureMeet
554class MeetPhiStates {
555public:
556 // phiStates is a mapping from PHINodes and SelectInst's to PhiStates.
Philip Reames860660e2015-02-20 22:05:18 +0000557 explicit MeetPhiStates(const ConflictStateMapTy &phiStates)
Philip Reamesd16a9b12015-02-20 01:06:44 +0000558 : phiStates(phiStates) {}
559
560 // Destructively meet the current result with the base V. V can
561 // either be a merge instruction (SelectInst / PHINode), in which
562 // case its status is looked up in the phiStates map; or a regular
563 // SSA value, in which case it is assumed to be a base.
564 void meetWith(Value *V) {
565 PhiState otherState = getStateForBDV(V);
566 assert((MeetPhiStates::pureMeet(otherState, currentResult) ==
567 MeetPhiStates::pureMeet(currentResult, otherState)) &&
568 "math is wrong: meet does not commute!");
569 currentResult = MeetPhiStates::pureMeet(otherState, currentResult);
570 }
571
572 PhiState getResult() const { return currentResult; }
573
574private:
Philip Reames860660e2015-02-20 22:05:18 +0000575 const ConflictStateMapTy &phiStates;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000576 PhiState currentResult;
577
578 /// Return a phi state for a base defining value. We'll generate a new
579 /// base state for known bases and expect to find a cached state otherwise
580 PhiState getStateForBDV(Value *baseValue) {
581 if (isKnownBaseResult(baseValue)) {
582 return PhiState(baseValue);
583 } else {
584 return lookupFromMap(baseValue);
585 }
586 }
587
588 PhiState lookupFromMap(Value *V) {
589 auto I = phiStates.find(V);
590 assert(I != phiStates.end() && "lookup failed!");
591 return I->second;
592 }
593
594 static PhiState pureMeet(const PhiState &stateA, const PhiState &stateB) {
595 switch (stateA.getStatus()) {
596 case PhiState::Unknown:
597 return stateB;
598
599 case PhiState::Base:
600 assert(stateA.getBase() && "can't be null");
David Blaikie82ad7872015-02-20 23:44:24 +0000601 if (stateB.isUnknown())
Philip Reamesd16a9b12015-02-20 01:06:44 +0000602 return stateA;
David Blaikie82ad7872015-02-20 23:44:24 +0000603
604 if (stateB.isBase()) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000605 if (stateA.getBase() == stateB.getBase()) {
606 assert(stateA == stateB && "equality broken!");
607 return stateA;
608 }
609 return PhiState(PhiState::Conflict);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000610 }
David Blaikie82ad7872015-02-20 23:44:24 +0000611 assert(stateB.isConflict() && "only three states!");
612 return PhiState(PhiState::Conflict);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000613
614 case PhiState::Conflict:
615 return stateA;
616 }
Reid Klecknera070ee52015-02-20 19:46:02 +0000617 llvm_unreachable("only three states!");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000618 }
619};
620}
621/// For a given value or instruction, figure out what base ptr it's derived
622/// from. For gc objects, this is simply itself. On success, returns a value
623/// which is the base pointer. (This is reliable and can be used for
624/// relocation.) On failure, returns nullptr.
Philip Reamesba198492015-04-14 00:41:34 +0000625static Value *findBasePointer(Value *I, DefiningValueMapTy &cache) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000626 Value *def = findBaseOrBDV(I, cache);
627
628 if (isKnownBaseResult(def)) {
629 return def;
630 }
631
632 // Here's the rough algorithm:
633 // - For every SSA value, construct a mapping to either an actual base
634 // pointer or a PHI which obscures the base pointer.
635 // - Construct a mapping from PHI to unknown TOP state. Use an
636 // optimistic algorithm to propagate base pointer information. Lattice
637 // looks like:
638 // UNKNOWN
639 // b1 b2 b3 b4
640 // CONFLICT
641 // When algorithm terminates, all PHIs will either have a single concrete
642 // base or be in a conflict state.
643 // - For every conflict, insert a dummy PHI node without arguments. Add
644 // these to the base[Instruction] = BasePtr mapping. For every
645 // non-conflict, add the actual base.
646 // - For every conflict, add arguments for the base[a] of each input
647 // arguments.
648 //
649 // Note: A simpler form of this would be to add the conflict form of all
650 // PHIs without running the optimistic algorithm. This would be
651 // analougous to pessimistic data flow and would likely lead to an
652 // overall worse solution.
653
Philip Reames860660e2015-02-20 22:05:18 +0000654 ConflictStateMapTy states;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000655 states[def] = PhiState();
656 // Recursively fill in all phis & selects reachable from the initial one
657 // for which we don't already know a definite base value for
Philip Reamesa226e612015-02-28 00:47:50 +0000658 // TODO: This should be rewritten with a worklist
Philip Reamesd16a9b12015-02-20 01:06:44 +0000659 bool done = false;
660 while (!done) {
661 done = true;
Philip Reamesa226e612015-02-28 00:47:50 +0000662 // Since we're adding elements to 'states' as we run, we can't keep
663 // iterators into the set.
Philip Reames704e78b2015-04-10 22:34:56 +0000664 SmallVector<Value *, 16> Keys;
Philip Reamesa226e612015-02-28 00:47:50 +0000665 Keys.reserve(states.size());
Philip Reamesd16a9b12015-02-20 01:06:44 +0000666 for (auto Pair : states) {
Philip Reamesa226e612015-02-28 00:47:50 +0000667 Value *V = Pair.first;
668 Keys.push_back(V);
669 }
670 for (Value *v : Keys) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000671 assert(!isKnownBaseResult(v) && "why did it get added?");
672 if (PHINode *phi = dyn_cast<PHINode>(v)) {
David Blaikie82ad7872015-02-20 23:44:24 +0000673 assert(phi->getNumIncomingValues() > 0 &&
674 "zero input phis are illegal");
675 for (Value *InVal : phi->incoming_values()) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000676 Value *local = findBaseOrBDV(InVal, cache);
677 if (!isKnownBaseResult(local) && states.find(local) == states.end()) {
678 states[local] = PhiState();
679 done = false;
680 }
681 }
682 } else if (SelectInst *sel = dyn_cast<SelectInst>(v)) {
683 Value *local = findBaseOrBDV(sel->getTrueValue(), cache);
684 if (!isKnownBaseResult(local) && states.find(local) == states.end()) {
685 states[local] = PhiState();
686 done = false;
687 }
688 local = findBaseOrBDV(sel->getFalseValue(), cache);
689 if (!isKnownBaseResult(local) && states.find(local) == states.end()) {
690 states[local] = PhiState();
691 done = false;
692 }
693 }
694 }
695 }
696
697 if (TraceLSP) {
698 errs() << "States after initialization:\n";
699 for (auto Pair : states) {
700 Instruction *v = cast<Instruction>(Pair.first);
701 PhiState state = Pair.second;
702 state.dump();
703 v->dump();
704 }
705 }
706
707 // TODO: come back and revisit the state transitions around inputs which
708 // have reached conflict state. The current version seems too conservative.
709
710 bool progress = true;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000711 while (progress) {
Yaron Keren42a7adf2015-02-28 13:11:24 +0000712#ifndef NDEBUG
713 size_t oldSize = states.size();
714#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +0000715 progress = false;
Philip Reamesa226e612015-02-28 00:47:50 +0000716 // We're only changing keys in this loop, thus safe to keep iterators
Philip Reamesd16a9b12015-02-20 01:06:44 +0000717 for (auto Pair : states) {
718 MeetPhiStates calculateMeet(states);
719 Value *v = Pair.first;
720 assert(!isKnownBaseResult(v) && "why did it get added?");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000721 if (SelectInst *select = dyn_cast<SelectInst>(v)) {
722 calculateMeet.meetWith(findBaseOrBDV(select->getTrueValue(), cache));
723 calculateMeet.meetWith(findBaseOrBDV(select->getFalseValue(), cache));
David Blaikie82ad7872015-02-20 23:44:24 +0000724 } else
725 for (Value *Val : cast<PHINode>(v)->incoming_values())
726 calculateMeet.meetWith(findBaseOrBDV(Val, cache));
Philip Reamesd16a9b12015-02-20 01:06:44 +0000727
728 PhiState oldState = states[v];
729 PhiState newState = calculateMeet.getResult();
730 if (oldState != newState) {
731 progress = true;
732 states[v] = newState;
733 }
734 }
735
736 assert(oldSize <= states.size());
737 assert(oldSize == states.size() || progress);
738 }
739
740 if (TraceLSP) {
741 errs() << "States after meet iteration:\n";
742 for (auto Pair : states) {
743 Instruction *v = cast<Instruction>(Pair.first);
744 PhiState state = Pair.second;
745 state.dump();
746 v->dump();
747 }
748 }
749
750 // Insert Phis for all conflicts
Philip Reames2e5bcbe2015-02-28 01:52:09 +0000751 // We want to keep naming deterministic in the loop that follows, so
752 // sort the keys before iteration. This is useful in allowing us to
753 // write stable tests. Note that there is no invalidation issue here.
Philip Reames704e78b2015-04-10 22:34:56 +0000754 SmallVector<Value *, 16> Keys;
Philip Reames2e5bcbe2015-02-28 01:52:09 +0000755 Keys.reserve(states.size());
Philip Reamesd16a9b12015-02-20 01:06:44 +0000756 for (auto Pair : states) {
Philip Reames2e5bcbe2015-02-28 01:52:09 +0000757 Value *V = Pair.first;
758 Keys.push_back(V);
759 }
760 std::sort(Keys.begin(), Keys.end(), order_by_name);
761 // TODO: adjust naming patterns to avoid this order of iteration dependency
762 for (Value *V : Keys) {
763 Instruction *v = cast<Instruction>(V);
764 PhiState state = states[V];
Philip Reamesd16a9b12015-02-20 01:06:44 +0000765 assert(!isKnownBaseResult(v) && "why did it get added?");
766 assert(!state.isUnknown() && "Optimistic algorithm didn't complete!");
Philip Reamesf986d682015-02-28 00:54:41 +0000767 if (!state.isConflict())
768 continue;
Philip Reames704e78b2015-04-10 22:34:56 +0000769
Philip Reamesf986d682015-02-28 00:54:41 +0000770 if (isa<PHINode>(v)) {
771 int num_preds =
772 std::distance(pred_begin(v->getParent()), pred_end(v->getParent()));
773 assert(num_preds > 0 && "how did we reach here");
774 PHINode *phi = PHINode::Create(v->getType(), num_preds, "base_phi", v);
Philip Reamesf986d682015-02-28 00:54:41 +0000775 // Add metadata marking this as a base value
776 auto *const_1 = ConstantInt::get(
777 Type::getInt32Ty(
778 v->getParent()->getParent()->getParent()->getContext()),
779 1);
780 auto MDConst = ConstantAsMetadata::get(const_1);
781 MDNode *md = MDNode::get(
782 v->getParent()->getParent()->getParent()->getContext(), MDConst);
783 phi->setMetadata("is_base_value", md);
784 states[v] = PhiState(PhiState::Conflict, phi);
785 } else {
786 SelectInst *sel = cast<SelectInst>(v);
787 // The undef will be replaced later
788 UndefValue *undef = UndefValue::get(sel->getType());
789 SelectInst *basesel = SelectInst::Create(sel->getCondition(), undef,
790 undef, "base_select", sel);
Philip Reamesf986d682015-02-28 00:54:41 +0000791 // Add metadata marking this as a base value
792 auto *const_1 = ConstantInt::get(
793 Type::getInt32Ty(
794 v->getParent()->getParent()->getParent()->getContext()),
795 1);
796 auto MDConst = ConstantAsMetadata::get(const_1);
797 MDNode *md = MDNode::get(
798 v->getParent()->getParent()->getParent()->getContext(), MDConst);
799 basesel->setMetadata("is_base_value", md);
800 states[v] = PhiState(PhiState::Conflict, basesel);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000801 }
802 }
803
804 // Fixup all the inputs of the new PHIs
805 for (auto Pair : states) {
806 Instruction *v = cast<Instruction>(Pair.first);
807 PhiState state = Pair.second;
808
809 assert(!isKnownBaseResult(v) && "why did it get added?");
810 assert(!state.isUnknown() && "Optimistic algorithm didn't complete!");
Philip Reames28e61ce2015-02-28 01:57:44 +0000811 if (!state.isConflict())
812 continue;
Philip Reames704e78b2015-04-10 22:34:56 +0000813
Philip Reames28e61ce2015-02-28 01:57:44 +0000814 if (PHINode *basephi = dyn_cast<PHINode>(state.getBase())) {
815 PHINode *phi = cast<PHINode>(v);
816 unsigned NumPHIValues = phi->getNumIncomingValues();
817 for (unsigned i = 0; i < NumPHIValues; i++) {
818 Value *InVal = phi->getIncomingValue(i);
819 BasicBlock *InBB = phi->getIncomingBlock(i);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000820
Philip Reames28e61ce2015-02-28 01:57:44 +0000821 // If we've already seen InBB, add the same incoming value
822 // we added for it earlier. The IR verifier requires phi
823 // nodes with multiple entries from the same basic block
824 // to have the same incoming value for each of those
825 // entries. If we don't do this check here and basephi
826 // has a different type than base, we'll end up adding two
827 // bitcasts (and hence two distinct values) as incoming
828 // values for the same basic block.
Philip Reamesd16a9b12015-02-20 01:06:44 +0000829
Philip Reames28e61ce2015-02-28 01:57:44 +0000830 int blockIndex = basephi->getBasicBlockIndex(InBB);
831 if (blockIndex != -1) {
832 Value *oldBase = basephi->getIncomingValue(blockIndex);
833 basephi->addIncoming(oldBase, InBB);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000834#ifndef NDEBUG
Philip Reames28e61ce2015-02-28 01:57:44 +0000835 Value *base = findBaseOrBDV(InVal, cache);
836 if (!isKnownBaseResult(base)) {
837 // Either conflict or base.
838 assert(states.count(base));
839 base = states[base].getBase();
840 assert(base != nullptr && "unknown PhiState!");
Philip Reames28e61ce2015-02-28 01:57:44 +0000841 }
Philip Reamesd16a9b12015-02-20 01:06:44 +0000842
Philip Reames28e61ce2015-02-28 01:57:44 +0000843 // In essense this assert states: the only way two
844 // values incoming from the same basic block may be
845 // different is by being different bitcasts of the same
846 // value. A cleanup that remains TODO is changing
847 // findBaseOrBDV to return an llvm::Value of the correct
848 // type (and still remain pure). This will remove the
849 // need to add bitcasts.
850 assert(base->stripPointerCasts() == oldBase->stripPointerCasts() &&
851 "sanity -- findBaseOrBDV should be pure!");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000852#endif
Philip Reames28e61ce2015-02-28 01:57:44 +0000853 continue;
854 }
Philip Reamesd16a9b12015-02-20 01:06:44 +0000855
Philip Reames28e61ce2015-02-28 01:57:44 +0000856 // Find either the defining value for the PHI or the normal base for
857 // a non-phi node
858 Value *base = findBaseOrBDV(InVal, cache);
859 if (!isKnownBaseResult(base)) {
860 // Either conflict or base.
861 assert(states.count(base));
862 base = states[base].getBase();
863 assert(base != nullptr && "unknown PhiState!");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000864 }
Philip Reames28e61ce2015-02-28 01:57:44 +0000865 assert(base && "can't be null");
866 // Must use original input BB since base may not be Instruction
867 // The cast is needed since base traversal may strip away bitcasts
868 if (base->getType() != basephi->getType()) {
869 base = new BitCastInst(base, basephi->getType(), "cast",
870 InBB->getTerminator());
Philip Reamesd16a9b12015-02-20 01:06:44 +0000871 }
Philip Reames28e61ce2015-02-28 01:57:44 +0000872 basephi->addIncoming(base, InBB);
873 }
874 assert(basephi->getNumIncomingValues() == NumPHIValues);
875 } else {
876 SelectInst *basesel = cast<SelectInst>(state.getBase());
877 SelectInst *sel = cast<SelectInst>(v);
878 // Operand 1 & 2 are true, false path respectively. TODO: refactor to
879 // something more safe and less hacky.
880 for (int i = 1; i <= 2; i++) {
881 Value *InVal = sel->getOperand(i);
882 // Find either the defining value for the PHI or the normal base for
883 // a non-phi node
884 Value *base = findBaseOrBDV(InVal, cache);
885 if (!isKnownBaseResult(base)) {
886 // Either conflict or base.
887 assert(states.count(base));
888 base = states[base].getBase();
889 assert(base != nullptr && "unknown PhiState!");
890 }
891 assert(base && "can't be null");
892 // Must use original input BB since base may not be Instruction
893 // The cast is needed since base traversal may strip away bitcasts
894 if (base->getType() != basesel->getType()) {
895 base = new BitCastInst(base, basesel->getType(), "cast", basesel);
Philip Reames28e61ce2015-02-28 01:57:44 +0000896 }
897 basesel->setOperand(i, base);
898 }
Philip Reamesd16a9b12015-02-20 01:06:44 +0000899 }
900 }
901
902 // Cache all of our results so we can cheaply reuse them
903 // NOTE: This is actually two caches: one of the base defining value
904 // relation and one of the base pointer relation! FIXME
905 for (auto item : states) {
906 Value *v = item.first;
907 Value *base = item.second.getBase();
908 assert(v && base);
909 assert(!isKnownBaseResult(v) && "why did it get added?");
910
911 if (TraceLSP) {
912 std::string fromstr =
913 cache.count(v) ? (cache[v]->hasName() ? cache[v]->getName() : "")
914 : "none";
915 errs() << "Updating base value cache"
916 << " for: " << (v->hasName() ? v->getName() : "")
917 << " from: " << fromstr
918 << " to: " << (base->hasName() ? base->getName() : "") << "\n";
919 }
920
921 assert(isKnownBaseResult(base) &&
922 "must be something we 'know' is a base pointer");
923 if (cache.count(v)) {
924 // Once we transition from the BDV relation being store in the cache to
925 // the base relation being stored, it must be stable
926 assert((!isKnownBaseResult(cache[v]) || cache[v] == base) &&
927 "base relation should be stable");
928 }
929 cache[v] = base;
930 }
931 assert(cache.find(def) != cache.end());
932 return cache[def];
933}
934
935// For a set of live pointers (base and/or derived), identify the base
936// pointer of the object which they are derived from. This routine will
937// mutate the IR graph as needed to make the 'base' pointer live at the
938// definition site of 'derived'. This ensures that any use of 'derived' can
939// also use 'base'. This may involve the insertion of a number of
940// additional PHI nodes.
941//
942// preconditions: live is a set of pointer type Values
943//
944// side effects: may insert PHI nodes into the existing CFG, will preserve
945// CFG, will not remove or mutate any existing nodes
946//
Philip Reamesf2041322015-02-20 19:26:04 +0000947// post condition: PointerToBase contains one (derived, base) pair for every
Philip Reamesd16a9b12015-02-20 01:06:44 +0000948// pointer in live. Note that derived can be equal to base if the original
949// pointer was a base pointer.
Philip Reames704e78b2015-04-10 22:34:56 +0000950static void
951findBasePointers(const StatepointLiveSetTy &live,
952 DenseMap<llvm::Value *, llvm::Value *> &PointerToBase,
Philip Reamesba198492015-04-14 00:41:34 +0000953 DominatorTree *DT, DefiningValueMapTy &DVCache) {
Philip Reames2e5bcbe2015-02-28 01:52:09 +0000954 // For the naming of values inserted to be deterministic - which makes for
955 // much cleaner and more stable tests - we need to assign an order to the
956 // live values. DenseSets do not provide a deterministic order across runs.
Philip Reames704e78b2015-04-10 22:34:56 +0000957 SmallVector<Value *, 64> Temp;
Philip Reames2e5bcbe2015-02-28 01:52:09 +0000958 Temp.insert(Temp.end(), live.begin(), live.end());
959 std::sort(Temp.begin(), Temp.end(), order_by_name);
960 for (Value *ptr : Temp) {
Philip Reamesba198492015-04-14 00:41:34 +0000961 Value *base = findBasePointer(ptr, DVCache);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000962 assert(base && "failed to find base pointer");
Philip Reamesf2041322015-02-20 19:26:04 +0000963 PointerToBase[ptr] = base;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000964 assert((!isa<Instruction>(base) || !isa<Instruction>(ptr) ||
965 DT->dominates(cast<Instruction>(base)->getParent(),
966 cast<Instruction>(ptr)->getParent())) &&
967 "The base we found better dominate the derived pointer");
968
David Blaikie82ad7872015-02-20 23:44:24 +0000969 // If you see this trip and like to live really dangerously, the code should
970 // be correct, just with idioms the verifier can't handle. You can try
971 // disabling the verifier at your own substaintial risk.
Philip Reames704e78b2015-04-10 22:34:56 +0000972 assert(!isa<ConstantPointerNull>(base) &&
Philip Reames24c6cd52015-03-27 05:47:00 +0000973 "the relocation code needs adjustment to handle the relocation of "
974 "a null pointer constant without causing false positives in the "
975 "safepoint ir verifier.");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000976 }
977}
978
979/// Find the required based pointers (and adjust the live set) for the given
980/// parse point.
981static void findBasePointers(DominatorTree &DT, DefiningValueMapTy &DVCache,
982 const CallSite &CS,
983 PartiallyConstructedSafepointRecord &result) {
Philip Reamesf2041322015-02-20 19:26:04 +0000984 DenseMap<llvm::Value *, llvm::Value *> PointerToBase;
Philip Reamesba198492015-04-14 00:41:34 +0000985 findBasePointers(result.liveset, PointerToBase, &DT, DVCache);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000986
987 if (PrintBasePointers) {
Philip Reamesa5aeaf42015-02-28 00:20:48 +0000988 // Note: Need to print these in a stable order since this is checked in
989 // some tests.
Philip Reamesd16a9b12015-02-20 01:06:44 +0000990 errs() << "Base Pairs (w/o Relocation):\n";
Philip Reames704e78b2015-04-10 22:34:56 +0000991 SmallVector<Value *, 64> Temp;
Philip Reamesa5aeaf42015-02-28 00:20:48 +0000992 Temp.reserve(PointerToBase.size());
Philip Reamesf2041322015-02-20 19:26:04 +0000993 for (auto Pair : PointerToBase) {
Philip Reamesa5aeaf42015-02-28 00:20:48 +0000994 Temp.push_back(Pair.first);
995 }
996 std::sort(Temp.begin(), Temp.end(), order_by_name);
997 for (Value *Ptr : Temp) {
998 Value *Base = PointerToBase[Ptr];
Philip Reames704e78b2015-04-10 22:34:56 +0000999 errs() << " derived %" << Ptr->getName() << " base %" << Base->getName()
1000 << "\n";
Philip Reamesd16a9b12015-02-20 01:06:44 +00001001 }
1002 }
1003
Philip Reamesf2041322015-02-20 19:26:04 +00001004 result.PointerToBase = PointerToBase;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001005}
1006
Philip Reamesdf1ef082015-04-10 22:53:14 +00001007/// Given an updated version of the dataflow liveness results, update the
1008/// liveset and base pointer maps for the call site CS.
1009static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData,
1010 const CallSite &CS,
1011 PartiallyConstructedSafepointRecord &result);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001012
Philip Reamesdf1ef082015-04-10 22:53:14 +00001013static void recomputeLiveInValues(
1014 Function &F, DominatorTree &DT, Pass *P, ArrayRef<CallSite> toUpdate,
Philip Reamesd2b66462015-02-20 22:39:41 +00001015 MutableArrayRef<struct PartiallyConstructedSafepointRecord> records) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00001016 // TODO-PERF: reuse the original liveness, then simply run the dataflow
1017 // again. The old values are still live and will help it stablize quickly.
1018 GCPtrLivenessData RevisedLivenessData;
1019 computeLiveInValues(DT, F, RevisedLivenessData);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001020 for (size_t i = 0; i < records.size(); i++) {
1021 struct PartiallyConstructedSafepointRecord &info = records[i];
Philip Reamesd2b66462015-02-20 22:39:41 +00001022 const CallSite &CS = toUpdate[i];
Philip Reamesdf1ef082015-04-10 22:53:14 +00001023 recomputeLiveInValues(RevisedLivenessData, CS, info);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001024 }
1025}
1026
Philip Reames69e51ca2015-04-13 18:07:21 +00001027// When inserting gc.relocate calls, we need to ensure there are no uses
1028// of the original value between the gc.statepoint and the gc.relocate call.
1029// One case which can arise is a phi node starting one of the successor blocks.
1030// We also need to be able to insert the gc.relocates only on the path which
1031// goes through the statepoint. We might need to split an edge to make this
Philip Reamesf209a152015-04-13 20:00:30 +00001032// possible.
1033static BasicBlock *
1034normalizeForInvokeSafepoint(BasicBlock *BB, BasicBlock *InvokeParent, Pass *P) {
Philip Reames69e51ca2015-04-13 18:07:21 +00001035 DominatorTree *DT = nullptr;
1036 if (auto *DTP = P->getAnalysisIfAvailable<DominatorTreeWrapperPass>())
1037 DT = &DTP->getDomTree();
Philip Reamesd16a9b12015-02-20 01:06:44 +00001038
Philip Reames69e51ca2015-04-13 18:07:21 +00001039 BasicBlock *Ret = BB;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001040 if (!BB->getUniquePredecessor()) {
Philip Reames69e51ca2015-04-13 18:07:21 +00001041 Ret = SplitBlockPredecessors(BB, InvokeParent, "", nullptr, DT);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001042 }
1043
Philip Reames69e51ca2015-04-13 18:07:21 +00001044 // Now that 'ret' has unique predecessor we can safely remove all phi nodes
1045 // from it
1046 FoldSingleEntryPHINodes(Ret);
1047 assert(!isa<PHINode>(Ret->begin()));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001048
Philip Reames69e51ca2015-04-13 18:07:21 +00001049 // At this point, we can safely insert a gc.relocate as the first instruction
1050 // in Ret if needed.
1051 return Ret;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001052}
1053
Philip Reamesd2b66462015-02-20 22:39:41 +00001054static int find_index(ArrayRef<Value *> livevec, Value *val) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001055 auto itr = std::find(livevec.begin(), livevec.end(), val);
1056 assert(livevec.end() != itr);
1057 size_t index = std::distance(livevec.begin(), itr);
1058 assert(index < livevec.size());
1059 return index;
1060}
1061
1062// Create new attribute set containing only attributes which can be transfered
1063// from original call to the safepoint.
1064static AttributeSet legalizeCallAttributes(AttributeSet AS) {
1065 AttributeSet ret;
1066
1067 for (unsigned Slot = 0; Slot < AS.getNumSlots(); Slot++) {
1068 unsigned index = AS.getSlotIndex(Slot);
1069
1070 if (index == AttributeSet::ReturnIndex ||
1071 index == AttributeSet::FunctionIndex) {
1072
1073 for (auto it = AS.begin(Slot), it_end = AS.end(Slot); it != it_end;
1074 ++it) {
1075 Attribute attr = *it;
1076
1077 // Do not allow certain attributes - just skip them
1078 // Safepoint can not be read only or read none.
1079 if (attr.hasAttribute(Attribute::ReadNone) ||
1080 attr.hasAttribute(Attribute::ReadOnly))
1081 continue;
1082
1083 ret = ret.addAttributes(
1084 AS.getContext(), index,
1085 AttributeSet::get(AS.getContext(), index, AttrBuilder(attr)));
1086 }
1087 }
1088
1089 // Just skip parameter attributes for now
1090 }
1091
1092 return ret;
1093}
1094
1095/// Helper function to place all gc relocates necessary for the given
1096/// statepoint.
1097/// Inputs:
1098/// liveVariables - list of variables to be relocated.
1099/// liveStart - index of the first live variable.
1100/// basePtrs - base pointers.
1101/// statepointToken - statepoint instruction to which relocates should be
1102/// bound.
1103/// Builder - Llvm IR builder to be used to construct new calls.
Sanjoy Das5665c992015-05-11 23:47:27 +00001104static void CreateGCRelocates(ArrayRef<llvm::Value *> LiveVariables,
1105 const int LiveStart,
1106 ArrayRef<llvm::Value *> BasePtrs,
1107 Instruction *StatepointToken,
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00001108 IRBuilder<> Builder) {
Philip Reamesd2b66462015-02-20 22:39:41 +00001109 SmallVector<Instruction *, 64> NewDefs;
Sanjoy Das5665c992015-05-11 23:47:27 +00001110 NewDefs.reserve(LiveVariables.size());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001111
Sanjoy Das5665c992015-05-11 23:47:27 +00001112 Module *M = StatepointToken->getParent()->getParent()->getParent();
Philip Reamesd16a9b12015-02-20 01:06:44 +00001113
Sanjoy Das5665c992015-05-11 23:47:27 +00001114 for (unsigned i = 0; i < LiveVariables.size(); i++) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001115 // We generate a (potentially) unique declaration for every pointer type
1116 // combination. This results is some blow up the function declarations in
1117 // the IR, but removes the need for argument bitcasts which shrinks the IR
1118 // greatly and makes it much more readable.
Sanjoy Das5665c992015-05-11 23:47:27 +00001119 SmallVector<Type *, 1> Types; // one per 'any' type
Sanjoy Das89c54912015-05-11 18:49:34 +00001120 // All gc_relocate are set to i8 addrspace(1)* type. This could help avoid
1121 // cases where the actual value's type mangling is not supported by llvm. A
1122 // bitcast is added later to convert gc_relocate to the actual value's type.
Sanjoy Das5665c992015-05-11 23:47:27 +00001123 Types.push_back(Type::getInt8PtrTy(M->getContext(), 1));
1124 Value *GCRelocateDecl = Intrinsic::getDeclaration(
1125 M, Intrinsic::experimental_gc_relocate, Types);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001126
1127 // Generate the gc.relocate call and save the result
Sanjoy Das5665c992015-05-11 23:47:27 +00001128 Value *BaseIdx =
Philip Reamesd16a9b12015-02-20 01:06:44 +00001129 ConstantInt::get(Type::getInt32Ty(M->getContext()),
Sanjoy Das5665c992015-05-11 23:47:27 +00001130 LiveStart + find_index(LiveVariables, BasePtrs[i]));
1131 Value *LiveIdx = ConstantInt::get(
Philip Reamesd16a9b12015-02-20 01:06:44 +00001132 Type::getInt32Ty(M->getContext()),
Sanjoy Das5665c992015-05-11 23:47:27 +00001133 LiveStart + find_index(LiveVariables, LiveVariables[i]));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001134
1135 // only specify a debug name if we can give a useful one
David Blaikieff6409d2015-05-18 22:13:54 +00001136 Value *Reloc = Builder.CreateCall(
1137 GCRelocateDecl, {StatepointToken, BaseIdx, LiveIdx},
Sanjoy Das5665c992015-05-11 23:47:27 +00001138 LiveVariables[i]->hasName() ? LiveVariables[i]->getName() + ".relocated"
Philip Reamesd16a9b12015-02-20 01:06:44 +00001139 : "");
1140 // Trick CodeGen into thinking there are lots of free registers at this
1141 // fake call.
Sanjoy Das5665c992015-05-11 23:47:27 +00001142 cast<CallInst>(Reloc)->setCallingConv(CallingConv::Cold);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001143
Sanjoy Das5665c992015-05-11 23:47:27 +00001144 NewDefs.push_back(cast<Instruction>(Reloc));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001145 }
Sanjoy Das5665c992015-05-11 23:47:27 +00001146 assert(NewDefs.size() == LiveVariables.size() &&
Philip Reamesd16a9b12015-02-20 01:06:44 +00001147 "missing or extra redefinition at safepoint");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001148}
1149
1150static void
1151makeStatepointExplicitImpl(const CallSite &CS, /* to replace */
1152 const SmallVectorImpl<llvm::Value *> &basePtrs,
1153 const SmallVectorImpl<llvm::Value *> &liveVariables,
1154 Pass *P,
1155 PartiallyConstructedSafepointRecord &result) {
1156 assert(basePtrs.size() == liveVariables.size());
1157 assert(isStatepoint(CS) &&
1158 "This method expects to be rewriting a statepoint");
1159
1160 BasicBlock *BB = CS.getInstruction()->getParent();
1161 assert(BB);
1162 Function *F = BB->getParent();
1163 assert(F && "must be set");
1164 Module *M = F->getParent();
Nick Lewyckyeb3231e2015-02-20 07:14:02 +00001165 (void)M;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001166 assert(M && "must be set");
1167
1168 // We're not changing the function signature of the statepoint since the gc
1169 // arguments go into the var args section.
1170 Function *gc_statepoint_decl = CS.getCalledFunction();
1171
1172 // Then go ahead and use the builder do actually do the inserts. We insert
1173 // immediately before the previous instruction under the assumption that all
1174 // arguments will be available here. We can't insert afterwards since we may
1175 // be replacing a terminator.
1176 Instruction *insertBefore = CS.getInstruction();
1177 IRBuilder<> Builder(insertBefore);
1178 // Copy all of the arguments from the original statepoint - this includes the
1179 // target, call args, and deopt args
Philip Reamesd2b66462015-02-20 22:39:41 +00001180 SmallVector<llvm::Value *, 64> args;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001181 args.insert(args.end(), CS.arg_begin(), CS.arg_end());
1182 // TODO: Clear the 'needs rewrite' flag
1183
1184 // add all the pointers to be relocated (gc arguments)
1185 // Capture the start of the live variable list for use in the gc_relocates
1186 const int live_start = args.size();
1187 args.insert(args.end(), liveVariables.begin(), liveVariables.end());
1188
1189 // Create the statepoint given all the arguments
1190 Instruction *token = nullptr;
1191 AttributeSet return_attributes;
1192 if (CS.isCall()) {
1193 CallInst *toReplace = cast<CallInst>(CS.getInstruction());
1194 CallInst *call =
1195 Builder.CreateCall(gc_statepoint_decl, args, "safepoint_token");
1196 call->setTailCall(toReplace->isTailCall());
1197 call->setCallingConv(toReplace->getCallingConv());
1198
1199 // Currently we will fail on parameter attributes and on certain
1200 // function attributes.
1201 AttributeSet new_attrs = legalizeCallAttributes(toReplace->getAttributes());
1202 // In case if we can handle this set of sttributes - set up function attrs
1203 // directly on statepoint and return attrs later for gc_result intrinsic.
1204 call->setAttributes(new_attrs.getFnAttributes());
1205 return_attributes = new_attrs.getRetAttributes();
1206
1207 token = call;
1208
1209 // Put the following gc_result and gc_relocate calls immediately after the
1210 // the old call (which we're about to delete)
1211 BasicBlock::iterator next(toReplace);
1212 assert(BB->end() != next && "not a terminator, must have next");
1213 next++;
1214 Instruction *IP = &*(next);
1215 Builder.SetInsertPoint(IP);
1216 Builder.SetCurrentDebugLocation(IP->getDebugLoc());
1217
David Blaikie82ad7872015-02-20 23:44:24 +00001218 } else {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001219 InvokeInst *toReplace = cast<InvokeInst>(CS.getInstruction());
1220
1221 // Insert the new invoke into the old block. We'll remove the old one in a
1222 // moment at which point this will become the new terminator for the
1223 // original block.
1224 InvokeInst *invoke = InvokeInst::Create(
1225 gc_statepoint_decl, toReplace->getNormalDest(),
1226 toReplace->getUnwindDest(), args, "", toReplace->getParent());
1227 invoke->setCallingConv(toReplace->getCallingConv());
1228
1229 // Currently we will fail on parameter attributes and on certain
1230 // function attributes.
1231 AttributeSet new_attrs = legalizeCallAttributes(toReplace->getAttributes());
1232 // In case if we can handle this set of sttributes - set up function attrs
1233 // directly on statepoint and return attrs later for gc_result intrinsic.
1234 invoke->setAttributes(new_attrs.getFnAttributes());
1235 return_attributes = new_attrs.getRetAttributes();
1236
1237 token = invoke;
1238
1239 // Generate gc relocates in exceptional path
Philip Reames69e51ca2015-04-13 18:07:21 +00001240 BasicBlock *unwindBlock = toReplace->getUnwindDest();
1241 assert(!isa<PHINode>(unwindBlock->begin()) &&
1242 unwindBlock->getUniquePredecessor() &&
1243 "can't safely insert in this block!");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001244
1245 Instruction *IP = &*(unwindBlock->getFirstInsertionPt());
1246 Builder.SetInsertPoint(IP);
1247 Builder.SetCurrentDebugLocation(toReplace->getDebugLoc());
1248
1249 // Extract second element from landingpad return value. We will attach
1250 // exceptional gc relocates to it.
1251 const unsigned idx = 1;
1252 Instruction *exceptional_token =
1253 cast<Instruction>(Builder.CreateExtractValue(
1254 unwindBlock->getLandingPadInst(), idx, "relocate_token"));
Philip Reamesf2041322015-02-20 19:26:04 +00001255 result.UnwindToken = exceptional_token;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001256
1257 // Just throw away return value. We will use the one we got for normal
1258 // block.
1259 (void)CreateGCRelocates(liveVariables, live_start, basePtrs,
1260 exceptional_token, Builder);
1261
1262 // Generate gc relocates and returns for normal block
Philip Reames69e51ca2015-04-13 18:07:21 +00001263 BasicBlock *normalDest = toReplace->getNormalDest();
1264 assert(!isa<PHINode>(normalDest->begin()) &&
1265 normalDest->getUniquePredecessor() &&
1266 "can't safely insert in this block!");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001267
1268 IP = &*(normalDest->getFirstInsertionPt());
1269 Builder.SetInsertPoint(IP);
1270
1271 // gc relocates will be generated later as if it were regular call
1272 // statepoint
Philip Reamesd16a9b12015-02-20 01:06:44 +00001273 }
1274 assert(token);
1275
1276 // Take the name of the original value call if it had one.
1277 token->takeName(CS.getInstruction());
1278
Philip Reames704e78b2015-04-10 22:34:56 +00001279// The GCResult is already inserted, we just need to find it
David Blaikie5e5d7842015-02-22 20:58:38 +00001280#ifndef NDEBUG
1281 Instruction *toReplace = CS.getInstruction();
1282 assert((toReplace->hasNUses(0) || toReplace->hasNUses(1)) &&
1283 "only valid use before rewrite is gc.result");
1284 assert(!toReplace->hasOneUse() ||
1285 isGCResult(cast<Instruction>(*toReplace->user_begin())));
1286#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +00001287
1288 // Update the gc.result of the original statepoint (if any) to use the newly
1289 // inserted statepoint. This is safe to do here since the token can't be
1290 // considered a live reference.
1291 CS.getInstruction()->replaceAllUsesWith(token);
1292
Philip Reames0a3240f2015-02-20 21:34:11 +00001293 result.StatepointToken = token;
1294
Philip Reamesd16a9b12015-02-20 01:06:44 +00001295 // Second, create a gc.relocate for every live variable
Philip Reames0a3240f2015-02-20 21:34:11 +00001296 CreateGCRelocates(liveVariables, live_start, basePtrs, token, Builder);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001297}
1298
1299namespace {
1300struct name_ordering {
1301 Value *base;
1302 Value *derived;
1303 bool operator()(name_ordering const &a, name_ordering const &b) {
1304 return -1 == a.derived->getName().compare(b.derived->getName());
1305 }
1306};
1307}
1308static void stablize_order(SmallVectorImpl<Value *> &basevec,
1309 SmallVectorImpl<Value *> &livevec) {
1310 assert(basevec.size() == livevec.size());
1311
Philip Reames860660e2015-02-20 22:05:18 +00001312 SmallVector<name_ordering, 64> temp;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001313 for (size_t i = 0; i < basevec.size(); i++) {
1314 name_ordering v;
1315 v.base = basevec[i];
1316 v.derived = livevec[i];
1317 temp.push_back(v);
1318 }
1319 std::sort(temp.begin(), temp.end(), name_ordering());
1320 for (size_t i = 0; i < basevec.size(); i++) {
1321 basevec[i] = temp[i].base;
1322 livevec[i] = temp[i].derived;
1323 }
1324}
1325
1326// Replace an existing gc.statepoint with a new one and a set of gc.relocates
1327// which make the relocations happening at this safepoint explicit.
Philip Reames704e78b2015-04-10 22:34:56 +00001328//
Philip Reamesd16a9b12015-02-20 01:06:44 +00001329// WARNING: Does not do any fixup to adjust users of the original live
1330// values. That's the callers responsibility.
1331static void
1332makeStatepointExplicit(DominatorTree &DT, const CallSite &CS, Pass *P,
1333 PartiallyConstructedSafepointRecord &result) {
Philip Reamesf2041322015-02-20 19:26:04 +00001334 auto liveset = result.liveset;
1335 auto PointerToBase = result.PointerToBase;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001336
1337 // Convert to vector for efficient cross referencing.
1338 SmallVector<Value *, 64> basevec, livevec;
1339 livevec.reserve(liveset.size());
1340 basevec.reserve(liveset.size());
1341 for (Value *L : liveset) {
1342 livevec.push_back(L);
1343
Philip Reamesf2041322015-02-20 19:26:04 +00001344 assert(PointerToBase.find(L) != PointerToBase.end());
1345 Value *base = PointerToBase[L];
Philip Reamesd16a9b12015-02-20 01:06:44 +00001346 basevec.push_back(base);
1347 }
1348 assert(livevec.size() == basevec.size());
1349
1350 // To make the output IR slightly more stable (for use in diffs), ensure a
1351 // fixed order of the values in the safepoint (by sorting the value name).
1352 // The order is otherwise meaningless.
1353 stablize_order(basevec, livevec);
1354
1355 // Do the actual rewriting and delete the old statepoint
1356 makeStatepointExplicitImpl(CS, basevec, livevec, P, result);
1357 CS.getInstruction()->eraseFromParent();
1358}
1359
1360// Helper function for the relocationViaAlloca.
1361// It receives iterator to the statepoint gc relocates and emits store to the
1362// assigned
1363// location (via allocaMap) for the each one of them.
1364// Add visited values into the visitedLiveValues set we will later use them
1365// for sanity check.
1366static void
Sanjoy Das5665c992015-05-11 23:47:27 +00001367insertRelocationStores(iterator_range<Value::user_iterator> GCRelocs,
1368 DenseMap<Value *, Value *> &AllocaMap,
1369 DenseSet<Value *> &VisitedLiveValues) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001370
Sanjoy Das5665c992015-05-11 23:47:27 +00001371 for (User *U : GCRelocs) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001372 if (!isa<IntrinsicInst>(U))
1373 continue;
1374
Sanjoy Das5665c992015-05-11 23:47:27 +00001375 IntrinsicInst *RelocatedValue = cast<IntrinsicInst>(U);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001376
1377 // We only care about relocates
Sanjoy Das5665c992015-05-11 23:47:27 +00001378 if (RelocatedValue->getIntrinsicID() !=
Philip Reamesd16a9b12015-02-20 01:06:44 +00001379 Intrinsic::experimental_gc_relocate) {
1380 continue;
1381 }
1382
Sanjoy Das5665c992015-05-11 23:47:27 +00001383 GCRelocateOperands RelocateOperands(RelocatedValue);
1384 Value *OriginalValue =
1385 const_cast<Value *>(RelocateOperands.getDerivedPtr());
1386 assert(AllocaMap.count(OriginalValue));
1387 Value *Alloca = AllocaMap[OriginalValue];
Philip Reamesd16a9b12015-02-20 01:06:44 +00001388
1389 // Emit store into the related alloca
Sanjoy Das89c54912015-05-11 18:49:34 +00001390 // All gc_relocate are i8 addrspace(1)* typed, and it must be bitcasted to
1391 // the correct type according to alloca.
Sanjoy Das5665c992015-05-11 23:47:27 +00001392 assert(RelocatedValue->getNextNode() && "Should always have one since it's not a terminator");
1393 IRBuilder<> Builder(RelocatedValue->getNextNode());
Sanjoy Das89c54912015-05-11 18:49:34 +00001394 Value *CastedRelocatedValue =
Sanjoy Das5665c992015-05-11 23:47:27 +00001395 Builder.CreateBitCast(RelocatedValue, cast<AllocaInst>(Alloca)->getAllocatedType(),
1396 RelocatedValue->hasName() ? RelocatedValue->getName() + ".casted" : "");
Sanjoy Das89c54912015-05-11 18:49:34 +00001397
Sanjoy Das5665c992015-05-11 23:47:27 +00001398 StoreInst *Store = new StoreInst(CastedRelocatedValue, Alloca);
1399 Store->insertAfter(cast<Instruction>(CastedRelocatedValue));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001400
1401#ifndef NDEBUG
Sanjoy Das5665c992015-05-11 23:47:27 +00001402 VisitedLiveValues.insert(OriginalValue);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001403#endif
1404 }
1405}
1406
Igor Laevskye0317182015-05-19 15:59:05 +00001407// Helper function for the "relocationViaAlloca". Similar to the
1408// "insertRelocationStores" but works for rematerialized values.
1409static void
1410insertRematerializationStores(
1411 RematerializedValueMapTy RematerializedValues,
1412 DenseMap<Value *, Value *> &AllocaMap,
1413 DenseSet<Value *> &VisitedLiveValues) {
1414
1415 for (auto RematerializedValuePair: RematerializedValues) {
1416 Instruction *RematerializedValue = RematerializedValuePair.first;
1417 Value *OriginalValue = RematerializedValuePair.second;
1418
1419 assert(AllocaMap.count(OriginalValue) &&
1420 "Can not find alloca for rematerialized value");
1421 Value *Alloca = AllocaMap[OriginalValue];
1422
1423 StoreInst *Store = new StoreInst(RematerializedValue, Alloca);
1424 Store->insertAfter(RematerializedValue);
1425
1426#ifndef NDEBUG
1427 VisitedLiveValues.insert(OriginalValue);
1428#endif
1429 }
1430}
1431
Philip Reamesd16a9b12015-02-20 01:06:44 +00001432/// do all the relocation update via allocas and mem2reg
1433static void relocationViaAlloca(
Igor Laevsky285fe842015-05-19 16:29:43 +00001434 Function &F, DominatorTree &DT, ArrayRef<Value *> Live,
1435 ArrayRef<struct PartiallyConstructedSafepointRecord> Records) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001436#ifndef NDEBUG
Philip Reamesa6ebf072015-03-27 05:53:16 +00001437 // record initial number of (static) allocas; we'll check we have the same
1438 // number when we get done.
1439 int InitialAllocaNum = 0;
Philip Reames704e78b2015-04-10 22:34:56 +00001440 for (auto I = F.getEntryBlock().begin(), E = F.getEntryBlock().end(); I != E;
1441 I++)
Philip Reamesa6ebf072015-03-27 05:53:16 +00001442 if (isa<AllocaInst>(*I))
1443 InitialAllocaNum++;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001444#endif
1445
1446 // TODO-PERF: change data structures, reserve
Igor Laevsky285fe842015-05-19 16:29:43 +00001447 DenseMap<Value *, Value *> AllocaMap;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001448 SmallVector<AllocaInst *, 200> PromotableAllocas;
Igor Laevskye0317182015-05-19 15:59:05 +00001449 // Used later to chack that we have enough allocas to store all values
1450 std::size_t NumRematerializedValues = 0;
Igor Laevsky285fe842015-05-19 16:29:43 +00001451 PromotableAllocas.reserve(Live.size());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001452
Igor Laevskye0317182015-05-19 15:59:05 +00001453 // Emit alloca for "LiveValue" and record it in "allocaMap" and
1454 // "PromotableAllocas"
1455 auto emitAllocaFor = [&](Value *LiveValue) {
1456 AllocaInst *Alloca = new AllocaInst(LiveValue->getType(), "",
1457 F.getEntryBlock().getFirstNonPHI());
Igor Laevsky285fe842015-05-19 16:29:43 +00001458 AllocaMap[LiveValue] = Alloca;
Igor Laevskye0317182015-05-19 15:59:05 +00001459 PromotableAllocas.push_back(Alloca);
1460 };
1461
Philip Reamesd16a9b12015-02-20 01:06:44 +00001462 // emit alloca for each live gc pointer
Igor Laevsky285fe842015-05-19 16:29:43 +00001463 for (unsigned i = 0; i < Live.size(); i++) {
1464 emitAllocaFor(Live[i]);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001465 }
1466
Igor Laevskye0317182015-05-19 15:59:05 +00001467 // emit allocas for rematerialized values
Igor Laevsky285fe842015-05-19 16:29:43 +00001468 for (size_t i = 0; i < Records.size(); i++) {
1469 const struct PartiallyConstructedSafepointRecord &Info = Records[i];
Igor Laevskye0317182015-05-19 15:59:05 +00001470
Igor Laevsky285fe842015-05-19 16:29:43 +00001471 for (auto RematerializedValuePair : Info.RematerializedValues) {
Igor Laevskye0317182015-05-19 15:59:05 +00001472 Value *OriginalValue = RematerializedValuePair.second;
Igor Laevsky285fe842015-05-19 16:29:43 +00001473 if (AllocaMap.count(OriginalValue) != 0)
Igor Laevskye0317182015-05-19 15:59:05 +00001474 continue;
1475
1476 emitAllocaFor(OriginalValue);
1477 ++NumRematerializedValues;
1478 }
1479 }
Igor Laevsky285fe842015-05-19 16:29:43 +00001480
Philip Reamesd16a9b12015-02-20 01:06:44 +00001481 // The next two loops are part of the same conceptual operation. We need to
1482 // insert a store to the alloca after the original def and at each
1483 // redefinition. We need to insert a load before each use. These are split
1484 // into distinct loops for performance reasons.
1485
1486 // update gc pointer after each statepoint
1487 // either store a relocated value or null (if no relocated value found for
1488 // this gc pointer and it is not a gc_result)
1489 // this must happen before we update the statepoint with load of alloca
1490 // otherwise we lose the link between statepoint and old def
Igor Laevsky285fe842015-05-19 16:29:43 +00001491 for (size_t i = 0; i < Records.size(); i++) {
1492 const struct PartiallyConstructedSafepointRecord &Info = Records[i];
1493 Value *Statepoint = Info.StatepointToken;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001494
1495 // This will be used for consistency check
Igor Laevsky285fe842015-05-19 16:29:43 +00001496 DenseSet<Value *> VisitedLiveValues;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001497
1498 // Insert stores for normal statepoint gc relocates
Igor Laevsky285fe842015-05-19 16:29:43 +00001499 insertRelocationStores(Statepoint->users(), AllocaMap, VisitedLiveValues);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001500
1501 // In case if it was invoke statepoint
1502 // we will insert stores for exceptional path gc relocates.
Philip Reames0a3240f2015-02-20 21:34:11 +00001503 if (isa<InvokeInst>(Statepoint)) {
Igor Laevsky285fe842015-05-19 16:29:43 +00001504 insertRelocationStores(Info.UnwindToken->users(), AllocaMap,
1505 VisitedLiveValues);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001506 }
1507
Igor Laevskye0317182015-05-19 15:59:05 +00001508 // Do similar thing with rematerialized values
Igor Laevsky285fe842015-05-19 16:29:43 +00001509 insertRematerializationStores(Info.RematerializedValues, AllocaMap,
1510 VisitedLiveValues);
Igor Laevskye0317182015-05-19 15:59:05 +00001511
Philip Reamese73300b2015-04-13 16:41:32 +00001512 if (ClobberNonLive) {
1513 // As a debuging aid, pretend that an unrelocated pointer becomes null at
1514 // the gc.statepoint. This will turn some subtle GC problems into
1515 // slightly easier to debug SEGVs. Note that on large IR files with
1516 // lots of gc.statepoints this is extremely costly both memory and time
1517 // wise.
1518 SmallVector<AllocaInst *, 64> ToClobber;
Igor Laevsky285fe842015-05-19 16:29:43 +00001519 for (auto Pair : AllocaMap) {
Philip Reamese73300b2015-04-13 16:41:32 +00001520 Value *Def = Pair.first;
1521 AllocaInst *Alloca = cast<AllocaInst>(Pair.second);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001522
Philip Reamese73300b2015-04-13 16:41:32 +00001523 // This value was relocated
Igor Laevsky285fe842015-05-19 16:29:43 +00001524 if (VisitedLiveValues.count(Def)) {
Philip Reamese73300b2015-04-13 16:41:32 +00001525 continue;
1526 }
1527 ToClobber.push_back(Alloca);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001528 }
Philip Reamesfa2fcf172015-02-20 19:51:56 +00001529
Philip Reamese73300b2015-04-13 16:41:32 +00001530 auto InsertClobbersAt = [&](Instruction *IP) {
1531 for (auto *AI : ToClobber) {
1532 auto AIType = cast<PointerType>(AI->getType());
1533 auto PT = cast<PointerType>(AIType->getElementType());
1534 Constant *CPN = ConstantPointerNull::get(PT);
Igor Laevsky285fe842015-05-19 16:29:43 +00001535 StoreInst *Store = new StoreInst(CPN, AI);
1536 Store->insertBefore(IP);
Philip Reamese73300b2015-04-13 16:41:32 +00001537 }
1538 };
1539
1540 // Insert the clobbering stores. These may get intermixed with the
1541 // gc.results and gc.relocates, but that's fine.
1542 if (auto II = dyn_cast<InvokeInst>(Statepoint)) {
1543 InsertClobbersAt(II->getNormalDest()->getFirstInsertionPt());
1544 InsertClobbersAt(II->getUnwindDest()->getFirstInsertionPt());
1545 } else {
1546 BasicBlock::iterator Next(cast<CallInst>(Statepoint));
1547 Next++;
1548 InsertClobbersAt(Next);
Philip Reamesfa2fcf172015-02-20 19:51:56 +00001549 }
David Blaikie82ad7872015-02-20 23:44:24 +00001550 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00001551 }
1552 // update use with load allocas and add store for gc_relocated
Igor Laevsky285fe842015-05-19 16:29:43 +00001553 for (auto Pair : AllocaMap) {
1554 Value *Def = Pair.first;
1555 Value *Alloca = Pair.second;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001556
1557 // we pre-record the uses of allocas so that we dont have to worry about
1558 // later update
1559 // that change the user information.
Igor Laevsky285fe842015-05-19 16:29:43 +00001560 SmallVector<Instruction *, 20> Uses;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001561 // PERF: trade a linear scan for repeated reallocation
Igor Laevsky285fe842015-05-19 16:29:43 +00001562 Uses.reserve(std::distance(Def->user_begin(), Def->user_end()));
1563 for (User *U : Def->users()) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001564 if (!isa<ConstantExpr>(U)) {
1565 // If the def has a ConstantExpr use, then the def is either a
1566 // ConstantExpr use itself or null. In either case
1567 // (recursively in the first, directly in the second), the oop
1568 // it is ultimately dependent on is null and this particular
1569 // use does not need to be fixed up.
Igor Laevsky285fe842015-05-19 16:29:43 +00001570 Uses.push_back(cast<Instruction>(U));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001571 }
1572 }
1573
Igor Laevsky285fe842015-05-19 16:29:43 +00001574 std::sort(Uses.begin(), Uses.end());
1575 auto Last = std::unique(Uses.begin(), Uses.end());
1576 Uses.erase(Last, Uses.end());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001577
Igor Laevsky285fe842015-05-19 16:29:43 +00001578 for (Instruction *Use : Uses) {
1579 if (isa<PHINode>(Use)) {
1580 PHINode *Phi = cast<PHINode>(Use);
1581 for (unsigned i = 0; i < Phi->getNumIncomingValues(); i++) {
1582 if (Def == Phi->getIncomingValue(i)) {
1583 LoadInst *Load = new LoadInst(
1584 Alloca, "", Phi->getIncomingBlock(i)->getTerminator());
1585 Phi->setIncomingValue(i, Load);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001586 }
1587 }
1588 } else {
Igor Laevsky285fe842015-05-19 16:29:43 +00001589 LoadInst *Load = new LoadInst(Alloca, "", Use);
1590 Use->replaceUsesOfWith(Def, Load);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001591 }
1592 }
1593
1594 // emit store for the initial gc value
1595 // store must be inserted after load, otherwise store will be in alloca's
1596 // use list and an extra load will be inserted before it
Igor Laevsky285fe842015-05-19 16:29:43 +00001597 StoreInst *Store = new StoreInst(Def, Alloca);
1598 if (Instruction *Inst = dyn_cast<Instruction>(Def)) {
1599 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(Inst)) {
Philip Reames6da37852015-03-04 00:13:52 +00001600 // InvokeInst is a TerminatorInst so the store need to be inserted
1601 // into its normal destination block.
Igor Laevsky285fe842015-05-19 16:29:43 +00001602 BasicBlock *NormalDest = Invoke->getNormalDest();
1603 Store->insertBefore(NormalDest->getFirstNonPHI());
Philip Reames6da37852015-03-04 00:13:52 +00001604 } else {
Igor Laevsky285fe842015-05-19 16:29:43 +00001605 assert(!Inst->isTerminator() &&
Philip Reames6da37852015-03-04 00:13:52 +00001606 "The only TerminatorInst that can produce a value is "
1607 "InvokeInst which is handled above.");
Igor Laevsky285fe842015-05-19 16:29:43 +00001608 Store->insertAfter(Inst);
Philip Reames6da37852015-03-04 00:13:52 +00001609 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00001610 } else {
Igor Laevsky285fe842015-05-19 16:29:43 +00001611 assert(isa<Argument>(Def));
1612 Store->insertAfter(cast<Instruction>(Alloca));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001613 }
1614 }
1615
Igor Laevsky285fe842015-05-19 16:29:43 +00001616 assert(PromotableAllocas.size() == Live.size() + NumRematerializedValues &&
Philip Reamesd16a9b12015-02-20 01:06:44 +00001617 "we must have the same allocas with lives");
1618 if (!PromotableAllocas.empty()) {
1619 // apply mem2reg to promote alloca to SSA
1620 PromoteMemToReg(PromotableAllocas, DT);
1621 }
1622
1623#ifndef NDEBUG
Philip Reames704e78b2015-04-10 22:34:56 +00001624 for (auto I = F.getEntryBlock().begin(), E = F.getEntryBlock().end(); I != E;
1625 I++)
Philip Reamesa6ebf072015-03-27 05:53:16 +00001626 if (isa<AllocaInst>(*I))
1627 InitialAllocaNum--;
1628 assert(InitialAllocaNum == 0 && "We must not introduce any extra allocas");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001629#endif
1630}
1631
1632/// Implement a unique function which doesn't require we sort the input
1633/// vector. Doing so has the effect of changing the output of a couple of
1634/// tests in ways which make them less useful in testing fused safepoints.
Philip Reamesd2b66462015-02-20 22:39:41 +00001635template <typename T> static void unique_unsorted(SmallVectorImpl<T> &Vec) {
1636 DenseSet<T> Seen;
1637 SmallVector<T, 128> TempVec;
1638 TempVec.reserve(Vec.size());
1639 for (auto Element : Vec)
1640 TempVec.push_back(Element);
1641 Vec.clear();
1642 for (auto V : TempVec) {
1643 if (Seen.insert(V).second) {
1644 Vec.push_back(V);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001645 }
1646 }
1647}
1648
Philip Reamesd16a9b12015-02-20 01:06:44 +00001649/// Insert holders so that each Value is obviously live through the entire
Philip Reamesf209a152015-04-13 20:00:30 +00001650/// lifetime of the call.
Philip Reamesd16a9b12015-02-20 01:06:44 +00001651static void insertUseHolderAfter(CallSite &CS, const ArrayRef<Value *> Values,
Philip Reamesf209a152015-04-13 20:00:30 +00001652 SmallVectorImpl<CallInst *> &Holders) {
Philip Reames21142752015-04-13 19:07:47 +00001653 if (Values.empty())
1654 // No values to hold live, might as well not insert the empty holder
1655 return;
1656
Philip Reamesd16a9b12015-02-20 01:06:44 +00001657 Module *M = CS.getInstruction()->getParent()->getParent()->getParent();
Philip Reamesf209a152015-04-13 20:00:30 +00001658 // Use a dummy vararg function to actually hold the values live
1659 Function *Func = cast<Function>(M->getOrInsertFunction(
1660 "__tmp_use", FunctionType::get(Type::getVoidTy(M->getContext()), true)));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001661 if (CS.isCall()) {
1662 // For call safepoints insert dummy calls right after safepoint
Philip Reamesf209a152015-04-13 20:00:30 +00001663 BasicBlock::iterator Next(CS.getInstruction());
1664 Next++;
1665 Holders.push_back(CallInst::Create(Func, Values, "", Next));
1666 return;
1667 }
1668 // For invoke safepooints insert dummy calls both in normal and
1669 // exceptional destination blocks
1670 auto *II = cast<InvokeInst>(CS.getInstruction());
1671 Holders.push_back(CallInst::Create(
1672 Func, Values, "", II->getNormalDest()->getFirstInsertionPt()));
1673 Holders.push_back(CallInst::Create(
1674 Func, Values, "", II->getUnwindDest()->getFirstInsertionPt()));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001675}
1676
1677static void findLiveReferences(
Philip Reamesd2b66462015-02-20 22:39:41 +00001678 Function &F, DominatorTree &DT, Pass *P, ArrayRef<CallSite> toUpdate,
1679 MutableArrayRef<struct PartiallyConstructedSafepointRecord> records) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00001680 GCPtrLivenessData OriginalLivenessData;
1681 computeLiveInValues(DT, F, OriginalLivenessData);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001682 for (size_t i = 0; i < records.size(); i++) {
1683 struct PartiallyConstructedSafepointRecord &info = records[i];
Philip Reamesd2b66462015-02-20 22:39:41 +00001684 const CallSite &CS = toUpdate[i];
Philip Reamesdf1ef082015-04-10 22:53:14 +00001685 analyzeParsePointLiveness(DT, OriginalLivenessData, CS, info);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001686 }
1687}
1688
Philip Reames8531d8c2015-04-10 21:48:25 +00001689/// Remove any vector of pointers from the liveset by scalarizing them over the
1690/// statepoint instruction. Adds the scalarized pieces to the liveset. It
1691/// would be preferrable to include the vector in the statepoint itself, but
1692/// the lowering code currently does not handle that. Extending it would be
1693/// slightly non-trivial since it requires a format change. Given how rare
1694/// such cases are (for the moment?) scalarizing is an acceptable comprimise.
1695static void splitVectorValues(Instruction *StatepointInst,
Philip Reames704e78b2015-04-10 22:34:56 +00001696 StatepointLiveSetTy &LiveSet, DominatorTree &DT) {
Philip Reames8531d8c2015-04-10 21:48:25 +00001697 SmallVector<Value *, 16> ToSplit;
1698 for (Value *V : LiveSet)
1699 if (isa<VectorType>(V->getType()))
1700 ToSplit.push_back(V);
1701
1702 if (ToSplit.empty())
1703 return;
1704
1705 Function &F = *(StatepointInst->getParent()->getParent());
1706
Philip Reames704e78b2015-04-10 22:34:56 +00001707 DenseMap<Value *, AllocaInst *> AllocaMap;
Philip Reames8531d8c2015-04-10 21:48:25 +00001708 // First is normal return, second is exceptional return (invoke only)
Philip Reames704e78b2015-04-10 22:34:56 +00001709 DenseMap<Value *, std::pair<Value *, Value *>> Replacements;
Philip Reames8531d8c2015-04-10 21:48:25 +00001710 for (Value *V : ToSplit) {
1711 LiveSet.erase(V);
1712
Philip Reames704e78b2015-04-10 22:34:56 +00001713 AllocaInst *Alloca =
1714 new AllocaInst(V->getType(), "", F.getEntryBlock().getFirstNonPHI());
Philip Reames8531d8c2015-04-10 21:48:25 +00001715 AllocaMap[V] = Alloca;
1716
1717 VectorType *VT = cast<VectorType>(V->getType());
1718 IRBuilder<> Builder(StatepointInst);
Philip Reames704e78b2015-04-10 22:34:56 +00001719 SmallVector<Value *, 16> Elements;
Philip Reames8531d8c2015-04-10 21:48:25 +00001720 for (unsigned i = 0; i < VT->getNumElements(); i++)
1721 Elements.push_back(Builder.CreateExtractElement(V, Builder.getInt32(i)));
1722 LiveSet.insert(Elements.begin(), Elements.end());
1723
1724 auto InsertVectorReform = [&](Instruction *IP) {
1725 Builder.SetInsertPoint(IP);
1726 Builder.SetCurrentDebugLocation(IP->getDebugLoc());
1727 Value *ResultVec = UndefValue::get(VT);
1728 for (unsigned i = 0; i < VT->getNumElements(); i++)
1729 ResultVec = Builder.CreateInsertElement(ResultVec, Elements[i],
1730 Builder.getInt32(i));
1731 return ResultVec;
1732 };
1733
1734 if (isa<CallInst>(StatepointInst)) {
1735 BasicBlock::iterator Next(StatepointInst);
1736 Next++;
1737 Instruction *IP = &*(Next);
1738 Replacements[V].first = InsertVectorReform(IP);
1739 Replacements[V].second = nullptr;
1740 } else {
1741 InvokeInst *Invoke = cast<InvokeInst>(StatepointInst);
1742 // We've already normalized - check that we don't have shared destination
Philip Reames704e78b2015-04-10 22:34:56 +00001743 // blocks
Philip Reames8531d8c2015-04-10 21:48:25 +00001744 BasicBlock *NormalDest = Invoke->getNormalDest();
1745 assert(!isa<PHINode>(NormalDest->begin()));
1746 BasicBlock *UnwindDest = Invoke->getUnwindDest();
1747 assert(!isa<PHINode>(UnwindDest->begin()));
1748 // Insert insert element sequences in both successors
1749 Instruction *IP = &*(NormalDest->getFirstInsertionPt());
1750 Replacements[V].first = InsertVectorReform(IP);
1751 IP = &*(UnwindDest->getFirstInsertionPt());
1752 Replacements[V].second = InsertVectorReform(IP);
1753 }
1754 }
1755 for (Value *V : ToSplit) {
1756 AllocaInst *Alloca = AllocaMap[V];
1757
1758 // Capture all users before we start mutating use lists
Philip Reames704e78b2015-04-10 22:34:56 +00001759 SmallVector<Instruction *, 16> Users;
Philip Reames8531d8c2015-04-10 21:48:25 +00001760 for (User *U : V->users())
1761 Users.push_back(cast<Instruction>(U));
1762
1763 for (Instruction *I : Users) {
1764 if (auto Phi = dyn_cast<PHINode>(I)) {
1765 for (unsigned i = 0; i < Phi->getNumIncomingValues(); i++)
1766 if (V == Phi->getIncomingValue(i)) {
Philip Reames704e78b2015-04-10 22:34:56 +00001767 LoadInst *Load = new LoadInst(
1768 Alloca, "", Phi->getIncomingBlock(i)->getTerminator());
Philip Reames8531d8c2015-04-10 21:48:25 +00001769 Phi->setIncomingValue(i, Load);
1770 }
1771 } else {
1772 LoadInst *Load = new LoadInst(Alloca, "", I);
1773 I->replaceUsesOfWith(V, Load);
1774 }
1775 }
1776
1777 // Store the original value and the replacement value into the alloca
1778 StoreInst *Store = new StoreInst(V, Alloca);
1779 if (auto I = dyn_cast<Instruction>(V))
1780 Store->insertAfter(I);
1781 else
1782 Store->insertAfter(Alloca);
Philip Reames704e78b2015-04-10 22:34:56 +00001783
Philip Reames8531d8c2015-04-10 21:48:25 +00001784 // Normal return for invoke, or call return
1785 Instruction *Replacement = cast<Instruction>(Replacements[V].first);
1786 (new StoreInst(Replacement, Alloca))->insertAfter(Replacement);
1787 // Unwind return for invoke only
1788 Replacement = cast_or_null<Instruction>(Replacements[V].second);
1789 if (Replacement)
1790 (new StoreInst(Replacement, Alloca))->insertAfter(Replacement);
1791 }
1792
1793 // apply mem2reg to promote alloca to SSA
Philip Reames704e78b2015-04-10 22:34:56 +00001794 SmallVector<AllocaInst *, 16> Allocas;
Philip Reames8531d8c2015-04-10 21:48:25 +00001795 for (Value *V : ToSplit)
1796 Allocas.push_back(AllocaMap[V]);
1797 PromoteMemToReg(Allocas, DT);
1798}
1799
Igor Laevskye0317182015-05-19 15:59:05 +00001800// Helper function for the "rematerializeLiveValues". It walks use chain
1801// starting from the "CurrentValue" until it meets "BaseValue". Only "simple"
1802// values are visited (currently it is GEP's and casts). Returns true if it
1803// sucessfully reached "BaseValue" and false otherwise.
1804// Fills "ChainToBase" array with all visited values. "BaseValue" is not
1805// recorded.
1806static bool findRematerializableChainToBasePointer(
1807 SmallVectorImpl<Instruction*> &ChainToBase,
1808 Value *CurrentValue, Value *BaseValue) {
1809
1810 // We have found a base value
1811 if (CurrentValue == BaseValue) {
1812 return true;
1813 }
1814
1815 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurrentValue)) {
1816 ChainToBase.push_back(GEP);
1817 return findRematerializableChainToBasePointer(ChainToBase,
1818 GEP->getPointerOperand(),
1819 BaseValue);
1820 }
1821
1822 if (CastInst *CI = dyn_cast<CastInst>(CurrentValue)) {
1823 Value *Def = CI->stripPointerCasts();
1824
1825 // This two checks are basically similar. First one is here for the
1826 // consistency with findBasePointers logic.
1827 assert(!isa<CastInst>(Def) && "not a pointer cast found");
1828 if (!CI->isNoopCast(CI->getModule()->getDataLayout()))
1829 return false;
1830
1831 ChainToBase.push_back(CI);
1832 return findRematerializableChainToBasePointer(ChainToBase, Def, BaseValue);
1833 }
1834
1835 // Not supported instruction in the chain
1836 return false;
1837}
1838
1839// Helper function for the "rematerializeLiveValues". Compute cost of the use
1840// chain we are going to rematerialize.
1841static unsigned
1842chainToBasePointerCost(SmallVectorImpl<Instruction*> &Chain,
1843 TargetTransformInfo &TTI) {
1844 unsigned Cost = 0;
1845
1846 for (Instruction *Instr : Chain) {
1847 if (CastInst *CI = dyn_cast<CastInst>(Instr)) {
1848 assert(CI->isNoopCast(CI->getModule()->getDataLayout()) &&
1849 "non noop cast is found during rematerialization");
1850
1851 Type *SrcTy = CI->getOperand(0)->getType();
1852 Cost += TTI.getCastInstrCost(CI->getOpcode(), CI->getType(), SrcTy);
1853
1854 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Instr)) {
1855 // Cost of the address calculation
1856 Type *ValTy = GEP->getPointerOperandType()->getPointerElementType();
1857 Cost += TTI.getAddressComputationCost(ValTy);
1858
1859 // And cost of the GEP itself
1860 // TODO: Use TTI->getGEPCost here (it exists, but appears to be not
1861 // allowed for the external usage)
1862 if (!GEP->hasAllConstantIndices())
1863 Cost += 2;
1864
1865 } else {
1866 llvm_unreachable("unsupported instruciton type during rematerialization");
1867 }
1868 }
1869
1870 return Cost;
1871}
1872
1873// From the statepoint liveset pick values that are cheaper to recompute then to
1874// relocate. Remove this values from the liveset, rematerialize them after
1875// statepoint and record them in "Info" structure. Note that similar to
1876// relocated values we don't do any user adjustments here.
1877static void rematerializeLiveValues(CallSite CS,
1878 PartiallyConstructedSafepointRecord &Info,
1879 TargetTransformInfo &TTI) {
Aaron Ballmanff7d4fa2015-05-20 14:53:50 +00001880 const unsigned int ChainLengthThreshold = 10;
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +00001881
Igor Laevskye0317182015-05-19 15:59:05 +00001882 // Record values we are going to delete from this statepoint live set.
1883 // We can not di this in following loop due to iterator invalidation.
1884 SmallVector<Value *, 32> LiveValuesToBeDeleted;
1885
1886 for (Value *LiveValue: Info.liveset) {
1887 // For each live pointer find it's defining chain
1888 SmallVector<Instruction *, 3> ChainToBase;
1889 assert(Info.PointerToBase.find(LiveValue) != Info.PointerToBase.end());
1890 bool FoundChain =
1891 findRematerializableChainToBasePointer(ChainToBase,
1892 LiveValue,
1893 Info.PointerToBase[LiveValue]);
1894 // Nothing to do, or chain is too long
1895 if (!FoundChain ||
1896 ChainToBase.size() == 0 ||
1897 ChainToBase.size() > ChainLengthThreshold)
1898 continue;
1899
1900 // Compute cost of this chain
1901 unsigned Cost = chainToBasePointerCost(ChainToBase, TTI);
1902 // TODO: We can also account for cases when we will be able to remove some
1903 // of the rematerialized values by later optimization passes. I.e if
1904 // we rematerialized several intersecting chains. Or if original values
1905 // don't have any uses besides this statepoint.
1906
1907 // For invokes we need to rematerialize each chain twice - for normal and
1908 // for unwind basic blocks. Model this by multiplying cost by two.
1909 if (CS.isInvoke()) {
1910 Cost *= 2;
1911 }
1912 // If it's too expensive - skip it
1913 if (Cost >= RematerializationThreshold)
1914 continue;
1915
1916 // Remove value from the live set
1917 LiveValuesToBeDeleted.push_back(LiveValue);
1918
1919 // Clone instructions and record them inside "Info" structure
1920
1921 // Walk backwards to visit top-most instructions first
1922 std::reverse(ChainToBase.begin(), ChainToBase.end());
1923
1924 // Utility function which clones all instructions from "ChainToBase"
1925 // and inserts them before "InsertBefore". Returns rematerialized value
1926 // which should be used after statepoint.
1927 auto rematerializeChain = [&ChainToBase](Instruction *InsertBefore) {
1928 Instruction *LastClonedValue = nullptr;
1929 Instruction *LastValue = nullptr;
1930 for (Instruction *Instr: ChainToBase) {
1931 // Only GEP's and casts are suported as we need to be careful to not
1932 // introduce any new uses of pointers not in the liveset.
1933 // Note that it's fine to introduce new uses of pointers which were
1934 // otherwise not used after this statepoint.
1935 assert(isa<GetElementPtrInst>(Instr) || isa<CastInst>(Instr));
1936
1937 Instruction *ClonedValue = Instr->clone();
1938 ClonedValue->insertBefore(InsertBefore);
1939 ClonedValue->setName(Instr->getName() + ".remat");
1940
1941 // If it is not first instruction in the chain then it uses previously
1942 // cloned value. We should update it to use cloned value.
1943 if (LastClonedValue) {
1944 assert(LastValue);
1945 ClonedValue->replaceUsesOfWith(LastValue, LastClonedValue);
1946#ifndef NDEBUG
Igor Laevskyd83f6972015-05-21 13:02:14 +00001947 // Assert that cloned instruction does not use any instructions from
1948 // this chain other than LastClonedValue
1949 for (auto OpValue : ClonedValue->operand_values()) {
1950 assert(std::find(ChainToBase.begin(), ChainToBase.end(), OpValue) ==
1951 ChainToBase.end() &&
1952 "incorrect use in rematerialization chain");
Igor Laevskye0317182015-05-19 15:59:05 +00001953 }
1954#endif
1955 }
1956
1957 LastClonedValue = ClonedValue;
1958 LastValue = Instr;
1959 }
1960 assert(LastClonedValue);
1961 return LastClonedValue;
1962 };
1963
1964 // Different cases for calls and invokes. For invokes we need to clone
1965 // instructions both on normal and unwind path.
1966 if (CS.isCall()) {
1967 Instruction *InsertBefore = CS.getInstruction()->getNextNode();
1968 assert(InsertBefore);
1969 Instruction *RematerializedValue = rematerializeChain(InsertBefore);
1970 Info.RematerializedValues[RematerializedValue] = LiveValue;
1971 } else {
1972 InvokeInst *Invoke = cast<InvokeInst>(CS.getInstruction());
1973
1974 Instruction *NormalInsertBefore =
1975 Invoke->getNormalDest()->getFirstInsertionPt();
1976 Instruction *UnwindInsertBefore =
1977 Invoke->getUnwindDest()->getFirstInsertionPt();
1978
1979 Instruction *NormalRematerializedValue =
1980 rematerializeChain(NormalInsertBefore);
1981 Instruction *UnwindRematerializedValue =
1982 rematerializeChain(UnwindInsertBefore);
1983
1984 Info.RematerializedValues[NormalRematerializedValue] = LiveValue;
1985 Info.RematerializedValues[UnwindRematerializedValue] = LiveValue;
1986 }
1987 }
1988
1989 // Remove rematerializaed values from the live set
1990 for (auto LiveValue: LiveValuesToBeDeleted) {
1991 Info.liveset.erase(LiveValue);
1992 }
1993}
1994
Philip Reamesd16a9b12015-02-20 01:06:44 +00001995static bool insertParsePoints(Function &F, DominatorTree &DT, Pass *P,
Philip Reamesd2b66462015-02-20 22:39:41 +00001996 SmallVectorImpl<CallSite> &toUpdate) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001997#ifndef NDEBUG
1998 // sanity check the input
1999 std::set<CallSite> uniqued;
2000 uniqued.insert(toUpdate.begin(), toUpdate.end());
2001 assert(uniqued.size() == toUpdate.size() && "no duplicates please!");
2002
2003 for (size_t i = 0; i < toUpdate.size(); i++) {
2004 CallSite &CS = toUpdate[i];
2005 assert(CS.getInstruction()->getParent()->getParent() == &F);
2006 assert(isStatepoint(CS) && "expected to already be a deopt statepoint");
2007 }
2008#endif
2009
Philip Reames69e51ca2015-04-13 18:07:21 +00002010 // When inserting gc.relocates for invokes, we need to be able to insert at
2011 // the top of the successor blocks. See the comment on
2012 // normalForInvokeSafepoint on exactly what is needed. Note that this step
Philip Reamesf209a152015-04-13 20:00:30 +00002013 // may restructure the CFG.
2014 for (CallSite CS : toUpdate) {
2015 if (!CS.isInvoke())
2016 continue;
2017 InvokeInst *invoke = cast<InvokeInst>(CS.getInstruction());
2018 normalizeForInvokeSafepoint(invoke->getNormalDest(), invoke->getParent(),
2019 P);
2020 normalizeForInvokeSafepoint(invoke->getUnwindDest(), invoke->getParent(),
2021 P);
2022 }
Philip Reames69e51ca2015-04-13 18:07:21 +00002023
Philip Reamesd16a9b12015-02-20 01:06:44 +00002024 // A list of dummy calls added to the IR to keep various values obviously
2025 // live in the IR. We'll remove all of these when done.
Philip Reamesd2b66462015-02-20 22:39:41 +00002026 SmallVector<CallInst *, 64> holders;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002027
2028 // Insert a dummy call with all of the arguments to the vm_state we'll need
2029 // for the actual safepoint insertion. This ensures reference arguments in
2030 // the deopt argument list are considered live through the safepoint (and
2031 // thus makes sure they get relocated.)
2032 for (size_t i = 0; i < toUpdate.size(); i++) {
2033 CallSite &CS = toUpdate[i];
2034 Statepoint StatepointCS(CS);
2035
2036 SmallVector<Value *, 64> DeoptValues;
2037 for (Use &U : StatepointCS.vm_state_args()) {
2038 Value *Arg = cast<Value>(&U);
Philip Reames8531d8c2015-04-10 21:48:25 +00002039 assert(!isUnhandledGCPointerType(Arg->getType()) &&
2040 "support for FCA unimplemented");
2041 if (isHandledGCPointerType(Arg->getType()))
Philip Reamesd16a9b12015-02-20 01:06:44 +00002042 DeoptValues.push_back(Arg);
2043 }
2044 insertUseHolderAfter(CS, DeoptValues, holders);
2045 }
2046
Philip Reamesd2b66462015-02-20 22:39:41 +00002047 SmallVector<struct PartiallyConstructedSafepointRecord, 64> records;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002048 records.reserve(toUpdate.size());
2049 for (size_t i = 0; i < toUpdate.size(); i++) {
2050 struct PartiallyConstructedSafepointRecord info;
2051 records.push_back(info);
2052 }
2053 assert(records.size() == toUpdate.size());
2054
2055 // A) Identify all gc pointers which are staticly live at the given call
2056 // site.
2057 findLiveReferences(F, DT, P, toUpdate, records);
2058
Philip Reames8531d8c2015-04-10 21:48:25 +00002059 // Do a limited scalarization of any live at safepoint vector values which
2060 // contain pointers. This enables this pass to run after vectorization at
2061 // the cost of some possible performance loss. TODO: it would be nice to
2062 // natively support vectors all the way through the backend so we don't need
2063 // to scalarize here.
2064 for (size_t i = 0; i < records.size(); i++) {
2065 struct PartiallyConstructedSafepointRecord &info = records[i];
2066 Instruction *statepoint = toUpdate[i].getInstruction();
2067 splitVectorValues(cast<Instruction>(statepoint), info.liveset, DT);
2068 }
2069
Philip Reamesd16a9b12015-02-20 01:06:44 +00002070 // B) Find the base pointers for each live pointer
2071 /* scope for caching */ {
2072 // Cache the 'defining value' relation used in the computation and
2073 // insertion of base phis and selects. This ensures that we don't insert
2074 // large numbers of duplicate base_phis.
2075 DefiningValueMapTy DVCache;
2076
2077 for (size_t i = 0; i < records.size(); i++) {
2078 struct PartiallyConstructedSafepointRecord &info = records[i];
2079 CallSite &CS = toUpdate[i];
2080 findBasePointers(DT, DVCache, CS, info);
2081 }
2082 } // end of cache scope
2083
2084 // The base phi insertion logic (for any safepoint) may have inserted new
2085 // instructions which are now live at some safepoint. The simplest such
2086 // example is:
2087 // loop:
2088 // phi a <-- will be a new base_phi here
2089 // safepoint 1 <-- that needs to be live here
2090 // gep a + 1
2091 // safepoint 2
2092 // br loop
Philip Reamesd16a9b12015-02-20 01:06:44 +00002093 // We insert some dummy calls after each safepoint to definitely hold live
2094 // the base pointers which were identified for that safepoint. We'll then
2095 // ask liveness for _every_ base inserted to see what is now live. Then we
2096 // remove the dummy calls.
2097 holders.reserve(holders.size() + records.size());
2098 for (size_t i = 0; i < records.size(); i++) {
2099 struct PartiallyConstructedSafepointRecord &info = records[i];
2100 CallSite &CS = toUpdate[i];
2101
2102 SmallVector<Value *, 128> Bases;
Philip Reamesf2041322015-02-20 19:26:04 +00002103 for (auto Pair : info.PointerToBase) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00002104 Bases.push_back(Pair.second);
2105 }
2106 insertUseHolderAfter(CS, Bases, holders);
2107 }
2108
Philip Reamesdf1ef082015-04-10 22:53:14 +00002109 // By selecting base pointers, we've effectively inserted new uses. Thus, we
2110 // need to rerun liveness. We may *also* have inserted new defs, but that's
2111 // not the key issue.
2112 recomputeLiveInValues(F, DT, P, toUpdate, records);
Philip Reamesd16a9b12015-02-20 01:06:44 +00002113
Philip Reamesd16a9b12015-02-20 01:06:44 +00002114 if (PrintBasePointers) {
2115 for (size_t i = 0; i < records.size(); i++) {
2116 struct PartiallyConstructedSafepointRecord &info = records[i];
2117 errs() << "Base Pairs: (w/Relocation)\n";
Philip Reamesf2041322015-02-20 19:26:04 +00002118 for (auto Pair : info.PointerToBase) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00002119 errs() << " derived %" << Pair.first->getName() << " base %"
2120 << Pair.second->getName() << "\n";
2121 }
2122 }
2123 }
2124 for (size_t i = 0; i < holders.size(); i++) {
2125 holders[i]->eraseFromParent();
2126 holders[i] = nullptr;
2127 }
2128 holders.clear();
2129
Igor Laevskye0317182015-05-19 15:59:05 +00002130 // In order to reduce live set of statepoint we might choose to rematerialize
2131 // some values instead of relocating them. This is purelly an optimization and
2132 // does not influence correctness.
2133 TargetTransformInfo &TTI =
2134 P->getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
2135
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +00002136 for (size_t i = 0; i < records.size(); i++) {
Igor Laevskye0317182015-05-19 15:59:05 +00002137 struct PartiallyConstructedSafepointRecord &info = records[i];
2138 CallSite &CS = toUpdate[i];
2139
2140 rematerializeLiveValues(CS, info, TTI);
2141 }
2142
Philip Reamesd16a9b12015-02-20 01:06:44 +00002143 // Now run through and replace the existing statepoints with new ones with
2144 // the live variables listed. We do not yet update uses of the values being
2145 // relocated. We have references to live variables that need to
2146 // survive to the last iteration of this loop. (By construction, the
2147 // previous statepoint can not be a live variable, thus we can and remove
2148 // the old statepoint calls as we go.)
2149 for (size_t i = 0; i < records.size(); i++) {
2150 struct PartiallyConstructedSafepointRecord &info = records[i];
2151 CallSite &CS = toUpdate[i];
2152 makeStatepointExplicit(DT, CS, P, info);
2153 }
2154 toUpdate.clear(); // prevent accident use of invalid CallSites
2155
Philip Reamesd16a9b12015-02-20 01:06:44 +00002156 // Do all the fixups of the original live variables to their relocated selves
Philip Reamesd2b66462015-02-20 22:39:41 +00002157 SmallVector<Value *, 128> live;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002158 for (size_t i = 0; i < records.size(); i++) {
2159 struct PartiallyConstructedSafepointRecord &info = records[i];
2160 // We can't simply save the live set from the original insertion. One of
2161 // the live values might be the result of a call which needs a safepoint.
2162 // That Value* no longer exists and we need to use the new gc_result.
2163 // Thankfully, the liveset is embedded in the statepoint (and updated), so
2164 // we just grab that.
Philip Reames0a3240f2015-02-20 21:34:11 +00002165 Statepoint statepoint(info.StatepointToken);
Philip Reamesd16a9b12015-02-20 01:06:44 +00002166 live.insert(live.end(), statepoint.gc_args_begin(),
2167 statepoint.gc_args_end());
Philip Reames9a2e01d2015-04-13 17:35:55 +00002168#ifndef NDEBUG
2169 // Do some basic sanity checks on our liveness results before performing
2170 // relocation. Relocation can and will turn mistakes in liveness results
2171 // into non-sensical code which is must harder to debug.
2172 // TODO: It would be nice to test consistency as well
2173 assert(DT.isReachableFromEntry(info.StatepointToken->getParent()) &&
2174 "statepoint must be reachable or liveness is meaningless");
2175 for (Value *V : statepoint.gc_args()) {
2176 if (!isa<Instruction>(V))
2177 // Non-instruction values trivial dominate all possible uses
2178 continue;
2179 auto LiveInst = cast<Instruction>(V);
2180 assert(DT.isReachableFromEntry(LiveInst->getParent()) &&
2181 "unreachable values should never be live");
2182 assert(DT.dominates(LiveInst, info.StatepointToken) &&
2183 "basic SSA liveness expectation violated by liveness analysis");
2184 }
2185#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +00002186 }
2187 unique_unsorted(live);
2188
Nick Lewyckyeb3231e2015-02-20 07:14:02 +00002189#ifndef NDEBUG
Philip Reamesd16a9b12015-02-20 01:06:44 +00002190 // sanity check
2191 for (auto ptr : live) {
2192 assert(isGCPointerType(ptr->getType()) && "must be a gc pointer type");
2193 }
Nick Lewyckyeb3231e2015-02-20 07:14:02 +00002194#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +00002195
2196 relocationViaAlloca(F, DT, live, records);
2197 return !records.empty();
2198}
2199
2200/// Returns true if this function should be rewritten by this pass. The main
2201/// point of this function is as an extension point for custom logic.
2202static bool shouldRewriteStatepointsIn(Function &F) {
2203 // TODO: This should check the GCStrategy
Philip Reames2ef029c2015-02-20 18:56:14 +00002204 if (F.hasGC()) {
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +00002205 const char *FunctionGCName = F.getGC();
2206 const StringRef StatepointExampleName("statepoint-example");
2207 const StringRef CoreCLRName("coreclr");
2208 return (StatepointExampleName == FunctionGCName) ||
NAKAMURA Takumi5582a6a2015-05-25 01:43:34 +00002209 (CoreCLRName == FunctionGCName);
2210 } else
Philip Reames2ef029c2015-02-20 18:56:14 +00002211 return false;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002212}
2213
2214bool RewriteStatepointsForGC::runOnFunction(Function &F) {
2215 // Nothing to do for declarations.
2216 if (F.isDeclaration() || F.empty())
2217 return false;
2218
2219 // Policy choice says not to rewrite - the most common reason is that we're
2220 // compiling code without a GCStrategy.
2221 if (!shouldRewriteStatepointsIn(F))
2222 return false;
2223
Philip Reames85b36a82015-04-10 22:07:04 +00002224 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Philip Reames704e78b2015-04-10 22:34:56 +00002225
Philip Reames85b36a82015-04-10 22:07:04 +00002226 // Gather all the statepoints which need rewritten. Be careful to only
2227 // consider those in reachable code since we need to ask dominance queries
2228 // when rewriting. We'll delete the unreachable ones in a moment.
Philip Reamesd2b66462015-02-20 22:39:41 +00002229 SmallVector<CallSite, 64> ParsePointNeeded;
Philip Reamesf66d7372015-04-10 22:16:58 +00002230 bool HasUnreachableStatepoint = false;
Philip Reamesd2b66462015-02-20 22:39:41 +00002231 for (Instruction &I : inst_range(F)) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00002232 // TODO: only the ones with the flag set!
Philip Reames85b36a82015-04-10 22:07:04 +00002233 if (isStatepoint(I)) {
2234 if (DT.isReachableFromEntry(I.getParent()))
2235 ParsePointNeeded.push_back(CallSite(&I));
2236 else
Philip Reamesf66d7372015-04-10 22:16:58 +00002237 HasUnreachableStatepoint = true;
Philip Reames85b36a82015-04-10 22:07:04 +00002238 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00002239 }
2240
Philip Reames85b36a82015-04-10 22:07:04 +00002241 bool MadeChange = false;
Philip Reames704e78b2015-04-10 22:34:56 +00002242
Philip Reames85b36a82015-04-10 22:07:04 +00002243 // Delete any unreachable statepoints so that we don't have unrewritten
2244 // statepoints surviving this pass. This makes testing easier and the
2245 // resulting IR less confusing to human readers. Rather than be fancy, we
2246 // just reuse a utility function which removes the unreachable blocks.
Philip Reamesf66d7372015-04-10 22:16:58 +00002247 if (HasUnreachableStatepoint)
Philip Reames85b36a82015-04-10 22:07:04 +00002248 MadeChange |= removeUnreachableBlocks(F);
2249
Philip Reamesd16a9b12015-02-20 01:06:44 +00002250 // Return early if no work to do.
2251 if (ParsePointNeeded.empty())
Philip Reames85b36a82015-04-10 22:07:04 +00002252 return MadeChange;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002253
Philip Reames85b36a82015-04-10 22:07:04 +00002254 // As a prepass, go ahead and aggressively destroy single entry phi nodes.
2255 // These are created by LCSSA. They have the effect of increasing the size
2256 // of liveness sets for no good reason. It may be harder to do this post
2257 // insertion since relocations and base phis can confuse things.
2258 for (BasicBlock &BB : F)
2259 if (BB.getUniquePredecessor()) {
2260 MadeChange = true;
2261 FoldSingleEntryPHINodes(&BB);
2262 }
2263
2264 MadeChange |= insertParsePoints(F, DT, this, ParsePointNeeded);
2265 return MadeChange;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002266}
Philip Reamesdf1ef082015-04-10 22:53:14 +00002267
2268// liveness computation via standard dataflow
2269// -------------------------------------------------------------------
2270
2271// TODO: Consider using bitvectors for liveness, the set of potentially
2272// interesting values should be small and easy to pre-compute.
2273
Philip Reamesdf1ef082015-04-10 22:53:14 +00002274/// Compute the live-in set for the location rbegin starting from
2275/// the live-out set of the basic block
2276static void computeLiveInValues(BasicBlock::reverse_iterator rbegin,
2277 BasicBlock::reverse_iterator rend,
2278 DenseSet<Value *> &LiveTmp) {
2279
2280 for (BasicBlock::reverse_iterator ritr = rbegin; ritr != rend; ritr++) {
2281 Instruction *I = &*ritr;
2282
2283 // KILL/Def - Remove this definition from LiveIn
2284 LiveTmp.erase(I);
2285
2286 // Don't consider *uses* in PHI nodes, we handle their contribution to
2287 // predecessor blocks when we seed the LiveOut sets
2288 if (isa<PHINode>(I))
2289 continue;
2290
2291 // USE - Add to the LiveIn set for this instruction
2292 for (Value *V : I->operands()) {
2293 assert(!isUnhandledGCPointerType(V->getType()) &&
2294 "support for FCA unimplemented");
Philip Reames63294cb2015-04-26 19:48:03 +00002295 if (isHandledGCPointerType(V->getType()) && !isa<Constant>(V)) {
2296 // The choice to exclude all things constant here is slightly subtle.
2297 // There are two idependent reasons:
2298 // - We assume that things which are constant (from LLVM's definition)
2299 // do not move at runtime. For example, the address of a global
2300 // variable is fixed, even though it's contents may not be.
2301 // - Second, we can't disallow arbitrary inttoptr constants even
2302 // if the language frontend does. Optimization passes are free to
2303 // locally exploit facts without respect to global reachability. This
2304 // can create sections of code which are dynamically unreachable and
2305 // contain just about anything. (see constants.ll in tests)
Philip Reamesdf1ef082015-04-10 22:53:14 +00002306 LiveTmp.insert(V);
2307 }
2308 }
2309 }
2310}
2311
2312static void computeLiveOutSeed(BasicBlock *BB, DenseSet<Value *> &LiveTmp) {
2313
2314 for (BasicBlock *Succ : successors(BB)) {
2315 const BasicBlock::iterator E(Succ->getFirstNonPHI());
2316 for (BasicBlock::iterator I = Succ->begin(); I != E; I++) {
2317 PHINode *Phi = cast<PHINode>(&*I);
2318 Value *V = Phi->getIncomingValueForBlock(BB);
2319 assert(!isUnhandledGCPointerType(V->getType()) &&
2320 "support for FCA unimplemented");
Philip Reames63294cb2015-04-26 19:48:03 +00002321 if (isHandledGCPointerType(V->getType()) && !isa<Constant>(V)) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00002322 LiveTmp.insert(V);
2323 }
2324 }
2325 }
2326}
2327
2328static DenseSet<Value *> computeKillSet(BasicBlock *BB) {
2329 DenseSet<Value *> KillSet;
2330 for (Instruction &I : *BB)
2331 if (isHandledGCPointerType(I.getType()))
2332 KillSet.insert(&I);
2333 return KillSet;
2334}
2335
Philip Reames9638ff92015-04-11 00:06:47 +00002336#ifndef NDEBUG
Philip Reamesdf1ef082015-04-10 22:53:14 +00002337/// Check that the items in 'Live' dominate 'TI'. This is used as a basic
2338/// sanity check for the liveness computation.
2339static void checkBasicSSA(DominatorTree &DT, DenseSet<Value *> &Live,
2340 TerminatorInst *TI, bool TermOkay = false) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00002341 for (Value *V : Live) {
2342 if (auto *I = dyn_cast<Instruction>(V)) {
2343 // The terminator can be a member of the LiveOut set. LLVM's definition
2344 // of instruction dominance states that V does not dominate itself. As
2345 // such, we need to special case this to allow it.
2346 if (TermOkay && TI == I)
2347 continue;
2348 assert(DT.dominates(I, TI) &&
2349 "basic SSA liveness expectation violated by liveness analysis");
2350 }
2351 }
Philip Reamesdf1ef082015-04-10 22:53:14 +00002352}
2353
2354/// Check that all the liveness sets used during the computation of liveness
2355/// obey basic SSA properties. This is useful for finding cases where we miss
2356/// a def.
2357static void checkBasicSSA(DominatorTree &DT, GCPtrLivenessData &Data,
2358 BasicBlock &BB) {
2359 checkBasicSSA(DT, Data.LiveSet[&BB], BB.getTerminator());
2360 checkBasicSSA(DT, Data.LiveOut[&BB], BB.getTerminator(), true);
2361 checkBasicSSA(DT, Data.LiveIn[&BB], BB.getTerminator());
2362}
Philip Reames9638ff92015-04-11 00:06:47 +00002363#endif
Philip Reamesdf1ef082015-04-10 22:53:14 +00002364
2365static void computeLiveInValues(DominatorTree &DT, Function &F,
2366 GCPtrLivenessData &Data) {
2367
Philip Reames4d80ede2015-04-10 23:11:26 +00002368 SmallSetVector<BasicBlock *, 200> Worklist;
Philip Reamesdf1ef082015-04-10 22:53:14 +00002369 auto AddPredsToWorklist = [&](BasicBlock *BB) {
Philip Reames4d80ede2015-04-10 23:11:26 +00002370 // We use a SetVector so that we don't have duplicates in the worklist.
2371 Worklist.insert(pred_begin(BB), pred_end(BB));
Philip Reamesdf1ef082015-04-10 22:53:14 +00002372 };
2373 auto NextItem = [&]() {
2374 BasicBlock *BB = Worklist.back();
2375 Worklist.pop_back();
Philip Reamesdf1ef082015-04-10 22:53:14 +00002376 return BB;
2377 };
2378
2379 // Seed the liveness for each individual block
2380 for (BasicBlock &BB : F) {
2381 Data.KillSet[&BB] = computeKillSet(&BB);
2382 Data.LiveSet[&BB].clear();
2383 computeLiveInValues(BB.rbegin(), BB.rend(), Data.LiveSet[&BB]);
2384
2385#ifndef NDEBUG
2386 for (Value *Kill : Data.KillSet[&BB])
2387 assert(!Data.LiveSet[&BB].count(Kill) && "live set contains kill");
2388#endif
2389
2390 Data.LiveOut[&BB] = DenseSet<Value *>();
2391 computeLiveOutSeed(&BB, Data.LiveOut[&BB]);
2392 Data.LiveIn[&BB] = Data.LiveSet[&BB];
2393 set_union(Data.LiveIn[&BB], Data.LiveOut[&BB]);
2394 set_subtract(Data.LiveIn[&BB], Data.KillSet[&BB]);
2395 if (!Data.LiveIn[&BB].empty())
2396 AddPredsToWorklist(&BB);
2397 }
2398
2399 // Propagate that liveness until stable
2400 while (!Worklist.empty()) {
2401 BasicBlock *BB = NextItem();
2402
2403 // Compute our new liveout set, then exit early if it hasn't changed
2404 // despite the contribution of our successor.
2405 DenseSet<Value *> LiveOut = Data.LiveOut[BB];
2406 const auto OldLiveOutSize = LiveOut.size();
2407 for (BasicBlock *Succ : successors(BB)) {
2408 assert(Data.LiveIn.count(Succ));
2409 set_union(LiveOut, Data.LiveIn[Succ]);
2410 }
2411 // assert OutLiveOut is a subset of LiveOut
2412 if (OldLiveOutSize == LiveOut.size()) {
2413 // If the sets are the same size, then we didn't actually add anything
2414 // when unioning our successors LiveIn Thus, the LiveIn of this block
2415 // hasn't changed.
2416 continue;
2417 }
2418 Data.LiveOut[BB] = LiveOut;
2419
2420 // Apply the effects of this basic block
2421 DenseSet<Value *> LiveTmp = LiveOut;
2422 set_union(LiveTmp, Data.LiveSet[BB]);
2423 set_subtract(LiveTmp, Data.KillSet[BB]);
2424
2425 assert(Data.LiveIn.count(BB));
2426 const DenseSet<Value *> &OldLiveIn = Data.LiveIn[BB];
2427 // assert: OldLiveIn is a subset of LiveTmp
2428 if (OldLiveIn.size() != LiveTmp.size()) {
2429 Data.LiveIn[BB] = LiveTmp;
2430 AddPredsToWorklist(BB);
2431 }
2432 } // while( !worklist.empty() )
2433
2434#ifndef NDEBUG
2435 // Sanity check our ouput against SSA properties. This helps catch any
2436 // missing kills during the above iteration.
2437 for (BasicBlock &BB : F) {
2438 checkBasicSSA(DT, Data, BB);
2439 }
2440#endif
2441}
2442
2443static void findLiveSetAtInst(Instruction *Inst, GCPtrLivenessData &Data,
2444 StatepointLiveSetTy &Out) {
2445
2446 BasicBlock *BB = Inst->getParent();
2447
2448 // Note: The copy is intentional and required
2449 assert(Data.LiveOut.count(BB));
2450 DenseSet<Value *> LiveOut = Data.LiveOut[BB];
2451
2452 // We want to handle the statepoint itself oddly. It's
2453 // call result is not live (normal), nor are it's arguments
2454 // (unless they're used again later). This adjustment is
2455 // specifically what we need to relocate
2456 BasicBlock::reverse_iterator rend(Inst);
2457 computeLiveInValues(BB->rbegin(), rend, LiveOut);
2458 LiveOut.erase(Inst);
2459 Out.insert(LiveOut.begin(), LiveOut.end());
2460}
2461
2462static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData,
2463 const CallSite &CS,
2464 PartiallyConstructedSafepointRecord &Info) {
2465 Instruction *Inst = CS.getInstruction();
2466 StatepointLiveSetTy Updated;
2467 findLiveSetAtInst(Inst, RevisedLivenessData, Updated);
2468
2469#ifndef NDEBUG
2470 DenseSet<Value *> Bases;
2471 for (auto KVPair : Info.PointerToBase) {
2472 Bases.insert(KVPair.second);
2473 }
2474#endif
2475 // We may have base pointers which are now live that weren't before. We need
2476 // to update the PointerToBase structure to reflect this.
2477 for (auto V : Updated)
2478 if (!Info.PointerToBase.count(V)) {
2479 assert(Bases.count(V) && "can't find base for unexpected live value");
2480 Info.PointerToBase[V] = V;
2481 continue;
2482 }
2483
2484#ifndef NDEBUG
2485 for (auto V : Updated) {
2486 assert(Info.PointerToBase.count(V) &&
2487 "must be able to find base for live value");
2488 }
2489#endif
2490
2491 // Remove any stale base mappings - this can happen since our liveness is
2492 // more precise then the one inherent in the base pointer analysis
2493 DenseSet<Value *> ToErase;
2494 for (auto KVPair : Info.PointerToBase)
2495 if (!Updated.count(KVPair.first))
2496 ToErase.insert(KVPair.first);
2497 for (auto V : ToErase)
2498 Info.PointerToBase.erase(V);
2499
2500#ifndef NDEBUG
2501 for (auto KVPair : Info.PointerToBase)
2502 assert(Updated.count(KVPair.first) && "record for non-live value");
2503#endif
2504
2505 Info.liveset = Updated;
2506}