blob: 2bd337814b4e44adc68b3b12e4cb11aa2e199555 [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"
Philip Reamesabcdc5e2015-08-27 01:02:28 +000017#include "llvm/Analysis/InstructionSimplify.h"
Igor Laevskye0317182015-05-19 15:59:05 +000018#include "llvm/Analysis/TargetTransformInfo.h"
Philip Reamesd16a9b12015-02-20 01:06:44 +000019#include "llvm/ADT/SetOperations.h"
20#include "llvm/ADT/Statistic.h"
21#include "llvm/ADT/DenseSet.h"
Philip Reames4d80ede2015-04-10 23:11:26 +000022#include "llvm/ADT/SetVector.h"
Swaroop Sridhar665bc9c2015-05-20 01:07:23 +000023#include "llvm/ADT/StringRef.h"
Philip Reamesd16a9b12015-02-20 01:06:44 +000024#include "llvm/IR/BasicBlock.h"
25#include "llvm/IR/CallSite.h"
26#include "llvm/IR/Dominators.h"
27#include "llvm/IR/Function.h"
28#include "llvm/IR/IRBuilder.h"
29#include "llvm/IR/InstIterator.h"
30#include "llvm/IR/Instructions.h"
31#include "llvm/IR/Intrinsics.h"
32#include "llvm/IR/IntrinsicInst.h"
33#include "llvm/IR/Module.h"
Sanjoy Das353a19e2015-06-02 22:33:37 +000034#include "llvm/IR/MDBuilder.h"
Philip Reamesd16a9b12015-02-20 01:06:44 +000035#include "llvm/IR/Statepoint.h"
36#include "llvm/IR/Value.h"
37#include "llvm/IR/Verifier.h"
38#include "llvm/Support/Debug.h"
39#include "llvm/Support/CommandLine.h"
40#include "llvm/Transforms/Scalar.h"
41#include "llvm/Transforms/Utils/BasicBlockUtils.h"
42#include "llvm/Transforms/Utils/Cloning.h"
43#include "llvm/Transforms/Utils/Local.h"
44#include "llvm/Transforms/Utils/PromoteMemToReg.h"
45
46#define DEBUG_TYPE "rewrite-statepoints-for-gc"
47
48using namespace llvm;
49
50// Print tracing output
51static cl::opt<bool> TraceLSP("trace-rewrite-statepoints", cl::Hidden,
52 cl::init(false));
53
54// Print the liveset found at the insert location
55static cl::opt<bool> PrintLiveSet("spp-print-liveset", cl::Hidden,
56 cl::init(false));
Philip Reames704e78b2015-04-10 22:34:56 +000057static cl::opt<bool> PrintLiveSetSize("spp-print-liveset-size", cl::Hidden,
58 cl::init(false));
Philip Reamesd16a9b12015-02-20 01:06:44 +000059// Print out the base pointers for debugging
Philip Reames704e78b2015-04-10 22:34:56 +000060static cl::opt<bool> PrintBasePointers("spp-print-base-pointers", cl::Hidden,
61 cl::init(false));
Philip Reamesd16a9b12015-02-20 01:06:44 +000062
Igor Laevskye0317182015-05-19 15:59:05 +000063// Cost threshold measuring when it is profitable to rematerialize value instead
64// of relocating it
65static cl::opt<unsigned>
66RematerializationThreshold("spp-rematerialization-threshold", cl::Hidden,
67 cl::init(6));
68
Philip Reamese73300b2015-04-13 16:41:32 +000069#ifdef XDEBUG
70static bool ClobberNonLive = true;
71#else
72static bool ClobberNonLive = false;
73#endif
74static cl::opt<bool, true> ClobberNonLiveOverride("rs4gc-clobber-non-live",
75 cl::location(ClobberNonLive),
76 cl::Hidden);
77
Benjamin Kramer6f665452015-02-20 14:00:58 +000078namespace {
Sanjoy Dasea45f0e2015-06-02 22:33:34 +000079struct RewriteStatepointsForGC : public ModulePass {
Philip Reamesd16a9b12015-02-20 01:06:44 +000080 static char ID; // Pass identification, replacement for typeid
81
Sanjoy Dasea45f0e2015-06-02 22:33:34 +000082 RewriteStatepointsForGC() : ModulePass(ID) {
Philip Reamesd16a9b12015-02-20 01:06:44 +000083 initializeRewriteStatepointsForGCPass(*PassRegistry::getPassRegistry());
84 }
Sanjoy Dasea45f0e2015-06-02 22:33:34 +000085 bool runOnFunction(Function &F);
86 bool runOnModule(Module &M) override {
87 bool Changed = false;
88 for (Function &F : M)
89 Changed |= runOnFunction(F);
Sanjoy Das353a19e2015-06-02 22:33:37 +000090
91 if (Changed) {
92 // stripDereferenceabilityInfo asserts that shouldRewriteStatepointsIn
93 // returns true for at least one function in the module. Since at least
94 // one function changed, we know that the precondition is satisfied.
95 stripDereferenceabilityInfo(M);
96 }
97
Sanjoy Dasea45f0e2015-06-02 22:33:34 +000098 return Changed;
99 }
Philip Reamesd16a9b12015-02-20 01:06:44 +0000100
101 void getAnalysisUsage(AnalysisUsage &AU) const override {
102 // We add and rewrite a bunch of instructions, but don't really do much
103 // else. We could in theory preserve a lot more analyses here.
104 AU.addRequired<DominatorTreeWrapperPass>();
Igor Laevskye0317182015-05-19 15:59:05 +0000105 AU.addRequired<TargetTransformInfoWrapperPass>();
Philip Reamesd16a9b12015-02-20 01:06:44 +0000106 }
Sanjoy Das353a19e2015-06-02 22:33:37 +0000107
108 /// The IR fed into RewriteStatepointsForGC may have had attributes implying
109 /// dereferenceability that are no longer valid/correct after
110 /// RewriteStatepointsForGC has run. This is because semantically, after
111 /// RewriteStatepointsForGC runs, all calls to gc.statepoint "free" the entire
112 /// heap. stripDereferenceabilityInfo (conservatively) restores correctness
113 /// by erasing all attributes in the module that externally imply
114 /// dereferenceability.
115 ///
116 void stripDereferenceabilityInfo(Module &M);
117
118 // Helpers for stripDereferenceabilityInfo
119 void stripDereferenceabilityInfoFromBody(Function &F);
120 void stripDereferenceabilityInfoFromPrototype(Function &F);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000121};
Benjamin Kramer6f665452015-02-20 14:00:58 +0000122} // namespace
Philip Reamesd16a9b12015-02-20 01:06:44 +0000123
124char RewriteStatepointsForGC::ID = 0;
125
Sanjoy Dasea45f0e2015-06-02 22:33:34 +0000126ModulePass *llvm::createRewriteStatepointsForGCPass() {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000127 return new RewriteStatepointsForGC();
128}
129
130INITIALIZE_PASS_BEGIN(RewriteStatepointsForGC, "rewrite-statepoints-for-gc",
131 "Make relocations explicit at statepoints", false, false)
132INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
133INITIALIZE_PASS_END(RewriteStatepointsForGC, "rewrite-statepoints-for-gc",
134 "Make relocations explicit at statepoints", false, false)
135
136namespace {
Philip Reamesdf1ef082015-04-10 22:53:14 +0000137struct GCPtrLivenessData {
138 /// Values defined in this block.
139 DenseMap<BasicBlock *, DenseSet<Value *>> KillSet;
140 /// Values used in this block (and thus live); does not included values
141 /// killed within this block.
142 DenseMap<BasicBlock *, DenseSet<Value *>> LiveSet;
143
144 /// Values live into this basic block (i.e. used by any
145 /// instruction in this basic block or ones reachable from here)
146 DenseMap<BasicBlock *, DenseSet<Value *>> LiveIn;
147
148 /// Values live out of this basic block (i.e. live into
149 /// any successor block)
150 DenseMap<BasicBlock *, DenseSet<Value *>> LiveOut;
151};
152
Philip Reamesd16a9b12015-02-20 01:06:44 +0000153// The type of the internal cache used inside the findBasePointers family
154// of functions. From the callers perspective, this is an opaque type and
155// should not be inspected.
156//
157// In the actual implementation this caches two relations:
158// - The base relation itself (i.e. this pointer is based on that one)
159// - The base defining value relation (i.e. before base_phi insertion)
160// Generally, after the execution of a full findBasePointer call, only the
161// base relation will remain. Internally, we add a mixture of the two
162// types, then update all the second type to the first type
Philip Reamese9c3b9b2015-02-20 22:48:20 +0000163typedef DenseMap<Value *, Value *> DefiningValueMapTy;
Philip Reames1f017542015-02-20 23:16:52 +0000164typedef DenseSet<llvm::Value *> StatepointLiveSetTy;
Igor Laevskye0317182015-05-19 15:59:05 +0000165typedef DenseMap<Instruction *, Value *> RematerializedValueMapTy;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000166
Philip Reamesd16a9b12015-02-20 01:06:44 +0000167struct PartiallyConstructedSafepointRecord {
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000168 /// The set of values known to be live across this safepoint
Philip Reames860660e2015-02-20 22:05:18 +0000169 StatepointLiveSetTy liveset;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000170
171 /// Mapping from live pointers to a base-defining-value
Philip Reamesf2041322015-02-20 19:26:04 +0000172 DenseMap<llvm::Value *, llvm::Value *> PointerToBase;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000173
Philip Reames0a3240f2015-02-20 21:34:11 +0000174 /// The *new* gc.statepoint instruction itself. This produces the token
175 /// that normal path gc.relocates and the gc.result are tied to.
176 Instruction *StatepointToken;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000177
Philip Reamesf2041322015-02-20 19:26:04 +0000178 /// Instruction to which exceptional gc relocates are attached
179 /// Makes it easier to iterate through them during relocationViaAlloca.
180 Instruction *UnwindToken;
Igor Laevskye0317182015-05-19 15:59:05 +0000181
182 /// Record live values we are rematerialized instead of relocating.
183 /// They are not included into 'liveset' field.
184 /// Maps rematerialized copy to it's original value.
185 RematerializedValueMapTy RematerializedValues;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000186};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000187}
Philip Reamesd16a9b12015-02-20 01:06:44 +0000188
Philip Reamesdf1ef082015-04-10 22:53:14 +0000189/// Compute the live-in set for every basic block in the function
190static void computeLiveInValues(DominatorTree &DT, Function &F,
191 GCPtrLivenessData &Data);
192
193/// Given results from the dataflow liveness computation, find the set of live
194/// Values at a particular instruction.
195static void findLiveSetAtInst(Instruction *inst, GCPtrLivenessData &Data,
196 StatepointLiveSetTy &out);
197
Philip Reamesd16a9b12015-02-20 01:06:44 +0000198// TODO: Once we can get to the GCStrategy, this becomes
199// Optional<bool> isGCManagedPointer(const Value *V) const override {
200
Craig Toppere3dcce92015-08-01 22:20:21 +0000201static bool isGCPointerType(Type *T) {
202 if (auto *PT = dyn_cast<PointerType>(T))
Philip Reamesd16a9b12015-02-20 01:06:44 +0000203 // For the sake of this example GC, we arbitrarily pick addrspace(1) as our
204 // GC managed heap. We know that a pointer into this heap needs to be
205 // updated and that no other pointer does.
206 return (1 == PT->getAddressSpace());
207 return false;
208}
209
Philip Reames8531d8c2015-04-10 21:48:25 +0000210// Return true if this type is one which a) is a gc pointer or contains a GC
211// pointer and b) is of a type this code expects to encounter as a live value.
212// (The insertion code will assert that a type which matches (a) and not (b)
Philip Reames704e78b2015-04-10 22:34:56 +0000213// is not encountered.)
Philip Reames8531d8c2015-04-10 21:48:25 +0000214static bool isHandledGCPointerType(Type *T) {
215 // We fully support gc pointers
216 if (isGCPointerType(T))
217 return true;
218 // We partially support vectors of gc pointers. The code will assert if it
219 // can't handle something.
220 if (auto VT = dyn_cast<VectorType>(T))
221 if (isGCPointerType(VT->getElementType()))
222 return true;
223 return false;
224}
225
226#ifndef NDEBUG
227/// Returns true if this type contains a gc pointer whether we know how to
228/// handle that type or not.
229static bool containsGCPtrType(Type *Ty) {
Philip Reames704e78b2015-04-10 22:34:56 +0000230 if (isGCPointerType(Ty))
Philip Reames8531d8c2015-04-10 21:48:25 +0000231 return true;
232 if (VectorType *VT = dyn_cast<VectorType>(Ty))
233 return isGCPointerType(VT->getScalarType());
234 if (ArrayType *AT = dyn_cast<ArrayType>(Ty))
235 return containsGCPtrType(AT->getElementType());
236 if (StructType *ST = dyn_cast<StructType>(Ty))
Philip Reames704e78b2015-04-10 22:34:56 +0000237 return std::any_of(
238 ST->subtypes().begin(), ST->subtypes().end(),
239 [](Type *SubType) { return containsGCPtrType(SubType); });
Philip Reames8531d8c2015-04-10 21:48:25 +0000240 return false;
241}
242
243// Returns true if this is a type which a) is a gc pointer or contains a GC
244// pointer and b) is of a type which the code doesn't expect (i.e. first class
245// aggregates). Used to trip assertions.
246static bool isUnhandledGCPointerType(Type *Ty) {
247 return containsGCPtrType(Ty) && !isHandledGCPointerType(Ty);
248}
249#endif
250
Philip Reamesd16a9b12015-02-20 01:06:44 +0000251static bool order_by_name(llvm::Value *a, llvm::Value *b) {
252 if (a->hasName() && b->hasName()) {
253 return -1 == a->getName().compare(b->getName());
254 } else if (a->hasName() && !b->hasName()) {
255 return true;
256 } else if (!a->hasName() && b->hasName()) {
257 return false;
258 } else {
259 // Better than nothing, but not stable
260 return a < b;
261 }
262}
263
Philip Reamesdf1ef082015-04-10 22:53:14 +0000264// Conservatively identifies any definitions which might be live at the
265// given instruction. The analysis is performed immediately before the
266// given instruction. Values defined by that instruction are not considered
267// live. Values used by that instruction are considered live.
268static void analyzeParsePointLiveness(
269 DominatorTree &DT, GCPtrLivenessData &OriginalLivenessData,
270 const CallSite &CS, PartiallyConstructedSafepointRecord &result) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000271 Instruction *inst = CS.getInstruction();
272
Philip Reames1f017542015-02-20 23:16:52 +0000273 StatepointLiveSetTy liveset;
Philip Reamesdf1ef082015-04-10 22:53:14 +0000274 findLiveSetAtInst(inst, OriginalLivenessData, liveset);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000275
276 if (PrintLiveSet) {
277 // Note: This output is used by several of the test cases
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000278 // The order of elements in a set is not stable, put them in a vec and sort
Philip Reamesd16a9b12015-02-20 01:06:44 +0000279 // by name
Philip Reames860660e2015-02-20 22:05:18 +0000280 SmallVector<Value *, 64> temp;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000281 temp.insert(temp.end(), liveset.begin(), liveset.end());
282 std::sort(temp.begin(), temp.end(), order_by_name);
283 errs() << "Live Variables:\n";
284 for (Value *V : temp) {
285 errs() << " " << V->getName(); // no newline
286 V->dump();
287 }
288 }
289 if (PrintLiveSetSize) {
290 errs() << "Safepoint For: " << CS.getCalledValue()->getName() << "\n";
291 errs() << "Number live values: " << liveset.size() << "\n";
292 }
293 result.liveset = liveset;
294}
295
Philip Reames311f7102015-05-12 22:19:52 +0000296static Value *findBaseDefiningValue(Value *I);
297
Philip Reames8fe7f132015-06-26 22:47:37 +0000298/// Return a base defining value for the 'Index' element of the given vector
299/// instruction 'I'. If Index is null, returns a BDV for the entire vector
300/// 'I'. As an optimization, this method will try to determine when the
301/// element is known to already be a base pointer. If this can be established,
302/// the second value in the returned pair will be true. Note that either a
303/// vector or a pointer typed value can be returned. For the former, the
304/// vector returned is a BDV (and possibly a base) of the entire vector 'I'.
305/// If the later, the return pointer is a BDV (or possibly a base) for the
306/// particular element in 'I'.
307static std::pair<Value *, bool>
308findBaseDefiningValueOfVector(Value *I, Value *Index = nullptr) {
Philip Reames8531d8c2015-04-10 21:48:25 +0000309 assert(I->getType()->isVectorTy() &&
310 cast<VectorType>(I->getType())->getElementType()->isPointerTy() &&
311 "Illegal to ask for the base pointer of a non-pointer type");
312
313 // Each case parallels findBaseDefiningValue below, see that code for
314 // detailed motivation.
315
316 if (isa<Argument>(I))
317 // An incoming argument to the function is a base pointer
Philip Reames8fe7f132015-06-26 22:47:37 +0000318 return std::make_pair(I, true);
Philip Reames8531d8c2015-04-10 21:48:25 +0000319
320 // We shouldn't see the address of a global as a vector value?
321 assert(!isa<GlobalVariable>(I) &&
322 "unexpected global variable found in base of vector");
323
324 // inlining could possibly introduce phi node that contains
325 // undef if callee has multiple returns
326 if (isa<UndefValue>(I))
327 // utterly meaningless, but useful for dealing with partially optimized
328 // code.
Philip Reames8fe7f132015-06-26 22:47:37 +0000329 return std::make_pair(I, true);
Philip Reames8531d8c2015-04-10 21:48:25 +0000330
331 // Due to inheritance, this must be _after_ the global variable and undef
332 // checks
333 if (Constant *Con = dyn_cast<Constant>(I)) {
334 assert(!isa<GlobalVariable>(I) && !isa<UndefValue>(I) &&
335 "order of checks wrong!");
336 assert(Con->isNullValue() && "null is the only case which makes sense");
Philip Reames8fe7f132015-06-26 22:47:37 +0000337 return std::make_pair(Con, true);
Philip Reames8531d8c2015-04-10 21:48:25 +0000338 }
Philip Reames8fe7f132015-06-26 22:47:37 +0000339
Philip Reames8531d8c2015-04-10 21:48:25 +0000340 if (isa<LoadInst>(I))
Philip Reames8fe7f132015-06-26 22:47:37 +0000341 return std::make_pair(I, true);
342
Philip Reames311f7102015-05-12 22:19:52 +0000343 // For an insert element, we might be able to look through it if we know
Philip Reames8fe7f132015-06-26 22:47:37 +0000344 // something about the indexes.
Philip Reames311f7102015-05-12 22:19:52 +0000345 if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(I)) {
Philip Reames8fe7f132015-06-26 22:47:37 +0000346 if (Index) {
347 Value *InsertIndex = IEI->getOperand(2);
348 // This index is inserting the value, look for its BDV
349 if (InsertIndex == Index)
350 return std::make_pair(findBaseDefiningValue(IEI->getOperand(1)), false);
351 // Both constant, and can't be equal per above. This insert is definitely
352 // not relevant, look back at the rest of the vector and keep trying.
353 if (isa<ConstantInt>(Index) && isa<ConstantInt>(InsertIndex))
354 return findBaseDefiningValueOfVector(IEI->getOperand(0), Index);
355 }
356
357 // We don't know whether this vector contains entirely base pointers or
358 // not. To be conservatively correct, we treat it as a BDV and will
359 // duplicate code as needed to construct a parallel vector of bases.
360 return std::make_pair(IEI, false);
Philip Reames311f7102015-05-12 22:19:52 +0000361 }
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +0000362
Philip Reames8fe7f132015-06-26 22:47:37 +0000363 if (isa<ShuffleVectorInst>(I))
364 // We don't know whether this vector contains entirely base pointers or
365 // not. To be conservatively correct, we treat it as a BDV and will
366 // duplicate code as needed to construct a parallel vector of bases.
367 // TODO: There a number of local optimizations which could be applied here
368 // for particular sufflevector patterns.
369 return std::make_pair(I, false);
370
371 // A PHI or Select is a base defining value. The outer findBasePointer
372 // algorithm is responsible for constructing a base value for this BDV.
373 assert((isa<SelectInst>(I) || isa<PHINode>(I)) &&
374 "unknown vector instruction - no base found for vector element");
375 return std::make_pair(I, false);
Philip Reames8531d8c2015-04-10 21:48:25 +0000376}
377
Philip Reames8fe7f132015-06-26 22:47:37 +0000378static bool isKnownBaseResult(Value *V);
379
Philip Reamesd16a9b12015-02-20 01:06:44 +0000380/// Helper function for findBasePointer - Will return a value which either a)
Philip Reames9ac4e382015-08-12 21:00:20 +0000381/// defines the base pointer for the input, b) blocks the simple search
382/// (i.e. a PHI or Select of two derived pointers), or c) involves a change
383/// from pointer to vector type or back.
Philip Reamesd16a9b12015-02-20 01:06:44 +0000384static Value *findBaseDefiningValue(Value *I) {
Philip Reames8fe7f132015-06-26 22:47:37 +0000385 if (I->getType()->isVectorTy())
386 return findBaseDefiningValueOfVector(I).first;
387
Philip Reamesd16a9b12015-02-20 01:06:44 +0000388 assert(I->getType()->isPointerTy() &&
389 "Illegal to ask for the base pointer of a non-pointer type");
390
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000391 if (isa<Argument>(I))
Philip Reamesd16a9b12015-02-20 01:06:44 +0000392 // An incoming argument to the function is a base pointer
393 // We should have never reached here if this argument isn't an gc value
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000394 return I;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000395
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000396 if (isa<GlobalVariable>(I))
Philip Reamesd16a9b12015-02-20 01:06:44 +0000397 // base case
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000398 return I;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000399
400 // inlining could possibly introduce phi node that contains
401 // undef if callee has multiple returns
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000402 if (isa<UndefValue>(I))
403 // utterly meaningless, but useful for dealing with
404 // partially optimized code.
Philip Reames704e78b2015-04-10 22:34:56 +0000405 return I;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000406
407 // Due to inheritance, this must be _after_ the global variable and undef
408 // checks
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000409 if (Constant *Con = dyn_cast<Constant>(I)) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000410 assert(!isa<GlobalVariable>(I) && !isa<UndefValue>(I) &&
411 "order of checks wrong!");
412 // Note: Finding a constant base for something marked for relocation
413 // doesn't really make sense. The most likely case is either a) some
414 // screwed up the address space usage or b) your validating against
415 // compiled C++ code w/o the proper separation. The only real exception
416 // is a null pointer. You could have generic code written to index of
417 // off a potentially null value and have proven it null. We also use
418 // null pointers in dead paths of relocation phis (which we might later
419 // want to find a base pointer for).
Philip Reames24c6cd52015-03-27 05:47:00 +0000420 assert(isa<ConstantPointerNull>(Con) &&
421 "null is the only case which makes sense");
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000422 return Con;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000423 }
424
425 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000426 Value *Def = CI->stripPointerCasts();
David Blaikie82ad7872015-02-20 23:44:24 +0000427 // If we find a cast instruction here, it means we've found a cast which is
428 // not simply a pointer cast (i.e. an inttoptr). We don't know how to
429 // handle int->ptr conversion.
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000430 assert(!isa<CastInst>(Def) && "shouldn't find another cast here");
431 return findBaseDefiningValue(Def);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000432 }
433
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000434 if (isa<LoadInst>(I))
435 return I; // The value loaded is an gc base itself
Philip Reamesd16a9b12015-02-20 01:06:44 +0000436
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000437 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I))
438 // The base of this GEP is the base
439 return findBaseDefiningValue(GEP->getPointerOperand());
Philip Reamesd16a9b12015-02-20 01:06:44 +0000440
441 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
442 switch (II->getIntrinsicID()) {
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000443 case Intrinsic::experimental_gc_result_ptr:
Philip Reamesd16a9b12015-02-20 01:06:44 +0000444 default:
445 // fall through to general call handling
446 break;
447 case Intrinsic::experimental_gc_statepoint:
448 case Intrinsic::experimental_gc_result_float:
449 case Intrinsic::experimental_gc_result_int:
450 llvm_unreachable("these don't produce pointers");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000451 case Intrinsic::experimental_gc_relocate: {
452 // Rerunning safepoint insertion after safepoints are already
453 // inserted is not supported. It could probably be made to work,
454 // but why are you doing this? There's no good reason.
455 llvm_unreachable("repeat safepoint insertion is not supported");
456 }
457 case Intrinsic::gcroot:
458 // Currently, this mechanism hasn't been extended to work with gcroot.
459 // There's no reason it couldn't be, but I haven't thought about the
460 // implications much.
461 llvm_unreachable(
462 "interaction with the gcroot mechanism is not supported");
463 }
464 }
465 // We assume that functions in the source language only return base
466 // pointers. This should probably be generalized via attributes to support
467 // both source language and internal functions.
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000468 if (isa<CallInst>(I) || isa<InvokeInst>(I))
469 return I;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000470
471 // I have absolutely no idea how to implement this part yet. It's not
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000472 // necessarily hard, I just haven't really looked at it yet.
Philip Reamesd16a9b12015-02-20 01:06:44 +0000473 assert(!isa<LandingPadInst>(I) && "Landing Pad is unimplemented");
474
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000475 if (isa<AtomicCmpXchgInst>(I))
Philip Reamesd16a9b12015-02-20 01:06:44 +0000476 // A CAS is effectively a atomic store and load combined under a
477 // predicate. From the perspective of base pointers, we just treat it
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000478 // like a load.
479 return I;
Philip Reames704e78b2015-04-10 22:34:56 +0000480
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000481 assert(!isa<AtomicRMWInst>(I) && "Xchg handled above, all others are "
Philip Reames704e78b2015-04-10 22:34:56 +0000482 "binary ops which don't apply to pointers");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000483
484 // The aggregate ops. Aggregates can either be in the heap or on the
485 // stack, but in either case, this is simply a field load. As a result,
486 // this is a defining definition of the base just like a load is.
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000487 if (isa<ExtractValueInst>(I))
488 return I;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000489
490 // We should never see an insert vector since that would require we be
491 // tracing back a struct value not a pointer value.
492 assert(!isa<InsertValueInst>(I) &&
493 "Base pointer for a struct is meaningless");
494
Philip Reames9ac4e382015-08-12 21:00:20 +0000495 // An extractelement produces a base result exactly when it's input does.
496 // We may need to insert a parallel instruction to extract the appropriate
497 // element out of the base vector corresponding to the input. Given this,
498 // it's analogous to the phi and select case even though it's not a merge.
499 if (auto *EEI = dyn_cast<ExtractElementInst>(I)) {
500 Value *VectorOperand = EEI->getVectorOperand();
501 Value *Index = EEI->getIndexOperand();
502 std::pair<Value *, bool> pair =
503 findBaseDefiningValueOfVector(VectorOperand, Index);
504 Value *VectorBase = pair.first;
505 if (VectorBase->getType()->isPointerTy())
506 // We found a BDV for this specific element with the vector. This is an
507 // optimization, but in practice it covers most of the useful cases
508 // created via scalarization. Note: The peephole optimization here is
509 // currently needed for correctness since the general algorithm doesn't
510 // yet handle insertelements. That will change shortly.
511 return VectorBase;
512 else {
513 assert(VectorBase->getType()->isVectorTy());
514 // Otherwise, we have an instruction which potentially produces a
515 // derived pointer and we need findBasePointers to clone code for us
516 // such that we can create an instruction which produces the
517 // accompanying base pointer.
518 return EEI;
519 }
520 }
521
Philip Reamesd16a9b12015-02-20 01:06:44 +0000522 // The last two cases here don't return a base pointer. Instead, they
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000523 // return a value which dynamically selects from among several base
Philip Reamesd16a9b12015-02-20 01:06:44 +0000524 // derived pointers (each with it's own base potentially). It's the job of
525 // the caller to resolve these.
Philip Reames704e78b2015-04-10 22:34:56 +0000526 assert((isa<SelectInst>(I) || isa<PHINode>(I)) &&
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000527 "missing instruction case in findBaseDefiningValing");
528 return I;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000529}
530
531/// Returns the base defining value for this value.
Philip Reames18d0feb2015-03-27 05:39:32 +0000532static Value *findBaseDefiningValueCached(Value *I, DefiningValueMapTy &Cache) {
533 Value *&Cached = Cache[I];
Benjamin Kramer6f665452015-02-20 14:00:58 +0000534 if (!Cached) {
535 Cached = findBaseDefiningValue(I);
Philip Reames2a892a62015-07-23 22:25:26 +0000536 DEBUG(dbgs() << "fBDV-cached: " << I->getName() << " -> "
537 << Cached->getName() << "\n");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000538 }
Philip Reames18d0feb2015-03-27 05:39:32 +0000539 assert(Cache[I] != nullptr);
Benjamin Kramer6f665452015-02-20 14:00:58 +0000540 return Cached;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000541}
542
543/// Return a base pointer for this value if known. Otherwise, return it's
544/// base defining value.
Philip Reames18d0feb2015-03-27 05:39:32 +0000545static Value *findBaseOrBDV(Value *I, DefiningValueMapTy &Cache) {
546 Value *Def = findBaseDefiningValueCached(I, Cache);
547 auto Found = Cache.find(Def);
548 if (Found != Cache.end()) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000549 // Either a base-of relation, or a self reference. Caller must check.
Benjamin Kramer6f665452015-02-20 14:00:58 +0000550 return Found->second;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000551 }
552 // Only a BDV available
Philip Reames18d0feb2015-03-27 05:39:32 +0000553 return Def;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000554}
555
556/// Given the result of a call to findBaseDefiningValue, or findBaseOrBDV,
557/// is it known to be a base pointer? Or do we need to continue searching.
Philip Reames18d0feb2015-03-27 05:39:32 +0000558static bool isKnownBaseResult(Value *V) {
Philip Reames9ac4e382015-08-12 21:00:20 +0000559 if (!isa<PHINode>(V) && !isa<SelectInst>(V) && !isa<ExtractElementInst>(V)) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000560 // no recursion possible
561 return true;
562 }
Philip Reames18d0feb2015-03-27 05:39:32 +0000563 if (isa<Instruction>(V) &&
564 cast<Instruction>(V)->getMetadata("is_base_value")) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000565 // This is a previously inserted base phi or select. We know
566 // that this is a base value.
567 return true;
568 }
569
570 // We need to keep searching
571 return false;
572}
573
Philip Reamesd16a9b12015-02-20 01:06:44 +0000574namespace {
Philip Reames9b141ed2015-07-23 22:49:14 +0000575/// Models the state of a single base defining value in the findBasePointer
576/// algorithm for determining where a new instruction is needed to propagate
577/// the base of this BDV.
578class BDVState {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000579public:
580 enum Status { Unknown, Base, Conflict };
581
Philip Reames9b141ed2015-07-23 22:49:14 +0000582 BDVState(Status s, Value *b = nullptr) : status(s), base(b) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000583 assert(status != Base || b);
584 }
Philip Reames9b141ed2015-07-23 22:49:14 +0000585 explicit BDVState(Value *b) : status(Base), base(b) {}
586 BDVState() : status(Unknown), base(nullptr) {}
Philip Reamesd16a9b12015-02-20 01:06:44 +0000587
588 Status getStatus() const { return status; }
589 Value *getBase() const { return base; }
590
591 bool isBase() const { return getStatus() == Base; }
592 bool isUnknown() const { return getStatus() == Unknown; }
593 bool isConflict() const { return getStatus() == Conflict; }
594
Philip Reames9b141ed2015-07-23 22:49:14 +0000595 bool operator==(const BDVState &other) const {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000596 return base == other.base && status == other.status;
597 }
598
Philip Reames9b141ed2015-07-23 22:49:14 +0000599 bool operator!=(const BDVState &other) const { return !(*this == other); }
Philip Reamesd16a9b12015-02-20 01:06:44 +0000600
Philip Reames2a892a62015-07-23 22:25:26 +0000601 LLVM_DUMP_METHOD
602 void dump() const { print(dbgs()); dbgs() << '\n'; }
603
604 void print(raw_ostream &OS) const {
605 OS << status << " (" << base << " - "
606 << (base ? base->getName() : "nullptr") << "): ";
Philip Reamesd16a9b12015-02-20 01:06:44 +0000607 }
608
609private:
610 Status status;
611 Value *base; // non null only if status == base
612};
613
Philip Reames9b141ed2015-07-23 22:49:14 +0000614inline raw_ostream &operator<<(raw_ostream &OS, const BDVState &State) {
Philip Reames2a892a62015-07-23 22:25:26 +0000615 State.print(OS);
616 return OS;
617}
618
619
Philip Reames9b141ed2015-07-23 22:49:14 +0000620typedef DenseMap<Value *, BDVState> ConflictStateMapTy;
621// Values of type BDVState form a lattice, and this is a helper
Philip Reamesd16a9b12015-02-20 01:06:44 +0000622// class that implementes the meet operation. The meat of the meet
Philip Reames9b141ed2015-07-23 22:49:14 +0000623// operation is implemented in MeetBDVStates::pureMeet
624class MeetBDVStates {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000625public:
Philip Reames273e6bb2015-07-23 21:41:27 +0000626 /// Initializes the currentResult to the TOP state so that if can be met with
627 /// any other state to produce that state.
Philip Reames9b141ed2015-07-23 22:49:14 +0000628 MeetBDVStates() {}
Philip Reamesd16a9b12015-02-20 01:06:44 +0000629
Philip Reames9b141ed2015-07-23 22:49:14 +0000630 // Destructively meet the current result with the given BDVState
631 void meetWith(BDVState otherState) {
Philip Reames273e6bb2015-07-23 21:41:27 +0000632 currentResult = meet(otherState, currentResult);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000633 }
634
Philip Reames9b141ed2015-07-23 22:49:14 +0000635 BDVState getResult() const { return currentResult; }
Philip Reamesd16a9b12015-02-20 01:06:44 +0000636
637private:
Philip Reames9b141ed2015-07-23 22:49:14 +0000638 BDVState currentResult;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000639
Philip Reames9b141ed2015-07-23 22:49:14 +0000640 /// Perform a meet operation on two elements of the BDVState lattice.
641 static BDVState meet(BDVState LHS, BDVState RHS) {
Philip Reames273e6bb2015-07-23 21:41:27 +0000642 assert((pureMeet(LHS, RHS) == pureMeet(RHS, LHS)) &&
643 "math is wrong: meet does not commute!");
Philip Reames9b141ed2015-07-23 22:49:14 +0000644 BDVState Result = pureMeet(LHS, RHS);
Philip Reames2a892a62015-07-23 22:25:26 +0000645 DEBUG(dbgs() << "meet of " << LHS << " with " << RHS
646 << " produced " << Result << "\n");
647 return Result;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000648 }
649
Philip Reames9b141ed2015-07-23 22:49:14 +0000650 static BDVState pureMeet(const BDVState &stateA, const BDVState &stateB) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000651 switch (stateA.getStatus()) {
Philip Reames9b141ed2015-07-23 22:49:14 +0000652 case BDVState::Unknown:
Philip Reamesd16a9b12015-02-20 01:06:44 +0000653 return stateB;
654
Philip Reames9b141ed2015-07-23 22:49:14 +0000655 case BDVState::Base:
Philip Reamesd16a9b12015-02-20 01:06:44 +0000656 assert(stateA.getBase() && "can't be null");
David Blaikie82ad7872015-02-20 23:44:24 +0000657 if (stateB.isUnknown())
Philip Reamesd16a9b12015-02-20 01:06:44 +0000658 return stateA;
David Blaikie82ad7872015-02-20 23:44:24 +0000659
660 if (stateB.isBase()) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000661 if (stateA.getBase() == stateB.getBase()) {
662 assert(stateA == stateB && "equality broken!");
663 return stateA;
664 }
Philip Reames9b141ed2015-07-23 22:49:14 +0000665 return BDVState(BDVState::Conflict);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000666 }
David Blaikie82ad7872015-02-20 23:44:24 +0000667 assert(stateB.isConflict() && "only three states!");
Philip Reames9b141ed2015-07-23 22:49:14 +0000668 return BDVState(BDVState::Conflict);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000669
Philip Reames9b141ed2015-07-23 22:49:14 +0000670 case BDVState::Conflict:
Philip Reamesd16a9b12015-02-20 01:06:44 +0000671 return stateA;
672 }
Reid Klecknera070ee52015-02-20 19:46:02 +0000673 llvm_unreachable("only three states!");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000674 }
675};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000676}
Philip Reamesd16a9b12015-02-20 01:06:44 +0000677/// For a given value or instruction, figure out what base ptr it's derived
678/// from. For gc objects, this is simply itself. On success, returns a value
679/// which is the base pointer. (This is reliable and can be used for
680/// relocation.) On failure, returns nullptr.
Philip Reamesba198492015-04-14 00:41:34 +0000681static Value *findBasePointer(Value *I, DefiningValueMapTy &cache) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000682 Value *def = findBaseOrBDV(I, cache);
683
684 if (isKnownBaseResult(def)) {
685 return def;
686 }
687
688 // Here's the rough algorithm:
689 // - For every SSA value, construct a mapping to either an actual base
690 // pointer or a PHI which obscures the base pointer.
691 // - Construct a mapping from PHI to unknown TOP state. Use an
692 // optimistic algorithm to propagate base pointer information. Lattice
693 // looks like:
694 // UNKNOWN
695 // b1 b2 b3 b4
696 // CONFLICT
697 // When algorithm terminates, all PHIs will either have a single concrete
698 // base or be in a conflict state.
699 // - For every conflict, insert a dummy PHI node without arguments. Add
700 // these to the base[Instruction] = BasePtr mapping. For every
701 // non-conflict, add the actual base.
702 // - For every conflict, add arguments for the base[a] of each input
703 // arguments.
704 //
705 // Note: A simpler form of this would be to add the conflict form of all
706 // PHIs without running the optimistic algorithm. This would be
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000707 // analogous to pessimistic data flow and would likely lead to an
Philip Reamesd16a9b12015-02-20 01:06:44 +0000708 // overall worse solution.
709
Philip Reames29e9ae72015-07-24 00:42:55 +0000710#ifndef NDEBUG
Philip Reames88958b22015-07-24 00:02:11 +0000711 auto isExpectedBDVType = [](Value *BDV) {
Philip Reames9ac4e382015-08-12 21:00:20 +0000712 return isa<PHINode>(BDV) || isa<SelectInst>(BDV) || isa<ExtractElementInst>(BDV);
Philip Reames88958b22015-07-24 00:02:11 +0000713 };
Philip Reames29e9ae72015-07-24 00:42:55 +0000714#endif
Philip Reames88958b22015-07-24 00:02:11 +0000715
716 // Once populated, will contain a mapping from each potentially non-base BDV
717 // to a lattice value (described above) which corresponds to that BDV.
Philip Reames860660e2015-02-20 22:05:18 +0000718 ConflictStateMapTy states;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000719 // Recursively fill in all phis & selects reachable from the initial one
720 // for which we don't already know a definite base value for
Philip Reames88958b22015-07-24 00:02:11 +0000721 /* scope */ {
722 DenseSet<Value *> Visited;
723 SmallVector<Value*, 16> Worklist;
724 Worklist.push_back(def);
725 Visited.insert(def);
726 while (!Worklist.empty()) {
727 Value *Current = Worklist.pop_back_val();
728 assert(!isKnownBaseResult(Current) && "why did it get added?");
729
730 auto visitIncomingValue = [&](Value *InVal) {
731 Value *Base = findBaseOrBDV(InVal, cache);
732 if (isKnownBaseResult(Base))
733 // Known bases won't need new instructions introduced and can be
734 // ignored safely
735 return;
736 assert(isExpectedBDVType(Base) && "the only non-base values "
737 "we see should be base defining values");
738 if (Visited.insert(Base).second)
739 Worklist.push_back(Base);
740 };
741 if (PHINode *Phi = dyn_cast<PHINode>(Current)) {
742 for (Value *InVal : Phi->incoming_values())
743 visitIncomingValue(InVal);
Philip Reames9ac4e382015-08-12 21:00:20 +0000744 } else if (SelectInst *Sel = dyn_cast<SelectInst>(Current)) {
Philip Reames88958b22015-07-24 00:02:11 +0000745 visitIncomingValue(Sel->getTrueValue());
746 visitIncomingValue(Sel->getFalseValue());
Philip Reames9ac4e382015-08-12 21:00:20 +0000747 } else if (auto *EE = dyn_cast<ExtractElementInst>(Current)) {
748 visitIncomingValue(EE->getVectorOperand());
749 } else {
750 // There are two classes of instructions we know we don't handle.
751 assert(isa<ShuffleVectorInst>(Current) ||
752 isa<InsertElementInst>(Current));
753 llvm_unreachable("unimplemented instruction case");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000754 }
755 }
Philip Reames88958b22015-07-24 00:02:11 +0000756 // The frontier of visited instructions are the ones we might need to
757 // duplicate, so fill in the starting state for the optimistic algorithm
758 // that follows.
759 for (Value *BDV : Visited) {
760 states[BDV] = BDVState();
761 }
Philip Reamesd16a9b12015-02-20 01:06:44 +0000762 }
763
764 if (TraceLSP) {
765 errs() << "States after initialization:\n";
Philip Reames2a892a62015-07-23 22:25:26 +0000766 for (auto Pair : states)
Philip Reames9ac4e382015-08-12 21:00:20 +0000767 dbgs() << " " << Pair.second << " for " << *Pair.first << "\n";
Philip Reamesd16a9b12015-02-20 01:06:44 +0000768 }
769
770 // TODO: come back and revisit the state transitions around inputs which
771 // have reached conflict state. The current version seems too conservative.
772
Philip Reames273e6bb2015-07-23 21:41:27 +0000773 // Return a phi state for a base defining value. We'll generate a new
774 // base state for known bases and expect to find a cached state otherwise.
775 auto getStateForBDV = [&](Value *baseValue) {
776 if (isKnownBaseResult(baseValue))
Philip Reames9b141ed2015-07-23 22:49:14 +0000777 return BDVState(baseValue);
Philip Reames273e6bb2015-07-23 21:41:27 +0000778 auto I = states.find(baseValue);
779 assert(I != states.end() && "lookup failed!");
780 return I->second;
781 };
782
Philip Reamesd16a9b12015-02-20 01:06:44 +0000783 bool progress = true;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000784 while (progress) {
Yaron Keren42a7adf2015-02-28 13:11:24 +0000785#ifndef NDEBUG
786 size_t oldSize = states.size();
787#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +0000788 progress = false;
Philip Reamesa226e612015-02-28 00:47:50 +0000789 // We're only changing keys in this loop, thus safe to keep iterators
Philip Reamesd16a9b12015-02-20 01:06:44 +0000790 for (auto Pair : states) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000791 Value *v = Pair.first;
792 assert(!isKnownBaseResult(v) && "why did it get added?");
Philip Reames273e6bb2015-07-23 21:41:27 +0000793
Philip Reames9b141ed2015-07-23 22:49:14 +0000794 // Given an input value for the current instruction, return a BDVState
Philip Reames273e6bb2015-07-23 21:41:27 +0000795 // instance which represents the BDV of that value.
796 auto getStateForInput = [&](Value *V) mutable {
797 Value *BDV = findBaseOrBDV(V, cache);
798 return getStateForBDV(BDV);
799 };
800
Philip Reames9b141ed2015-07-23 22:49:14 +0000801 MeetBDVStates calculateMeet;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000802 if (SelectInst *select = dyn_cast<SelectInst>(v)) {
Philip Reames273e6bb2015-07-23 21:41:27 +0000803 calculateMeet.meetWith(getStateForInput(select->getTrueValue()));
804 calculateMeet.meetWith(getStateForInput(select->getFalseValue()));
Philip Reames9ac4e382015-08-12 21:00:20 +0000805 } else if (PHINode *Phi = dyn_cast<PHINode>(v)) {
806 for (Value *Val : Phi->incoming_values())
Philip Reames273e6bb2015-07-23 21:41:27 +0000807 calculateMeet.meetWith(getStateForInput(Val));
Philip Reames9ac4e382015-08-12 21:00:20 +0000808 } else {
809 // The 'meet' for an extractelement is slightly trivial, but it's still
810 // useful in that it drives us to conflict if our input is.
811 auto *EE = cast<ExtractElementInst>(v);
812 calculateMeet.meetWith(getStateForInput(EE->getVectorOperand()));
813 }
814
Philip Reamesd16a9b12015-02-20 01:06:44 +0000815
Philip Reames9b141ed2015-07-23 22:49:14 +0000816 BDVState oldState = states[v];
817 BDVState newState = calculateMeet.getResult();
Philip Reamesd16a9b12015-02-20 01:06:44 +0000818 if (oldState != newState) {
819 progress = true;
820 states[v] = newState;
821 }
822 }
823
824 assert(oldSize <= states.size());
825 assert(oldSize == states.size() || progress);
826 }
827
828 if (TraceLSP) {
829 errs() << "States after meet iteration:\n";
Philip Reames2a892a62015-07-23 22:25:26 +0000830 for (auto Pair : states)
Philip Reames9ac4e382015-08-12 21:00:20 +0000831 dbgs() << " " << Pair.second << " for " << *Pair.first << "\n";
Philip Reamesd16a9b12015-02-20 01:06:44 +0000832 }
833
834 // Insert Phis for all conflicts
Philip Reames2e5bcbe2015-02-28 01:52:09 +0000835 // We want to keep naming deterministic in the loop that follows, so
836 // sort the keys before iteration. This is useful in allowing us to
837 // write stable tests. Note that there is no invalidation issue here.
Philip Reames704e78b2015-04-10 22:34:56 +0000838 SmallVector<Value *, 16> Keys;
Philip Reames2e5bcbe2015-02-28 01:52:09 +0000839 Keys.reserve(states.size());
Philip Reamesd16a9b12015-02-20 01:06:44 +0000840 for (auto Pair : states) {
Philip Reames2e5bcbe2015-02-28 01:52:09 +0000841 Value *V = Pair.first;
842 Keys.push_back(V);
843 }
844 std::sort(Keys.begin(), Keys.end(), order_by_name);
845 // TODO: adjust naming patterns to avoid this order of iteration dependency
846 for (Value *V : Keys) {
Philip Reames6ff1a1e32015-07-21 19:04:38 +0000847 Instruction *I = cast<Instruction>(V);
Philip Reames9b141ed2015-07-23 22:49:14 +0000848 BDVState State = states[I];
Philip Reames6ff1a1e32015-07-21 19:04:38 +0000849 assert(!isKnownBaseResult(I) && "why did it get added?");
850 assert(!State.isUnknown() && "Optimistic algorithm didn't complete!");
Philip Reames9ac4e382015-08-12 21:00:20 +0000851
852 // extractelement instructions are a bit special in that we may need to
853 // insert an extract even when we know an exact base for the instruction.
854 // The problem is that we need to convert from a vector base to a scalar
855 // base for the particular indice we're interested in.
856 if (State.isBase() && isa<ExtractElementInst>(I) &&
857 isa<VectorType>(State.getBase()->getType())) {
858 auto *EE = cast<ExtractElementInst>(I);
859 // TODO: In many cases, the new instruction is just EE itself. We should
860 // exploit this, but can't do it here since it would break the invariant
861 // about the BDV not being known to be a base.
862 auto *BaseInst = ExtractElementInst::Create(State.getBase(),
863 EE->getIndexOperand(),
864 "base_ee", EE);
865 BaseInst->setMetadata("is_base_value", MDNode::get(I->getContext(), {}));
866 states[I] = BDVState(BDVState::Base, BaseInst);
867 }
868
Philip Reames6ff1a1e32015-07-21 19:04:38 +0000869 if (!State.isConflict())
Philip Reamesf986d682015-02-28 00:54:41 +0000870 continue;
Philip Reames704e78b2015-04-10 22:34:56 +0000871
Philip Reames6ff1a1e32015-07-21 19:04:38 +0000872 /// Create and insert a new instruction which will represent the base of
873 /// the given instruction 'I'.
874 auto MakeBaseInstPlaceholder = [](Instruction *I) -> Instruction* {
875 if (isa<PHINode>(I)) {
876 BasicBlock *BB = I->getParent();
877 int NumPreds = std::distance(pred_begin(BB), pred_end(BB));
878 assert(NumPreds > 0 && "how did we reach here");
Philip Reamesfa2c6302015-07-24 19:01:39 +0000879 std::string Name = I->hasName() ?
880 (I->getName() + ".base").str() : "base_phi";
881 return PHINode::Create(I->getType(), NumPreds, Name, I);
Philip Reames9ac4e382015-08-12 21:00:20 +0000882 } else if (SelectInst *Sel = dyn_cast<SelectInst>(I)) {
883 // The undef will be replaced later
884 UndefValue *Undef = UndefValue::get(Sel->getType());
885 std::string Name = I->hasName() ?
886 (I->getName() + ".base").str() : "base_select";
887 return SelectInst::Create(Sel->getCondition(), Undef,
888 Undef, Name, Sel);
889 } else {
890 auto *EE = cast<ExtractElementInst>(I);
891 UndefValue *Undef = UndefValue::get(EE->getVectorOperand()->getType());
892 std::string Name = I->hasName() ?
893 (I->getName() + ".base").str() : "base_ee";
894 return ExtractElementInst::Create(Undef, EE->getIndexOperand(), Name,
895 EE);
Philip Reames6ff1a1e32015-07-21 19:04:38 +0000896 }
Philip Reames6ff1a1e32015-07-21 19:04:38 +0000897 };
898 Instruction *BaseInst = MakeBaseInstPlaceholder(I);
899 // Add metadata marking this as a base value
900 BaseInst->setMetadata("is_base_value", MDNode::get(I->getContext(), {}));
Philip Reames9b141ed2015-07-23 22:49:14 +0000901 states[I] = BDVState(BDVState::Conflict, BaseInst);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000902 }
903
904 // Fixup all the inputs of the new PHIs
905 for (auto Pair : states) {
906 Instruction *v = cast<Instruction>(Pair.first);
Philip Reames9b141ed2015-07-23 22:49:14 +0000907 BDVState state = Pair.second;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000908
909 assert(!isKnownBaseResult(v) && "why did it get added?");
910 assert(!state.isUnknown() && "Optimistic algorithm didn't complete!");
Philip Reames28e61ce2015-02-28 01:57:44 +0000911 if (!state.isConflict())
912 continue;
Philip Reames704e78b2015-04-10 22:34:56 +0000913
Philip Reames28e61ce2015-02-28 01:57:44 +0000914 if (PHINode *basephi = dyn_cast<PHINode>(state.getBase())) {
915 PHINode *phi = cast<PHINode>(v);
916 unsigned NumPHIValues = phi->getNumIncomingValues();
917 for (unsigned i = 0; i < NumPHIValues; i++) {
918 Value *InVal = phi->getIncomingValue(i);
919 BasicBlock *InBB = phi->getIncomingBlock(i);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000920
Philip Reames28e61ce2015-02-28 01:57:44 +0000921 // If we've already seen InBB, add the same incoming value
922 // we added for it earlier. The IR verifier requires phi
923 // nodes with multiple entries from the same basic block
924 // to have the same incoming value for each of those
925 // entries. If we don't do this check here and basephi
926 // has a different type than base, we'll end up adding two
927 // bitcasts (and hence two distinct values) as incoming
928 // values for the same basic block.
Philip Reamesd16a9b12015-02-20 01:06:44 +0000929
Philip Reames28e61ce2015-02-28 01:57:44 +0000930 int blockIndex = basephi->getBasicBlockIndex(InBB);
931 if (blockIndex != -1) {
932 Value *oldBase = basephi->getIncomingValue(blockIndex);
933 basephi->addIncoming(oldBase, InBB);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000934#ifndef NDEBUG
Philip Reames28e61ce2015-02-28 01:57:44 +0000935 Value *base = findBaseOrBDV(InVal, cache);
936 if (!isKnownBaseResult(base)) {
937 // Either conflict or base.
938 assert(states.count(base));
939 base = states[base].getBase();
Philip Reames9b141ed2015-07-23 22:49:14 +0000940 assert(base != nullptr && "unknown BDVState!");
Philip Reames28e61ce2015-02-28 01:57:44 +0000941 }
Philip Reamesd16a9b12015-02-20 01:06:44 +0000942
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000943 // In essence this assert states: the only way two
Philip Reames28e61ce2015-02-28 01:57:44 +0000944 // values incoming from the same basic block may be
945 // different is by being different bitcasts of the same
946 // value. A cleanup that remains TODO is changing
947 // findBaseOrBDV to return an llvm::Value of the correct
948 // type (and still remain pure). This will remove the
949 // need to add bitcasts.
950 assert(base->stripPointerCasts() == oldBase->stripPointerCasts() &&
951 "sanity -- findBaseOrBDV should be pure!");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000952#endif
Philip Reames28e61ce2015-02-28 01:57:44 +0000953 continue;
954 }
Philip Reamesd16a9b12015-02-20 01:06:44 +0000955
Philip Reames28e61ce2015-02-28 01:57:44 +0000956 // Find either the defining value for the PHI or the normal base for
957 // a non-phi node
958 Value *base = findBaseOrBDV(InVal, cache);
959 if (!isKnownBaseResult(base)) {
960 // Either conflict or base.
961 assert(states.count(base));
962 base = states[base].getBase();
Philip Reames9b141ed2015-07-23 22:49:14 +0000963 assert(base != nullptr && "unknown BDVState!");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000964 }
Philip Reames28e61ce2015-02-28 01:57:44 +0000965 assert(base && "can't be null");
966 // Must use original input BB since base may not be Instruction
967 // The cast is needed since base traversal may strip away bitcasts
968 if (base->getType() != basephi->getType()) {
969 base = new BitCastInst(base, basephi->getType(), "cast",
970 InBB->getTerminator());
Philip Reamesd16a9b12015-02-20 01:06:44 +0000971 }
Philip Reames28e61ce2015-02-28 01:57:44 +0000972 basephi->addIncoming(base, InBB);
973 }
974 assert(basephi->getNumIncomingValues() == NumPHIValues);
Philip Reames9ac4e382015-08-12 21:00:20 +0000975 } else if (SelectInst *basesel = dyn_cast<SelectInst>(state.getBase())) {
Philip Reames28e61ce2015-02-28 01:57:44 +0000976 SelectInst *sel = cast<SelectInst>(v);
977 // Operand 1 & 2 are true, false path respectively. TODO: refactor to
978 // something more safe and less hacky.
979 for (int i = 1; i <= 2; i++) {
980 Value *InVal = sel->getOperand(i);
981 // Find either the defining value for the PHI or the normal base for
982 // a non-phi node
983 Value *base = findBaseOrBDV(InVal, cache);
984 if (!isKnownBaseResult(base)) {
985 // Either conflict or base.
986 assert(states.count(base));
987 base = states[base].getBase();
Philip Reames9b141ed2015-07-23 22:49:14 +0000988 assert(base != nullptr && "unknown BDVState!");
Philip Reames28e61ce2015-02-28 01:57:44 +0000989 }
990 assert(base && "can't be null");
991 // Must use original input BB since base may not be Instruction
992 // The cast is needed since base traversal may strip away bitcasts
993 if (base->getType() != basesel->getType()) {
994 base = new BitCastInst(base, basesel->getType(), "cast", basesel);
Philip Reames28e61ce2015-02-28 01:57:44 +0000995 }
996 basesel->setOperand(i, base);
997 }
Philip Reames9ac4e382015-08-12 21:00:20 +0000998 } else {
999 auto *BaseEE = cast<ExtractElementInst>(state.getBase());
1000 Value *InVal = cast<ExtractElementInst>(v)->getVectorOperand();
1001 Value *Base = findBaseOrBDV(InVal, cache);
1002 if (!isKnownBaseResult(Base)) {
1003 // Either conflict or base.
1004 assert(states.count(Base));
1005 Base = states[Base].getBase();
1006 assert(Base != nullptr && "unknown BDVState!");
1007 }
1008 assert(Base && "can't be null");
1009 BaseEE->setOperand(0, Base);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001010 }
1011 }
1012
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001013 // Now that we're done with the algorithm, see if we can optimize the
1014 // results slightly by reducing the number of new instructions needed.
1015 // Arguably, this should be integrated into the algorithm above, but
1016 // doing as a post process step is easier to reason about for the moment.
1017 DenseMap<Value *, Value *> ReverseMap;
1018 SmallPtrSet<Instruction *, 16> NewInsts;
1019 SmallSetVector<Instruction *, 16> Worklist;
1020 for (auto Item : states) {
1021 Value *V = Item.first;
1022 Value *Base = Item.second.getBase();
1023 assert(V && Base);
1024 assert(!isKnownBaseResult(V) && "why did it get added?");
1025 assert(isKnownBaseResult(Base) &&
1026 "must be something we 'know' is a base pointer");
1027 if (!Item.second.isConflict())
1028 continue;
1029
1030 ReverseMap[Base] = V;
1031 if (auto *BaseI = dyn_cast<Instruction>(Base)) {
1032 NewInsts.insert(BaseI);
1033 Worklist.insert(BaseI);
1034 }
1035 }
1036 auto PushNewUsers = [&](Instruction *I) {
1037 for (User *U : I->users())
1038 if (auto *UI = dyn_cast<Instruction>(U))
1039 if (NewInsts.count(UI))
1040 Worklist.insert(UI);
1041 };
1042 const DataLayout &DL = cast<Instruction>(def)->getModule()->getDataLayout();
1043 while (!Worklist.empty()) {
1044 Instruction *BaseI = Worklist.pop_back_val();
1045 Value *Bdv = ReverseMap[BaseI];
1046 if (auto *BdvI = dyn_cast<Instruction>(Bdv))
1047 if (BaseI->isIdenticalTo(BdvI)) {
1048 DEBUG(dbgs() << "Identical Base: " << *BaseI << "\n");
1049 PushNewUsers(BaseI);
1050 BaseI->replaceAllUsesWith(Bdv);
1051 BaseI->eraseFromParent();
1052 states[Bdv] = BDVState(BDVState::Conflict, Bdv);
1053 NewInsts.erase(BaseI);
1054 ReverseMap.erase(BaseI);
1055 continue;
1056 }
1057 if (Value *V = SimplifyInstruction(BaseI, DL)) {
1058 DEBUG(dbgs() << "Base " << *BaseI << " simplified to " << *V << "\n");
1059 PushNewUsers(BaseI);
1060 BaseI->replaceAllUsesWith(V);
1061 BaseI->eraseFromParent();
1062 states[Bdv] = BDVState(BDVState::Conflict, V);
1063 NewInsts.erase(BaseI);
1064 ReverseMap.erase(BaseI);
1065 continue;
1066 }
1067 }
1068
Philip Reamesd16a9b12015-02-20 01:06:44 +00001069 // Cache all of our results so we can cheaply reuse them
1070 // NOTE: This is actually two caches: one of the base defining value
1071 // relation and one of the base pointer relation! FIXME
1072 for (auto item : states) {
1073 Value *v = item.first;
1074 Value *base = item.second.getBase();
1075 assert(v && base);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001076
1077 if (TraceLSP) {
1078 std::string fromstr =
1079 cache.count(v) ? (cache[v]->hasName() ? cache[v]->getName() : "")
1080 : "none";
1081 errs() << "Updating base value cache"
1082 << " for: " << (v->hasName() ? v->getName() : "")
1083 << " from: " << fromstr
1084 << " to: " << (base->hasName() ? base->getName() : "") << "\n";
1085 }
1086
Philip Reamesd16a9b12015-02-20 01:06:44 +00001087 if (cache.count(v)) {
1088 // Once we transition from the BDV relation being store in the cache to
1089 // the base relation being stored, it must be stable
1090 assert((!isKnownBaseResult(cache[v]) || cache[v] == base) &&
1091 "base relation should be stable");
1092 }
1093 cache[v] = base;
1094 }
1095 assert(cache.find(def) != cache.end());
1096 return cache[def];
1097}
1098
1099// For a set of live pointers (base and/or derived), identify the base
1100// pointer of the object which they are derived from. This routine will
1101// mutate the IR graph as needed to make the 'base' pointer live at the
1102// definition site of 'derived'. This ensures that any use of 'derived' can
1103// also use 'base'. This may involve the insertion of a number of
1104// additional PHI nodes.
1105//
1106// preconditions: live is a set of pointer type Values
1107//
1108// side effects: may insert PHI nodes into the existing CFG, will preserve
1109// CFG, will not remove or mutate any existing nodes
1110//
Philip Reamesf2041322015-02-20 19:26:04 +00001111// post condition: PointerToBase contains one (derived, base) pair for every
Philip Reamesd16a9b12015-02-20 01:06:44 +00001112// pointer in live. Note that derived can be equal to base if the original
1113// pointer was a base pointer.
Philip Reames704e78b2015-04-10 22:34:56 +00001114static void
1115findBasePointers(const StatepointLiveSetTy &live,
1116 DenseMap<llvm::Value *, llvm::Value *> &PointerToBase,
Philip Reamesba198492015-04-14 00:41:34 +00001117 DominatorTree *DT, DefiningValueMapTy &DVCache) {
Philip Reames2e5bcbe2015-02-28 01:52:09 +00001118 // For the naming of values inserted to be deterministic - which makes for
1119 // much cleaner and more stable tests - we need to assign an order to the
1120 // live values. DenseSets do not provide a deterministic order across runs.
Philip Reames704e78b2015-04-10 22:34:56 +00001121 SmallVector<Value *, 64> Temp;
Philip Reames2e5bcbe2015-02-28 01:52:09 +00001122 Temp.insert(Temp.end(), live.begin(), live.end());
1123 std::sort(Temp.begin(), Temp.end(), order_by_name);
1124 for (Value *ptr : Temp) {
Philip Reamesba198492015-04-14 00:41:34 +00001125 Value *base = findBasePointer(ptr, DVCache);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001126 assert(base && "failed to find base pointer");
Philip Reamesf2041322015-02-20 19:26:04 +00001127 PointerToBase[ptr] = base;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001128 assert((!isa<Instruction>(base) || !isa<Instruction>(ptr) ||
1129 DT->dominates(cast<Instruction>(base)->getParent(),
1130 cast<Instruction>(ptr)->getParent())) &&
1131 "The base we found better dominate the derived pointer");
1132
David Blaikie82ad7872015-02-20 23:44:24 +00001133 // If you see this trip and like to live really dangerously, the code should
1134 // be correct, just with idioms the verifier can't handle. You can try
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001135 // disabling the verifier at your own substantial risk.
Philip Reames704e78b2015-04-10 22:34:56 +00001136 assert(!isa<ConstantPointerNull>(base) &&
Philip Reames24c6cd52015-03-27 05:47:00 +00001137 "the relocation code needs adjustment to handle the relocation of "
1138 "a null pointer constant without causing false positives in the "
1139 "safepoint ir verifier.");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001140 }
1141}
1142
1143/// Find the required based pointers (and adjust the live set) for the given
1144/// parse point.
1145static void findBasePointers(DominatorTree &DT, DefiningValueMapTy &DVCache,
1146 const CallSite &CS,
1147 PartiallyConstructedSafepointRecord &result) {
Philip Reamesf2041322015-02-20 19:26:04 +00001148 DenseMap<llvm::Value *, llvm::Value *> PointerToBase;
Philip Reamesba198492015-04-14 00:41:34 +00001149 findBasePointers(result.liveset, PointerToBase, &DT, DVCache);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001150
1151 if (PrintBasePointers) {
Philip Reamesa5aeaf42015-02-28 00:20:48 +00001152 // Note: Need to print these in a stable order since this is checked in
1153 // some tests.
Philip Reamesd16a9b12015-02-20 01:06:44 +00001154 errs() << "Base Pairs (w/o Relocation):\n";
Philip Reames704e78b2015-04-10 22:34:56 +00001155 SmallVector<Value *, 64> Temp;
Philip Reamesa5aeaf42015-02-28 00:20:48 +00001156 Temp.reserve(PointerToBase.size());
Philip Reamesf2041322015-02-20 19:26:04 +00001157 for (auto Pair : PointerToBase) {
Philip Reamesa5aeaf42015-02-28 00:20:48 +00001158 Temp.push_back(Pair.first);
1159 }
1160 std::sort(Temp.begin(), Temp.end(), order_by_name);
1161 for (Value *Ptr : Temp) {
1162 Value *Base = PointerToBase[Ptr];
Philip Reames704e78b2015-04-10 22:34:56 +00001163 errs() << " derived %" << Ptr->getName() << " base %" << Base->getName()
1164 << "\n";
Philip Reamesd16a9b12015-02-20 01:06:44 +00001165 }
1166 }
1167
Philip Reamesf2041322015-02-20 19:26:04 +00001168 result.PointerToBase = PointerToBase;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001169}
1170
Philip Reamesdf1ef082015-04-10 22:53:14 +00001171/// Given an updated version of the dataflow liveness results, update the
1172/// liveset and base pointer maps for the call site CS.
1173static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData,
1174 const CallSite &CS,
1175 PartiallyConstructedSafepointRecord &result);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001176
Philip Reamesdf1ef082015-04-10 22:53:14 +00001177static void recomputeLiveInValues(
1178 Function &F, DominatorTree &DT, Pass *P, ArrayRef<CallSite> toUpdate,
Philip Reamesd2b66462015-02-20 22:39:41 +00001179 MutableArrayRef<struct PartiallyConstructedSafepointRecord> records) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00001180 // TODO-PERF: reuse the original liveness, then simply run the dataflow
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001181 // again. The old values are still live and will help it stabilize quickly.
Philip Reamesdf1ef082015-04-10 22:53:14 +00001182 GCPtrLivenessData RevisedLivenessData;
1183 computeLiveInValues(DT, F, RevisedLivenessData);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001184 for (size_t i = 0; i < records.size(); i++) {
1185 struct PartiallyConstructedSafepointRecord &info = records[i];
Philip Reamesd2b66462015-02-20 22:39:41 +00001186 const CallSite &CS = toUpdate[i];
Philip Reamesdf1ef082015-04-10 22:53:14 +00001187 recomputeLiveInValues(RevisedLivenessData, CS, info);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001188 }
1189}
1190
Philip Reames69e51ca2015-04-13 18:07:21 +00001191// When inserting gc.relocate calls, we need to ensure there are no uses
1192// of the original value between the gc.statepoint and the gc.relocate call.
1193// One case which can arise is a phi node starting one of the successor blocks.
1194// We also need to be able to insert the gc.relocates only on the path which
1195// goes through the statepoint. We might need to split an edge to make this
Philip Reamesf209a152015-04-13 20:00:30 +00001196// possible.
1197static BasicBlock *
Sanjoy Dasea45f0e2015-06-02 22:33:34 +00001198normalizeForInvokeSafepoint(BasicBlock *BB, BasicBlock *InvokeParent,
1199 DominatorTree &DT) {
Philip Reames69e51ca2015-04-13 18:07:21 +00001200 BasicBlock *Ret = BB;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001201 if (!BB->getUniquePredecessor()) {
Chandler Carruth96ada252015-07-22 09:52:54 +00001202 Ret = SplitBlockPredecessors(BB, InvokeParent, "", &DT);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001203 }
1204
Philip Reames69e51ca2015-04-13 18:07:21 +00001205 // Now that 'ret' has unique predecessor we can safely remove all phi nodes
1206 // from it
1207 FoldSingleEntryPHINodes(Ret);
1208 assert(!isa<PHINode>(Ret->begin()));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001209
Philip Reames69e51ca2015-04-13 18:07:21 +00001210 // At this point, we can safely insert a gc.relocate as the first instruction
1211 // in Ret if needed.
1212 return Ret;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001213}
1214
Philip Reamesd2b66462015-02-20 22:39:41 +00001215static int find_index(ArrayRef<Value *> livevec, Value *val) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001216 auto itr = std::find(livevec.begin(), livevec.end(), val);
1217 assert(livevec.end() != itr);
1218 size_t index = std::distance(livevec.begin(), itr);
1219 assert(index < livevec.size());
1220 return index;
1221}
1222
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001223// Create new attribute set containing only attributes which can be transferred
Philip Reamesd16a9b12015-02-20 01:06:44 +00001224// from original call to the safepoint.
1225static AttributeSet legalizeCallAttributes(AttributeSet AS) {
1226 AttributeSet ret;
1227
1228 for (unsigned Slot = 0; Slot < AS.getNumSlots(); Slot++) {
1229 unsigned index = AS.getSlotIndex(Slot);
1230
1231 if (index == AttributeSet::ReturnIndex ||
1232 index == AttributeSet::FunctionIndex) {
1233
1234 for (auto it = AS.begin(Slot), it_end = AS.end(Slot); it != it_end;
1235 ++it) {
1236 Attribute attr = *it;
1237
1238 // Do not allow certain attributes - just skip them
1239 // Safepoint can not be read only or read none.
1240 if (attr.hasAttribute(Attribute::ReadNone) ||
1241 attr.hasAttribute(Attribute::ReadOnly))
1242 continue;
1243
1244 ret = ret.addAttributes(
1245 AS.getContext(), index,
1246 AttributeSet::get(AS.getContext(), index, AttrBuilder(attr)));
1247 }
1248 }
1249
1250 // Just skip parameter attributes for now
1251 }
1252
1253 return ret;
1254}
1255
1256/// Helper function to place all gc relocates necessary for the given
1257/// statepoint.
1258/// Inputs:
1259/// liveVariables - list of variables to be relocated.
1260/// liveStart - index of the first live variable.
1261/// basePtrs - base pointers.
1262/// statepointToken - statepoint instruction to which relocates should be
1263/// bound.
1264/// Builder - Llvm IR builder to be used to construct new calls.
Sanjoy Das5665c992015-05-11 23:47:27 +00001265static void CreateGCRelocates(ArrayRef<llvm::Value *> LiveVariables,
1266 const int LiveStart,
1267 ArrayRef<llvm::Value *> BasePtrs,
1268 Instruction *StatepointToken,
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00001269 IRBuilder<> Builder) {
Philip Reames94babb72015-07-21 17:18:03 +00001270 if (LiveVariables.empty())
1271 return;
1272
1273 // All gc_relocate are set to i8 addrspace(1)* type. We originally generated
1274 // unique declarations for each pointer type, but this proved problematic
1275 // because the intrinsic mangling code is incomplete and fragile. Since
1276 // we're moving towards a single unified pointer type anyways, we can just
1277 // cast everything to an i8* of the right address space. A bitcast is added
1278 // later to convert gc_relocate to the actual value's type.
Philip Reames74ce2e72015-07-21 16:51:17 +00001279 Module *M = StatepointToken->getModule();
Philip Reames94babb72015-07-21 17:18:03 +00001280 auto AS = cast<PointerType>(LiveVariables[0]->getType())->getAddressSpace();
1281 Type *Types[] = {Type::getInt8PtrTy(M->getContext(), AS)};
1282 Value *GCRelocateDecl =
1283 Intrinsic::getDeclaration(M, Intrinsic::experimental_gc_relocate, Types);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001284
Sanjoy Das5665c992015-05-11 23:47:27 +00001285 for (unsigned i = 0; i < LiveVariables.size(); i++) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001286 // Generate the gc.relocate call and save the result
Sanjoy Das5665c992015-05-11 23:47:27 +00001287 Value *BaseIdx =
Philip Reamesf3880502015-07-21 00:49:55 +00001288 Builder.getInt32(LiveStart + find_index(LiveVariables, BasePtrs[i]));
1289 Value *LiveIdx =
1290 Builder.getInt32(LiveStart + find_index(LiveVariables, LiveVariables[i]));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001291
1292 // only specify a debug name if we can give a useful one
Philip Reames74ce2e72015-07-21 16:51:17 +00001293 CallInst *Reloc = Builder.CreateCall(
David Blaikieff6409d2015-05-18 22:13:54 +00001294 GCRelocateDecl, {StatepointToken, BaseIdx, LiveIdx},
Sanjoy Das5665c992015-05-11 23:47:27 +00001295 LiveVariables[i]->hasName() ? LiveVariables[i]->getName() + ".relocated"
Philip Reamesd16a9b12015-02-20 01:06:44 +00001296 : "");
1297 // Trick CodeGen into thinking there are lots of free registers at this
1298 // fake call.
Philip Reames74ce2e72015-07-21 16:51:17 +00001299 Reloc->setCallingConv(CallingConv::Cold);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001300 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00001301}
1302
1303static void
1304makeStatepointExplicitImpl(const CallSite &CS, /* to replace */
1305 const SmallVectorImpl<llvm::Value *> &basePtrs,
1306 const SmallVectorImpl<llvm::Value *> &liveVariables,
1307 Pass *P,
1308 PartiallyConstructedSafepointRecord &result) {
1309 assert(basePtrs.size() == liveVariables.size());
1310 assert(isStatepoint(CS) &&
1311 "This method expects to be rewriting a statepoint");
1312
1313 BasicBlock *BB = CS.getInstruction()->getParent();
1314 assert(BB);
1315 Function *F = BB->getParent();
1316 assert(F && "must be set");
1317 Module *M = F->getParent();
Nick Lewyckyeb3231e2015-02-20 07:14:02 +00001318 (void)M;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001319 assert(M && "must be set");
1320
1321 // We're not changing the function signature of the statepoint since the gc
1322 // arguments go into the var args section.
1323 Function *gc_statepoint_decl = CS.getCalledFunction();
1324
1325 // Then go ahead and use the builder do actually do the inserts. We insert
1326 // immediately before the previous instruction under the assumption that all
1327 // arguments will be available here. We can't insert afterwards since we may
1328 // be replacing a terminator.
1329 Instruction *insertBefore = CS.getInstruction();
1330 IRBuilder<> Builder(insertBefore);
1331 // Copy all of the arguments from the original statepoint - this includes the
1332 // target, call args, and deopt args
Philip Reamesd2b66462015-02-20 22:39:41 +00001333 SmallVector<llvm::Value *, 64> args;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001334 args.insert(args.end(), CS.arg_begin(), CS.arg_end());
1335 // TODO: Clear the 'needs rewrite' flag
1336
1337 // add all the pointers to be relocated (gc arguments)
1338 // Capture the start of the live variable list for use in the gc_relocates
1339 const int live_start = args.size();
1340 args.insert(args.end(), liveVariables.begin(), liveVariables.end());
1341
1342 // Create the statepoint given all the arguments
1343 Instruction *token = nullptr;
1344 AttributeSet return_attributes;
1345 if (CS.isCall()) {
1346 CallInst *toReplace = cast<CallInst>(CS.getInstruction());
1347 CallInst *call =
1348 Builder.CreateCall(gc_statepoint_decl, args, "safepoint_token");
1349 call->setTailCall(toReplace->isTailCall());
1350 call->setCallingConv(toReplace->getCallingConv());
1351
1352 // Currently we will fail on parameter attributes and on certain
1353 // function attributes.
1354 AttributeSet new_attrs = legalizeCallAttributes(toReplace->getAttributes());
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001355 // In case if we can handle this set of attributes - set up function attrs
Philip Reamesd16a9b12015-02-20 01:06:44 +00001356 // directly on statepoint and return attrs later for gc_result intrinsic.
1357 call->setAttributes(new_attrs.getFnAttributes());
1358 return_attributes = new_attrs.getRetAttributes();
1359
1360 token = call;
1361
1362 // Put the following gc_result and gc_relocate calls immediately after the
1363 // the old call (which we're about to delete)
1364 BasicBlock::iterator next(toReplace);
1365 assert(BB->end() != next && "not a terminator, must have next");
1366 next++;
1367 Instruction *IP = &*(next);
1368 Builder.SetInsertPoint(IP);
1369 Builder.SetCurrentDebugLocation(IP->getDebugLoc());
1370
David Blaikie82ad7872015-02-20 23:44:24 +00001371 } else {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001372 InvokeInst *toReplace = cast<InvokeInst>(CS.getInstruction());
1373
1374 // Insert the new invoke into the old block. We'll remove the old one in a
1375 // moment at which point this will become the new terminator for the
1376 // original block.
1377 InvokeInst *invoke = InvokeInst::Create(
1378 gc_statepoint_decl, toReplace->getNormalDest(),
Philip Reamesfa2c6302015-07-24 19:01:39 +00001379 toReplace->getUnwindDest(), args, "statepoint_token", toReplace->getParent());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001380 invoke->setCallingConv(toReplace->getCallingConv());
1381
1382 // Currently we will fail on parameter attributes and on certain
1383 // function attributes.
1384 AttributeSet new_attrs = legalizeCallAttributes(toReplace->getAttributes());
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001385 // In case if we can handle this set of attributes - set up function attrs
Philip Reamesd16a9b12015-02-20 01:06:44 +00001386 // directly on statepoint and return attrs later for gc_result intrinsic.
1387 invoke->setAttributes(new_attrs.getFnAttributes());
1388 return_attributes = new_attrs.getRetAttributes();
1389
1390 token = invoke;
1391
1392 // Generate gc relocates in exceptional path
Philip Reames69e51ca2015-04-13 18:07:21 +00001393 BasicBlock *unwindBlock = toReplace->getUnwindDest();
1394 assert(!isa<PHINode>(unwindBlock->begin()) &&
1395 unwindBlock->getUniquePredecessor() &&
1396 "can't safely insert in this block!");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001397
1398 Instruction *IP = &*(unwindBlock->getFirstInsertionPt());
1399 Builder.SetInsertPoint(IP);
1400 Builder.SetCurrentDebugLocation(toReplace->getDebugLoc());
1401
1402 // Extract second element from landingpad return value. We will attach
1403 // exceptional gc relocates to it.
1404 const unsigned idx = 1;
1405 Instruction *exceptional_token =
1406 cast<Instruction>(Builder.CreateExtractValue(
1407 unwindBlock->getLandingPadInst(), idx, "relocate_token"));
Philip Reamesf2041322015-02-20 19:26:04 +00001408 result.UnwindToken = exceptional_token;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001409
Philip Reames6ff1a1e32015-07-21 19:04:38 +00001410 CreateGCRelocates(liveVariables, live_start, basePtrs,
1411 exceptional_token, Builder);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001412
1413 // Generate gc relocates and returns for normal block
Philip Reames69e51ca2015-04-13 18:07:21 +00001414 BasicBlock *normalDest = toReplace->getNormalDest();
1415 assert(!isa<PHINode>(normalDest->begin()) &&
1416 normalDest->getUniquePredecessor() &&
1417 "can't safely insert in this block!");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001418
1419 IP = &*(normalDest->getFirstInsertionPt());
1420 Builder.SetInsertPoint(IP);
1421
1422 // gc relocates will be generated later as if it were regular call
1423 // statepoint
Philip Reamesd16a9b12015-02-20 01:06:44 +00001424 }
1425 assert(token);
1426
1427 // Take the name of the original value call if it had one.
1428 token->takeName(CS.getInstruction());
1429
Philip Reames704e78b2015-04-10 22:34:56 +00001430// The GCResult is already inserted, we just need to find it
David Blaikie5e5d7842015-02-22 20:58:38 +00001431#ifndef NDEBUG
1432 Instruction *toReplace = CS.getInstruction();
1433 assert((toReplace->hasNUses(0) || toReplace->hasNUses(1)) &&
1434 "only valid use before rewrite is gc.result");
1435 assert(!toReplace->hasOneUse() ||
1436 isGCResult(cast<Instruction>(*toReplace->user_begin())));
1437#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +00001438
1439 // Update the gc.result of the original statepoint (if any) to use the newly
1440 // inserted statepoint. This is safe to do here since the token can't be
1441 // considered a live reference.
1442 CS.getInstruction()->replaceAllUsesWith(token);
1443
Philip Reames0a3240f2015-02-20 21:34:11 +00001444 result.StatepointToken = token;
1445
Philip Reamesd16a9b12015-02-20 01:06:44 +00001446 // Second, create a gc.relocate for every live variable
Philip Reames0a3240f2015-02-20 21:34:11 +00001447 CreateGCRelocates(liveVariables, live_start, basePtrs, token, Builder);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001448}
1449
1450namespace {
1451struct name_ordering {
1452 Value *base;
1453 Value *derived;
1454 bool operator()(name_ordering const &a, name_ordering const &b) {
1455 return -1 == a.derived->getName().compare(b.derived->getName());
1456 }
1457};
1458}
1459static void stablize_order(SmallVectorImpl<Value *> &basevec,
1460 SmallVectorImpl<Value *> &livevec) {
1461 assert(basevec.size() == livevec.size());
1462
Philip Reames860660e2015-02-20 22:05:18 +00001463 SmallVector<name_ordering, 64> temp;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001464 for (size_t i = 0; i < basevec.size(); i++) {
1465 name_ordering v;
1466 v.base = basevec[i];
1467 v.derived = livevec[i];
1468 temp.push_back(v);
1469 }
1470 std::sort(temp.begin(), temp.end(), name_ordering());
1471 for (size_t i = 0; i < basevec.size(); i++) {
1472 basevec[i] = temp[i].base;
1473 livevec[i] = temp[i].derived;
1474 }
1475}
1476
1477// Replace an existing gc.statepoint with a new one and a set of gc.relocates
1478// which make the relocations happening at this safepoint explicit.
Philip Reames704e78b2015-04-10 22:34:56 +00001479//
Philip Reamesd16a9b12015-02-20 01:06:44 +00001480// WARNING: Does not do any fixup to adjust users of the original live
1481// values. That's the callers responsibility.
1482static void
1483makeStatepointExplicit(DominatorTree &DT, const CallSite &CS, Pass *P,
1484 PartiallyConstructedSafepointRecord &result) {
Philip Reamesf2041322015-02-20 19:26:04 +00001485 auto liveset = result.liveset;
1486 auto PointerToBase = result.PointerToBase;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001487
1488 // Convert to vector for efficient cross referencing.
1489 SmallVector<Value *, 64> basevec, livevec;
1490 livevec.reserve(liveset.size());
1491 basevec.reserve(liveset.size());
1492 for (Value *L : liveset) {
1493 livevec.push_back(L);
Philip Reames74ce2e72015-07-21 16:51:17 +00001494 assert(PointerToBase.count(L));
Philip Reamesf2041322015-02-20 19:26:04 +00001495 Value *base = PointerToBase[L];
Philip Reamesd16a9b12015-02-20 01:06:44 +00001496 basevec.push_back(base);
1497 }
1498 assert(livevec.size() == basevec.size());
1499
1500 // To make the output IR slightly more stable (for use in diffs), ensure a
1501 // fixed order of the values in the safepoint (by sorting the value name).
1502 // The order is otherwise meaningless.
1503 stablize_order(basevec, livevec);
1504
1505 // Do the actual rewriting and delete the old statepoint
1506 makeStatepointExplicitImpl(CS, basevec, livevec, P, result);
1507 CS.getInstruction()->eraseFromParent();
1508}
1509
1510// Helper function for the relocationViaAlloca.
1511// It receives iterator to the statepoint gc relocates and emits store to the
1512// assigned
1513// location (via allocaMap) for the each one of them.
1514// Add visited values into the visitedLiveValues set we will later use them
1515// for sanity check.
1516static void
Sanjoy Das5665c992015-05-11 23:47:27 +00001517insertRelocationStores(iterator_range<Value::user_iterator> GCRelocs,
1518 DenseMap<Value *, Value *> &AllocaMap,
1519 DenseSet<Value *> &VisitedLiveValues) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001520
Sanjoy Das5665c992015-05-11 23:47:27 +00001521 for (User *U : GCRelocs) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001522 if (!isa<IntrinsicInst>(U))
1523 continue;
1524
Sanjoy Das5665c992015-05-11 23:47:27 +00001525 IntrinsicInst *RelocatedValue = cast<IntrinsicInst>(U);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001526
1527 // We only care about relocates
Sanjoy Das5665c992015-05-11 23:47:27 +00001528 if (RelocatedValue->getIntrinsicID() !=
Philip Reamesd16a9b12015-02-20 01:06:44 +00001529 Intrinsic::experimental_gc_relocate) {
1530 continue;
1531 }
1532
Sanjoy Das5665c992015-05-11 23:47:27 +00001533 GCRelocateOperands RelocateOperands(RelocatedValue);
1534 Value *OriginalValue =
1535 const_cast<Value *>(RelocateOperands.getDerivedPtr());
1536 assert(AllocaMap.count(OriginalValue));
1537 Value *Alloca = AllocaMap[OriginalValue];
Philip Reamesd16a9b12015-02-20 01:06:44 +00001538
1539 // Emit store into the related alloca
Sanjoy Das89c54912015-05-11 18:49:34 +00001540 // All gc_relocate are i8 addrspace(1)* typed, and it must be bitcasted to
1541 // the correct type according to alloca.
Sanjoy Das5665c992015-05-11 23:47:27 +00001542 assert(RelocatedValue->getNextNode() && "Should always have one since it's not a terminator");
1543 IRBuilder<> Builder(RelocatedValue->getNextNode());
Sanjoy Das89c54912015-05-11 18:49:34 +00001544 Value *CastedRelocatedValue =
Sanjoy Das5665c992015-05-11 23:47:27 +00001545 Builder.CreateBitCast(RelocatedValue, cast<AllocaInst>(Alloca)->getAllocatedType(),
1546 RelocatedValue->hasName() ? RelocatedValue->getName() + ".casted" : "");
Sanjoy Das89c54912015-05-11 18:49:34 +00001547
Sanjoy Das5665c992015-05-11 23:47:27 +00001548 StoreInst *Store = new StoreInst(CastedRelocatedValue, Alloca);
1549 Store->insertAfter(cast<Instruction>(CastedRelocatedValue));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001550
1551#ifndef NDEBUG
Sanjoy Das5665c992015-05-11 23:47:27 +00001552 VisitedLiveValues.insert(OriginalValue);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001553#endif
1554 }
1555}
1556
Igor Laevskye0317182015-05-19 15:59:05 +00001557// Helper function for the "relocationViaAlloca". Similar to the
1558// "insertRelocationStores" but works for rematerialized values.
1559static void
1560insertRematerializationStores(
1561 RematerializedValueMapTy RematerializedValues,
1562 DenseMap<Value *, Value *> &AllocaMap,
1563 DenseSet<Value *> &VisitedLiveValues) {
1564
1565 for (auto RematerializedValuePair: RematerializedValues) {
1566 Instruction *RematerializedValue = RematerializedValuePair.first;
1567 Value *OriginalValue = RematerializedValuePair.second;
1568
1569 assert(AllocaMap.count(OriginalValue) &&
1570 "Can not find alloca for rematerialized value");
1571 Value *Alloca = AllocaMap[OriginalValue];
1572
1573 StoreInst *Store = new StoreInst(RematerializedValue, Alloca);
1574 Store->insertAfter(RematerializedValue);
1575
1576#ifndef NDEBUG
1577 VisitedLiveValues.insert(OriginalValue);
1578#endif
1579 }
1580}
1581
Philip Reamesd16a9b12015-02-20 01:06:44 +00001582/// do all the relocation update via allocas and mem2reg
1583static void relocationViaAlloca(
Igor Laevsky285fe842015-05-19 16:29:43 +00001584 Function &F, DominatorTree &DT, ArrayRef<Value *> Live,
1585 ArrayRef<struct PartiallyConstructedSafepointRecord> Records) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001586#ifndef NDEBUG
Philip Reamesa6ebf072015-03-27 05:53:16 +00001587 // record initial number of (static) allocas; we'll check we have the same
1588 // number when we get done.
1589 int InitialAllocaNum = 0;
Philip Reames704e78b2015-04-10 22:34:56 +00001590 for (auto I = F.getEntryBlock().begin(), E = F.getEntryBlock().end(); I != E;
1591 I++)
Philip Reamesa6ebf072015-03-27 05:53:16 +00001592 if (isa<AllocaInst>(*I))
1593 InitialAllocaNum++;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001594#endif
1595
1596 // TODO-PERF: change data structures, reserve
Igor Laevsky285fe842015-05-19 16:29:43 +00001597 DenseMap<Value *, Value *> AllocaMap;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001598 SmallVector<AllocaInst *, 200> PromotableAllocas;
Igor Laevskye0317182015-05-19 15:59:05 +00001599 // Used later to chack that we have enough allocas to store all values
1600 std::size_t NumRematerializedValues = 0;
Igor Laevsky285fe842015-05-19 16:29:43 +00001601 PromotableAllocas.reserve(Live.size());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001602
Igor Laevskye0317182015-05-19 15:59:05 +00001603 // Emit alloca for "LiveValue" and record it in "allocaMap" and
1604 // "PromotableAllocas"
1605 auto emitAllocaFor = [&](Value *LiveValue) {
1606 AllocaInst *Alloca = new AllocaInst(LiveValue->getType(), "",
1607 F.getEntryBlock().getFirstNonPHI());
Igor Laevsky285fe842015-05-19 16:29:43 +00001608 AllocaMap[LiveValue] = Alloca;
Igor Laevskye0317182015-05-19 15:59:05 +00001609 PromotableAllocas.push_back(Alloca);
1610 };
1611
Philip Reamesd16a9b12015-02-20 01:06:44 +00001612 // emit alloca for each live gc pointer
Igor Laevsky285fe842015-05-19 16:29:43 +00001613 for (unsigned i = 0; i < Live.size(); i++) {
1614 emitAllocaFor(Live[i]);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001615 }
1616
Igor Laevskye0317182015-05-19 15:59:05 +00001617 // emit allocas for rematerialized values
Igor Laevsky285fe842015-05-19 16:29:43 +00001618 for (size_t i = 0; i < Records.size(); i++) {
1619 const struct PartiallyConstructedSafepointRecord &Info = Records[i];
Igor Laevskye0317182015-05-19 15:59:05 +00001620
Igor Laevsky285fe842015-05-19 16:29:43 +00001621 for (auto RematerializedValuePair : Info.RematerializedValues) {
Igor Laevskye0317182015-05-19 15:59:05 +00001622 Value *OriginalValue = RematerializedValuePair.second;
Igor Laevsky285fe842015-05-19 16:29:43 +00001623 if (AllocaMap.count(OriginalValue) != 0)
Igor Laevskye0317182015-05-19 15:59:05 +00001624 continue;
1625
1626 emitAllocaFor(OriginalValue);
1627 ++NumRematerializedValues;
1628 }
1629 }
Igor Laevsky285fe842015-05-19 16:29:43 +00001630
Philip Reamesd16a9b12015-02-20 01:06:44 +00001631 // The next two loops are part of the same conceptual operation. We need to
1632 // insert a store to the alloca after the original def and at each
1633 // redefinition. We need to insert a load before each use. These are split
1634 // into distinct loops for performance reasons.
1635
1636 // update gc pointer after each statepoint
1637 // either store a relocated value or null (if no relocated value found for
1638 // this gc pointer and it is not a gc_result)
1639 // this must happen before we update the statepoint with load of alloca
1640 // otherwise we lose the link between statepoint and old def
Igor Laevsky285fe842015-05-19 16:29:43 +00001641 for (size_t i = 0; i < Records.size(); i++) {
1642 const struct PartiallyConstructedSafepointRecord &Info = Records[i];
1643 Value *Statepoint = Info.StatepointToken;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001644
1645 // This will be used for consistency check
Igor Laevsky285fe842015-05-19 16:29:43 +00001646 DenseSet<Value *> VisitedLiveValues;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001647
1648 // Insert stores for normal statepoint gc relocates
Igor Laevsky285fe842015-05-19 16:29:43 +00001649 insertRelocationStores(Statepoint->users(), AllocaMap, VisitedLiveValues);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001650
1651 // In case if it was invoke statepoint
1652 // we will insert stores for exceptional path gc relocates.
Philip Reames0a3240f2015-02-20 21:34:11 +00001653 if (isa<InvokeInst>(Statepoint)) {
Igor Laevsky285fe842015-05-19 16:29:43 +00001654 insertRelocationStores(Info.UnwindToken->users(), AllocaMap,
1655 VisitedLiveValues);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001656 }
1657
Igor Laevskye0317182015-05-19 15:59:05 +00001658 // Do similar thing with rematerialized values
Igor Laevsky285fe842015-05-19 16:29:43 +00001659 insertRematerializationStores(Info.RematerializedValues, AllocaMap,
1660 VisitedLiveValues);
Igor Laevskye0317182015-05-19 15:59:05 +00001661
Philip Reamese73300b2015-04-13 16:41:32 +00001662 if (ClobberNonLive) {
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001663 // As a debugging aid, pretend that an unrelocated pointer becomes null at
Philip Reamese73300b2015-04-13 16:41:32 +00001664 // the gc.statepoint. This will turn some subtle GC problems into
1665 // slightly easier to debug SEGVs. Note that on large IR files with
1666 // lots of gc.statepoints this is extremely costly both memory and time
1667 // wise.
1668 SmallVector<AllocaInst *, 64> ToClobber;
Igor Laevsky285fe842015-05-19 16:29:43 +00001669 for (auto Pair : AllocaMap) {
Philip Reamese73300b2015-04-13 16:41:32 +00001670 Value *Def = Pair.first;
1671 AllocaInst *Alloca = cast<AllocaInst>(Pair.second);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001672
Philip Reamese73300b2015-04-13 16:41:32 +00001673 // This value was relocated
Igor Laevsky285fe842015-05-19 16:29:43 +00001674 if (VisitedLiveValues.count(Def)) {
Philip Reamese73300b2015-04-13 16:41:32 +00001675 continue;
1676 }
1677 ToClobber.push_back(Alloca);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001678 }
Philip Reamesfa2fcf172015-02-20 19:51:56 +00001679
Philip Reamese73300b2015-04-13 16:41:32 +00001680 auto InsertClobbersAt = [&](Instruction *IP) {
1681 for (auto *AI : ToClobber) {
1682 auto AIType = cast<PointerType>(AI->getType());
1683 auto PT = cast<PointerType>(AIType->getElementType());
1684 Constant *CPN = ConstantPointerNull::get(PT);
Igor Laevsky285fe842015-05-19 16:29:43 +00001685 StoreInst *Store = new StoreInst(CPN, AI);
1686 Store->insertBefore(IP);
Philip Reamese73300b2015-04-13 16:41:32 +00001687 }
1688 };
1689
1690 // Insert the clobbering stores. These may get intermixed with the
1691 // gc.results and gc.relocates, but that's fine.
1692 if (auto II = dyn_cast<InvokeInst>(Statepoint)) {
1693 InsertClobbersAt(II->getNormalDest()->getFirstInsertionPt());
1694 InsertClobbersAt(II->getUnwindDest()->getFirstInsertionPt());
1695 } else {
1696 BasicBlock::iterator Next(cast<CallInst>(Statepoint));
1697 Next++;
1698 InsertClobbersAt(Next);
Philip Reamesfa2fcf172015-02-20 19:51:56 +00001699 }
David Blaikie82ad7872015-02-20 23:44:24 +00001700 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00001701 }
1702 // update use with load allocas and add store for gc_relocated
Igor Laevsky285fe842015-05-19 16:29:43 +00001703 for (auto Pair : AllocaMap) {
1704 Value *Def = Pair.first;
1705 Value *Alloca = Pair.second;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001706
1707 // we pre-record the uses of allocas so that we dont have to worry about
1708 // later update
1709 // that change the user information.
Igor Laevsky285fe842015-05-19 16:29:43 +00001710 SmallVector<Instruction *, 20> Uses;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001711 // PERF: trade a linear scan for repeated reallocation
Igor Laevsky285fe842015-05-19 16:29:43 +00001712 Uses.reserve(std::distance(Def->user_begin(), Def->user_end()));
1713 for (User *U : Def->users()) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001714 if (!isa<ConstantExpr>(U)) {
1715 // If the def has a ConstantExpr use, then the def is either a
1716 // ConstantExpr use itself or null. In either case
1717 // (recursively in the first, directly in the second), the oop
1718 // it is ultimately dependent on is null and this particular
1719 // use does not need to be fixed up.
Igor Laevsky285fe842015-05-19 16:29:43 +00001720 Uses.push_back(cast<Instruction>(U));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001721 }
1722 }
1723
Igor Laevsky285fe842015-05-19 16:29:43 +00001724 std::sort(Uses.begin(), Uses.end());
1725 auto Last = std::unique(Uses.begin(), Uses.end());
1726 Uses.erase(Last, Uses.end());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001727
Igor Laevsky285fe842015-05-19 16:29:43 +00001728 for (Instruction *Use : Uses) {
1729 if (isa<PHINode>(Use)) {
1730 PHINode *Phi = cast<PHINode>(Use);
1731 for (unsigned i = 0; i < Phi->getNumIncomingValues(); i++) {
1732 if (Def == Phi->getIncomingValue(i)) {
1733 LoadInst *Load = new LoadInst(
1734 Alloca, "", Phi->getIncomingBlock(i)->getTerminator());
1735 Phi->setIncomingValue(i, Load);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001736 }
1737 }
1738 } else {
Igor Laevsky285fe842015-05-19 16:29:43 +00001739 LoadInst *Load = new LoadInst(Alloca, "", Use);
1740 Use->replaceUsesOfWith(Def, Load);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001741 }
1742 }
1743
1744 // emit store for the initial gc value
1745 // store must be inserted after load, otherwise store will be in alloca's
1746 // use list and an extra load will be inserted before it
Igor Laevsky285fe842015-05-19 16:29:43 +00001747 StoreInst *Store = new StoreInst(Def, Alloca);
1748 if (Instruction *Inst = dyn_cast<Instruction>(Def)) {
1749 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(Inst)) {
Philip Reames6da37852015-03-04 00:13:52 +00001750 // InvokeInst is a TerminatorInst so the store need to be inserted
1751 // into its normal destination block.
Igor Laevsky285fe842015-05-19 16:29:43 +00001752 BasicBlock *NormalDest = Invoke->getNormalDest();
1753 Store->insertBefore(NormalDest->getFirstNonPHI());
Philip Reames6da37852015-03-04 00:13:52 +00001754 } else {
Igor Laevsky285fe842015-05-19 16:29:43 +00001755 assert(!Inst->isTerminator() &&
Philip Reames6da37852015-03-04 00:13:52 +00001756 "The only TerminatorInst that can produce a value is "
1757 "InvokeInst which is handled above.");
Igor Laevsky285fe842015-05-19 16:29:43 +00001758 Store->insertAfter(Inst);
Philip Reames6da37852015-03-04 00:13:52 +00001759 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00001760 } else {
Igor Laevsky285fe842015-05-19 16:29:43 +00001761 assert(isa<Argument>(Def));
1762 Store->insertAfter(cast<Instruction>(Alloca));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001763 }
1764 }
1765
Igor Laevsky285fe842015-05-19 16:29:43 +00001766 assert(PromotableAllocas.size() == Live.size() + NumRematerializedValues &&
Philip Reamesd16a9b12015-02-20 01:06:44 +00001767 "we must have the same allocas with lives");
1768 if (!PromotableAllocas.empty()) {
1769 // apply mem2reg to promote alloca to SSA
1770 PromoteMemToReg(PromotableAllocas, DT);
1771 }
1772
1773#ifndef NDEBUG
Philip Reames704e78b2015-04-10 22:34:56 +00001774 for (auto I = F.getEntryBlock().begin(), E = F.getEntryBlock().end(); I != E;
1775 I++)
Philip Reamesa6ebf072015-03-27 05:53:16 +00001776 if (isa<AllocaInst>(*I))
1777 InitialAllocaNum--;
1778 assert(InitialAllocaNum == 0 && "We must not introduce any extra allocas");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001779#endif
1780}
1781
1782/// Implement a unique function which doesn't require we sort the input
1783/// vector. Doing so has the effect of changing the output of a couple of
1784/// tests in ways which make them less useful in testing fused safepoints.
Philip Reamesd2b66462015-02-20 22:39:41 +00001785template <typename T> static void unique_unsorted(SmallVectorImpl<T> &Vec) {
Benjamin Kramer258ea0d2015-06-13 19:50:38 +00001786 SmallSet<T, 8> Seen;
1787 Vec.erase(std::remove_if(Vec.begin(), Vec.end(), [&](const T &V) {
1788 return !Seen.insert(V).second;
1789 }), Vec.end());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001790}
1791
Philip Reamesd16a9b12015-02-20 01:06:44 +00001792/// Insert holders so that each Value is obviously live through the entire
Philip Reamesf209a152015-04-13 20:00:30 +00001793/// lifetime of the call.
Philip Reamesd16a9b12015-02-20 01:06:44 +00001794static void insertUseHolderAfter(CallSite &CS, const ArrayRef<Value *> Values,
Philip Reamesf209a152015-04-13 20:00:30 +00001795 SmallVectorImpl<CallInst *> &Holders) {
Philip Reames21142752015-04-13 19:07:47 +00001796 if (Values.empty())
1797 // No values to hold live, might as well not insert the empty holder
1798 return;
1799
Philip Reamesd16a9b12015-02-20 01:06:44 +00001800 Module *M = CS.getInstruction()->getParent()->getParent()->getParent();
Philip Reamesf209a152015-04-13 20:00:30 +00001801 // Use a dummy vararg function to actually hold the values live
1802 Function *Func = cast<Function>(M->getOrInsertFunction(
1803 "__tmp_use", FunctionType::get(Type::getVoidTy(M->getContext()), true)));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001804 if (CS.isCall()) {
1805 // For call safepoints insert dummy calls right after safepoint
Philip Reamesf209a152015-04-13 20:00:30 +00001806 BasicBlock::iterator Next(CS.getInstruction());
1807 Next++;
1808 Holders.push_back(CallInst::Create(Func, Values, "", Next));
1809 return;
1810 }
1811 // For invoke safepooints insert dummy calls both in normal and
1812 // exceptional destination blocks
1813 auto *II = cast<InvokeInst>(CS.getInstruction());
1814 Holders.push_back(CallInst::Create(
1815 Func, Values, "", II->getNormalDest()->getFirstInsertionPt()));
1816 Holders.push_back(CallInst::Create(
1817 Func, Values, "", II->getUnwindDest()->getFirstInsertionPt()));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001818}
1819
1820static void findLiveReferences(
Philip Reamesd2b66462015-02-20 22:39:41 +00001821 Function &F, DominatorTree &DT, Pass *P, ArrayRef<CallSite> toUpdate,
1822 MutableArrayRef<struct PartiallyConstructedSafepointRecord> records) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00001823 GCPtrLivenessData OriginalLivenessData;
1824 computeLiveInValues(DT, F, OriginalLivenessData);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001825 for (size_t i = 0; i < records.size(); i++) {
1826 struct PartiallyConstructedSafepointRecord &info = records[i];
Philip Reamesd2b66462015-02-20 22:39:41 +00001827 const CallSite &CS = toUpdate[i];
Philip Reamesdf1ef082015-04-10 22:53:14 +00001828 analyzeParsePointLiveness(DT, OriginalLivenessData, CS, info);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001829 }
1830}
1831
Philip Reames8531d8c2015-04-10 21:48:25 +00001832/// Remove any vector of pointers from the liveset by scalarizing them over the
1833/// statepoint instruction. Adds the scalarized pieces to the liveset. It
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001834/// would be preferable to include the vector in the statepoint itself, but
Philip Reames8531d8c2015-04-10 21:48:25 +00001835/// the lowering code currently does not handle that. Extending it would be
1836/// slightly non-trivial since it requires a format change. Given how rare
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001837/// such cases are (for the moment?) scalarizing is an acceptable compromise.
Philip Reames8531d8c2015-04-10 21:48:25 +00001838static void splitVectorValues(Instruction *StatepointInst,
Philip Reames8fe7f132015-06-26 22:47:37 +00001839 StatepointLiveSetTy &LiveSet,
1840 DenseMap<Value *, Value *>& PointerToBase,
1841 DominatorTree &DT) {
Philip Reames8531d8c2015-04-10 21:48:25 +00001842 SmallVector<Value *, 16> ToSplit;
1843 for (Value *V : LiveSet)
1844 if (isa<VectorType>(V->getType()))
1845 ToSplit.push_back(V);
1846
1847 if (ToSplit.empty())
1848 return;
1849
Philip Reames8fe7f132015-06-26 22:47:37 +00001850 DenseMap<Value *, SmallVector<Value *, 16>> ElementMapping;
1851
Philip Reames8531d8c2015-04-10 21:48:25 +00001852 Function &F = *(StatepointInst->getParent()->getParent());
1853
Philip Reames704e78b2015-04-10 22:34:56 +00001854 DenseMap<Value *, AllocaInst *> AllocaMap;
Philip Reames8531d8c2015-04-10 21:48:25 +00001855 // First is normal return, second is exceptional return (invoke only)
Philip Reames704e78b2015-04-10 22:34:56 +00001856 DenseMap<Value *, std::pair<Value *, Value *>> Replacements;
Philip Reames8531d8c2015-04-10 21:48:25 +00001857 for (Value *V : ToSplit) {
Philip Reames704e78b2015-04-10 22:34:56 +00001858 AllocaInst *Alloca =
1859 new AllocaInst(V->getType(), "", F.getEntryBlock().getFirstNonPHI());
Philip Reames8531d8c2015-04-10 21:48:25 +00001860 AllocaMap[V] = Alloca;
1861
1862 VectorType *VT = cast<VectorType>(V->getType());
1863 IRBuilder<> Builder(StatepointInst);
Philip Reames704e78b2015-04-10 22:34:56 +00001864 SmallVector<Value *, 16> Elements;
Philip Reames8531d8c2015-04-10 21:48:25 +00001865 for (unsigned i = 0; i < VT->getNumElements(); i++)
1866 Elements.push_back(Builder.CreateExtractElement(V, Builder.getInt32(i)));
Philip Reames8fe7f132015-06-26 22:47:37 +00001867 ElementMapping[V] = Elements;
Philip Reames8531d8c2015-04-10 21:48:25 +00001868
1869 auto InsertVectorReform = [&](Instruction *IP) {
1870 Builder.SetInsertPoint(IP);
1871 Builder.SetCurrentDebugLocation(IP->getDebugLoc());
1872 Value *ResultVec = UndefValue::get(VT);
1873 for (unsigned i = 0; i < VT->getNumElements(); i++)
1874 ResultVec = Builder.CreateInsertElement(ResultVec, Elements[i],
1875 Builder.getInt32(i));
1876 return ResultVec;
1877 };
1878
1879 if (isa<CallInst>(StatepointInst)) {
1880 BasicBlock::iterator Next(StatepointInst);
1881 Next++;
1882 Instruction *IP = &*(Next);
1883 Replacements[V].first = InsertVectorReform(IP);
1884 Replacements[V].second = nullptr;
1885 } else {
1886 InvokeInst *Invoke = cast<InvokeInst>(StatepointInst);
1887 // We've already normalized - check that we don't have shared destination
Philip Reames704e78b2015-04-10 22:34:56 +00001888 // blocks
Philip Reames8531d8c2015-04-10 21:48:25 +00001889 BasicBlock *NormalDest = Invoke->getNormalDest();
1890 assert(!isa<PHINode>(NormalDest->begin()));
1891 BasicBlock *UnwindDest = Invoke->getUnwindDest();
1892 assert(!isa<PHINode>(UnwindDest->begin()));
1893 // Insert insert element sequences in both successors
1894 Instruction *IP = &*(NormalDest->getFirstInsertionPt());
1895 Replacements[V].first = InsertVectorReform(IP);
1896 IP = &*(UnwindDest->getFirstInsertionPt());
1897 Replacements[V].second = InsertVectorReform(IP);
1898 }
1899 }
Philip Reames8fe7f132015-06-26 22:47:37 +00001900
Philip Reames8531d8c2015-04-10 21:48:25 +00001901 for (Value *V : ToSplit) {
1902 AllocaInst *Alloca = AllocaMap[V];
1903
1904 // Capture all users before we start mutating use lists
Philip Reames704e78b2015-04-10 22:34:56 +00001905 SmallVector<Instruction *, 16> Users;
Philip Reames8531d8c2015-04-10 21:48:25 +00001906 for (User *U : V->users())
1907 Users.push_back(cast<Instruction>(U));
1908
1909 for (Instruction *I : Users) {
1910 if (auto Phi = dyn_cast<PHINode>(I)) {
1911 for (unsigned i = 0; i < Phi->getNumIncomingValues(); i++)
1912 if (V == Phi->getIncomingValue(i)) {
Philip Reames704e78b2015-04-10 22:34:56 +00001913 LoadInst *Load = new LoadInst(
1914 Alloca, "", Phi->getIncomingBlock(i)->getTerminator());
Philip Reames8531d8c2015-04-10 21:48:25 +00001915 Phi->setIncomingValue(i, Load);
1916 }
1917 } else {
1918 LoadInst *Load = new LoadInst(Alloca, "", I);
1919 I->replaceUsesOfWith(V, Load);
1920 }
1921 }
1922
1923 // Store the original value and the replacement value into the alloca
1924 StoreInst *Store = new StoreInst(V, Alloca);
1925 if (auto I = dyn_cast<Instruction>(V))
1926 Store->insertAfter(I);
1927 else
1928 Store->insertAfter(Alloca);
Philip Reames704e78b2015-04-10 22:34:56 +00001929
Philip Reames8531d8c2015-04-10 21:48:25 +00001930 // Normal return for invoke, or call return
1931 Instruction *Replacement = cast<Instruction>(Replacements[V].first);
1932 (new StoreInst(Replacement, Alloca))->insertAfter(Replacement);
1933 // Unwind return for invoke only
1934 Replacement = cast_or_null<Instruction>(Replacements[V].second);
1935 if (Replacement)
1936 (new StoreInst(Replacement, Alloca))->insertAfter(Replacement);
1937 }
1938
1939 // apply mem2reg to promote alloca to SSA
Philip Reames704e78b2015-04-10 22:34:56 +00001940 SmallVector<AllocaInst *, 16> Allocas;
Philip Reames8531d8c2015-04-10 21:48:25 +00001941 for (Value *V : ToSplit)
1942 Allocas.push_back(AllocaMap[V]);
1943 PromoteMemToReg(Allocas, DT);
Philip Reames8fe7f132015-06-26 22:47:37 +00001944
1945 // Update our tracking of live pointers and base mappings to account for the
1946 // changes we just made.
1947 for (Value *V : ToSplit) {
1948 auto &Elements = ElementMapping[V];
1949
1950 LiveSet.erase(V);
1951 LiveSet.insert(Elements.begin(), Elements.end());
1952 // We need to update the base mapping as well.
1953 assert(PointerToBase.count(V));
1954 Value *OldBase = PointerToBase[V];
1955 auto &BaseElements = ElementMapping[OldBase];
1956 PointerToBase.erase(V);
1957 assert(Elements.size() == BaseElements.size());
1958 for (unsigned i = 0; i < Elements.size(); i++) {
1959 Value *Elem = Elements[i];
1960 PointerToBase[Elem] = BaseElements[i];
1961 }
1962 }
Philip Reames8531d8c2015-04-10 21:48:25 +00001963}
1964
Igor Laevskye0317182015-05-19 15:59:05 +00001965// Helper function for the "rematerializeLiveValues". It walks use chain
1966// starting from the "CurrentValue" until it meets "BaseValue". Only "simple"
1967// values are visited (currently it is GEP's and casts). Returns true if it
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001968// successfully reached "BaseValue" and false otherwise.
Igor Laevskye0317182015-05-19 15:59:05 +00001969// Fills "ChainToBase" array with all visited values. "BaseValue" is not
1970// recorded.
1971static bool findRematerializableChainToBasePointer(
1972 SmallVectorImpl<Instruction*> &ChainToBase,
1973 Value *CurrentValue, Value *BaseValue) {
1974
1975 // We have found a base value
1976 if (CurrentValue == BaseValue) {
1977 return true;
1978 }
1979
1980 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurrentValue)) {
1981 ChainToBase.push_back(GEP);
1982 return findRematerializableChainToBasePointer(ChainToBase,
1983 GEP->getPointerOperand(),
1984 BaseValue);
1985 }
1986
1987 if (CastInst *CI = dyn_cast<CastInst>(CurrentValue)) {
1988 Value *Def = CI->stripPointerCasts();
1989
1990 // This two checks are basically similar. First one is here for the
1991 // consistency with findBasePointers logic.
1992 assert(!isa<CastInst>(Def) && "not a pointer cast found");
1993 if (!CI->isNoopCast(CI->getModule()->getDataLayout()))
1994 return false;
1995
1996 ChainToBase.push_back(CI);
1997 return findRematerializableChainToBasePointer(ChainToBase, Def, BaseValue);
1998 }
1999
2000 // Not supported instruction in the chain
2001 return false;
2002}
2003
2004// Helper function for the "rematerializeLiveValues". Compute cost of the use
2005// chain we are going to rematerialize.
2006static unsigned
2007chainToBasePointerCost(SmallVectorImpl<Instruction*> &Chain,
2008 TargetTransformInfo &TTI) {
2009 unsigned Cost = 0;
2010
2011 for (Instruction *Instr : Chain) {
2012 if (CastInst *CI = dyn_cast<CastInst>(Instr)) {
2013 assert(CI->isNoopCast(CI->getModule()->getDataLayout()) &&
2014 "non noop cast is found during rematerialization");
2015
2016 Type *SrcTy = CI->getOperand(0)->getType();
2017 Cost += TTI.getCastInstrCost(CI->getOpcode(), CI->getType(), SrcTy);
2018
2019 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Instr)) {
2020 // Cost of the address calculation
2021 Type *ValTy = GEP->getPointerOperandType()->getPointerElementType();
2022 Cost += TTI.getAddressComputationCost(ValTy);
2023
2024 // And cost of the GEP itself
2025 // TODO: Use TTI->getGEPCost here (it exists, but appears to be not
2026 // allowed for the external usage)
2027 if (!GEP->hasAllConstantIndices())
2028 Cost += 2;
2029
2030 } else {
2031 llvm_unreachable("unsupported instruciton type during rematerialization");
2032 }
2033 }
2034
2035 return Cost;
2036}
2037
2038// From the statepoint liveset pick values that are cheaper to recompute then to
2039// relocate. Remove this values from the liveset, rematerialize them after
2040// statepoint and record them in "Info" structure. Note that similar to
2041// relocated values we don't do any user adjustments here.
2042static void rematerializeLiveValues(CallSite CS,
2043 PartiallyConstructedSafepointRecord &Info,
2044 TargetTransformInfo &TTI) {
Aaron Ballmanff7d4fa2015-05-20 14:53:50 +00002045 const unsigned int ChainLengthThreshold = 10;
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +00002046
Igor Laevskye0317182015-05-19 15:59:05 +00002047 // Record values we are going to delete from this statepoint live set.
2048 // We can not di this in following loop due to iterator invalidation.
2049 SmallVector<Value *, 32> LiveValuesToBeDeleted;
2050
2051 for (Value *LiveValue: Info.liveset) {
2052 // For each live pointer find it's defining chain
2053 SmallVector<Instruction *, 3> ChainToBase;
Philip Reames74ce2e72015-07-21 16:51:17 +00002054 assert(Info.PointerToBase.count(LiveValue));
Igor Laevskye0317182015-05-19 15:59:05 +00002055 bool FoundChain =
2056 findRematerializableChainToBasePointer(ChainToBase,
2057 LiveValue,
2058 Info.PointerToBase[LiveValue]);
2059 // Nothing to do, or chain is too long
2060 if (!FoundChain ||
2061 ChainToBase.size() == 0 ||
2062 ChainToBase.size() > ChainLengthThreshold)
2063 continue;
2064
2065 // Compute cost of this chain
2066 unsigned Cost = chainToBasePointerCost(ChainToBase, TTI);
2067 // TODO: We can also account for cases when we will be able to remove some
2068 // of the rematerialized values by later optimization passes. I.e if
2069 // we rematerialized several intersecting chains. Or if original values
2070 // don't have any uses besides this statepoint.
2071
2072 // For invokes we need to rematerialize each chain twice - for normal and
2073 // for unwind basic blocks. Model this by multiplying cost by two.
2074 if (CS.isInvoke()) {
2075 Cost *= 2;
2076 }
2077 // If it's too expensive - skip it
2078 if (Cost >= RematerializationThreshold)
2079 continue;
2080
2081 // Remove value from the live set
2082 LiveValuesToBeDeleted.push_back(LiveValue);
2083
2084 // Clone instructions and record them inside "Info" structure
2085
2086 // Walk backwards to visit top-most instructions first
2087 std::reverse(ChainToBase.begin(), ChainToBase.end());
2088
2089 // Utility function which clones all instructions from "ChainToBase"
2090 // and inserts them before "InsertBefore". Returns rematerialized value
2091 // which should be used after statepoint.
2092 auto rematerializeChain = [&ChainToBase](Instruction *InsertBefore) {
2093 Instruction *LastClonedValue = nullptr;
2094 Instruction *LastValue = nullptr;
2095 for (Instruction *Instr: ChainToBase) {
2096 // Only GEP's and casts are suported as we need to be careful to not
2097 // introduce any new uses of pointers not in the liveset.
2098 // Note that it's fine to introduce new uses of pointers which were
2099 // otherwise not used after this statepoint.
2100 assert(isa<GetElementPtrInst>(Instr) || isa<CastInst>(Instr));
2101
2102 Instruction *ClonedValue = Instr->clone();
2103 ClonedValue->insertBefore(InsertBefore);
2104 ClonedValue->setName(Instr->getName() + ".remat");
2105
2106 // If it is not first instruction in the chain then it uses previously
2107 // cloned value. We should update it to use cloned value.
2108 if (LastClonedValue) {
2109 assert(LastValue);
2110 ClonedValue->replaceUsesOfWith(LastValue, LastClonedValue);
2111#ifndef NDEBUG
Igor Laevskyd83f6972015-05-21 13:02:14 +00002112 // Assert that cloned instruction does not use any instructions from
2113 // this chain other than LastClonedValue
2114 for (auto OpValue : ClonedValue->operand_values()) {
2115 assert(std::find(ChainToBase.begin(), ChainToBase.end(), OpValue) ==
2116 ChainToBase.end() &&
2117 "incorrect use in rematerialization chain");
Igor Laevskye0317182015-05-19 15:59:05 +00002118 }
2119#endif
2120 }
2121
2122 LastClonedValue = ClonedValue;
2123 LastValue = Instr;
2124 }
2125 assert(LastClonedValue);
2126 return LastClonedValue;
2127 };
2128
2129 // Different cases for calls and invokes. For invokes we need to clone
2130 // instructions both on normal and unwind path.
2131 if (CS.isCall()) {
2132 Instruction *InsertBefore = CS.getInstruction()->getNextNode();
2133 assert(InsertBefore);
2134 Instruction *RematerializedValue = rematerializeChain(InsertBefore);
2135 Info.RematerializedValues[RematerializedValue] = LiveValue;
2136 } else {
2137 InvokeInst *Invoke = cast<InvokeInst>(CS.getInstruction());
2138
2139 Instruction *NormalInsertBefore =
2140 Invoke->getNormalDest()->getFirstInsertionPt();
2141 Instruction *UnwindInsertBefore =
2142 Invoke->getUnwindDest()->getFirstInsertionPt();
2143
2144 Instruction *NormalRematerializedValue =
2145 rematerializeChain(NormalInsertBefore);
2146 Instruction *UnwindRematerializedValue =
2147 rematerializeChain(UnwindInsertBefore);
2148
2149 Info.RematerializedValues[NormalRematerializedValue] = LiveValue;
2150 Info.RematerializedValues[UnwindRematerializedValue] = LiveValue;
2151 }
2152 }
2153
2154 // Remove rematerializaed values from the live set
2155 for (auto LiveValue: LiveValuesToBeDeleted) {
2156 Info.liveset.erase(LiveValue);
2157 }
2158}
2159
Philip Reamesd16a9b12015-02-20 01:06:44 +00002160static bool insertParsePoints(Function &F, DominatorTree &DT, Pass *P,
Philip Reamesd2b66462015-02-20 22:39:41 +00002161 SmallVectorImpl<CallSite> &toUpdate) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00002162#ifndef NDEBUG
2163 // sanity check the input
2164 std::set<CallSite> uniqued;
2165 uniqued.insert(toUpdate.begin(), toUpdate.end());
2166 assert(uniqued.size() == toUpdate.size() && "no duplicates please!");
2167
2168 for (size_t i = 0; i < toUpdate.size(); i++) {
2169 CallSite &CS = toUpdate[i];
2170 assert(CS.getInstruction()->getParent()->getParent() == &F);
2171 assert(isStatepoint(CS) && "expected to already be a deopt statepoint");
2172 }
2173#endif
2174
Philip Reames69e51ca2015-04-13 18:07:21 +00002175 // When inserting gc.relocates for invokes, we need to be able to insert at
2176 // the top of the successor blocks. See the comment on
2177 // normalForInvokeSafepoint on exactly what is needed. Note that this step
Philip Reamesf209a152015-04-13 20:00:30 +00002178 // may restructure the CFG.
2179 for (CallSite CS : toUpdate) {
2180 if (!CS.isInvoke())
2181 continue;
2182 InvokeInst *invoke = cast<InvokeInst>(CS.getInstruction());
2183 normalizeForInvokeSafepoint(invoke->getNormalDest(), invoke->getParent(),
Sanjoy Dasea45f0e2015-06-02 22:33:34 +00002184 DT);
Philip Reamesf209a152015-04-13 20:00:30 +00002185 normalizeForInvokeSafepoint(invoke->getUnwindDest(), invoke->getParent(),
Sanjoy Dasea45f0e2015-06-02 22:33:34 +00002186 DT);
Philip Reamesf209a152015-04-13 20:00:30 +00002187 }
Philip Reames69e51ca2015-04-13 18:07:21 +00002188
Philip Reamesd16a9b12015-02-20 01:06:44 +00002189 // A list of dummy calls added to the IR to keep various values obviously
2190 // live in the IR. We'll remove all of these when done.
Philip Reamesd2b66462015-02-20 22:39:41 +00002191 SmallVector<CallInst *, 64> holders;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002192
2193 // Insert a dummy call with all of the arguments to the vm_state we'll need
2194 // for the actual safepoint insertion. This ensures reference arguments in
2195 // the deopt argument list are considered live through the safepoint (and
2196 // thus makes sure they get relocated.)
2197 for (size_t i = 0; i < toUpdate.size(); i++) {
2198 CallSite &CS = toUpdate[i];
2199 Statepoint StatepointCS(CS);
2200
2201 SmallVector<Value *, 64> DeoptValues;
2202 for (Use &U : StatepointCS.vm_state_args()) {
2203 Value *Arg = cast<Value>(&U);
Philip Reames8531d8c2015-04-10 21:48:25 +00002204 assert(!isUnhandledGCPointerType(Arg->getType()) &&
2205 "support for FCA unimplemented");
2206 if (isHandledGCPointerType(Arg->getType()))
Philip Reamesd16a9b12015-02-20 01:06:44 +00002207 DeoptValues.push_back(Arg);
2208 }
2209 insertUseHolderAfter(CS, DeoptValues, holders);
2210 }
2211
Philip Reamesd2b66462015-02-20 22:39:41 +00002212 SmallVector<struct PartiallyConstructedSafepointRecord, 64> records;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002213 records.reserve(toUpdate.size());
2214 for (size_t i = 0; i < toUpdate.size(); i++) {
2215 struct PartiallyConstructedSafepointRecord info;
2216 records.push_back(info);
2217 }
2218 assert(records.size() == toUpdate.size());
2219
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002220 // A) Identify all gc pointers which are statically live at the given call
Philip Reamesd16a9b12015-02-20 01:06:44 +00002221 // site.
2222 findLiveReferences(F, DT, P, toUpdate, records);
2223
2224 // B) Find the base pointers for each live pointer
2225 /* scope for caching */ {
2226 // Cache the 'defining value' relation used in the computation and
2227 // insertion of base phis and selects. This ensures that we don't insert
2228 // large numbers of duplicate base_phis.
2229 DefiningValueMapTy DVCache;
2230
2231 for (size_t i = 0; i < records.size(); i++) {
2232 struct PartiallyConstructedSafepointRecord &info = records[i];
2233 CallSite &CS = toUpdate[i];
2234 findBasePointers(DT, DVCache, CS, info);
2235 }
2236 } // end of cache scope
2237
2238 // The base phi insertion logic (for any safepoint) may have inserted new
2239 // instructions which are now live at some safepoint. The simplest such
2240 // example is:
2241 // loop:
2242 // phi a <-- will be a new base_phi here
2243 // safepoint 1 <-- that needs to be live here
2244 // gep a + 1
2245 // safepoint 2
2246 // br loop
Philip Reamesd16a9b12015-02-20 01:06:44 +00002247 // We insert some dummy calls after each safepoint to definitely hold live
2248 // the base pointers which were identified for that safepoint. We'll then
2249 // ask liveness for _every_ base inserted to see what is now live. Then we
2250 // remove the dummy calls.
2251 holders.reserve(holders.size() + records.size());
2252 for (size_t i = 0; i < records.size(); i++) {
2253 struct PartiallyConstructedSafepointRecord &info = records[i];
2254 CallSite &CS = toUpdate[i];
2255
2256 SmallVector<Value *, 128> Bases;
Philip Reamesf2041322015-02-20 19:26:04 +00002257 for (auto Pair : info.PointerToBase) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00002258 Bases.push_back(Pair.second);
2259 }
2260 insertUseHolderAfter(CS, Bases, holders);
2261 }
2262
Philip Reamesdf1ef082015-04-10 22:53:14 +00002263 // By selecting base pointers, we've effectively inserted new uses. Thus, we
2264 // need to rerun liveness. We may *also* have inserted new defs, but that's
2265 // not the key issue.
2266 recomputeLiveInValues(F, DT, P, toUpdate, records);
Philip Reamesd16a9b12015-02-20 01:06:44 +00002267
Philip Reamesd16a9b12015-02-20 01:06:44 +00002268 if (PrintBasePointers) {
2269 for (size_t i = 0; i < records.size(); i++) {
2270 struct PartiallyConstructedSafepointRecord &info = records[i];
2271 errs() << "Base Pairs: (w/Relocation)\n";
Philip Reamesf2041322015-02-20 19:26:04 +00002272 for (auto Pair : info.PointerToBase) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00002273 errs() << " derived %" << Pair.first->getName() << " base %"
2274 << Pair.second->getName() << "\n";
2275 }
2276 }
2277 }
2278 for (size_t i = 0; i < holders.size(); i++) {
2279 holders[i]->eraseFromParent();
2280 holders[i] = nullptr;
2281 }
2282 holders.clear();
2283
Philip Reames8fe7f132015-06-26 22:47:37 +00002284 // Do a limited scalarization of any live at safepoint vector values which
2285 // contain pointers. This enables this pass to run after vectorization at
2286 // the cost of some possible performance loss. TODO: it would be nice to
2287 // natively support vectors all the way through the backend so we don't need
2288 // to scalarize here.
2289 for (size_t i = 0; i < records.size(); i++) {
2290 struct PartiallyConstructedSafepointRecord &info = records[i];
2291 Instruction *statepoint = toUpdate[i].getInstruction();
2292 splitVectorValues(cast<Instruction>(statepoint), info.liveset,
2293 info.PointerToBase, DT);
2294 }
2295
Igor Laevskye0317182015-05-19 15:59:05 +00002296 // In order to reduce live set of statepoint we might choose to rematerialize
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002297 // some values instead of relocating them. This is purely an optimization and
Igor Laevskye0317182015-05-19 15:59:05 +00002298 // does not influence correctness.
2299 TargetTransformInfo &TTI =
2300 P->getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
2301
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +00002302 for (size_t i = 0; i < records.size(); i++) {
Igor Laevskye0317182015-05-19 15:59:05 +00002303 struct PartiallyConstructedSafepointRecord &info = records[i];
2304 CallSite &CS = toUpdate[i];
2305
2306 rematerializeLiveValues(CS, info, TTI);
2307 }
2308
Philip Reamesd16a9b12015-02-20 01:06:44 +00002309 // Now run through and replace the existing statepoints with new ones with
2310 // the live variables listed. We do not yet update uses of the values being
2311 // relocated. We have references to live variables that need to
2312 // survive to the last iteration of this loop. (By construction, the
2313 // previous statepoint can not be a live variable, thus we can and remove
2314 // the old statepoint calls as we go.)
2315 for (size_t i = 0; i < records.size(); i++) {
2316 struct PartiallyConstructedSafepointRecord &info = records[i];
2317 CallSite &CS = toUpdate[i];
2318 makeStatepointExplicit(DT, CS, P, info);
2319 }
2320 toUpdate.clear(); // prevent accident use of invalid CallSites
2321
Philip Reamesd16a9b12015-02-20 01:06:44 +00002322 // Do all the fixups of the original live variables to their relocated selves
Philip Reamesd2b66462015-02-20 22:39:41 +00002323 SmallVector<Value *, 128> live;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002324 for (size_t i = 0; i < records.size(); i++) {
2325 struct PartiallyConstructedSafepointRecord &info = records[i];
2326 // We can't simply save the live set from the original insertion. One of
2327 // the live values might be the result of a call which needs a safepoint.
2328 // That Value* no longer exists and we need to use the new gc_result.
2329 // Thankfully, the liveset is embedded in the statepoint (and updated), so
2330 // we just grab that.
Philip Reames0a3240f2015-02-20 21:34:11 +00002331 Statepoint statepoint(info.StatepointToken);
Philip Reamesd16a9b12015-02-20 01:06:44 +00002332 live.insert(live.end(), statepoint.gc_args_begin(),
2333 statepoint.gc_args_end());
Philip Reames9a2e01d2015-04-13 17:35:55 +00002334#ifndef NDEBUG
2335 // Do some basic sanity checks on our liveness results before performing
2336 // relocation. Relocation can and will turn mistakes in liveness results
2337 // into non-sensical code which is must harder to debug.
2338 // TODO: It would be nice to test consistency as well
2339 assert(DT.isReachableFromEntry(info.StatepointToken->getParent()) &&
2340 "statepoint must be reachable or liveness is meaningless");
2341 for (Value *V : statepoint.gc_args()) {
2342 if (!isa<Instruction>(V))
2343 // Non-instruction values trivial dominate all possible uses
2344 continue;
2345 auto LiveInst = cast<Instruction>(V);
2346 assert(DT.isReachableFromEntry(LiveInst->getParent()) &&
2347 "unreachable values should never be live");
2348 assert(DT.dominates(LiveInst, info.StatepointToken) &&
2349 "basic SSA liveness expectation violated by liveness analysis");
2350 }
2351#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +00002352 }
2353 unique_unsorted(live);
2354
Nick Lewyckyeb3231e2015-02-20 07:14:02 +00002355#ifndef NDEBUG
Philip Reamesd16a9b12015-02-20 01:06:44 +00002356 // sanity check
2357 for (auto ptr : live) {
2358 assert(isGCPointerType(ptr->getType()) && "must be a gc pointer type");
2359 }
Nick Lewyckyeb3231e2015-02-20 07:14:02 +00002360#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +00002361
2362 relocationViaAlloca(F, DT, live, records);
2363 return !records.empty();
2364}
2365
Sanjoy Das353a19e2015-06-02 22:33:37 +00002366// Handles both return values and arguments for Functions and CallSites.
2367template <typename AttrHolder>
2368static void RemoveDerefAttrAtIndex(LLVMContext &Ctx, AttrHolder &AH,
2369 unsigned Index) {
2370 AttrBuilder R;
2371 if (AH.getDereferenceableBytes(Index))
2372 R.addAttribute(Attribute::get(Ctx, Attribute::Dereferenceable,
2373 AH.getDereferenceableBytes(Index)));
2374 if (AH.getDereferenceableOrNullBytes(Index))
2375 R.addAttribute(Attribute::get(Ctx, Attribute::DereferenceableOrNull,
2376 AH.getDereferenceableOrNullBytes(Index)));
2377
2378 if (!R.empty())
2379 AH.setAttributes(AH.getAttributes().removeAttributes(
2380 Ctx, Index, AttributeSet::get(Ctx, Index, R)));
Vasileios Kalintiris9f77f612015-06-03 08:51:30 +00002381}
Sanjoy Das353a19e2015-06-02 22:33:37 +00002382
2383void
2384RewriteStatepointsForGC::stripDereferenceabilityInfoFromPrototype(Function &F) {
2385 LLVMContext &Ctx = F.getContext();
2386
2387 for (Argument &A : F.args())
2388 if (isa<PointerType>(A.getType()))
2389 RemoveDerefAttrAtIndex(Ctx, F, A.getArgNo() + 1);
2390
2391 if (isa<PointerType>(F.getReturnType()))
2392 RemoveDerefAttrAtIndex(Ctx, F, AttributeSet::ReturnIndex);
2393}
2394
2395void RewriteStatepointsForGC::stripDereferenceabilityInfoFromBody(Function &F) {
2396 if (F.empty())
2397 return;
2398
2399 LLVMContext &Ctx = F.getContext();
2400 MDBuilder Builder(Ctx);
2401
Nico Rieck78199512015-08-06 19:10:45 +00002402 for (Instruction &I : instructions(F)) {
Sanjoy Das353a19e2015-06-02 22:33:37 +00002403 if (const MDNode *MD = I.getMetadata(LLVMContext::MD_tbaa)) {
2404 assert(MD->getNumOperands() < 5 && "unrecognized metadata shape!");
2405 bool IsImmutableTBAA =
2406 MD->getNumOperands() == 4 &&
2407 mdconst::extract<ConstantInt>(MD->getOperand(3))->getValue() == 1;
2408
2409 if (!IsImmutableTBAA)
2410 continue; // no work to do, MD_tbaa is already marked mutable
2411
2412 MDNode *Base = cast<MDNode>(MD->getOperand(0));
2413 MDNode *Access = cast<MDNode>(MD->getOperand(1));
2414 uint64_t Offset =
2415 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue();
2416
2417 MDNode *MutableTBAA =
2418 Builder.createTBAAStructTagNode(Base, Access, Offset);
2419 I.setMetadata(LLVMContext::MD_tbaa, MutableTBAA);
2420 }
2421
2422 if (CallSite CS = CallSite(&I)) {
2423 for (int i = 0, e = CS.arg_size(); i != e; i++)
2424 if (isa<PointerType>(CS.getArgument(i)->getType()))
2425 RemoveDerefAttrAtIndex(Ctx, CS, i + 1);
2426 if (isa<PointerType>(CS.getType()))
2427 RemoveDerefAttrAtIndex(Ctx, CS, AttributeSet::ReturnIndex);
2428 }
2429 }
2430}
2431
Philip Reamesd16a9b12015-02-20 01:06:44 +00002432/// Returns true if this function should be rewritten by this pass. The main
2433/// point of this function is as an extension point for custom logic.
2434static bool shouldRewriteStatepointsIn(Function &F) {
2435 // TODO: This should check the GCStrategy
Philip Reames2ef029c2015-02-20 18:56:14 +00002436 if (F.hasGC()) {
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +00002437 const char *FunctionGCName = F.getGC();
2438 const StringRef StatepointExampleName("statepoint-example");
2439 const StringRef CoreCLRName("coreclr");
2440 return (StatepointExampleName == FunctionGCName) ||
NAKAMURA Takumi5582a6a2015-05-25 01:43:34 +00002441 (CoreCLRName == FunctionGCName);
2442 } else
Philip Reames2ef029c2015-02-20 18:56:14 +00002443 return false;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002444}
2445
Sanjoy Das353a19e2015-06-02 22:33:37 +00002446void RewriteStatepointsForGC::stripDereferenceabilityInfo(Module &M) {
2447#ifndef NDEBUG
2448 assert(std::any_of(M.begin(), M.end(), shouldRewriteStatepointsIn) &&
2449 "precondition!");
2450#endif
2451
2452 for (Function &F : M)
2453 stripDereferenceabilityInfoFromPrototype(F);
2454
2455 for (Function &F : M)
2456 stripDereferenceabilityInfoFromBody(F);
2457}
2458
Philip Reamesd16a9b12015-02-20 01:06:44 +00002459bool RewriteStatepointsForGC::runOnFunction(Function &F) {
2460 // Nothing to do for declarations.
2461 if (F.isDeclaration() || F.empty())
2462 return false;
2463
2464 // Policy choice says not to rewrite - the most common reason is that we're
2465 // compiling code without a GCStrategy.
2466 if (!shouldRewriteStatepointsIn(F))
2467 return false;
2468
Sanjoy Dasea45f0e2015-06-02 22:33:34 +00002469 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
Philip Reames704e78b2015-04-10 22:34:56 +00002470
Philip Reames85b36a82015-04-10 22:07:04 +00002471 // Gather all the statepoints which need rewritten. Be careful to only
2472 // consider those in reachable code since we need to ask dominance queries
2473 // when rewriting. We'll delete the unreachable ones in a moment.
Philip Reamesd2b66462015-02-20 22:39:41 +00002474 SmallVector<CallSite, 64> ParsePointNeeded;
Philip Reamesf66d7372015-04-10 22:16:58 +00002475 bool HasUnreachableStatepoint = false;
Nico Rieck78199512015-08-06 19:10:45 +00002476 for (Instruction &I : instructions(F)) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00002477 // TODO: only the ones with the flag set!
Philip Reames85b36a82015-04-10 22:07:04 +00002478 if (isStatepoint(I)) {
2479 if (DT.isReachableFromEntry(I.getParent()))
2480 ParsePointNeeded.push_back(CallSite(&I));
2481 else
Philip Reamesf66d7372015-04-10 22:16:58 +00002482 HasUnreachableStatepoint = true;
Philip Reames85b36a82015-04-10 22:07:04 +00002483 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00002484 }
2485
Philip Reames85b36a82015-04-10 22:07:04 +00002486 bool MadeChange = false;
Philip Reames704e78b2015-04-10 22:34:56 +00002487
Philip Reames85b36a82015-04-10 22:07:04 +00002488 // Delete any unreachable statepoints so that we don't have unrewritten
2489 // statepoints surviving this pass. This makes testing easier and the
2490 // resulting IR less confusing to human readers. Rather than be fancy, we
2491 // just reuse a utility function which removes the unreachable blocks.
Philip Reamesf66d7372015-04-10 22:16:58 +00002492 if (HasUnreachableStatepoint)
Philip Reames85b36a82015-04-10 22:07:04 +00002493 MadeChange |= removeUnreachableBlocks(F);
2494
Philip Reamesd16a9b12015-02-20 01:06:44 +00002495 // Return early if no work to do.
2496 if (ParsePointNeeded.empty())
Philip Reames85b36a82015-04-10 22:07:04 +00002497 return MadeChange;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002498
Philip Reames85b36a82015-04-10 22:07:04 +00002499 // As a prepass, go ahead and aggressively destroy single entry phi nodes.
2500 // These are created by LCSSA. They have the effect of increasing the size
2501 // of liveness sets for no good reason. It may be harder to do this post
2502 // insertion since relocations and base phis can confuse things.
2503 for (BasicBlock &BB : F)
2504 if (BB.getUniquePredecessor()) {
2505 MadeChange = true;
2506 FoldSingleEntryPHINodes(&BB);
2507 }
2508
Philip Reames971dc3a2015-08-12 22:11:45 +00002509 // Before we start introducing relocations, we want to tweak the IR a bit to
2510 // avoid unfortunate code generation effects. The main example is that we
2511 // want to try to make sure the comparison feeding a branch is after any
2512 // safepoints. Otherwise, we end up with a comparison of pre-relocation
2513 // values feeding a branch after relocation. This is semantically correct,
2514 // but results in extra register pressure since both the pre-relocation and
2515 // post-relocation copies must be available in registers. For code without
2516 // relocations this is handled elsewhere, but teaching the scheduler to
2517 // reverse the transform we're about to do would be slightly complex.
2518 // Note: This may extend the live range of the inputs to the icmp and thus
2519 // increase the liveset of any statepoint we move over. This is profitable
2520 // as long as all statepoints are in rare blocks. If we had in-register
2521 // lowering for live values this would be a much safer transform.
2522 auto getConditionInst = [](TerminatorInst *TI) -> Instruction* {
2523 if (auto *BI = dyn_cast<BranchInst>(TI))
2524 if (BI->isConditional())
2525 return dyn_cast<Instruction>(BI->getCondition());
2526 // TODO: Extend this to handle switches
2527 return nullptr;
2528 };
2529 for (BasicBlock &BB : F) {
2530 TerminatorInst *TI = BB.getTerminator();
2531 if (auto *Cond = getConditionInst(TI))
2532 // TODO: Handle more than just ICmps here. We should be able to move
2533 // most instructions without side effects or memory access.
2534 if (isa<ICmpInst>(Cond) && Cond->hasOneUse()) {
2535 MadeChange = true;
2536 Cond->moveBefore(TI);
2537 }
2538 }
2539
Philip Reames85b36a82015-04-10 22:07:04 +00002540 MadeChange |= insertParsePoints(F, DT, this, ParsePointNeeded);
2541 return MadeChange;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002542}
Philip Reamesdf1ef082015-04-10 22:53:14 +00002543
2544// liveness computation via standard dataflow
2545// -------------------------------------------------------------------
2546
2547// TODO: Consider using bitvectors for liveness, the set of potentially
2548// interesting values should be small and easy to pre-compute.
2549
Philip Reamesdf1ef082015-04-10 22:53:14 +00002550/// Compute the live-in set for the location rbegin starting from
2551/// the live-out set of the basic block
2552static void computeLiveInValues(BasicBlock::reverse_iterator rbegin,
2553 BasicBlock::reverse_iterator rend,
2554 DenseSet<Value *> &LiveTmp) {
2555
2556 for (BasicBlock::reverse_iterator ritr = rbegin; ritr != rend; ritr++) {
2557 Instruction *I = &*ritr;
2558
2559 // KILL/Def - Remove this definition from LiveIn
2560 LiveTmp.erase(I);
2561
2562 // Don't consider *uses* in PHI nodes, we handle their contribution to
2563 // predecessor blocks when we seed the LiveOut sets
2564 if (isa<PHINode>(I))
2565 continue;
2566
2567 // USE - Add to the LiveIn set for this instruction
2568 for (Value *V : I->operands()) {
2569 assert(!isUnhandledGCPointerType(V->getType()) &&
2570 "support for FCA unimplemented");
Philip Reames63294cb2015-04-26 19:48:03 +00002571 if (isHandledGCPointerType(V->getType()) && !isa<Constant>(V)) {
2572 // The choice to exclude all things constant here is slightly subtle.
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002573 // There are two independent reasons:
Philip Reames63294cb2015-04-26 19:48:03 +00002574 // - We assume that things which are constant (from LLVM's definition)
2575 // do not move at runtime. For example, the address of a global
2576 // variable is fixed, even though it's contents may not be.
2577 // - Second, we can't disallow arbitrary inttoptr constants even
2578 // if the language frontend does. Optimization passes are free to
2579 // locally exploit facts without respect to global reachability. This
2580 // can create sections of code which are dynamically unreachable and
2581 // contain just about anything. (see constants.ll in tests)
Philip Reamesdf1ef082015-04-10 22:53:14 +00002582 LiveTmp.insert(V);
2583 }
2584 }
2585 }
2586}
2587
2588static void computeLiveOutSeed(BasicBlock *BB, DenseSet<Value *> &LiveTmp) {
2589
2590 for (BasicBlock *Succ : successors(BB)) {
2591 const BasicBlock::iterator E(Succ->getFirstNonPHI());
2592 for (BasicBlock::iterator I = Succ->begin(); I != E; I++) {
2593 PHINode *Phi = cast<PHINode>(&*I);
2594 Value *V = Phi->getIncomingValueForBlock(BB);
2595 assert(!isUnhandledGCPointerType(V->getType()) &&
2596 "support for FCA unimplemented");
Philip Reames63294cb2015-04-26 19:48:03 +00002597 if (isHandledGCPointerType(V->getType()) && !isa<Constant>(V)) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00002598 LiveTmp.insert(V);
2599 }
2600 }
2601 }
2602}
2603
2604static DenseSet<Value *> computeKillSet(BasicBlock *BB) {
2605 DenseSet<Value *> KillSet;
2606 for (Instruction &I : *BB)
2607 if (isHandledGCPointerType(I.getType()))
2608 KillSet.insert(&I);
2609 return KillSet;
2610}
2611
Philip Reames9638ff92015-04-11 00:06:47 +00002612#ifndef NDEBUG
Philip Reamesdf1ef082015-04-10 22:53:14 +00002613/// Check that the items in 'Live' dominate 'TI'. This is used as a basic
2614/// sanity check for the liveness computation.
2615static void checkBasicSSA(DominatorTree &DT, DenseSet<Value *> &Live,
2616 TerminatorInst *TI, bool TermOkay = false) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00002617 for (Value *V : Live) {
2618 if (auto *I = dyn_cast<Instruction>(V)) {
2619 // The terminator can be a member of the LiveOut set. LLVM's definition
2620 // of instruction dominance states that V does not dominate itself. As
2621 // such, we need to special case this to allow it.
2622 if (TermOkay && TI == I)
2623 continue;
2624 assert(DT.dominates(I, TI) &&
2625 "basic SSA liveness expectation violated by liveness analysis");
2626 }
2627 }
Philip Reamesdf1ef082015-04-10 22:53:14 +00002628}
2629
2630/// Check that all the liveness sets used during the computation of liveness
2631/// obey basic SSA properties. This is useful for finding cases where we miss
2632/// a def.
2633static void checkBasicSSA(DominatorTree &DT, GCPtrLivenessData &Data,
2634 BasicBlock &BB) {
2635 checkBasicSSA(DT, Data.LiveSet[&BB], BB.getTerminator());
2636 checkBasicSSA(DT, Data.LiveOut[&BB], BB.getTerminator(), true);
2637 checkBasicSSA(DT, Data.LiveIn[&BB], BB.getTerminator());
2638}
Philip Reames9638ff92015-04-11 00:06:47 +00002639#endif
Philip Reamesdf1ef082015-04-10 22:53:14 +00002640
2641static void computeLiveInValues(DominatorTree &DT, Function &F,
2642 GCPtrLivenessData &Data) {
2643
Philip Reames4d80ede2015-04-10 23:11:26 +00002644 SmallSetVector<BasicBlock *, 200> Worklist;
Philip Reamesdf1ef082015-04-10 22:53:14 +00002645 auto AddPredsToWorklist = [&](BasicBlock *BB) {
Philip Reames4d80ede2015-04-10 23:11:26 +00002646 // We use a SetVector so that we don't have duplicates in the worklist.
2647 Worklist.insert(pred_begin(BB), pred_end(BB));
Philip Reamesdf1ef082015-04-10 22:53:14 +00002648 };
2649 auto NextItem = [&]() {
2650 BasicBlock *BB = Worklist.back();
2651 Worklist.pop_back();
Philip Reamesdf1ef082015-04-10 22:53:14 +00002652 return BB;
2653 };
2654
2655 // Seed the liveness for each individual block
2656 for (BasicBlock &BB : F) {
2657 Data.KillSet[&BB] = computeKillSet(&BB);
2658 Data.LiveSet[&BB].clear();
2659 computeLiveInValues(BB.rbegin(), BB.rend(), Data.LiveSet[&BB]);
2660
2661#ifndef NDEBUG
2662 for (Value *Kill : Data.KillSet[&BB])
2663 assert(!Data.LiveSet[&BB].count(Kill) && "live set contains kill");
2664#endif
2665
2666 Data.LiveOut[&BB] = DenseSet<Value *>();
2667 computeLiveOutSeed(&BB, Data.LiveOut[&BB]);
2668 Data.LiveIn[&BB] = Data.LiveSet[&BB];
2669 set_union(Data.LiveIn[&BB], Data.LiveOut[&BB]);
2670 set_subtract(Data.LiveIn[&BB], Data.KillSet[&BB]);
2671 if (!Data.LiveIn[&BB].empty())
2672 AddPredsToWorklist(&BB);
2673 }
2674
2675 // Propagate that liveness until stable
2676 while (!Worklist.empty()) {
2677 BasicBlock *BB = NextItem();
2678
2679 // Compute our new liveout set, then exit early if it hasn't changed
2680 // despite the contribution of our successor.
2681 DenseSet<Value *> LiveOut = Data.LiveOut[BB];
2682 const auto OldLiveOutSize = LiveOut.size();
2683 for (BasicBlock *Succ : successors(BB)) {
2684 assert(Data.LiveIn.count(Succ));
2685 set_union(LiveOut, Data.LiveIn[Succ]);
2686 }
2687 // assert OutLiveOut is a subset of LiveOut
2688 if (OldLiveOutSize == LiveOut.size()) {
2689 // If the sets are the same size, then we didn't actually add anything
2690 // when unioning our successors LiveIn Thus, the LiveIn of this block
2691 // hasn't changed.
2692 continue;
2693 }
2694 Data.LiveOut[BB] = LiveOut;
2695
2696 // Apply the effects of this basic block
2697 DenseSet<Value *> LiveTmp = LiveOut;
2698 set_union(LiveTmp, Data.LiveSet[BB]);
2699 set_subtract(LiveTmp, Data.KillSet[BB]);
2700
2701 assert(Data.LiveIn.count(BB));
2702 const DenseSet<Value *> &OldLiveIn = Data.LiveIn[BB];
2703 // assert: OldLiveIn is a subset of LiveTmp
2704 if (OldLiveIn.size() != LiveTmp.size()) {
2705 Data.LiveIn[BB] = LiveTmp;
2706 AddPredsToWorklist(BB);
2707 }
2708 } // while( !worklist.empty() )
2709
2710#ifndef NDEBUG
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002711 // Sanity check our output against SSA properties. This helps catch any
Philip Reamesdf1ef082015-04-10 22:53:14 +00002712 // missing kills during the above iteration.
2713 for (BasicBlock &BB : F) {
2714 checkBasicSSA(DT, Data, BB);
2715 }
2716#endif
2717}
2718
2719static void findLiveSetAtInst(Instruction *Inst, GCPtrLivenessData &Data,
2720 StatepointLiveSetTy &Out) {
2721
2722 BasicBlock *BB = Inst->getParent();
2723
2724 // Note: The copy is intentional and required
2725 assert(Data.LiveOut.count(BB));
2726 DenseSet<Value *> LiveOut = Data.LiveOut[BB];
2727
2728 // We want to handle the statepoint itself oddly. It's
2729 // call result is not live (normal), nor are it's arguments
2730 // (unless they're used again later). This adjustment is
2731 // specifically what we need to relocate
2732 BasicBlock::reverse_iterator rend(Inst);
2733 computeLiveInValues(BB->rbegin(), rend, LiveOut);
2734 LiveOut.erase(Inst);
2735 Out.insert(LiveOut.begin(), LiveOut.end());
2736}
2737
2738static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData,
2739 const CallSite &CS,
2740 PartiallyConstructedSafepointRecord &Info) {
2741 Instruction *Inst = CS.getInstruction();
2742 StatepointLiveSetTy Updated;
2743 findLiveSetAtInst(Inst, RevisedLivenessData, Updated);
2744
2745#ifndef NDEBUG
2746 DenseSet<Value *> Bases;
2747 for (auto KVPair : Info.PointerToBase) {
2748 Bases.insert(KVPair.second);
2749 }
2750#endif
2751 // We may have base pointers which are now live that weren't before. We need
2752 // to update the PointerToBase structure to reflect this.
2753 for (auto V : Updated)
2754 if (!Info.PointerToBase.count(V)) {
2755 assert(Bases.count(V) && "can't find base for unexpected live value");
2756 Info.PointerToBase[V] = V;
2757 continue;
2758 }
2759
2760#ifndef NDEBUG
2761 for (auto V : Updated) {
2762 assert(Info.PointerToBase.count(V) &&
2763 "must be able to find base for live value");
2764 }
2765#endif
2766
2767 // Remove any stale base mappings - this can happen since our liveness is
2768 // more precise then the one inherent in the base pointer analysis
2769 DenseSet<Value *> ToErase;
2770 for (auto KVPair : Info.PointerToBase)
2771 if (!Updated.count(KVPair.first))
2772 ToErase.insert(KVPair.first);
2773 for (auto V : ToErase)
2774 Info.PointerToBase.erase(V);
2775
2776#ifndef NDEBUG
2777 for (auto KVPair : Info.PointerToBase)
2778 assert(Updated.count(KVPair.first) && "record for non-live value");
2779#endif
2780
2781 Info.liveset = Updated;
2782}