blob: 17d969ed02a4573b65efd6bbdb3d93ed13efaf5b [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 Reames15d55632015-09-09 23:26:08 +000024#include "llvm/ADT/MapVector.h"
Philip Reamesd16a9b12015-02-20 01:06:44 +000025#include "llvm/IR/BasicBlock.h"
26#include "llvm/IR/CallSite.h"
27#include "llvm/IR/Dominators.h"
28#include "llvm/IR/Function.h"
29#include "llvm/IR/IRBuilder.h"
30#include "llvm/IR/InstIterator.h"
31#include "llvm/IR/Instructions.h"
32#include "llvm/IR/Intrinsics.h"
33#include "llvm/IR/IntrinsicInst.h"
34#include "llvm/IR/Module.h"
Sanjoy Das353a19e2015-06-02 22:33:37 +000035#include "llvm/IR/MDBuilder.h"
Philip Reamesd16a9b12015-02-20 01:06:44 +000036#include "llvm/IR/Statepoint.h"
37#include "llvm/IR/Value.h"
38#include "llvm/IR/Verifier.h"
39#include "llvm/Support/Debug.h"
40#include "llvm/Support/CommandLine.h"
41#include "llvm/Transforms/Scalar.h"
42#include "llvm/Transforms/Utils/BasicBlockUtils.h"
43#include "llvm/Transforms/Utils/Cloning.h"
44#include "llvm/Transforms/Utils/Local.h"
45#include "llvm/Transforms/Utils/PromoteMemToReg.h"
46
47#define DEBUG_TYPE "rewrite-statepoints-for-gc"
48
49using namespace llvm;
50
Philip Reamesd16a9b12015-02-20 01:06:44 +000051// Print the liveset found at the insert location
52static cl::opt<bool> PrintLiveSet("spp-print-liveset", cl::Hidden,
53 cl::init(false));
Philip Reames704e78b2015-04-10 22:34:56 +000054static cl::opt<bool> PrintLiveSetSize("spp-print-liveset-size", cl::Hidden,
55 cl::init(false));
Philip Reamesd16a9b12015-02-20 01:06:44 +000056// Print out the base pointers for debugging
Philip Reames704e78b2015-04-10 22:34:56 +000057static cl::opt<bool> PrintBasePointers("spp-print-base-pointers", cl::Hidden,
58 cl::init(false));
Philip Reamesd16a9b12015-02-20 01:06:44 +000059
Igor Laevskye0317182015-05-19 15:59:05 +000060// Cost threshold measuring when it is profitable to rematerialize value instead
61// of relocating it
62static cl::opt<unsigned>
63RematerializationThreshold("spp-rematerialization-threshold", cl::Hidden,
64 cl::init(6));
65
Philip Reamese73300b2015-04-13 16:41:32 +000066#ifdef XDEBUG
67static bool ClobberNonLive = true;
68#else
69static bool ClobberNonLive = false;
70#endif
71static cl::opt<bool, true> ClobberNonLiveOverride("rs4gc-clobber-non-live",
72 cl::location(ClobberNonLive),
73 cl::Hidden);
74
Benjamin Kramer6f665452015-02-20 14:00:58 +000075namespace {
Sanjoy Dasea45f0e2015-06-02 22:33:34 +000076struct RewriteStatepointsForGC : public ModulePass {
Philip Reamesd16a9b12015-02-20 01:06:44 +000077 static char ID; // Pass identification, replacement for typeid
78
Sanjoy Dasea45f0e2015-06-02 22:33:34 +000079 RewriteStatepointsForGC() : ModulePass(ID) {
Philip Reamesd16a9b12015-02-20 01:06:44 +000080 initializeRewriteStatepointsForGCPass(*PassRegistry::getPassRegistry());
81 }
Sanjoy Dasea45f0e2015-06-02 22:33:34 +000082 bool runOnFunction(Function &F);
83 bool runOnModule(Module &M) override {
84 bool Changed = false;
85 for (Function &F : M)
86 Changed |= runOnFunction(F);
Sanjoy Das353a19e2015-06-02 22:33:37 +000087
88 if (Changed) {
89 // stripDereferenceabilityInfo asserts that shouldRewriteStatepointsIn
90 // returns true for at least one function in the module. Since at least
91 // one function changed, we know that the precondition is satisfied.
92 stripDereferenceabilityInfo(M);
93 }
94
Sanjoy Dasea45f0e2015-06-02 22:33:34 +000095 return Changed;
96 }
Philip Reamesd16a9b12015-02-20 01:06:44 +000097
98 void getAnalysisUsage(AnalysisUsage &AU) const override {
99 // We add and rewrite a bunch of instructions, but don't really do much
100 // else. We could in theory preserve a lot more analyses here.
101 AU.addRequired<DominatorTreeWrapperPass>();
Igor Laevskye0317182015-05-19 15:59:05 +0000102 AU.addRequired<TargetTransformInfoWrapperPass>();
Philip Reamesd16a9b12015-02-20 01:06:44 +0000103 }
Sanjoy Das353a19e2015-06-02 22:33:37 +0000104
105 /// The IR fed into RewriteStatepointsForGC may have had attributes implying
106 /// dereferenceability that are no longer valid/correct after
107 /// RewriteStatepointsForGC has run. This is because semantically, after
108 /// RewriteStatepointsForGC runs, all calls to gc.statepoint "free" the entire
109 /// heap. stripDereferenceabilityInfo (conservatively) restores correctness
110 /// by erasing all attributes in the module that externally imply
111 /// dereferenceability.
112 ///
113 void stripDereferenceabilityInfo(Module &M);
114
115 // Helpers for stripDereferenceabilityInfo
116 void stripDereferenceabilityInfoFromBody(Function &F);
117 void stripDereferenceabilityInfoFromPrototype(Function &F);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000118};
Benjamin Kramer6f665452015-02-20 14:00:58 +0000119} // namespace
Philip Reamesd16a9b12015-02-20 01:06:44 +0000120
121char RewriteStatepointsForGC::ID = 0;
122
Sanjoy Dasea45f0e2015-06-02 22:33:34 +0000123ModulePass *llvm::createRewriteStatepointsForGCPass() {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000124 return new RewriteStatepointsForGC();
125}
126
127INITIALIZE_PASS_BEGIN(RewriteStatepointsForGC, "rewrite-statepoints-for-gc",
128 "Make relocations explicit at statepoints", false, false)
129INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
130INITIALIZE_PASS_END(RewriteStatepointsForGC, "rewrite-statepoints-for-gc",
131 "Make relocations explicit at statepoints", false, false)
132
133namespace {
Philip Reamesdf1ef082015-04-10 22:53:14 +0000134struct GCPtrLivenessData {
135 /// Values defined in this block.
136 DenseMap<BasicBlock *, DenseSet<Value *>> KillSet;
137 /// Values used in this block (and thus live); does not included values
138 /// killed within this block.
139 DenseMap<BasicBlock *, DenseSet<Value *>> LiveSet;
140
141 /// Values live into this basic block (i.e. used by any
142 /// instruction in this basic block or ones reachable from here)
143 DenseMap<BasicBlock *, DenseSet<Value *>> LiveIn;
144
145 /// Values live out of this basic block (i.e. live into
146 /// any successor block)
147 DenseMap<BasicBlock *, DenseSet<Value *>> LiveOut;
148};
149
Philip Reamesd16a9b12015-02-20 01:06:44 +0000150// The type of the internal cache used inside the findBasePointers family
151// of functions. From the callers perspective, this is an opaque type and
152// should not be inspected.
153//
154// In the actual implementation this caches two relations:
155// - The base relation itself (i.e. this pointer is based on that one)
156// - The base defining value relation (i.e. before base_phi insertion)
157// Generally, after the execution of a full findBasePointer call, only the
158// base relation will remain. Internally, we add a mixture of the two
159// types, then update all the second type to the first type
Philip Reamese9c3b9b2015-02-20 22:48:20 +0000160typedef DenseMap<Value *, Value *> DefiningValueMapTy;
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +0000161typedef DenseSet<Value *> StatepointLiveSetTy;
Igor Laevskye0317182015-05-19 15:59:05 +0000162typedef DenseMap<Instruction *, Value *> RematerializedValueMapTy;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000163
Philip Reamesd16a9b12015-02-20 01:06:44 +0000164struct PartiallyConstructedSafepointRecord {
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000165 /// The set of values known to be live across this safepoint
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +0000166 StatepointLiveSetTy LiveSet;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000167
168 /// Mapping from live pointers to a base-defining-value
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +0000169 DenseMap<Value *, Value *> PointerToBase;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000170
Philip Reames0a3240f2015-02-20 21:34:11 +0000171 /// The *new* gc.statepoint instruction itself. This produces the token
172 /// that normal path gc.relocates and the gc.result are tied to.
173 Instruction *StatepointToken;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000174
Philip Reamesf2041322015-02-20 19:26:04 +0000175 /// Instruction to which exceptional gc relocates are attached
176 /// Makes it easier to iterate through them during relocationViaAlloca.
177 Instruction *UnwindToken;
Igor Laevskye0317182015-05-19 15:59:05 +0000178
179 /// Record live values we are rematerialized instead of relocating.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +0000180 /// They are not included into 'LiveSet' field.
Igor Laevskye0317182015-05-19 15:59:05 +0000181 /// Maps rematerialized copy to it's original value.
182 RematerializedValueMapTy RematerializedValues;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000183};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000184}
Philip Reamesd16a9b12015-02-20 01:06:44 +0000185
Philip Reamesdf1ef082015-04-10 22:53:14 +0000186/// Compute the live-in set for every basic block in the function
187static void computeLiveInValues(DominatorTree &DT, Function &F,
188 GCPtrLivenessData &Data);
189
190/// Given results from the dataflow liveness computation, find the set of live
191/// Values at a particular instruction.
192static void findLiveSetAtInst(Instruction *inst, GCPtrLivenessData &Data,
193 StatepointLiveSetTy &out);
194
Philip Reamesd16a9b12015-02-20 01:06:44 +0000195// TODO: Once we can get to the GCStrategy, this becomes
196// Optional<bool> isGCManagedPointer(const Value *V) const override {
197
Craig Toppere3dcce92015-08-01 22:20:21 +0000198static bool isGCPointerType(Type *T) {
199 if (auto *PT = dyn_cast<PointerType>(T))
Philip Reamesd16a9b12015-02-20 01:06:44 +0000200 // For the sake of this example GC, we arbitrarily pick addrspace(1) as our
201 // GC managed heap. We know that a pointer into this heap needs to be
202 // updated and that no other pointer does.
203 return (1 == PT->getAddressSpace());
204 return false;
205}
206
Philip Reames8531d8c2015-04-10 21:48:25 +0000207// Return true if this type is one which a) is a gc pointer or contains a GC
208// pointer and b) is of a type this code expects to encounter as a live value.
209// (The insertion code will assert that a type which matches (a) and not (b)
Philip Reames704e78b2015-04-10 22:34:56 +0000210// is not encountered.)
Philip Reames8531d8c2015-04-10 21:48:25 +0000211static bool isHandledGCPointerType(Type *T) {
212 // We fully support gc pointers
213 if (isGCPointerType(T))
214 return true;
215 // We partially support vectors of gc pointers. The code will assert if it
216 // can't handle something.
217 if (auto VT = dyn_cast<VectorType>(T))
218 if (isGCPointerType(VT->getElementType()))
219 return true;
220 return false;
221}
222
223#ifndef NDEBUG
224/// Returns true if this type contains a gc pointer whether we know how to
225/// handle that type or not.
226static bool containsGCPtrType(Type *Ty) {
Philip Reames704e78b2015-04-10 22:34:56 +0000227 if (isGCPointerType(Ty))
Philip Reames8531d8c2015-04-10 21:48:25 +0000228 return true;
229 if (VectorType *VT = dyn_cast<VectorType>(Ty))
230 return isGCPointerType(VT->getScalarType());
231 if (ArrayType *AT = dyn_cast<ArrayType>(Ty))
232 return containsGCPtrType(AT->getElementType());
233 if (StructType *ST = dyn_cast<StructType>(Ty))
Philip Reames704e78b2015-04-10 22:34:56 +0000234 return std::any_of(
235 ST->subtypes().begin(), ST->subtypes().end(),
236 [](Type *SubType) { return containsGCPtrType(SubType); });
Philip Reames8531d8c2015-04-10 21:48:25 +0000237 return false;
238}
239
240// Returns true if this is a type which a) is a gc pointer or contains a GC
241// pointer and b) is of a type which the code doesn't expect (i.e. first class
242// aggregates). Used to trip assertions.
243static bool isUnhandledGCPointerType(Type *Ty) {
244 return containsGCPtrType(Ty) && !isHandledGCPointerType(Ty);
245}
246#endif
247
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +0000248static bool order_by_name(Value *a, Value *b) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000249 if (a->hasName() && b->hasName()) {
250 return -1 == a->getName().compare(b->getName());
251 } else if (a->hasName() && !b->hasName()) {
252 return true;
253 } else if (!a->hasName() && b->hasName()) {
254 return false;
255 } else {
256 // Better than nothing, but not stable
257 return a < b;
258 }
259}
260
Philip Reamesece70b82015-09-09 23:57:18 +0000261// Return the name of the value suffixed with the provided value, or if the
262// value didn't have a name, the default value specified.
263static std::string suffixed_name_or(Value *V, StringRef Suffix,
264 StringRef DefaultName) {
265 return V->hasName() ? (V->getName() + Suffix).str() : DefaultName.str();
266}
267
Philip Reamesdf1ef082015-04-10 22:53:14 +0000268// Conservatively identifies any definitions which might be live at the
269// given instruction. The analysis is performed immediately before the
270// given instruction. Values defined by that instruction are not considered
271// live. Values used by that instruction are considered live.
272static void analyzeParsePointLiveness(
273 DominatorTree &DT, GCPtrLivenessData &OriginalLivenessData,
274 const CallSite &CS, PartiallyConstructedSafepointRecord &result) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000275 Instruction *inst = CS.getInstruction();
276
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +0000277 StatepointLiveSetTy LiveSet;
278 findLiveSetAtInst(inst, OriginalLivenessData, LiveSet);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000279
280 if (PrintLiveSet) {
281 // Note: This output is used by several of the test cases
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000282 // The order of elements in a set is not stable, put them in a vec and sort
Philip Reamesd16a9b12015-02-20 01:06:44 +0000283 // by name
Philip Reamesdab35f32015-09-02 21:11:44 +0000284 SmallVector<Value *, 64> Temp;
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +0000285 Temp.insert(Temp.end(), LiveSet.begin(), LiveSet.end());
Philip Reamesdab35f32015-09-02 21:11:44 +0000286 std::sort(Temp.begin(), Temp.end(), order_by_name);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000287 errs() << "Live Variables:\n";
Philip Reamesdab35f32015-09-02 21:11:44 +0000288 for (Value *V : Temp)
289 dbgs() << " " << V->getName() << " " << *V << "\n";
Philip Reamesd16a9b12015-02-20 01:06:44 +0000290 }
291 if (PrintLiveSetSize) {
292 errs() << "Safepoint For: " << CS.getCalledValue()->getName() << "\n";
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +0000293 errs() << "Number live values: " << LiveSet.size() << "\n";
Philip Reamesd16a9b12015-02-20 01:06:44 +0000294 }
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +0000295 result.LiveSet = LiveSet;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000296}
297
Philip Reamesf5b8e472015-09-03 21:34:30 +0000298static bool isKnownBaseResult(Value *V);
299namespace {
300/// A single base defining value - An immediate base defining value for an
301/// instruction 'Def' is an input to 'Def' whose base is also a base of 'Def'.
302/// For instructions which have multiple pointer [vector] inputs or that
303/// transition between vector and scalar types, there is no immediate base
304/// defining value. The 'base defining value' for 'Def' is the transitive
305/// closure of this relation stopping at the first instruction which has no
306/// immediate base defining value. The b.d.v. might itself be a base pointer,
307/// but it can also be an arbitrary derived pointer.
308struct BaseDefiningValueResult {
309 /// Contains the value which is the base defining value.
310 Value * const BDV;
311 /// True if the base defining value is also known to be an actual base
312 /// pointer.
313 const bool IsKnownBase;
314 BaseDefiningValueResult(Value *BDV, bool IsKnownBase)
315 : BDV(BDV), IsKnownBase(IsKnownBase) {
316#ifndef NDEBUG
317 // Check consistency between new and old means of checking whether a BDV is
318 // a base.
319 bool MustBeBase = isKnownBaseResult(BDV);
320 assert(!MustBeBase || MustBeBase == IsKnownBase);
321#endif
322 }
323};
324}
325
326static BaseDefiningValueResult findBaseDefiningValue(Value *I);
Philip Reames311f7102015-05-12 22:19:52 +0000327
Philip Reames8fe7f132015-06-26 22:47:37 +0000328/// Return a base defining value for the 'Index' element of the given vector
329/// instruction 'I'. If Index is null, returns a BDV for the entire vector
330/// 'I'. As an optimization, this method will try to determine when the
331/// element is known to already be a base pointer. If this can be established,
332/// the second value in the returned pair will be true. Note that either a
333/// vector or a pointer typed value can be returned. For the former, the
334/// vector returned is a BDV (and possibly a base) of the entire vector 'I'.
335/// If the later, the return pointer is a BDV (or possibly a base) for the
336/// particular element in 'I'.
Philip Reamesf5b8e472015-09-03 21:34:30 +0000337static BaseDefiningValueResult
Philip Reames66287132015-09-09 23:40:12 +0000338findBaseDefiningValueOfVector(Value *I) {
Philip Reames8531d8c2015-04-10 21:48:25 +0000339 assert(I->getType()->isVectorTy() &&
340 cast<VectorType>(I->getType())->getElementType()->isPointerTy() &&
341 "Illegal to ask for the base pointer of a non-pointer type");
342
343 // Each case parallels findBaseDefiningValue below, see that code for
344 // detailed motivation.
345
346 if (isa<Argument>(I))
347 // An incoming argument to the function is a base pointer
Philip Reamesf5b8e472015-09-03 21:34:30 +0000348 return BaseDefiningValueResult(I, true);
Philip Reames8531d8c2015-04-10 21:48:25 +0000349
350 // We shouldn't see the address of a global as a vector value?
351 assert(!isa<GlobalVariable>(I) &&
352 "unexpected global variable found in base of vector");
353
354 // inlining could possibly introduce phi node that contains
355 // undef if callee has multiple returns
356 if (isa<UndefValue>(I))
357 // utterly meaningless, but useful for dealing with partially optimized
358 // code.
Philip Reamesf5b8e472015-09-03 21:34:30 +0000359 return BaseDefiningValueResult(I, true);
Philip Reames8531d8c2015-04-10 21:48:25 +0000360
361 // Due to inheritance, this must be _after_ the global variable and undef
362 // checks
363 if (Constant *Con = dyn_cast<Constant>(I)) {
364 assert(!isa<GlobalVariable>(I) && !isa<UndefValue>(I) &&
365 "order of checks wrong!");
366 assert(Con->isNullValue() && "null is the only case which makes sense");
Philip Reamesf5b8e472015-09-03 21:34:30 +0000367 return BaseDefiningValueResult(Con, true);
Philip Reames8531d8c2015-04-10 21:48:25 +0000368 }
Philip Reames8fe7f132015-06-26 22:47:37 +0000369
Philip Reames8531d8c2015-04-10 21:48:25 +0000370 if (isa<LoadInst>(I))
Philip Reamesf5b8e472015-09-03 21:34:30 +0000371 return BaseDefiningValueResult(I, true);
Philip Reamesf5b8e472015-09-03 21:34:30 +0000372
Philip Reames66287132015-09-09 23:40:12 +0000373 if (isa<InsertElementInst>(I))
Philip Reames8fe7f132015-06-26 22:47:37 +0000374 // We don't know whether this vector contains entirely base pointers or
375 // not. To be conservatively correct, we treat it as a BDV and will
376 // duplicate code as needed to construct a parallel vector of bases.
Philip Reames66287132015-09-09 23:40:12 +0000377 return BaseDefiningValueResult(I, false);
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +0000378
Philip Reames8fe7f132015-06-26 22:47:37 +0000379 if (isa<ShuffleVectorInst>(I))
380 // We don't know whether this vector contains entirely base pointers or
381 // not. To be conservatively correct, we treat it as a BDV and will
382 // duplicate code as needed to construct a parallel vector of bases.
383 // TODO: There a number of local optimizations which could be applied here
384 // for particular sufflevector patterns.
Philip Reamesf5b8e472015-09-03 21:34:30 +0000385 return BaseDefiningValueResult(I, false);
Philip Reames8fe7f132015-06-26 22:47:37 +0000386
387 // A PHI or Select is a base defining value. The outer findBasePointer
388 // algorithm is responsible for constructing a base value for this BDV.
389 assert((isa<SelectInst>(I) || isa<PHINode>(I)) &&
390 "unknown vector instruction - no base found for vector element");
Philip Reamesf5b8e472015-09-03 21:34:30 +0000391 return BaseDefiningValueResult(I, false);
Philip Reames8531d8c2015-04-10 21:48:25 +0000392}
393
Philip Reamesd16a9b12015-02-20 01:06:44 +0000394/// Helper function for findBasePointer - Will return a value which either a)
Philip Reames9ac4e382015-08-12 21:00:20 +0000395/// defines the base pointer for the input, b) blocks the simple search
396/// (i.e. a PHI or Select of two derived pointers), or c) involves a change
397/// from pointer to vector type or back.
Philip Reamesf5b8e472015-09-03 21:34:30 +0000398static BaseDefiningValueResult findBaseDefiningValue(Value *I) {
Philip Reames8fe7f132015-06-26 22:47:37 +0000399 if (I->getType()->isVectorTy())
Philip Reamesf5b8e472015-09-03 21:34:30 +0000400 return findBaseDefiningValueOfVector(I);
Philip Reames8fe7f132015-06-26 22:47:37 +0000401
Philip Reamesd16a9b12015-02-20 01:06:44 +0000402 assert(I->getType()->isPointerTy() &&
403 "Illegal to ask for the base pointer of a non-pointer type");
404
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000405 if (isa<Argument>(I))
Philip Reamesd16a9b12015-02-20 01:06:44 +0000406 // An incoming argument to the function is a base pointer
407 // We should have never reached here if this argument isn't an gc value
Philip Reamesf5b8e472015-09-03 21:34:30 +0000408 return BaseDefiningValueResult(I, true);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000409
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000410 if (isa<GlobalVariable>(I))
Philip Reamesd16a9b12015-02-20 01:06:44 +0000411 // base case
Philip Reamesf5b8e472015-09-03 21:34:30 +0000412 return BaseDefiningValueResult(I, true);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000413
414 // inlining could possibly introduce phi node that contains
415 // undef if callee has multiple returns
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000416 if (isa<UndefValue>(I))
417 // utterly meaningless, but useful for dealing with
418 // partially optimized code.
Philip Reamesf5b8e472015-09-03 21:34:30 +0000419 return BaseDefiningValueResult(I, true);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000420
421 // Due to inheritance, this must be _after_ the global variable and undef
422 // checks
Philip Reames3ea15892015-09-03 21:57:40 +0000423 if (isa<Constant>(I)) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000424 assert(!isa<GlobalVariable>(I) && !isa<UndefValue>(I) &&
425 "order of checks wrong!");
426 // Note: Finding a constant base for something marked for relocation
427 // doesn't really make sense. The most likely case is either a) some
428 // screwed up the address space usage or b) your validating against
429 // compiled C++ code w/o the proper separation. The only real exception
430 // is a null pointer. You could have generic code written to index of
431 // off a potentially null value and have proven it null. We also use
432 // null pointers in dead paths of relocation phis (which we might later
433 // want to find a base pointer for).
Philip Reames3ea15892015-09-03 21:57:40 +0000434 assert(isa<ConstantPointerNull>(I) &&
Philip Reames24c6cd52015-03-27 05:47:00 +0000435 "null is the only case which makes sense");
Philip Reamesf5b8e472015-09-03 21:34:30 +0000436 return BaseDefiningValueResult(I, true);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000437 }
438
439 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000440 Value *Def = CI->stripPointerCasts();
David Blaikie82ad7872015-02-20 23:44:24 +0000441 // If we find a cast instruction here, it means we've found a cast which is
442 // not simply a pointer cast (i.e. an inttoptr). We don't know how to
443 // handle int->ptr conversion.
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000444 assert(!isa<CastInst>(Def) && "shouldn't find another cast here");
445 return findBaseDefiningValue(Def);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000446 }
447
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000448 if (isa<LoadInst>(I))
Philip Reamesf5b8e472015-09-03 21:34:30 +0000449 // The value loaded is an gc base itself
450 return BaseDefiningValueResult(I, true);
451
Philip Reamesd16a9b12015-02-20 01:06:44 +0000452
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000453 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I))
454 // The base of this GEP is the base
455 return findBaseDefiningValue(GEP->getPointerOperand());
Philip Reamesd16a9b12015-02-20 01:06:44 +0000456
457 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
458 switch (II->getIntrinsicID()) {
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000459 case Intrinsic::experimental_gc_result_ptr:
Philip Reamesd16a9b12015-02-20 01:06:44 +0000460 default:
461 // fall through to general call handling
462 break;
463 case Intrinsic::experimental_gc_statepoint:
464 case Intrinsic::experimental_gc_result_float:
465 case Intrinsic::experimental_gc_result_int:
466 llvm_unreachable("these don't produce pointers");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000467 case Intrinsic::experimental_gc_relocate: {
468 // Rerunning safepoint insertion after safepoints are already
469 // inserted is not supported. It could probably be made to work,
470 // but why are you doing this? There's no good reason.
471 llvm_unreachable("repeat safepoint insertion is not supported");
472 }
473 case Intrinsic::gcroot:
474 // Currently, this mechanism hasn't been extended to work with gcroot.
475 // There's no reason it couldn't be, but I haven't thought about the
476 // implications much.
477 llvm_unreachable(
478 "interaction with the gcroot mechanism is not supported");
479 }
480 }
481 // We assume that functions in the source language only return base
482 // pointers. This should probably be generalized via attributes to support
483 // both source language and internal functions.
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000484 if (isa<CallInst>(I) || isa<InvokeInst>(I))
Philip Reamesf5b8e472015-09-03 21:34:30 +0000485 return BaseDefiningValueResult(I, true);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000486
487 // I have absolutely no idea how to implement this part yet. It's not
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000488 // necessarily hard, I just haven't really looked at it yet.
Philip Reamesd16a9b12015-02-20 01:06:44 +0000489 assert(!isa<LandingPadInst>(I) && "Landing Pad is unimplemented");
490
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000491 if (isa<AtomicCmpXchgInst>(I))
Philip Reamesd16a9b12015-02-20 01:06:44 +0000492 // A CAS is effectively a atomic store and load combined under a
493 // predicate. From the perspective of base pointers, we just treat it
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000494 // like a load.
Philip Reamesf5b8e472015-09-03 21:34:30 +0000495 return BaseDefiningValueResult(I, true);
Philip Reames704e78b2015-04-10 22:34:56 +0000496
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000497 assert(!isa<AtomicRMWInst>(I) && "Xchg handled above, all others are "
Philip Reames704e78b2015-04-10 22:34:56 +0000498 "binary ops which don't apply to pointers");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000499
500 // The aggregate ops. Aggregates can either be in the heap or on the
501 // stack, but in either case, this is simply a field load. As a result,
502 // this is a defining definition of the base just like a load is.
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000503 if (isa<ExtractValueInst>(I))
Philip Reamesf5b8e472015-09-03 21:34:30 +0000504 return BaseDefiningValueResult(I, true);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000505
506 // We should never see an insert vector since that would require we be
507 // tracing back a struct value not a pointer value.
508 assert(!isa<InsertValueInst>(I) &&
509 "Base pointer for a struct is meaningless");
510
Philip Reames9ac4e382015-08-12 21:00:20 +0000511 // An extractelement produces a base result exactly when it's input does.
512 // We may need to insert a parallel instruction to extract the appropriate
513 // element out of the base vector corresponding to the input. Given this,
514 // it's analogous to the phi and select case even though it's not a merge.
Philip Reames66287132015-09-09 23:40:12 +0000515 if (isa<ExtractElementInst>(I))
516 // Note: There a lot of obvious peephole cases here. This are deliberately
517 // handled after the main base pointer inference algorithm to make writing
518 // test cases to exercise that code easier.
519 return BaseDefiningValueResult(I, false);
Philip Reames9ac4e382015-08-12 21:00:20 +0000520
Philip Reamesd16a9b12015-02-20 01:06:44 +0000521 // The last two cases here don't return a base pointer. Instead, they
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000522 // return a value which dynamically selects from among several base
Philip Reamesd16a9b12015-02-20 01:06:44 +0000523 // derived pointers (each with it's own base potentially). It's the job of
524 // the caller to resolve these.
Philip Reames704e78b2015-04-10 22:34:56 +0000525 assert((isa<SelectInst>(I) || isa<PHINode>(I)) &&
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000526 "missing instruction case in findBaseDefiningValing");
Philip Reamesf5b8e472015-09-03 21:34:30 +0000527 return BaseDefiningValueResult(I, false);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000528}
529
530/// Returns the base defining value for this value.
Philip Reames18d0feb2015-03-27 05:39:32 +0000531static Value *findBaseDefiningValueCached(Value *I, DefiningValueMapTy &Cache) {
532 Value *&Cached = Cache[I];
Benjamin Kramer6f665452015-02-20 14:00:58 +0000533 if (!Cached) {
Philip Reamesf5b8e472015-09-03 21:34:30 +0000534 Cached = findBaseDefiningValue(I).BDV;
Philip Reames2a892a62015-07-23 22:25:26 +0000535 DEBUG(dbgs() << "fBDV-cached: " << I->getName() << " -> "
536 << Cached->getName() << "\n");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000537 }
Philip Reames18d0feb2015-03-27 05:39:32 +0000538 assert(Cache[I] != nullptr);
Benjamin Kramer6f665452015-02-20 14:00:58 +0000539 return Cached;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000540}
541
542/// Return a base pointer for this value if known. Otherwise, return it's
543/// base defining value.
Philip Reames18d0feb2015-03-27 05:39:32 +0000544static Value *findBaseOrBDV(Value *I, DefiningValueMapTy &Cache) {
545 Value *Def = findBaseDefiningValueCached(I, Cache);
546 auto Found = Cache.find(Def);
547 if (Found != Cache.end()) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000548 // Either a base-of relation, or a self reference. Caller must check.
Benjamin Kramer6f665452015-02-20 14:00:58 +0000549 return Found->second;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000550 }
551 // Only a BDV available
Philip Reames18d0feb2015-03-27 05:39:32 +0000552 return Def;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000553}
554
555/// Given the result of a call to findBaseDefiningValue, or findBaseOrBDV,
556/// is it known to be a base pointer? Or do we need to continue searching.
Philip Reames18d0feb2015-03-27 05:39:32 +0000557static bool isKnownBaseResult(Value *V) {
Philip Reames66287132015-09-09 23:40:12 +0000558 if (!isa<PHINode>(V) && !isa<SelectInst>(V) &&
559 !isa<ExtractElementInst>(V) && !isa<InsertElementInst>(V) &&
560 !isa<ShuffleVectorInst>(V)) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000561 // no recursion possible
562 return true;
563 }
Philip Reames18d0feb2015-03-27 05:39:32 +0000564 if (isa<Instruction>(V) &&
565 cast<Instruction>(V)->getMetadata("is_base_value")) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000566 // This is a previously inserted base phi or select. We know
567 // that this is a base value.
568 return true;
569 }
570
571 // We need to keep searching
572 return false;
573}
574
Philip Reamesd16a9b12015-02-20 01:06:44 +0000575namespace {
Philip Reames9b141ed2015-07-23 22:49:14 +0000576/// Models the state of a single base defining value in the findBasePointer
577/// algorithm for determining where a new instruction is needed to propagate
578/// the base of this BDV.
579class BDVState {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000580public:
581 enum Status { Unknown, Base, Conflict };
582
Philip Reames9b141ed2015-07-23 22:49:14 +0000583 BDVState(Status s, Value *b = nullptr) : status(s), base(b) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000584 assert(status != Base || b);
585 }
Philip Reames9b141ed2015-07-23 22:49:14 +0000586 explicit BDVState(Value *b) : status(Base), base(b) {}
587 BDVState() : status(Unknown), base(nullptr) {}
Philip Reamesd16a9b12015-02-20 01:06:44 +0000588
589 Status getStatus() const { return status; }
590 Value *getBase() const { return base; }
591
592 bool isBase() const { return getStatus() == Base; }
593 bool isUnknown() const { return getStatus() == Unknown; }
594 bool isConflict() const { return getStatus() == Conflict; }
595
Philip Reames9b141ed2015-07-23 22:49:14 +0000596 bool operator==(const BDVState &other) const {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000597 return base == other.base && status == other.status;
598 }
599
Philip Reames9b141ed2015-07-23 22:49:14 +0000600 bool operator!=(const BDVState &other) const { return !(*this == other); }
Philip Reamesd16a9b12015-02-20 01:06:44 +0000601
Philip Reames2a892a62015-07-23 22:25:26 +0000602 LLVM_DUMP_METHOD
603 void dump() const { print(dbgs()); dbgs() << '\n'; }
604
605 void print(raw_ostream &OS) const {
Philip Reamesdab35f32015-09-02 21:11:44 +0000606 switch (status) {
607 case Unknown:
608 OS << "U";
609 break;
610 case Base:
611 OS << "B";
612 break;
613 case Conflict:
614 OS << "C";
615 break;
616 };
617 OS << " (" << base << " - "
Philip Reames2a892a62015-07-23 22:25:26 +0000618 << (base ? base->getName() : "nullptr") << "): ";
Philip Reamesd16a9b12015-02-20 01:06:44 +0000619 }
620
621private:
622 Status status;
623 Value *base; // non null only if status == base
624};
Philip Reamesb3967cd2015-09-02 22:30:53 +0000625}
Philip Reamesd16a9b12015-02-20 01:06:44 +0000626
Philip Reames6906e922015-09-02 21:57:17 +0000627#ifndef NDEBUG
Philip Reamesb3967cd2015-09-02 22:30:53 +0000628static raw_ostream &operator<<(raw_ostream &OS, const BDVState &State) {
Philip Reames2a892a62015-07-23 22:25:26 +0000629 State.print(OS);
630 return OS;
631}
Philip Reames6906e922015-09-02 21:57:17 +0000632#endif
Philip Reames2a892a62015-07-23 22:25:26 +0000633
Philip Reamesb3967cd2015-09-02 22:30:53 +0000634namespace {
Philip Reames9b141ed2015-07-23 22:49:14 +0000635// Values of type BDVState form a lattice, and this is a helper
Philip Reamesd16a9b12015-02-20 01:06:44 +0000636// class that implementes the meet operation. The meat of the meet
Philip Reames9b141ed2015-07-23 22:49:14 +0000637// operation is implemented in MeetBDVStates::pureMeet
638class MeetBDVStates {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000639public:
Philip Reames273e6bb2015-07-23 21:41:27 +0000640 /// Initializes the currentResult to the TOP state so that if can be met with
641 /// any other state to produce that state.
Philip Reames9b141ed2015-07-23 22:49:14 +0000642 MeetBDVStates() {}
Philip Reamesd16a9b12015-02-20 01:06:44 +0000643
Philip Reames9b141ed2015-07-23 22:49:14 +0000644 // Destructively meet the current result with the given BDVState
645 void meetWith(BDVState otherState) {
Philip Reames273e6bb2015-07-23 21:41:27 +0000646 currentResult = meet(otherState, currentResult);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000647 }
648
Philip Reames9b141ed2015-07-23 22:49:14 +0000649 BDVState getResult() const { return currentResult; }
Philip Reamesd16a9b12015-02-20 01:06:44 +0000650
651private:
Philip Reames9b141ed2015-07-23 22:49:14 +0000652 BDVState currentResult;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000653
Philip Reames9b141ed2015-07-23 22:49:14 +0000654 /// Perform a meet operation on two elements of the BDVState lattice.
655 static BDVState meet(BDVState LHS, BDVState RHS) {
Philip Reames273e6bb2015-07-23 21:41:27 +0000656 assert((pureMeet(LHS, RHS) == pureMeet(RHS, LHS)) &&
657 "math is wrong: meet does not commute!");
Philip Reames9b141ed2015-07-23 22:49:14 +0000658 BDVState Result = pureMeet(LHS, RHS);
Philip Reames2a892a62015-07-23 22:25:26 +0000659 DEBUG(dbgs() << "meet of " << LHS << " with " << RHS
660 << " produced " << Result << "\n");
661 return Result;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000662 }
663
Philip Reames9b141ed2015-07-23 22:49:14 +0000664 static BDVState pureMeet(const BDVState &stateA, const BDVState &stateB) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000665 switch (stateA.getStatus()) {
Philip Reames9b141ed2015-07-23 22:49:14 +0000666 case BDVState::Unknown:
Philip Reamesd16a9b12015-02-20 01:06:44 +0000667 return stateB;
668
Philip Reames9b141ed2015-07-23 22:49:14 +0000669 case BDVState::Base:
Philip Reamesd16a9b12015-02-20 01:06:44 +0000670 assert(stateA.getBase() && "can't be null");
David Blaikie82ad7872015-02-20 23:44:24 +0000671 if (stateB.isUnknown())
Philip Reamesd16a9b12015-02-20 01:06:44 +0000672 return stateA;
David Blaikie82ad7872015-02-20 23:44:24 +0000673
674 if (stateB.isBase()) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000675 if (stateA.getBase() == stateB.getBase()) {
676 assert(stateA == stateB && "equality broken!");
677 return stateA;
678 }
Philip Reames9b141ed2015-07-23 22:49:14 +0000679 return BDVState(BDVState::Conflict);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000680 }
David Blaikie82ad7872015-02-20 23:44:24 +0000681 assert(stateB.isConflict() && "only three states!");
Philip Reames9b141ed2015-07-23 22:49:14 +0000682 return BDVState(BDVState::Conflict);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000683
Philip Reames9b141ed2015-07-23 22:49:14 +0000684 case BDVState::Conflict:
Philip Reamesd16a9b12015-02-20 01:06:44 +0000685 return stateA;
686 }
Reid Klecknera070ee52015-02-20 19:46:02 +0000687 llvm_unreachable("only three states!");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000688 }
689};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000690}
Philip Reamesb3967cd2015-09-02 22:30:53 +0000691
692
Philip Reamesd16a9b12015-02-20 01:06:44 +0000693/// For a given value or instruction, figure out what base ptr it's derived
694/// from. For gc objects, this is simply itself. On success, returns a value
695/// which is the base pointer. (This is reliable and can be used for
696/// relocation.) On failure, returns nullptr.
Philip Reamesba198492015-04-14 00:41:34 +0000697static Value *findBasePointer(Value *I, DefiningValueMapTy &cache) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000698 Value *def = findBaseOrBDV(I, cache);
699
700 if (isKnownBaseResult(def)) {
701 return def;
702 }
703
704 // Here's the rough algorithm:
705 // - For every SSA value, construct a mapping to either an actual base
706 // pointer or a PHI which obscures the base pointer.
707 // - Construct a mapping from PHI to unknown TOP state. Use an
708 // optimistic algorithm to propagate base pointer information. Lattice
709 // looks like:
710 // UNKNOWN
711 // b1 b2 b3 b4
712 // CONFLICT
713 // When algorithm terminates, all PHIs will either have a single concrete
714 // base or be in a conflict state.
715 // - For every conflict, insert a dummy PHI node without arguments. Add
716 // these to the base[Instruction] = BasePtr mapping. For every
717 // non-conflict, add the actual base.
718 // - For every conflict, add arguments for the base[a] of each input
719 // arguments.
720 //
721 // Note: A simpler form of this would be to add the conflict form of all
722 // PHIs without running the optimistic algorithm. This would be
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000723 // analogous to pessimistic data flow and would likely lead to an
Philip Reamesd16a9b12015-02-20 01:06:44 +0000724 // overall worse solution.
725
Philip Reames29e9ae72015-07-24 00:42:55 +0000726#ifndef NDEBUG
Philip Reames88958b22015-07-24 00:02:11 +0000727 auto isExpectedBDVType = [](Value *BDV) {
Philip Reames66287132015-09-09 23:40:12 +0000728 return isa<PHINode>(BDV) || isa<SelectInst>(BDV) ||
729 isa<ExtractElementInst>(BDV) || isa<InsertElementInst>(BDV);
Philip Reames88958b22015-07-24 00:02:11 +0000730 };
Philip Reames29e9ae72015-07-24 00:42:55 +0000731#endif
Philip Reames88958b22015-07-24 00:02:11 +0000732
733 // Once populated, will contain a mapping from each potentially non-base BDV
734 // to a lattice value (described above) which corresponds to that BDV.
Philip Reames15d55632015-09-09 23:26:08 +0000735 // We use the order of insertion (DFS over the def/use graph) to provide a
736 // stable deterministic ordering for visiting DenseMaps (which are unordered)
737 // below. This is important for deterministic compilation.
Philip Reames34d7a742015-09-10 00:22:49 +0000738 MapVector<Value *, BDVState> States;
Philip Reames15d55632015-09-09 23:26:08 +0000739
740 // Recursively fill in all base defining values reachable from the initial
741 // one for which we don't already know a definite base value for
Philip Reames88958b22015-07-24 00:02:11 +0000742 /* scope */ {
Philip Reames88958b22015-07-24 00:02:11 +0000743 SmallVector<Value*, 16> Worklist;
744 Worklist.push_back(def);
Philip Reames34d7a742015-09-10 00:22:49 +0000745 States.insert(std::make_pair(def, BDVState()));
Philip Reames88958b22015-07-24 00:02:11 +0000746 while (!Worklist.empty()) {
747 Value *Current = Worklist.pop_back_val();
748 assert(!isKnownBaseResult(Current) && "why did it get added?");
749
750 auto visitIncomingValue = [&](Value *InVal) {
751 Value *Base = findBaseOrBDV(InVal, cache);
752 if (isKnownBaseResult(Base))
753 // Known bases won't need new instructions introduced and can be
754 // ignored safely
755 return;
756 assert(isExpectedBDVType(Base) && "the only non-base values "
757 "we see should be base defining values");
Philip Reames34d7a742015-09-10 00:22:49 +0000758 if (States.insert(std::make_pair(Base, BDVState())).second)
Philip Reames88958b22015-07-24 00:02:11 +0000759 Worklist.push_back(Base);
760 };
761 if (PHINode *Phi = dyn_cast<PHINode>(Current)) {
762 for (Value *InVal : Phi->incoming_values())
763 visitIncomingValue(InVal);
Philip Reames9ac4e382015-08-12 21:00:20 +0000764 } else if (SelectInst *Sel = dyn_cast<SelectInst>(Current)) {
Philip Reames88958b22015-07-24 00:02:11 +0000765 visitIncomingValue(Sel->getTrueValue());
766 visitIncomingValue(Sel->getFalseValue());
Philip Reames9ac4e382015-08-12 21:00:20 +0000767 } else if (auto *EE = dyn_cast<ExtractElementInst>(Current)) {
768 visitIncomingValue(EE->getVectorOperand());
Philip Reames66287132015-09-09 23:40:12 +0000769 } else if (auto *IE = dyn_cast<InsertElementInst>(Current)) {
770 visitIncomingValue(IE->getOperand(0)); // vector operand
771 visitIncomingValue(IE->getOperand(1)); // scalar operand
Philip Reames9ac4e382015-08-12 21:00:20 +0000772 } else {
Philip Reames66287132015-09-09 23:40:12 +0000773 // There is one known class of instructions we know we don't handle.
774 assert(isa<ShuffleVectorInst>(Current));
Philip Reames9ac4e382015-08-12 21:00:20 +0000775 llvm_unreachable("unimplemented instruction case");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000776 }
777 }
778 }
779
Philip Reamesdab35f32015-09-02 21:11:44 +0000780#ifndef NDEBUG
781 DEBUG(dbgs() << "States after initialization:\n");
Philip Reames34d7a742015-09-10 00:22:49 +0000782 for (auto Pair : States) {
Philip Reamesdab35f32015-09-02 21:11:44 +0000783 DEBUG(dbgs() << " " << Pair.second << " for " << *Pair.first << "\n");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000784 }
Philip Reamesdab35f32015-09-02 21:11:44 +0000785#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +0000786
Philip Reames273e6bb2015-07-23 21:41:27 +0000787 // Return a phi state for a base defining value. We'll generate a new
788 // base state for known bases and expect to find a cached state otherwise.
789 auto getStateForBDV = [&](Value *baseValue) {
790 if (isKnownBaseResult(baseValue))
Philip Reames9b141ed2015-07-23 22:49:14 +0000791 return BDVState(baseValue);
Philip Reames34d7a742015-09-10 00:22:49 +0000792 auto I = States.find(baseValue);
793 assert(I != States.end() && "lookup failed!");
Philip Reames273e6bb2015-07-23 21:41:27 +0000794 return I->second;
795 };
796
Philip Reamesd16a9b12015-02-20 01:06:44 +0000797 bool progress = true;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000798 while (progress) {
Yaron Keren42a7adf2015-02-28 13:11:24 +0000799#ifndef NDEBUG
Philip Reamesb4e55f32015-09-10 00:32:56 +0000800 const size_t oldSize = States.size();
Yaron Keren42a7adf2015-02-28 13:11:24 +0000801#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +0000802 progress = false;
Philip Reames15d55632015-09-09 23:26:08 +0000803 // We're only changing values in this loop, thus safe to keep iterators.
804 // Since this is computing a fixed point, the order of visit does not
805 // effect the result. TODO: We could use a worklist here and make this run
806 // much faster.
Philip Reames34d7a742015-09-10 00:22:49 +0000807 for (auto Pair : States) {
Philip Reamesece70b82015-09-09 23:57:18 +0000808 Value *BDV = Pair.first;
809 assert(!isKnownBaseResult(BDV) && "why did it get added?");
Philip Reames273e6bb2015-07-23 21:41:27 +0000810
Philip Reames9b141ed2015-07-23 22:49:14 +0000811 // Given an input value for the current instruction, return a BDVState
Philip Reames273e6bb2015-07-23 21:41:27 +0000812 // instance which represents the BDV of that value.
813 auto getStateForInput = [&](Value *V) mutable {
814 Value *BDV = findBaseOrBDV(V, cache);
815 return getStateForBDV(BDV);
816 };
817
Philip Reames9b141ed2015-07-23 22:49:14 +0000818 MeetBDVStates calculateMeet;
Philip Reamesece70b82015-09-09 23:57:18 +0000819 if (SelectInst *select = dyn_cast<SelectInst>(BDV)) {
Philip Reames273e6bb2015-07-23 21:41:27 +0000820 calculateMeet.meetWith(getStateForInput(select->getTrueValue()));
821 calculateMeet.meetWith(getStateForInput(select->getFalseValue()));
Philip Reamesece70b82015-09-09 23:57:18 +0000822 } else if (PHINode *Phi = dyn_cast<PHINode>(BDV)) {
Philip Reames9ac4e382015-08-12 21:00:20 +0000823 for (Value *Val : Phi->incoming_values())
Philip Reames273e6bb2015-07-23 21:41:27 +0000824 calculateMeet.meetWith(getStateForInput(Val));
Philip Reamesece70b82015-09-09 23:57:18 +0000825 } else if (auto *EE = dyn_cast<ExtractElementInst>(BDV)) {
Philip Reames9ac4e382015-08-12 21:00:20 +0000826 // The 'meet' for an extractelement is slightly trivial, but it's still
827 // useful in that it drives us to conflict if our input is.
Philip Reames9ac4e382015-08-12 21:00:20 +0000828 calculateMeet.meetWith(getStateForInput(EE->getVectorOperand()));
Philip Reames66287132015-09-09 23:40:12 +0000829 } else {
830 // Given there's a inherent type mismatch between the operands, will
831 // *always* produce Conflict.
Philip Reamesece70b82015-09-09 23:57:18 +0000832 auto *IE = cast<InsertElementInst>(BDV);
Philip Reames66287132015-09-09 23:40:12 +0000833 calculateMeet.meetWith(getStateForInput(IE->getOperand(0)));
834 calculateMeet.meetWith(getStateForInput(IE->getOperand(1)));
Philip Reames9ac4e382015-08-12 21:00:20 +0000835 }
836
Philip Reames34d7a742015-09-10 00:22:49 +0000837 BDVState oldState = States[BDV];
Philip Reames9b141ed2015-07-23 22:49:14 +0000838 BDVState newState = calculateMeet.getResult();
Philip Reamesd16a9b12015-02-20 01:06:44 +0000839 if (oldState != newState) {
840 progress = true;
Philip Reames34d7a742015-09-10 00:22:49 +0000841 States[BDV] = newState;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000842 }
843 }
844
Philip Reamesb4e55f32015-09-10 00:32:56 +0000845 assert(oldSize == States.size() &&
846 "fixed point shouldn't be adding any new nodes to state");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000847 }
848
Philip Reamesdab35f32015-09-02 21:11:44 +0000849#ifndef NDEBUG
850 DEBUG(dbgs() << "States after meet iteration:\n");
Philip Reames34d7a742015-09-10 00:22:49 +0000851 for (auto Pair : States) {
Philip Reamesdab35f32015-09-02 21:11:44 +0000852 DEBUG(dbgs() << " " << Pair.second << " for " << *Pair.first << "\n");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000853 }
Philip Reamesdab35f32015-09-02 21:11:44 +0000854#endif
855
Philip Reamesd16a9b12015-02-20 01:06:44 +0000856 // Insert Phis for all conflicts
Philip Reames2e5bcbe2015-02-28 01:52:09 +0000857 // TODO: adjust naming patterns to avoid this order of iteration dependency
Philip Reames34d7a742015-09-10 00:22:49 +0000858 for (auto Pair : States) {
Philip Reames15d55632015-09-09 23:26:08 +0000859 Instruction *I = cast<Instruction>(Pair.first);
860 BDVState State = Pair.second;
Philip Reames6ff1a1e32015-07-21 19:04:38 +0000861 assert(!isKnownBaseResult(I) && "why did it get added?");
862 assert(!State.isUnknown() && "Optimistic algorithm didn't complete!");
Philip Reames9ac4e382015-08-12 21:00:20 +0000863
864 // extractelement instructions are a bit special in that we may need to
865 // insert an extract even when we know an exact base for the instruction.
866 // The problem is that we need to convert from a vector base to a scalar
867 // base for the particular indice we're interested in.
868 if (State.isBase() && isa<ExtractElementInst>(I) &&
869 isa<VectorType>(State.getBase()->getType())) {
870 auto *EE = cast<ExtractElementInst>(I);
871 // TODO: In many cases, the new instruction is just EE itself. We should
872 // exploit this, but can't do it here since it would break the invariant
873 // about the BDV not being known to be a base.
874 auto *BaseInst = ExtractElementInst::Create(State.getBase(),
875 EE->getIndexOperand(),
876 "base_ee", EE);
877 BaseInst->setMetadata("is_base_value", MDNode::get(I->getContext(), {}));
Philip Reames34d7a742015-09-10 00:22:49 +0000878 States[I] = BDVState(BDVState::Base, BaseInst);
Philip Reames9ac4e382015-08-12 21:00:20 +0000879 }
Philip Reames66287132015-09-09 23:40:12 +0000880
881 // Since we're joining a vector and scalar base, they can never be the
882 // same. As a result, we should always see insert element having reached
883 // the conflict state.
884 if (isa<InsertElementInst>(I)) {
885 assert(State.isConflict());
886 }
Philip Reames9ac4e382015-08-12 21:00:20 +0000887
Philip Reames6ff1a1e32015-07-21 19:04:38 +0000888 if (!State.isConflict())
Philip Reamesf986d682015-02-28 00:54:41 +0000889 continue;
Philip Reames704e78b2015-04-10 22:34:56 +0000890
Philip Reames6ff1a1e32015-07-21 19:04:38 +0000891 /// Create and insert a new instruction which will represent the base of
892 /// the given instruction 'I'.
893 auto MakeBaseInstPlaceholder = [](Instruction *I) -> Instruction* {
894 if (isa<PHINode>(I)) {
895 BasicBlock *BB = I->getParent();
896 int NumPreds = std::distance(pred_begin(BB), pred_end(BB));
897 assert(NumPreds > 0 && "how did we reach here");
Philip Reamesece70b82015-09-09 23:57:18 +0000898 std::string Name = suffixed_name_or(I, ".base", "base_phi");
Philip Reamesfa2c6302015-07-24 19:01:39 +0000899 return PHINode::Create(I->getType(), NumPreds, Name, I);
Philip Reames9ac4e382015-08-12 21:00:20 +0000900 } else if (SelectInst *Sel = dyn_cast<SelectInst>(I)) {
901 // The undef will be replaced later
902 UndefValue *Undef = UndefValue::get(Sel->getType());
Philip Reamesece70b82015-09-09 23:57:18 +0000903 std::string Name = suffixed_name_or(I, ".base", "base_select");
Philip Reames9ac4e382015-08-12 21:00:20 +0000904 return SelectInst::Create(Sel->getCondition(), Undef,
905 Undef, Name, Sel);
Philip Reames66287132015-09-09 23:40:12 +0000906 } else if (auto *EE = dyn_cast<ExtractElementInst>(I)) {
Philip Reames9ac4e382015-08-12 21:00:20 +0000907 UndefValue *Undef = UndefValue::get(EE->getVectorOperand()->getType());
Philip Reamesece70b82015-09-09 23:57:18 +0000908 std::string Name = suffixed_name_or(I, ".base", "base_ee");
Philip Reames9ac4e382015-08-12 21:00:20 +0000909 return ExtractElementInst::Create(Undef, EE->getIndexOperand(), Name,
910 EE);
Philip Reames66287132015-09-09 23:40:12 +0000911 } else {
912 auto *IE = cast<InsertElementInst>(I);
913 UndefValue *VecUndef = UndefValue::get(IE->getOperand(0)->getType());
914 UndefValue *ScalarUndef = UndefValue::get(IE->getOperand(1)->getType());
Philip Reamesece70b82015-09-09 23:57:18 +0000915 std::string Name = suffixed_name_or(I, ".base", "base_ie");
Philip Reames66287132015-09-09 23:40:12 +0000916 return InsertElementInst::Create(VecUndef, ScalarUndef,
917 IE->getOperand(2), Name, IE);
Philip Reames6ff1a1e32015-07-21 19:04:38 +0000918 }
Philip Reames66287132015-09-09 23:40:12 +0000919
Philip Reames6ff1a1e32015-07-21 19:04:38 +0000920 };
921 Instruction *BaseInst = MakeBaseInstPlaceholder(I);
922 // Add metadata marking this as a base value
923 BaseInst->setMetadata("is_base_value", MDNode::get(I->getContext(), {}));
Philip Reames34d7a742015-09-10 00:22:49 +0000924 States[I] = BDVState(BDVState::Conflict, BaseInst);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000925 }
926
Philip Reames3ea15892015-09-03 21:57:40 +0000927 // Returns a instruction which produces the base pointer for a given
928 // instruction. The instruction is assumed to be an input to one of the BDVs
929 // seen in the inference algorithm above. As such, we must either already
930 // know it's base defining value is a base, or have inserted a new
931 // instruction to propagate the base of it's BDV and have entered that newly
932 // introduced instruction into the state table. In either case, we are
933 // assured to be able to determine an instruction which produces it's base
934 // pointer.
935 auto getBaseForInput = [&](Value *Input, Instruction *InsertPt) {
936 Value *BDV = findBaseOrBDV(Input, cache);
937 Value *Base = nullptr;
938 if (isKnownBaseResult(BDV)) {
939 Base = BDV;
940 } else {
941 // Either conflict or base.
Philip Reames34d7a742015-09-10 00:22:49 +0000942 assert(States.count(BDV));
943 Base = States[BDV].getBase();
Philip Reames3ea15892015-09-03 21:57:40 +0000944 }
945 assert(Base && "can't be null");
946 // The cast is needed since base traversal may strip away bitcasts
947 if (Base->getType() != Input->getType() &&
948 InsertPt) {
949 Base = new BitCastInst(Base, Input->getType(), "cast",
950 InsertPt);
951 }
952 return Base;
953 };
954
Philip Reames15d55632015-09-09 23:26:08 +0000955 // Fixup all the inputs of the new PHIs. Visit order needs to be
956 // deterministic and predictable because we're naming newly created
957 // instructions.
Philip Reames34d7a742015-09-10 00:22:49 +0000958 for (auto Pair : States) {
Philip Reames7540e3a2015-09-10 00:01:53 +0000959 Instruction *BDV = cast<Instruction>(Pair.first);
Philip Reamesc8ded462015-09-10 00:27:50 +0000960 BDVState State = Pair.second;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000961
Philip Reames7540e3a2015-09-10 00:01:53 +0000962 assert(!isKnownBaseResult(BDV) && "why did it get added?");
Philip Reamesc8ded462015-09-10 00:27:50 +0000963 assert(!State.isUnknown() && "Optimistic algorithm didn't complete!");
964 if (!State.isConflict())
Philip Reames28e61ce2015-02-28 01:57:44 +0000965 continue;
Philip Reames704e78b2015-04-10 22:34:56 +0000966
Philip Reamesc8ded462015-09-10 00:27:50 +0000967 if (PHINode *basephi = dyn_cast<PHINode>(State.getBase())) {
Philip Reames7540e3a2015-09-10 00:01:53 +0000968 PHINode *phi = cast<PHINode>(BDV);
Philip Reames28e61ce2015-02-28 01:57:44 +0000969 unsigned NumPHIValues = phi->getNumIncomingValues();
970 for (unsigned i = 0; i < NumPHIValues; i++) {
971 Value *InVal = phi->getIncomingValue(i);
972 BasicBlock *InBB = phi->getIncomingBlock(i);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000973
Philip Reames28e61ce2015-02-28 01:57:44 +0000974 // If we've already seen InBB, add the same incoming value
975 // we added for it earlier. The IR verifier requires phi
976 // nodes with multiple entries from the same basic block
977 // to have the same incoming value for each of those
978 // entries. If we don't do this check here and basephi
979 // has a different type than base, we'll end up adding two
980 // bitcasts (and hence two distinct values) as incoming
981 // values for the same basic block.
Philip Reamesd16a9b12015-02-20 01:06:44 +0000982
Philip Reames28e61ce2015-02-28 01:57:44 +0000983 int blockIndex = basephi->getBasicBlockIndex(InBB);
984 if (blockIndex != -1) {
985 Value *oldBase = basephi->getIncomingValue(blockIndex);
986 basephi->addIncoming(oldBase, InBB);
Philip Reames3ea15892015-09-03 21:57:40 +0000987
Philip Reamesd16a9b12015-02-20 01:06:44 +0000988#ifndef NDEBUG
Philip Reames3ea15892015-09-03 21:57:40 +0000989 Value *Base = getBaseForInput(InVal, nullptr);
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000990 // In essence this assert states: the only way two
Philip Reames28e61ce2015-02-28 01:57:44 +0000991 // values incoming from the same basic block may be
992 // different is by being different bitcasts of the same
993 // value. A cleanup that remains TODO is changing
994 // findBaseOrBDV to return an llvm::Value of the correct
995 // type (and still remain pure). This will remove the
996 // need to add bitcasts.
Philip Reames3ea15892015-09-03 21:57:40 +0000997 assert(Base->stripPointerCasts() == oldBase->stripPointerCasts() &&
Philip Reames28e61ce2015-02-28 01:57:44 +0000998 "sanity -- findBaseOrBDV should be pure!");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000999#endif
Philip Reames28e61ce2015-02-28 01:57:44 +00001000 continue;
1001 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00001002
Philip Reames3ea15892015-09-03 21:57:40 +00001003 // Find the instruction which produces the base for each input. We may
1004 // need to insert a bitcast in the incoming block.
1005 // TODO: Need to split critical edges if insertion is needed
1006 Value *Base = getBaseForInput(InVal, InBB->getTerminator());
1007 basephi->addIncoming(Base, InBB);
Philip Reames28e61ce2015-02-28 01:57:44 +00001008 }
1009 assert(basephi->getNumIncomingValues() == NumPHIValues);
Philip Reamesc8ded462015-09-10 00:27:50 +00001010 } else if (SelectInst *BaseSel = dyn_cast<SelectInst>(State.getBase())) {
Philip Reames7540e3a2015-09-10 00:01:53 +00001011 SelectInst *Sel = cast<SelectInst>(BDV);
Philip Reames28e61ce2015-02-28 01:57:44 +00001012 // Operand 1 & 2 are true, false path respectively. TODO: refactor to
1013 // something more safe and less hacky.
1014 for (int i = 1; i <= 2; i++) {
Philip Reames3ea15892015-09-03 21:57:40 +00001015 Value *InVal = Sel->getOperand(i);
1016 // Find the instruction which produces the base for each input. We may
1017 // need to insert a bitcast.
1018 Value *Base = getBaseForInput(InVal, BaseSel);
1019 BaseSel->setOperand(i, Base);
Philip Reames28e61ce2015-02-28 01:57:44 +00001020 }
Philip Reamesc8ded462015-09-10 00:27:50 +00001021 } else if (auto *BaseEE = dyn_cast<ExtractElementInst>(State.getBase())) {
Philip Reames7540e3a2015-09-10 00:01:53 +00001022 Value *InVal = cast<ExtractElementInst>(BDV)->getVectorOperand();
Philip Reames3ea15892015-09-03 21:57:40 +00001023 // Find the instruction which produces the base for each input. We may
1024 // need to insert a bitcast.
1025 Value *Base = getBaseForInput(InVal, BaseEE);
Philip Reames9ac4e382015-08-12 21:00:20 +00001026 BaseEE->setOperand(0, Base);
Philip Reames66287132015-09-09 23:40:12 +00001027 } else {
Philip Reamesc8ded462015-09-10 00:27:50 +00001028 auto *BaseIE = cast<InsertElementInst>(State.getBase());
Philip Reames7540e3a2015-09-10 00:01:53 +00001029 auto *BdvIE = cast<InsertElementInst>(BDV);
Philip Reames66287132015-09-09 23:40:12 +00001030 auto UpdateOperand = [&](int OperandIdx) {
1031 Value *InVal = BdvIE->getOperand(OperandIdx);
Philip Reames953817b2015-09-10 00:44:10 +00001032 Value *Base = getBaseForInput(InVal, BaseIE);
Philip Reames66287132015-09-09 23:40:12 +00001033 BaseIE->setOperand(OperandIdx, Base);
1034 };
1035 UpdateOperand(0); // vector operand
1036 UpdateOperand(1); // scalar operand
Philip Reamesd16a9b12015-02-20 01:06:44 +00001037 }
Philip Reames66287132015-09-09 23:40:12 +00001038
Philip Reamesd16a9b12015-02-20 01:06:44 +00001039 }
1040
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001041 // Now that we're done with the algorithm, see if we can optimize the
1042 // results slightly by reducing the number of new instructions needed.
1043 // Arguably, this should be integrated into the algorithm above, but
1044 // doing as a post process step is easier to reason about for the moment.
1045 DenseMap<Value *, Value *> ReverseMap;
1046 SmallPtrSet<Instruction *, 16> NewInsts;
Philip Reames9546f362015-09-02 22:25:07 +00001047 SmallSetVector<AssertingVH<Instruction>, 16> Worklist;
Philip Reames246e6182015-09-03 20:24:29 +00001048 // Note: We need to visit the states in a deterministic order. We uses the
1049 // Keys we sorted above for this purpose. Note that we are papering over a
1050 // bigger problem with the algorithm above - it's visit order is not
1051 // deterministic. A larger change is needed to fix this.
Philip Reames34d7a742015-09-10 00:22:49 +00001052 for (auto Pair : States) {
Philip Reames15d55632015-09-09 23:26:08 +00001053 auto *BDV = Pair.first;
1054 auto State = Pair.second;
Philip Reames246e6182015-09-03 20:24:29 +00001055 Value *Base = State.getBase();
Philip Reames15d55632015-09-09 23:26:08 +00001056 assert(BDV && Base);
1057 assert(!isKnownBaseResult(BDV) && "why did it get added?");
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001058 assert(isKnownBaseResult(Base) &&
1059 "must be something we 'know' is a base pointer");
Philip Reames246e6182015-09-03 20:24:29 +00001060 if (!State.isConflict())
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001061 continue;
1062
Philip Reames15d55632015-09-09 23:26:08 +00001063 ReverseMap[Base] = BDV;
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001064 if (auto *BaseI = dyn_cast<Instruction>(Base)) {
1065 NewInsts.insert(BaseI);
1066 Worklist.insert(BaseI);
1067 }
1068 }
Philip Reames9546f362015-09-02 22:25:07 +00001069 auto ReplaceBaseInstWith = [&](Value *BDV, Instruction *BaseI,
1070 Value *Replacement) {
1071 // Add users which are new instructions (excluding self references)
1072 for (User *U : BaseI->users())
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001073 if (auto *UI = dyn_cast<Instruction>(U))
Philip Reames9546f362015-09-02 22:25:07 +00001074 if (NewInsts.count(UI) && UI != BaseI)
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001075 Worklist.insert(UI);
Philip Reames9546f362015-09-02 22:25:07 +00001076 // Then do the actual replacement
1077 NewInsts.erase(BaseI);
1078 ReverseMap.erase(BaseI);
1079 BaseI->replaceAllUsesWith(Replacement);
1080 BaseI->eraseFromParent();
Philip Reames34d7a742015-09-10 00:22:49 +00001081 assert(States.count(BDV));
1082 assert(States[BDV].isConflict() && States[BDV].getBase() == BaseI);
1083 States[BDV] = BDVState(BDVState::Conflict, Replacement);
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001084 };
1085 const DataLayout &DL = cast<Instruction>(def)->getModule()->getDataLayout();
1086 while (!Worklist.empty()) {
1087 Instruction *BaseI = Worklist.pop_back_val();
Philip Reamesdab35f32015-09-02 21:11:44 +00001088 assert(NewInsts.count(BaseI));
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001089 Value *Bdv = ReverseMap[BaseI];
1090 if (auto *BdvI = dyn_cast<Instruction>(Bdv))
1091 if (BaseI->isIdenticalTo(BdvI)) {
1092 DEBUG(dbgs() << "Identical Base: " << *BaseI << "\n");
Philip Reames9546f362015-09-02 22:25:07 +00001093 ReplaceBaseInstWith(Bdv, BaseI, Bdv);
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001094 continue;
1095 }
1096 if (Value *V = SimplifyInstruction(BaseI, DL)) {
1097 DEBUG(dbgs() << "Base " << *BaseI << " simplified to " << *V << "\n");
Philip Reames9546f362015-09-02 22:25:07 +00001098 ReplaceBaseInstWith(Bdv, BaseI, V);
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001099 continue;
1100 }
1101 }
1102
Philip Reamesd16a9b12015-02-20 01:06:44 +00001103 // Cache all of our results so we can cheaply reuse them
1104 // NOTE: This is actually two caches: one of the base defining value
1105 // relation and one of the base pointer relation! FIXME
Philip Reames34d7a742015-09-10 00:22:49 +00001106 for (auto Pair : States) {
Philip Reames15d55632015-09-09 23:26:08 +00001107 auto *BDV = Pair.first;
1108 Value *base = Pair.second.getBase();
1109 assert(BDV && base);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001110
Philip Reamesece70b82015-09-09 23:57:18 +00001111 std::string fromstr = cache.count(BDV) ? cache[BDV]->getName() : "none";
Philip Reamesdab35f32015-09-02 21:11:44 +00001112 DEBUG(dbgs() << "Updating base value cache"
Philip Reamesece70b82015-09-09 23:57:18 +00001113 << " for: " << BDV->getName()
Philip Reamesdab35f32015-09-02 21:11:44 +00001114 << " from: " << fromstr
Philip Reamesece70b82015-09-09 23:57:18 +00001115 << " to: " << base->getName() << "\n");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001116
Philip Reames15d55632015-09-09 23:26:08 +00001117 if (cache.count(BDV)) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001118 // Once we transition from the BDV relation being store in the cache to
1119 // the base relation being stored, it must be stable
Philip Reames15d55632015-09-09 23:26:08 +00001120 assert((!isKnownBaseResult(cache[BDV]) || cache[BDV] == base) &&
Philip Reamesd16a9b12015-02-20 01:06:44 +00001121 "base relation should be stable");
1122 }
Philip Reames15d55632015-09-09 23:26:08 +00001123 cache[BDV] = base;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001124 }
1125 assert(cache.find(def) != cache.end());
1126 return cache[def];
1127}
1128
1129// For a set of live pointers (base and/or derived), identify the base
1130// pointer of the object which they are derived from. This routine will
1131// mutate the IR graph as needed to make the 'base' pointer live at the
1132// definition site of 'derived'. This ensures that any use of 'derived' can
1133// also use 'base'. This may involve the insertion of a number of
1134// additional PHI nodes.
1135//
1136// preconditions: live is a set of pointer type Values
1137//
1138// side effects: may insert PHI nodes into the existing CFG, will preserve
1139// CFG, will not remove or mutate any existing nodes
1140//
Philip Reamesf2041322015-02-20 19:26:04 +00001141// post condition: PointerToBase contains one (derived, base) pair for every
Philip Reamesd16a9b12015-02-20 01:06:44 +00001142// pointer in live. Note that derived can be equal to base if the original
1143// pointer was a base pointer.
Philip Reames704e78b2015-04-10 22:34:56 +00001144static void
1145findBasePointers(const StatepointLiveSetTy &live,
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001146 DenseMap<Value *, Value *> &PointerToBase,
Philip Reamesba198492015-04-14 00:41:34 +00001147 DominatorTree *DT, DefiningValueMapTy &DVCache) {
Philip Reames2e5bcbe2015-02-28 01:52:09 +00001148 // For the naming of values inserted to be deterministic - which makes for
1149 // much cleaner and more stable tests - we need to assign an order to the
1150 // live values. DenseSets do not provide a deterministic order across runs.
Philip Reames704e78b2015-04-10 22:34:56 +00001151 SmallVector<Value *, 64> Temp;
Philip Reames2e5bcbe2015-02-28 01:52:09 +00001152 Temp.insert(Temp.end(), live.begin(), live.end());
1153 std::sort(Temp.begin(), Temp.end(), order_by_name);
1154 for (Value *ptr : Temp) {
Philip Reamesba198492015-04-14 00:41:34 +00001155 Value *base = findBasePointer(ptr, DVCache);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001156 assert(base && "failed to find base pointer");
Philip Reamesf2041322015-02-20 19:26:04 +00001157 PointerToBase[ptr] = base;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001158 assert((!isa<Instruction>(base) || !isa<Instruction>(ptr) ||
1159 DT->dominates(cast<Instruction>(base)->getParent(),
1160 cast<Instruction>(ptr)->getParent())) &&
1161 "The base we found better dominate the derived pointer");
1162
David Blaikie82ad7872015-02-20 23:44:24 +00001163 // If you see this trip and like to live really dangerously, the code should
1164 // be correct, just with idioms the verifier can't handle. You can try
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001165 // disabling the verifier at your own substantial risk.
Philip Reames704e78b2015-04-10 22:34:56 +00001166 assert(!isa<ConstantPointerNull>(base) &&
Philip Reames24c6cd52015-03-27 05:47:00 +00001167 "the relocation code needs adjustment to handle the relocation of "
1168 "a null pointer constant without causing false positives in the "
1169 "safepoint ir verifier.");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001170 }
1171}
1172
1173/// Find the required based pointers (and adjust the live set) for the given
1174/// parse point.
1175static void findBasePointers(DominatorTree &DT, DefiningValueMapTy &DVCache,
1176 const CallSite &CS,
1177 PartiallyConstructedSafepointRecord &result) {
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001178 DenseMap<Value *, Value *> PointerToBase;
1179 findBasePointers(result.LiveSet, PointerToBase, &DT, DVCache);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001180
1181 if (PrintBasePointers) {
Philip Reamesa5aeaf42015-02-28 00:20:48 +00001182 // Note: Need to print these in a stable order since this is checked in
1183 // some tests.
Philip Reamesd16a9b12015-02-20 01:06:44 +00001184 errs() << "Base Pairs (w/o Relocation):\n";
Philip Reames704e78b2015-04-10 22:34:56 +00001185 SmallVector<Value *, 64> Temp;
Philip Reamesa5aeaf42015-02-28 00:20:48 +00001186 Temp.reserve(PointerToBase.size());
Philip Reamesf2041322015-02-20 19:26:04 +00001187 for (auto Pair : PointerToBase) {
Philip Reamesa5aeaf42015-02-28 00:20:48 +00001188 Temp.push_back(Pair.first);
1189 }
1190 std::sort(Temp.begin(), Temp.end(), order_by_name);
1191 for (Value *Ptr : Temp) {
1192 Value *Base = PointerToBase[Ptr];
Philip Reames704e78b2015-04-10 22:34:56 +00001193 errs() << " derived %" << Ptr->getName() << " base %" << Base->getName()
1194 << "\n";
Philip Reamesd16a9b12015-02-20 01:06:44 +00001195 }
1196 }
1197
Philip Reamesf2041322015-02-20 19:26:04 +00001198 result.PointerToBase = PointerToBase;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001199}
1200
Philip Reamesdf1ef082015-04-10 22:53:14 +00001201/// Given an updated version of the dataflow liveness results, update the
1202/// liveset and base pointer maps for the call site CS.
1203static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData,
1204 const CallSite &CS,
1205 PartiallyConstructedSafepointRecord &result);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001206
Philip Reamesdf1ef082015-04-10 22:53:14 +00001207static void recomputeLiveInValues(
1208 Function &F, DominatorTree &DT, Pass *P, ArrayRef<CallSite> toUpdate,
Philip Reamesd2b66462015-02-20 22:39:41 +00001209 MutableArrayRef<struct PartiallyConstructedSafepointRecord> records) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00001210 // TODO-PERF: reuse the original liveness, then simply run the dataflow
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001211 // again. The old values are still live and will help it stabilize quickly.
Philip Reamesdf1ef082015-04-10 22:53:14 +00001212 GCPtrLivenessData RevisedLivenessData;
1213 computeLiveInValues(DT, F, RevisedLivenessData);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001214 for (size_t i = 0; i < records.size(); i++) {
1215 struct PartiallyConstructedSafepointRecord &info = records[i];
Philip Reamesd2b66462015-02-20 22:39:41 +00001216 const CallSite &CS = toUpdate[i];
Philip Reamesdf1ef082015-04-10 22:53:14 +00001217 recomputeLiveInValues(RevisedLivenessData, CS, info);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001218 }
1219}
1220
Philip Reames69e51ca2015-04-13 18:07:21 +00001221// When inserting gc.relocate calls, we need to ensure there are no uses
1222// of the original value between the gc.statepoint and the gc.relocate call.
1223// One case which can arise is a phi node starting one of the successor blocks.
1224// We also need to be able to insert the gc.relocates only on the path which
1225// goes through the statepoint. We might need to split an edge to make this
Philip Reamesf209a152015-04-13 20:00:30 +00001226// possible.
1227static BasicBlock *
Sanjoy Dasea45f0e2015-06-02 22:33:34 +00001228normalizeForInvokeSafepoint(BasicBlock *BB, BasicBlock *InvokeParent,
1229 DominatorTree &DT) {
Philip Reames69e51ca2015-04-13 18:07:21 +00001230 BasicBlock *Ret = BB;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001231 if (!BB->getUniquePredecessor()) {
Chandler Carruth96ada252015-07-22 09:52:54 +00001232 Ret = SplitBlockPredecessors(BB, InvokeParent, "", &DT);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001233 }
1234
Philip Reames69e51ca2015-04-13 18:07:21 +00001235 // Now that 'ret' has unique predecessor we can safely remove all phi nodes
1236 // from it
1237 FoldSingleEntryPHINodes(Ret);
1238 assert(!isa<PHINode>(Ret->begin()));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001239
Philip Reames69e51ca2015-04-13 18:07:21 +00001240 // At this point, we can safely insert a gc.relocate as the first instruction
1241 // in Ret if needed.
1242 return Ret;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001243}
1244
Philip Reamesd2b66462015-02-20 22:39:41 +00001245static int find_index(ArrayRef<Value *> livevec, Value *val) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001246 auto itr = std::find(livevec.begin(), livevec.end(), val);
1247 assert(livevec.end() != itr);
1248 size_t index = std::distance(livevec.begin(), itr);
1249 assert(index < livevec.size());
1250 return index;
1251}
1252
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001253// Create new attribute set containing only attributes which can be transferred
Philip Reamesd16a9b12015-02-20 01:06:44 +00001254// from original call to the safepoint.
1255static AttributeSet legalizeCallAttributes(AttributeSet AS) {
1256 AttributeSet ret;
1257
1258 for (unsigned Slot = 0; Slot < AS.getNumSlots(); Slot++) {
1259 unsigned index = AS.getSlotIndex(Slot);
1260
1261 if (index == AttributeSet::ReturnIndex ||
1262 index == AttributeSet::FunctionIndex) {
1263
1264 for (auto it = AS.begin(Slot), it_end = AS.end(Slot); it != it_end;
1265 ++it) {
1266 Attribute attr = *it;
1267
1268 // Do not allow certain attributes - just skip them
1269 // Safepoint can not be read only or read none.
1270 if (attr.hasAttribute(Attribute::ReadNone) ||
1271 attr.hasAttribute(Attribute::ReadOnly))
1272 continue;
1273
1274 ret = ret.addAttributes(
1275 AS.getContext(), index,
1276 AttributeSet::get(AS.getContext(), index, AttrBuilder(attr)));
1277 }
1278 }
1279
1280 // Just skip parameter attributes for now
1281 }
1282
1283 return ret;
1284}
1285
1286/// Helper function to place all gc relocates necessary for the given
1287/// statepoint.
1288/// Inputs:
1289/// liveVariables - list of variables to be relocated.
1290/// liveStart - index of the first live variable.
1291/// basePtrs - base pointers.
1292/// statepointToken - statepoint instruction to which relocates should be
1293/// bound.
1294/// Builder - Llvm IR builder to be used to construct new calls.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001295static void CreateGCRelocates(ArrayRef<Value *> LiveVariables,
Sanjoy Das5665c992015-05-11 23:47:27 +00001296 const int LiveStart,
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001297 ArrayRef<Value *> BasePtrs,
Sanjoy Das5665c992015-05-11 23:47:27 +00001298 Instruction *StatepointToken,
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00001299 IRBuilder<> Builder) {
Philip Reames94babb72015-07-21 17:18:03 +00001300 if (LiveVariables.empty())
1301 return;
1302
1303 // All gc_relocate are set to i8 addrspace(1)* type. We originally generated
1304 // unique declarations for each pointer type, but this proved problematic
1305 // because the intrinsic mangling code is incomplete and fragile. Since
1306 // we're moving towards a single unified pointer type anyways, we can just
1307 // cast everything to an i8* of the right address space. A bitcast is added
1308 // later to convert gc_relocate to the actual value's type.
Philip Reames74ce2e72015-07-21 16:51:17 +00001309 Module *M = StatepointToken->getModule();
Philip Reames94babb72015-07-21 17:18:03 +00001310 auto AS = cast<PointerType>(LiveVariables[0]->getType())->getAddressSpace();
1311 Type *Types[] = {Type::getInt8PtrTy(M->getContext(), AS)};
1312 Value *GCRelocateDecl =
1313 Intrinsic::getDeclaration(M, Intrinsic::experimental_gc_relocate, Types);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001314
Sanjoy Das5665c992015-05-11 23:47:27 +00001315 for (unsigned i = 0; i < LiveVariables.size(); i++) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001316 // Generate the gc.relocate call and save the result
Sanjoy Das5665c992015-05-11 23:47:27 +00001317 Value *BaseIdx =
Philip Reamesf3880502015-07-21 00:49:55 +00001318 Builder.getInt32(LiveStart + find_index(LiveVariables, BasePtrs[i]));
1319 Value *LiveIdx =
1320 Builder.getInt32(LiveStart + find_index(LiveVariables, LiveVariables[i]));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001321
1322 // only specify a debug name if we can give a useful one
Philip Reames74ce2e72015-07-21 16:51:17 +00001323 CallInst *Reloc = Builder.CreateCall(
David Blaikieff6409d2015-05-18 22:13:54 +00001324 GCRelocateDecl, {StatepointToken, BaseIdx, LiveIdx},
Philip Reamesece70b82015-09-09 23:57:18 +00001325 suffixed_name_or(LiveVariables[i], ".relocated", ""));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001326 // Trick CodeGen into thinking there are lots of free registers at this
1327 // fake call.
Philip Reames74ce2e72015-07-21 16:51:17 +00001328 Reloc->setCallingConv(CallingConv::Cold);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001329 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00001330}
1331
1332static void
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001333makeStatepointExplicitImpl(const CallSite CS, /* to replace */
1334 const SmallVectorImpl<Value *> &BasePtrs,
1335 const SmallVectorImpl<Value *> &LiveVariables,
1336 PartiallyConstructedSafepointRecord &Result) {
1337 assert(BasePtrs.size() == LiveVariables.size());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001338 assert(isStatepoint(CS) &&
1339 "This method expects to be rewriting a statepoint");
1340
1341 BasicBlock *BB = CS.getInstruction()->getParent();
Philip Reamesd16a9b12015-02-20 01:06:44 +00001342 Function *F = BB->getParent();
Philip Reamesd16a9b12015-02-20 01:06:44 +00001343 Module *M = F->getParent();
1344 assert(M && "must be set");
1345
1346 // We're not changing the function signature of the statepoint since the gc
1347 // arguments go into the var args section.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001348 Function *GCStatepointDecl = CS.getCalledFunction();
Philip Reamesd16a9b12015-02-20 01:06:44 +00001349
1350 // Then go ahead and use the builder do actually do the inserts. We insert
1351 // immediately before the previous instruction under the assumption that all
1352 // arguments will be available here. We can't insert afterwards since we may
1353 // be replacing a terminator.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001354 Instruction *InsertBefore = CS.getInstruction();
1355 IRBuilder<> Builder(InsertBefore);
1356
Philip Reamesd16a9b12015-02-20 01:06:44 +00001357 // Copy all of the arguments from the original statepoint - this includes the
1358 // target, call args, and deopt args
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001359 SmallVector<llvm::Value *, 64> Args;
1360 Args.insert(Args.end(), CS.arg_begin(), CS.arg_end());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001361 // TODO: Clear the 'needs rewrite' flag
1362
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001363 // Add all the pointers to be relocated (gc arguments) and capture the start
1364 // of the live variable list for use in the gc_relocates
1365 const int LiveStartIdx = Args.size();
1366 Args.insert(Args.end(), LiveVariables.begin(), LiveVariables.end());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001367
1368 // Create the statepoint given all the arguments
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001369 Instruction *Token = nullptr;
1370 AttributeSet ReturnAttrs;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001371 if (CS.isCall()) {
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001372 CallInst *ToReplace = cast<CallInst>(CS.getInstruction());
1373 CallInst *Call =
1374 Builder.CreateCall(GCStatepointDecl, Args, "safepoint_token");
1375 Call->setTailCall(ToReplace->isTailCall());
1376 Call->setCallingConv(ToReplace->getCallingConv());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001377
1378 // Currently we will fail on parameter attributes and on certain
1379 // function attributes.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001380 AttributeSet NewAttrs = legalizeCallAttributes(ToReplace->getAttributes());
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001381 // In case if we can handle this set of attributes - set up function attrs
Philip Reamesd16a9b12015-02-20 01:06:44 +00001382 // directly on statepoint and return attrs later for gc_result intrinsic.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001383 Call->setAttributes(NewAttrs.getFnAttributes());
1384 ReturnAttrs = NewAttrs.getRetAttributes();
Philip Reamesd16a9b12015-02-20 01:06:44 +00001385
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001386 Token = Call;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001387
1388 // Put the following gc_result and gc_relocate calls immediately after the
1389 // the old call (which we're about to delete)
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001390 assert(ToReplace->getNextNode() && "Not a terminator, must have next!");
1391 Builder.SetInsertPoint(ToReplace->getNextNode());
1392 Builder.SetCurrentDebugLocation(ToReplace->getNextNode()->getDebugLoc());
David Blaikie82ad7872015-02-20 23:44:24 +00001393 } else {
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001394 InvokeInst *ToReplace = cast<InvokeInst>(CS.getInstruction());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001395
1396 // Insert the new invoke into the old block. We'll remove the old one in a
1397 // moment at which point this will become the new terminator for the
1398 // original block.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001399 InvokeInst *Invoke =
1400 InvokeInst::Create(GCStatepointDecl, ToReplace->getNormalDest(),
1401 ToReplace->getUnwindDest(), Args, "statepoint_token",
1402 ToReplace->getParent());
1403 Invoke->setCallingConv(ToReplace->getCallingConv());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001404
1405 // Currently we will fail on parameter attributes and on certain
1406 // function attributes.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001407 AttributeSet NewAttrs = legalizeCallAttributes(ToReplace->getAttributes());
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001408 // In case if we can handle this set of attributes - set up function attrs
Philip Reamesd16a9b12015-02-20 01:06:44 +00001409 // directly on statepoint and return attrs later for gc_result intrinsic.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001410 Invoke->setAttributes(NewAttrs.getFnAttributes());
1411 ReturnAttrs = NewAttrs.getRetAttributes();
Philip Reamesd16a9b12015-02-20 01:06:44 +00001412
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001413 Token = Invoke;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001414
1415 // Generate gc relocates in exceptional path
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001416 BasicBlock *UnwindBlock = ToReplace->getUnwindDest();
1417 assert(!isa<PHINode>(UnwindBlock->begin()) &&
1418 UnwindBlock->getUniquePredecessor() &&
Philip Reames69e51ca2015-04-13 18:07:21 +00001419 "can't safely insert in this block!");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001420
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001421 Builder.SetInsertPoint(UnwindBlock->getFirstInsertionPt());
1422 Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001423
1424 // Extract second element from landingpad return value. We will attach
1425 // exceptional gc relocates to it.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001426 Instruction *ExceptionalToken =
Philip Reamesd16a9b12015-02-20 01:06:44 +00001427 cast<Instruction>(Builder.CreateExtractValue(
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001428 UnwindBlock->getLandingPadInst(), 1, "relocate_token"));
1429 Result.UnwindToken = ExceptionalToken;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001430
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001431 CreateGCRelocates(LiveVariables, LiveStartIdx, BasePtrs, ExceptionalToken,
1432 Builder);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001433
1434 // Generate gc relocates and returns for normal block
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001435 BasicBlock *NormalDest = ToReplace->getNormalDest();
1436 assert(!isa<PHINode>(NormalDest->begin()) &&
1437 NormalDest->getUniquePredecessor() &&
Philip Reames69e51ca2015-04-13 18:07:21 +00001438 "can't safely insert in this block!");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001439
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001440 Builder.SetInsertPoint(NormalDest->getFirstInsertionPt());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001441
1442 // gc relocates will be generated later as if it were regular call
1443 // statepoint
Philip Reamesd16a9b12015-02-20 01:06:44 +00001444 }
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001445 assert(Token && "Should be set in one of the above branches!");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001446
1447 // Take the name of the original value call if it had one.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001448 Token->takeName(CS.getInstruction());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001449
Philip Reames704e78b2015-04-10 22:34:56 +00001450// The GCResult is already inserted, we just need to find it
David Blaikie5e5d7842015-02-22 20:58:38 +00001451#ifndef NDEBUG
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001452 Instruction *ToReplace = CS.getInstruction();
1453 assert(!ToReplace->hasNUsesOrMore(2) &&
David Blaikie5e5d7842015-02-22 20:58:38 +00001454 "only valid use before rewrite is gc.result");
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001455 assert(!ToReplace->hasOneUse() ||
1456 isGCResult(cast<Instruction>(*ToReplace->user_begin())));
David Blaikie5e5d7842015-02-22 20:58:38 +00001457#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +00001458
1459 // Update the gc.result of the original statepoint (if any) to use the newly
1460 // inserted statepoint. This is safe to do here since the token can't be
1461 // considered a live reference.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001462 CS.getInstruction()->replaceAllUsesWith(Token);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001463
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001464 Result.StatepointToken = Token;
Philip Reames0a3240f2015-02-20 21:34:11 +00001465
Philip Reamesd16a9b12015-02-20 01:06:44 +00001466 // Second, create a gc.relocate for every live variable
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001467 CreateGCRelocates(LiveVariables, LiveStartIdx, BasePtrs, Token, Builder);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001468}
1469
1470namespace {
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001471struct NameOrdering {
1472 Value *Base;
1473 Value *Derived;
1474
1475 bool operator()(NameOrdering const &a, NameOrdering const &b) {
1476 return -1 == a.Derived->getName().compare(b.Derived->getName());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001477 }
1478};
1479}
Philip Reamesd16a9b12015-02-20 01:06:44 +00001480
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001481static void StabilizeOrder(SmallVectorImpl<Value *> &BaseVec,
1482 SmallVectorImpl<Value *> &LiveVec) {
1483 assert(BaseVec.size() == LiveVec.size());
1484
1485 SmallVector<NameOrdering, 64> Temp;
1486 for (size_t i = 0; i < BaseVec.size(); i++) {
1487 NameOrdering v;
1488 v.Base = BaseVec[i];
1489 v.Derived = LiveVec[i];
1490 Temp.push_back(v);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001491 }
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001492
1493 std::sort(Temp.begin(), Temp.end(), NameOrdering());
1494 for (size_t i = 0; i < BaseVec.size(); i++) {
1495 BaseVec[i] = Temp[i].Base;
1496 LiveVec[i] = Temp[i].Derived;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001497 }
1498}
1499
1500// Replace an existing gc.statepoint with a new one and a set of gc.relocates
1501// which make the relocations happening at this safepoint explicit.
Philip Reames704e78b2015-04-10 22:34:56 +00001502//
Philip Reamesd16a9b12015-02-20 01:06:44 +00001503// WARNING: Does not do any fixup to adjust users of the original live
1504// values. That's the callers responsibility.
1505static void
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001506makeStatepointExplicit(DominatorTree &DT, const CallSite &CS,
1507 PartiallyConstructedSafepointRecord &Result) {
1508 auto LiveSet = Result.LiveSet;
1509 auto PointerToBase = Result.PointerToBase;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001510
1511 // Convert to vector for efficient cross referencing.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001512 SmallVector<Value *, 64> BaseVec, LiveVec;
1513 LiveVec.reserve(LiveSet.size());
1514 BaseVec.reserve(LiveSet.size());
1515 for (Value *L : LiveSet) {
1516 LiveVec.push_back(L);
Philip Reames74ce2e72015-07-21 16:51:17 +00001517 assert(PointerToBase.count(L));
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001518 Value *Base = PointerToBase[L];
1519 BaseVec.push_back(Base);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001520 }
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001521 assert(LiveVec.size() == BaseVec.size());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001522
1523 // To make the output IR slightly more stable (for use in diffs), ensure a
1524 // fixed order of the values in the safepoint (by sorting the value name).
1525 // The order is otherwise meaningless.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001526 StabilizeOrder(BaseVec, LiveVec);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001527
1528 // Do the actual rewriting and delete the old statepoint
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001529 makeStatepointExplicitImpl(CS, BaseVec, LiveVec, Result);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001530 CS.getInstruction()->eraseFromParent();
1531}
1532
1533// Helper function for the relocationViaAlloca.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001534//
1535// It receives iterator to the statepoint gc relocates and emits a store to the
1536// assigned location (via allocaMap) for the each one of them. It adds the
1537// visited values into the visitedLiveValues set, which we will later use them
1538// for sanity checking.
Philip Reamesd16a9b12015-02-20 01:06:44 +00001539static void
Sanjoy Das5665c992015-05-11 23:47:27 +00001540insertRelocationStores(iterator_range<Value::user_iterator> GCRelocs,
1541 DenseMap<Value *, Value *> &AllocaMap,
1542 DenseSet<Value *> &VisitedLiveValues) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001543
Sanjoy Das5665c992015-05-11 23:47:27 +00001544 for (User *U : GCRelocs) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001545 if (!isa<IntrinsicInst>(U))
1546 continue;
1547
Sanjoy Das5665c992015-05-11 23:47:27 +00001548 IntrinsicInst *RelocatedValue = cast<IntrinsicInst>(U);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001549
1550 // We only care about relocates
Sanjoy Das5665c992015-05-11 23:47:27 +00001551 if (RelocatedValue->getIntrinsicID() !=
Philip Reamesd16a9b12015-02-20 01:06:44 +00001552 Intrinsic::experimental_gc_relocate) {
1553 continue;
1554 }
1555
Sanjoy Das5665c992015-05-11 23:47:27 +00001556 GCRelocateOperands RelocateOperands(RelocatedValue);
1557 Value *OriginalValue =
1558 const_cast<Value *>(RelocateOperands.getDerivedPtr());
1559 assert(AllocaMap.count(OriginalValue));
1560 Value *Alloca = AllocaMap[OriginalValue];
Philip Reamesd16a9b12015-02-20 01:06:44 +00001561
1562 // Emit store into the related alloca
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001563 // All gc_relocates are i8 addrspace(1)* typed, and it must be bitcasted to
Sanjoy Das89c54912015-05-11 18:49:34 +00001564 // the correct type according to alloca.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001565 assert(RelocatedValue->getNextNode() &&
1566 "Should always have one since it's not a terminator");
Sanjoy Das5665c992015-05-11 23:47:27 +00001567 IRBuilder<> Builder(RelocatedValue->getNextNode());
Sanjoy Das89c54912015-05-11 18:49:34 +00001568 Value *CastedRelocatedValue =
Philip Reamesece70b82015-09-09 23:57:18 +00001569 Builder.CreateBitCast(RelocatedValue,
1570 cast<AllocaInst>(Alloca)->getAllocatedType(),
1571 suffixed_name_or(RelocatedValue, ".casted", ""));
Sanjoy Das89c54912015-05-11 18:49:34 +00001572
Sanjoy Das5665c992015-05-11 23:47:27 +00001573 StoreInst *Store = new StoreInst(CastedRelocatedValue, Alloca);
1574 Store->insertAfter(cast<Instruction>(CastedRelocatedValue));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001575
1576#ifndef NDEBUG
Sanjoy Das5665c992015-05-11 23:47:27 +00001577 VisitedLiveValues.insert(OriginalValue);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001578#endif
1579 }
1580}
1581
Igor Laevskye0317182015-05-19 15:59:05 +00001582// Helper function for the "relocationViaAlloca". Similar to the
1583// "insertRelocationStores" but works for rematerialized values.
1584static void
1585insertRematerializationStores(
1586 RematerializedValueMapTy RematerializedValues,
1587 DenseMap<Value *, Value *> &AllocaMap,
1588 DenseSet<Value *> &VisitedLiveValues) {
1589
1590 for (auto RematerializedValuePair: RematerializedValues) {
1591 Instruction *RematerializedValue = RematerializedValuePair.first;
1592 Value *OriginalValue = RematerializedValuePair.second;
1593
1594 assert(AllocaMap.count(OriginalValue) &&
1595 "Can not find alloca for rematerialized value");
1596 Value *Alloca = AllocaMap[OriginalValue];
1597
1598 StoreInst *Store = new StoreInst(RematerializedValue, Alloca);
1599 Store->insertAfter(RematerializedValue);
1600
1601#ifndef NDEBUG
1602 VisitedLiveValues.insert(OriginalValue);
1603#endif
1604 }
1605}
1606
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001607/// Do all the relocation update via allocas and mem2reg
Philip Reamesd16a9b12015-02-20 01:06:44 +00001608static void relocationViaAlloca(
Igor Laevsky285fe842015-05-19 16:29:43 +00001609 Function &F, DominatorTree &DT, ArrayRef<Value *> Live,
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001610 ArrayRef<PartiallyConstructedSafepointRecord> Records) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001611#ifndef NDEBUG
Philip Reamesa6ebf072015-03-27 05:53:16 +00001612 // record initial number of (static) allocas; we'll check we have the same
1613 // number when we get done.
1614 int InitialAllocaNum = 0;
Philip Reames704e78b2015-04-10 22:34:56 +00001615 for (auto I = F.getEntryBlock().begin(), E = F.getEntryBlock().end(); I != E;
1616 I++)
Philip Reamesa6ebf072015-03-27 05:53:16 +00001617 if (isa<AllocaInst>(*I))
1618 InitialAllocaNum++;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001619#endif
1620
1621 // TODO-PERF: change data structures, reserve
Igor Laevsky285fe842015-05-19 16:29:43 +00001622 DenseMap<Value *, Value *> AllocaMap;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001623 SmallVector<AllocaInst *, 200> PromotableAllocas;
Igor Laevskye0317182015-05-19 15:59:05 +00001624 // Used later to chack that we have enough allocas to store all values
1625 std::size_t NumRematerializedValues = 0;
Igor Laevsky285fe842015-05-19 16:29:43 +00001626 PromotableAllocas.reserve(Live.size());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001627
Igor Laevskye0317182015-05-19 15:59:05 +00001628 // Emit alloca for "LiveValue" and record it in "allocaMap" and
1629 // "PromotableAllocas"
1630 auto emitAllocaFor = [&](Value *LiveValue) {
1631 AllocaInst *Alloca = new AllocaInst(LiveValue->getType(), "",
1632 F.getEntryBlock().getFirstNonPHI());
Igor Laevsky285fe842015-05-19 16:29:43 +00001633 AllocaMap[LiveValue] = Alloca;
Igor Laevskye0317182015-05-19 15:59:05 +00001634 PromotableAllocas.push_back(Alloca);
1635 };
1636
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001637 // Emit alloca for each live gc pointer
1638 for (Value *V : Live)
1639 emitAllocaFor(V);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001640
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001641 // Emit allocas for rematerialized values
1642 for (const auto &Info : Records)
Igor Laevsky285fe842015-05-19 16:29:43 +00001643 for (auto RematerializedValuePair : Info.RematerializedValues) {
Igor Laevskye0317182015-05-19 15:59:05 +00001644 Value *OriginalValue = RematerializedValuePair.second;
Igor Laevsky285fe842015-05-19 16:29:43 +00001645 if (AllocaMap.count(OriginalValue) != 0)
Igor Laevskye0317182015-05-19 15:59:05 +00001646 continue;
1647
1648 emitAllocaFor(OriginalValue);
1649 ++NumRematerializedValues;
1650 }
Igor Laevsky285fe842015-05-19 16:29:43 +00001651
Philip Reamesd16a9b12015-02-20 01:06:44 +00001652 // The next two loops are part of the same conceptual operation. We need to
1653 // insert a store to the alloca after the original def and at each
1654 // redefinition. We need to insert a load before each use. These are split
1655 // into distinct loops for performance reasons.
1656
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001657 // Update gc pointer after each statepoint: either store a relocated value or
1658 // null (if no relocated value was found for this gc pointer and it is not a
1659 // gc_result). This must happen before we update the statepoint with load of
1660 // alloca otherwise we lose the link between statepoint and old def.
1661 for (const auto &Info : Records) {
Igor Laevsky285fe842015-05-19 16:29:43 +00001662 Value *Statepoint = Info.StatepointToken;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001663
1664 // This will be used for consistency check
Igor Laevsky285fe842015-05-19 16:29:43 +00001665 DenseSet<Value *> VisitedLiveValues;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001666
1667 // Insert stores for normal statepoint gc relocates
Igor Laevsky285fe842015-05-19 16:29:43 +00001668 insertRelocationStores(Statepoint->users(), AllocaMap, VisitedLiveValues);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001669
1670 // In case if it was invoke statepoint
1671 // we will insert stores for exceptional path gc relocates.
Philip Reames0a3240f2015-02-20 21:34:11 +00001672 if (isa<InvokeInst>(Statepoint)) {
Igor Laevsky285fe842015-05-19 16:29:43 +00001673 insertRelocationStores(Info.UnwindToken->users(), AllocaMap,
1674 VisitedLiveValues);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001675 }
1676
Igor Laevskye0317182015-05-19 15:59:05 +00001677 // Do similar thing with rematerialized values
Igor Laevsky285fe842015-05-19 16:29:43 +00001678 insertRematerializationStores(Info.RematerializedValues, AllocaMap,
1679 VisitedLiveValues);
Igor Laevskye0317182015-05-19 15:59:05 +00001680
Philip Reamese73300b2015-04-13 16:41:32 +00001681 if (ClobberNonLive) {
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001682 // As a debugging aid, pretend that an unrelocated pointer becomes null at
Philip Reamese73300b2015-04-13 16:41:32 +00001683 // the gc.statepoint. This will turn some subtle GC problems into
1684 // slightly easier to debug SEGVs. Note that on large IR files with
1685 // lots of gc.statepoints this is extremely costly both memory and time
1686 // wise.
1687 SmallVector<AllocaInst *, 64> ToClobber;
Igor Laevsky285fe842015-05-19 16:29:43 +00001688 for (auto Pair : AllocaMap) {
Philip Reamese73300b2015-04-13 16:41:32 +00001689 Value *Def = Pair.first;
1690 AllocaInst *Alloca = cast<AllocaInst>(Pair.second);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001691
Philip Reamese73300b2015-04-13 16:41:32 +00001692 // This value was relocated
Igor Laevsky285fe842015-05-19 16:29:43 +00001693 if (VisitedLiveValues.count(Def)) {
Philip Reamese73300b2015-04-13 16:41:32 +00001694 continue;
1695 }
1696 ToClobber.push_back(Alloca);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001697 }
Philip Reamesfa2fcf172015-02-20 19:51:56 +00001698
Philip Reamese73300b2015-04-13 16:41:32 +00001699 auto InsertClobbersAt = [&](Instruction *IP) {
1700 for (auto *AI : ToClobber) {
1701 auto AIType = cast<PointerType>(AI->getType());
1702 auto PT = cast<PointerType>(AIType->getElementType());
1703 Constant *CPN = ConstantPointerNull::get(PT);
Igor Laevsky285fe842015-05-19 16:29:43 +00001704 StoreInst *Store = new StoreInst(CPN, AI);
1705 Store->insertBefore(IP);
Philip Reamese73300b2015-04-13 16:41:32 +00001706 }
1707 };
1708
1709 // Insert the clobbering stores. These may get intermixed with the
1710 // gc.results and gc.relocates, but that's fine.
1711 if (auto II = dyn_cast<InvokeInst>(Statepoint)) {
1712 InsertClobbersAt(II->getNormalDest()->getFirstInsertionPt());
1713 InsertClobbersAt(II->getUnwindDest()->getFirstInsertionPt());
1714 } else {
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001715 InsertClobbersAt(cast<Instruction>(Statepoint)->getNextNode());
Philip Reamesfa2fcf172015-02-20 19:51:56 +00001716 }
David Blaikie82ad7872015-02-20 23:44:24 +00001717 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00001718 }
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001719
1720 // Update use with load allocas and add store for gc_relocated.
Igor Laevsky285fe842015-05-19 16:29:43 +00001721 for (auto Pair : AllocaMap) {
1722 Value *Def = Pair.first;
1723 Value *Alloca = Pair.second;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001724
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001725 // We pre-record the uses of allocas so that we dont have to worry about
1726 // later update that changes the user information..
1727
Igor Laevsky285fe842015-05-19 16:29:43 +00001728 SmallVector<Instruction *, 20> Uses;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001729 // PERF: trade a linear scan for repeated reallocation
Igor Laevsky285fe842015-05-19 16:29:43 +00001730 Uses.reserve(std::distance(Def->user_begin(), Def->user_end()));
1731 for (User *U : Def->users()) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001732 if (!isa<ConstantExpr>(U)) {
1733 // If the def has a ConstantExpr use, then the def is either a
1734 // ConstantExpr use itself or null. In either case
1735 // (recursively in the first, directly in the second), the oop
1736 // it is ultimately dependent on is null and this particular
1737 // use does not need to be fixed up.
Igor Laevsky285fe842015-05-19 16:29:43 +00001738 Uses.push_back(cast<Instruction>(U));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001739 }
1740 }
1741
Igor Laevsky285fe842015-05-19 16:29:43 +00001742 std::sort(Uses.begin(), Uses.end());
1743 auto Last = std::unique(Uses.begin(), Uses.end());
1744 Uses.erase(Last, Uses.end());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001745
Igor Laevsky285fe842015-05-19 16:29:43 +00001746 for (Instruction *Use : Uses) {
1747 if (isa<PHINode>(Use)) {
1748 PHINode *Phi = cast<PHINode>(Use);
1749 for (unsigned i = 0; i < Phi->getNumIncomingValues(); i++) {
1750 if (Def == Phi->getIncomingValue(i)) {
1751 LoadInst *Load = new LoadInst(
1752 Alloca, "", Phi->getIncomingBlock(i)->getTerminator());
1753 Phi->setIncomingValue(i, Load);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001754 }
1755 }
1756 } else {
Igor Laevsky285fe842015-05-19 16:29:43 +00001757 LoadInst *Load = new LoadInst(Alloca, "", Use);
1758 Use->replaceUsesOfWith(Def, Load);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001759 }
1760 }
1761
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001762 // Emit store for the initial gc value. Store must be inserted after load,
1763 // otherwise store will be in alloca's use list and an extra load will be
1764 // inserted before it.
Igor Laevsky285fe842015-05-19 16:29:43 +00001765 StoreInst *Store = new StoreInst(Def, Alloca);
1766 if (Instruction *Inst = dyn_cast<Instruction>(Def)) {
1767 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(Inst)) {
Philip Reames6da37852015-03-04 00:13:52 +00001768 // InvokeInst is a TerminatorInst so the store need to be inserted
1769 // into its normal destination block.
Igor Laevsky285fe842015-05-19 16:29:43 +00001770 BasicBlock *NormalDest = Invoke->getNormalDest();
1771 Store->insertBefore(NormalDest->getFirstNonPHI());
Philip Reames6da37852015-03-04 00:13:52 +00001772 } else {
Igor Laevsky285fe842015-05-19 16:29:43 +00001773 assert(!Inst->isTerminator() &&
Philip Reames6da37852015-03-04 00:13:52 +00001774 "The only TerminatorInst that can produce a value is "
1775 "InvokeInst which is handled above.");
Igor Laevsky285fe842015-05-19 16:29:43 +00001776 Store->insertAfter(Inst);
Philip Reames6da37852015-03-04 00:13:52 +00001777 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00001778 } else {
Igor Laevsky285fe842015-05-19 16:29:43 +00001779 assert(isa<Argument>(Def));
1780 Store->insertAfter(cast<Instruction>(Alloca));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001781 }
1782 }
1783
Igor Laevsky285fe842015-05-19 16:29:43 +00001784 assert(PromotableAllocas.size() == Live.size() + NumRematerializedValues &&
Philip Reamesd16a9b12015-02-20 01:06:44 +00001785 "we must have the same allocas with lives");
1786 if (!PromotableAllocas.empty()) {
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001787 // Apply mem2reg to promote alloca to SSA
Philip Reamesd16a9b12015-02-20 01:06:44 +00001788 PromoteMemToReg(PromotableAllocas, DT);
1789 }
1790
1791#ifndef NDEBUG
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001792 for (auto &I : F.getEntryBlock())
1793 if (isa<AllocaInst>(I))
Philip Reamesa6ebf072015-03-27 05:53:16 +00001794 InitialAllocaNum--;
1795 assert(InitialAllocaNum == 0 && "We must not introduce any extra allocas");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001796#endif
1797}
1798
1799/// Implement a unique function which doesn't require we sort the input
1800/// vector. Doing so has the effect of changing the output of a couple of
1801/// tests in ways which make them less useful in testing fused safepoints.
Philip Reamesd2b66462015-02-20 22:39:41 +00001802template <typename T> static void unique_unsorted(SmallVectorImpl<T> &Vec) {
Benjamin Kramer258ea0d2015-06-13 19:50:38 +00001803 SmallSet<T, 8> Seen;
1804 Vec.erase(std::remove_if(Vec.begin(), Vec.end(), [&](const T &V) {
1805 return !Seen.insert(V).second;
1806 }), Vec.end());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001807}
1808
Philip Reamesd16a9b12015-02-20 01:06:44 +00001809/// Insert holders so that each Value is obviously live through the entire
Philip Reamesf209a152015-04-13 20:00:30 +00001810/// lifetime of the call.
Philip Reamesd16a9b12015-02-20 01:06:44 +00001811static void insertUseHolderAfter(CallSite &CS, const ArrayRef<Value *> Values,
Philip Reamesf209a152015-04-13 20:00:30 +00001812 SmallVectorImpl<CallInst *> &Holders) {
Philip Reames21142752015-04-13 19:07:47 +00001813 if (Values.empty())
1814 // No values to hold live, might as well not insert the empty holder
1815 return;
1816
Philip Reamesd16a9b12015-02-20 01:06:44 +00001817 Module *M = CS.getInstruction()->getParent()->getParent()->getParent();
Philip Reamesf209a152015-04-13 20:00:30 +00001818 // Use a dummy vararg function to actually hold the values live
1819 Function *Func = cast<Function>(M->getOrInsertFunction(
1820 "__tmp_use", FunctionType::get(Type::getVoidTy(M->getContext()), true)));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001821 if (CS.isCall()) {
1822 // For call safepoints insert dummy calls right after safepoint
Philip Reamesf209a152015-04-13 20:00:30 +00001823 BasicBlock::iterator Next(CS.getInstruction());
1824 Next++;
1825 Holders.push_back(CallInst::Create(Func, Values, "", Next));
1826 return;
1827 }
1828 // For invoke safepooints insert dummy calls both in normal and
1829 // exceptional destination blocks
1830 auto *II = cast<InvokeInst>(CS.getInstruction());
1831 Holders.push_back(CallInst::Create(
1832 Func, Values, "", II->getNormalDest()->getFirstInsertionPt()));
1833 Holders.push_back(CallInst::Create(
1834 Func, Values, "", II->getUnwindDest()->getFirstInsertionPt()));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001835}
1836
1837static void findLiveReferences(
Philip Reamesd2b66462015-02-20 22:39:41 +00001838 Function &F, DominatorTree &DT, Pass *P, ArrayRef<CallSite> toUpdate,
1839 MutableArrayRef<struct PartiallyConstructedSafepointRecord> records) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00001840 GCPtrLivenessData OriginalLivenessData;
1841 computeLiveInValues(DT, F, OriginalLivenessData);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001842 for (size_t i = 0; i < records.size(); i++) {
1843 struct PartiallyConstructedSafepointRecord &info = records[i];
Philip Reamesd2b66462015-02-20 22:39:41 +00001844 const CallSite &CS = toUpdate[i];
Philip Reamesdf1ef082015-04-10 22:53:14 +00001845 analyzeParsePointLiveness(DT, OriginalLivenessData, CS, info);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001846 }
1847}
1848
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001849/// Remove any vector of pointers from the live set by scalarizing them over the
1850/// statepoint instruction. Adds the scalarized pieces to the live set. It
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001851/// would be preferable to include the vector in the statepoint itself, but
Philip Reames8531d8c2015-04-10 21:48:25 +00001852/// the lowering code currently does not handle that. Extending it would be
1853/// slightly non-trivial since it requires a format change. Given how rare
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001854/// such cases are (for the moment?) scalarizing is an acceptable compromise.
Philip Reames8531d8c2015-04-10 21:48:25 +00001855static void splitVectorValues(Instruction *StatepointInst,
Philip Reames8fe7f132015-06-26 22:47:37 +00001856 StatepointLiveSetTy &LiveSet,
1857 DenseMap<Value *, Value *>& PointerToBase,
1858 DominatorTree &DT) {
Philip Reames8531d8c2015-04-10 21:48:25 +00001859 SmallVector<Value *, 16> ToSplit;
1860 for (Value *V : LiveSet)
1861 if (isa<VectorType>(V->getType()))
1862 ToSplit.push_back(V);
1863
1864 if (ToSplit.empty())
1865 return;
1866
Philip Reames8fe7f132015-06-26 22:47:37 +00001867 DenseMap<Value *, SmallVector<Value *, 16>> ElementMapping;
1868
Philip Reames8531d8c2015-04-10 21:48:25 +00001869 Function &F = *(StatepointInst->getParent()->getParent());
1870
Philip Reames704e78b2015-04-10 22:34:56 +00001871 DenseMap<Value *, AllocaInst *> AllocaMap;
Philip Reames8531d8c2015-04-10 21:48:25 +00001872 // First is normal return, second is exceptional return (invoke only)
Philip Reames704e78b2015-04-10 22:34:56 +00001873 DenseMap<Value *, std::pair<Value *, Value *>> Replacements;
Philip Reames8531d8c2015-04-10 21:48:25 +00001874 for (Value *V : ToSplit) {
Philip Reames704e78b2015-04-10 22:34:56 +00001875 AllocaInst *Alloca =
1876 new AllocaInst(V->getType(), "", F.getEntryBlock().getFirstNonPHI());
Philip Reames8531d8c2015-04-10 21:48:25 +00001877 AllocaMap[V] = Alloca;
1878
1879 VectorType *VT = cast<VectorType>(V->getType());
1880 IRBuilder<> Builder(StatepointInst);
Philip Reames704e78b2015-04-10 22:34:56 +00001881 SmallVector<Value *, 16> Elements;
Philip Reames8531d8c2015-04-10 21:48:25 +00001882 for (unsigned i = 0; i < VT->getNumElements(); i++)
1883 Elements.push_back(Builder.CreateExtractElement(V, Builder.getInt32(i)));
Philip Reames8fe7f132015-06-26 22:47:37 +00001884 ElementMapping[V] = Elements;
Philip Reames8531d8c2015-04-10 21:48:25 +00001885
1886 auto InsertVectorReform = [&](Instruction *IP) {
1887 Builder.SetInsertPoint(IP);
1888 Builder.SetCurrentDebugLocation(IP->getDebugLoc());
1889 Value *ResultVec = UndefValue::get(VT);
1890 for (unsigned i = 0; i < VT->getNumElements(); i++)
1891 ResultVec = Builder.CreateInsertElement(ResultVec, Elements[i],
1892 Builder.getInt32(i));
1893 return ResultVec;
1894 };
1895
1896 if (isa<CallInst>(StatepointInst)) {
1897 BasicBlock::iterator Next(StatepointInst);
1898 Next++;
1899 Instruction *IP = &*(Next);
1900 Replacements[V].first = InsertVectorReform(IP);
1901 Replacements[V].second = nullptr;
1902 } else {
1903 InvokeInst *Invoke = cast<InvokeInst>(StatepointInst);
1904 // We've already normalized - check that we don't have shared destination
Philip Reames704e78b2015-04-10 22:34:56 +00001905 // blocks
Philip Reames8531d8c2015-04-10 21:48:25 +00001906 BasicBlock *NormalDest = Invoke->getNormalDest();
1907 assert(!isa<PHINode>(NormalDest->begin()));
1908 BasicBlock *UnwindDest = Invoke->getUnwindDest();
1909 assert(!isa<PHINode>(UnwindDest->begin()));
1910 // Insert insert element sequences in both successors
1911 Instruction *IP = &*(NormalDest->getFirstInsertionPt());
1912 Replacements[V].first = InsertVectorReform(IP);
1913 IP = &*(UnwindDest->getFirstInsertionPt());
1914 Replacements[V].second = InsertVectorReform(IP);
1915 }
1916 }
Philip Reames8fe7f132015-06-26 22:47:37 +00001917
Philip Reames8531d8c2015-04-10 21:48:25 +00001918 for (Value *V : ToSplit) {
1919 AllocaInst *Alloca = AllocaMap[V];
1920
1921 // Capture all users before we start mutating use lists
Philip Reames704e78b2015-04-10 22:34:56 +00001922 SmallVector<Instruction *, 16> Users;
Philip Reames8531d8c2015-04-10 21:48:25 +00001923 for (User *U : V->users())
1924 Users.push_back(cast<Instruction>(U));
1925
1926 for (Instruction *I : Users) {
1927 if (auto Phi = dyn_cast<PHINode>(I)) {
1928 for (unsigned i = 0; i < Phi->getNumIncomingValues(); i++)
1929 if (V == Phi->getIncomingValue(i)) {
Philip Reames704e78b2015-04-10 22:34:56 +00001930 LoadInst *Load = new LoadInst(
1931 Alloca, "", Phi->getIncomingBlock(i)->getTerminator());
Philip Reames8531d8c2015-04-10 21:48:25 +00001932 Phi->setIncomingValue(i, Load);
1933 }
1934 } else {
1935 LoadInst *Load = new LoadInst(Alloca, "", I);
1936 I->replaceUsesOfWith(V, Load);
1937 }
1938 }
1939
1940 // Store the original value and the replacement value into the alloca
1941 StoreInst *Store = new StoreInst(V, Alloca);
1942 if (auto I = dyn_cast<Instruction>(V))
1943 Store->insertAfter(I);
1944 else
1945 Store->insertAfter(Alloca);
Philip Reames704e78b2015-04-10 22:34:56 +00001946
Philip Reames8531d8c2015-04-10 21:48:25 +00001947 // Normal return for invoke, or call return
1948 Instruction *Replacement = cast<Instruction>(Replacements[V].first);
1949 (new StoreInst(Replacement, Alloca))->insertAfter(Replacement);
1950 // Unwind return for invoke only
1951 Replacement = cast_or_null<Instruction>(Replacements[V].second);
1952 if (Replacement)
1953 (new StoreInst(Replacement, Alloca))->insertAfter(Replacement);
1954 }
1955
1956 // apply mem2reg to promote alloca to SSA
Philip Reames704e78b2015-04-10 22:34:56 +00001957 SmallVector<AllocaInst *, 16> Allocas;
Philip Reames8531d8c2015-04-10 21:48:25 +00001958 for (Value *V : ToSplit)
1959 Allocas.push_back(AllocaMap[V]);
1960 PromoteMemToReg(Allocas, DT);
Philip Reames8fe7f132015-06-26 22:47:37 +00001961
1962 // Update our tracking of live pointers and base mappings to account for the
1963 // changes we just made.
1964 for (Value *V : ToSplit) {
1965 auto &Elements = ElementMapping[V];
1966
1967 LiveSet.erase(V);
1968 LiveSet.insert(Elements.begin(), Elements.end());
1969 // We need to update the base mapping as well.
1970 assert(PointerToBase.count(V));
1971 Value *OldBase = PointerToBase[V];
1972 auto &BaseElements = ElementMapping[OldBase];
1973 PointerToBase.erase(V);
1974 assert(Elements.size() == BaseElements.size());
1975 for (unsigned i = 0; i < Elements.size(); i++) {
1976 Value *Elem = Elements[i];
1977 PointerToBase[Elem] = BaseElements[i];
1978 }
1979 }
Philip Reames8531d8c2015-04-10 21:48:25 +00001980}
1981
Igor Laevskye0317182015-05-19 15:59:05 +00001982// Helper function for the "rematerializeLiveValues". It walks use chain
1983// starting from the "CurrentValue" until it meets "BaseValue". Only "simple"
1984// values are visited (currently it is GEP's and casts). Returns true if it
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001985// successfully reached "BaseValue" and false otherwise.
Igor Laevskye0317182015-05-19 15:59:05 +00001986// Fills "ChainToBase" array with all visited values. "BaseValue" is not
1987// recorded.
1988static bool findRematerializableChainToBasePointer(
1989 SmallVectorImpl<Instruction*> &ChainToBase,
1990 Value *CurrentValue, Value *BaseValue) {
1991
1992 // We have found a base value
1993 if (CurrentValue == BaseValue) {
1994 return true;
1995 }
1996
1997 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurrentValue)) {
1998 ChainToBase.push_back(GEP);
1999 return findRematerializableChainToBasePointer(ChainToBase,
2000 GEP->getPointerOperand(),
2001 BaseValue);
2002 }
2003
2004 if (CastInst *CI = dyn_cast<CastInst>(CurrentValue)) {
2005 Value *Def = CI->stripPointerCasts();
2006
2007 // This two checks are basically similar. First one is here for the
2008 // consistency with findBasePointers logic.
2009 assert(!isa<CastInst>(Def) && "not a pointer cast found");
2010 if (!CI->isNoopCast(CI->getModule()->getDataLayout()))
2011 return false;
2012
2013 ChainToBase.push_back(CI);
2014 return findRematerializableChainToBasePointer(ChainToBase, Def, BaseValue);
2015 }
2016
2017 // Not supported instruction in the chain
2018 return false;
2019}
2020
2021// Helper function for the "rematerializeLiveValues". Compute cost of the use
2022// chain we are going to rematerialize.
2023static unsigned
2024chainToBasePointerCost(SmallVectorImpl<Instruction*> &Chain,
2025 TargetTransformInfo &TTI) {
2026 unsigned Cost = 0;
2027
2028 for (Instruction *Instr : Chain) {
2029 if (CastInst *CI = dyn_cast<CastInst>(Instr)) {
2030 assert(CI->isNoopCast(CI->getModule()->getDataLayout()) &&
2031 "non noop cast is found during rematerialization");
2032
2033 Type *SrcTy = CI->getOperand(0)->getType();
2034 Cost += TTI.getCastInstrCost(CI->getOpcode(), CI->getType(), SrcTy);
2035
2036 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Instr)) {
2037 // Cost of the address calculation
2038 Type *ValTy = GEP->getPointerOperandType()->getPointerElementType();
2039 Cost += TTI.getAddressComputationCost(ValTy);
2040
2041 // And cost of the GEP itself
2042 // TODO: Use TTI->getGEPCost here (it exists, but appears to be not
2043 // allowed for the external usage)
2044 if (!GEP->hasAllConstantIndices())
2045 Cost += 2;
2046
2047 } else {
2048 llvm_unreachable("unsupported instruciton type during rematerialization");
2049 }
2050 }
2051
2052 return Cost;
2053}
2054
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002055// From the statepoint live set pick values that are cheaper to recompute then
2056// to relocate. Remove this values from the live set, rematerialize them after
Igor Laevskye0317182015-05-19 15:59:05 +00002057// statepoint and record them in "Info" structure. Note that similar to
2058// relocated values we don't do any user adjustments here.
2059static void rematerializeLiveValues(CallSite CS,
2060 PartiallyConstructedSafepointRecord &Info,
2061 TargetTransformInfo &TTI) {
Aaron Ballmanff7d4fa2015-05-20 14:53:50 +00002062 const unsigned int ChainLengthThreshold = 10;
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +00002063
Igor Laevskye0317182015-05-19 15:59:05 +00002064 // Record values we are going to delete from this statepoint live set.
2065 // We can not di this in following loop due to iterator invalidation.
2066 SmallVector<Value *, 32> LiveValuesToBeDeleted;
2067
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002068 for (Value *LiveValue: Info.LiveSet) {
Igor Laevskye0317182015-05-19 15:59:05 +00002069 // For each live pointer find it's defining chain
2070 SmallVector<Instruction *, 3> ChainToBase;
Philip Reames74ce2e72015-07-21 16:51:17 +00002071 assert(Info.PointerToBase.count(LiveValue));
Igor Laevskye0317182015-05-19 15:59:05 +00002072 bool FoundChain =
2073 findRematerializableChainToBasePointer(ChainToBase,
2074 LiveValue,
2075 Info.PointerToBase[LiveValue]);
2076 // Nothing to do, or chain is too long
2077 if (!FoundChain ||
2078 ChainToBase.size() == 0 ||
2079 ChainToBase.size() > ChainLengthThreshold)
2080 continue;
2081
2082 // Compute cost of this chain
2083 unsigned Cost = chainToBasePointerCost(ChainToBase, TTI);
2084 // TODO: We can also account for cases when we will be able to remove some
2085 // of the rematerialized values by later optimization passes. I.e if
2086 // we rematerialized several intersecting chains. Or if original values
2087 // don't have any uses besides this statepoint.
2088
2089 // For invokes we need to rematerialize each chain twice - for normal and
2090 // for unwind basic blocks. Model this by multiplying cost by two.
2091 if (CS.isInvoke()) {
2092 Cost *= 2;
2093 }
2094 // If it's too expensive - skip it
2095 if (Cost >= RematerializationThreshold)
2096 continue;
2097
2098 // Remove value from the live set
2099 LiveValuesToBeDeleted.push_back(LiveValue);
2100
2101 // Clone instructions and record them inside "Info" structure
2102
2103 // Walk backwards to visit top-most instructions first
2104 std::reverse(ChainToBase.begin(), ChainToBase.end());
2105
2106 // Utility function which clones all instructions from "ChainToBase"
2107 // and inserts them before "InsertBefore". Returns rematerialized value
2108 // which should be used after statepoint.
2109 auto rematerializeChain = [&ChainToBase](Instruction *InsertBefore) {
2110 Instruction *LastClonedValue = nullptr;
2111 Instruction *LastValue = nullptr;
2112 for (Instruction *Instr: ChainToBase) {
2113 // Only GEP's and casts are suported as we need to be careful to not
2114 // introduce any new uses of pointers not in the liveset.
2115 // Note that it's fine to introduce new uses of pointers which were
2116 // otherwise not used after this statepoint.
2117 assert(isa<GetElementPtrInst>(Instr) || isa<CastInst>(Instr));
2118
2119 Instruction *ClonedValue = Instr->clone();
2120 ClonedValue->insertBefore(InsertBefore);
2121 ClonedValue->setName(Instr->getName() + ".remat");
2122
2123 // If it is not first instruction in the chain then it uses previously
2124 // cloned value. We should update it to use cloned value.
2125 if (LastClonedValue) {
2126 assert(LastValue);
2127 ClonedValue->replaceUsesOfWith(LastValue, LastClonedValue);
2128#ifndef NDEBUG
Igor Laevskyd83f6972015-05-21 13:02:14 +00002129 // Assert that cloned instruction does not use any instructions from
2130 // this chain other than LastClonedValue
2131 for (auto OpValue : ClonedValue->operand_values()) {
2132 assert(std::find(ChainToBase.begin(), ChainToBase.end(), OpValue) ==
2133 ChainToBase.end() &&
2134 "incorrect use in rematerialization chain");
Igor Laevskye0317182015-05-19 15:59:05 +00002135 }
2136#endif
2137 }
2138
2139 LastClonedValue = ClonedValue;
2140 LastValue = Instr;
2141 }
2142 assert(LastClonedValue);
2143 return LastClonedValue;
2144 };
2145
2146 // Different cases for calls and invokes. For invokes we need to clone
2147 // instructions both on normal and unwind path.
2148 if (CS.isCall()) {
2149 Instruction *InsertBefore = CS.getInstruction()->getNextNode();
2150 assert(InsertBefore);
2151 Instruction *RematerializedValue = rematerializeChain(InsertBefore);
2152 Info.RematerializedValues[RematerializedValue] = LiveValue;
2153 } else {
2154 InvokeInst *Invoke = cast<InvokeInst>(CS.getInstruction());
2155
2156 Instruction *NormalInsertBefore =
2157 Invoke->getNormalDest()->getFirstInsertionPt();
2158 Instruction *UnwindInsertBefore =
2159 Invoke->getUnwindDest()->getFirstInsertionPt();
2160
2161 Instruction *NormalRematerializedValue =
2162 rematerializeChain(NormalInsertBefore);
2163 Instruction *UnwindRematerializedValue =
2164 rematerializeChain(UnwindInsertBefore);
2165
2166 Info.RematerializedValues[NormalRematerializedValue] = LiveValue;
2167 Info.RematerializedValues[UnwindRematerializedValue] = LiveValue;
2168 }
2169 }
2170
2171 // Remove rematerializaed values from the live set
2172 for (auto LiveValue: LiveValuesToBeDeleted) {
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002173 Info.LiveSet.erase(LiveValue);
Igor Laevskye0317182015-05-19 15:59:05 +00002174 }
2175}
2176
Philip Reamesd16a9b12015-02-20 01:06:44 +00002177static bool insertParsePoints(Function &F, DominatorTree &DT, Pass *P,
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002178 SmallVectorImpl<CallSite> &ToUpdate) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00002179#ifndef NDEBUG
2180 // sanity check the input
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002181 std::set<CallSite> Uniqued;
2182 Uniqued.insert(ToUpdate.begin(), ToUpdate.end());
2183 assert(Uniqued.size() == ToUpdate.size() && "no duplicates please!");
Philip Reamesd16a9b12015-02-20 01:06:44 +00002184
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002185 for (CallSite CS : ToUpdate) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00002186 assert(CS.getInstruction()->getParent()->getParent() == &F);
2187 assert(isStatepoint(CS) && "expected to already be a deopt statepoint");
2188 }
2189#endif
2190
Philip Reames69e51ca2015-04-13 18:07:21 +00002191 // When inserting gc.relocates for invokes, we need to be able to insert at
2192 // the top of the successor blocks. See the comment on
2193 // normalForInvokeSafepoint on exactly what is needed. Note that this step
Philip Reamesf209a152015-04-13 20:00:30 +00002194 // may restructure the CFG.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002195 for (CallSite CS : ToUpdate) {
Philip Reamesf209a152015-04-13 20:00:30 +00002196 if (!CS.isInvoke())
2197 continue;
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002198 auto *II = cast<InvokeInst>(CS.getInstruction());
2199 normalizeForInvokeSafepoint(II->getNormalDest(), II->getParent(), DT);
2200 normalizeForInvokeSafepoint(II->getUnwindDest(), II->getParent(), DT);
Philip Reamesf209a152015-04-13 20:00:30 +00002201 }
Philip Reames69e51ca2015-04-13 18:07:21 +00002202
Philip Reamesd16a9b12015-02-20 01:06:44 +00002203 // A list of dummy calls added to the IR to keep various values obviously
2204 // live in the IR. We'll remove all of these when done.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002205 SmallVector<CallInst *, 64> Holders;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002206
2207 // Insert a dummy call with all of the arguments to the vm_state we'll need
2208 // for the actual safepoint insertion. This ensures reference arguments in
2209 // the deopt argument list are considered live through the safepoint (and
2210 // thus makes sure they get relocated.)
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002211 for (CallSite CS : ToUpdate) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00002212 Statepoint StatepointCS(CS);
2213
2214 SmallVector<Value *, 64> DeoptValues;
2215 for (Use &U : StatepointCS.vm_state_args()) {
2216 Value *Arg = cast<Value>(&U);
Philip Reames8531d8c2015-04-10 21:48:25 +00002217 assert(!isUnhandledGCPointerType(Arg->getType()) &&
2218 "support for FCA unimplemented");
2219 if (isHandledGCPointerType(Arg->getType()))
Philip Reamesd16a9b12015-02-20 01:06:44 +00002220 DeoptValues.push_back(Arg);
2221 }
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002222 insertUseHolderAfter(CS, DeoptValues, Holders);
Philip Reamesd16a9b12015-02-20 01:06:44 +00002223 }
2224
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002225 SmallVector<PartiallyConstructedSafepointRecord, 64> Records(ToUpdate.size());
Philip Reamesd16a9b12015-02-20 01:06:44 +00002226
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002227 // A) Identify all gc pointers which are statically live at the given call
Philip Reamesd16a9b12015-02-20 01:06:44 +00002228 // site.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002229 findLiveReferences(F, DT, P, ToUpdate, Records);
Philip Reamesd16a9b12015-02-20 01:06:44 +00002230
2231 // B) Find the base pointers for each live pointer
2232 /* scope for caching */ {
2233 // Cache the 'defining value' relation used in the computation and
2234 // insertion of base phis and selects. This ensures that we don't insert
2235 // large numbers of duplicate base_phis.
2236 DefiningValueMapTy DVCache;
2237
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002238 for (size_t i = 0; i < Records.size(); i++) {
2239 PartiallyConstructedSafepointRecord &info = Records[i];
2240 findBasePointers(DT, DVCache, ToUpdate[i], info);
Philip Reamesd16a9b12015-02-20 01:06:44 +00002241 }
2242 } // end of cache scope
2243
2244 // The base phi insertion logic (for any safepoint) may have inserted new
2245 // instructions which are now live at some safepoint. The simplest such
2246 // example is:
2247 // loop:
2248 // phi a <-- will be a new base_phi here
2249 // safepoint 1 <-- that needs to be live here
2250 // gep a + 1
2251 // safepoint 2
2252 // br loop
Philip Reamesd16a9b12015-02-20 01:06:44 +00002253 // We insert some dummy calls after each safepoint to definitely hold live
2254 // the base pointers which were identified for that safepoint. We'll then
2255 // ask liveness for _every_ base inserted to see what is now live. Then we
2256 // remove the dummy calls.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002257 Holders.reserve(Holders.size() + Records.size());
2258 for (size_t i = 0; i < Records.size(); i++) {
2259 PartiallyConstructedSafepointRecord &Info = Records[i];
Philip Reamesd16a9b12015-02-20 01:06:44 +00002260
2261 SmallVector<Value *, 128> Bases;
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002262 for (auto Pair : Info.PointerToBase)
Philip Reamesd16a9b12015-02-20 01:06:44 +00002263 Bases.push_back(Pair.second);
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002264
2265 insertUseHolderAfter(ToUpdate[i], Bases, Holders);
Philip Reamesd16a9b12015-02-20 01:06:44 +00002266 }
2267
Philip Reamesdf1ef082015-04-10 22:53:14 +00002268 // By selecting base pointers, we've effectively inserted new uses. Thus, we
2269 // need to rerun liveness. We may *also* have inserted new defs, but that's
2270 // not the key issue.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002271 recomputeLiveInValues(F, DT, P, ToUpdate, Records);
Philip Reamesd16a9b12015-02-20 01:06:44 +00002272
Philip Reamesd16a9b12015-02-20 01:06:44 +00002273 if (PrintBasePointers) {
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002274 for (auto &Info : Records) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00002275 errs() << "Base Pairs: (w/Relocation)\n";
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002276 for (auto Pair : Info.PointerToBase)
Philip Reamesd16a9b12015-02-20 01:06:44 +00002277 errs() << " derived %" << Pair.first->getName() << " base %"
2278 << Pair.second->getName() << "\n";
Philip Reamesd16a9b12015-02-20 01:06:44 +00002279 }
2280 }
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002281
2282 for (CallInst *CI : Holders)
2283 CI->eraseFromParent();
2284
2285 Holders.clear();
Philip Reamesd16a9b12015-02-20 01:06:44 +00002286
Philip Reames8fe7f132015-06-26 22:47:37 +00002287 // Do a limited scalarization of any live at safepoint vector values which
2288 // contain pointers. This enables this pass to run after vectorization at
2289 // the cost of some possible performance loss. TODO: it would be nice to
2290 // natively support vectors all the way through the backend so we don't need
2291 // to scalarize here.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002292 for (size_t i = 0; i < Records.size(); i++) {
2293 PartiallyConstructedSafepointRecord &Info = Records[i];
2294 Instruction *Statepoint = ToUpdate[i].getInstruction();
2295 splitVectorValues(cast<Instruction>(Statepoint), Info.LiveSet,
2296 Info.PointerToBase, DT);
Philip Reames8fe7f132015-06-26 22:47:37 +00002297 }
2298
Igor Laevskye0317182015-05-19 15:59:05 +00002299 // In order to reduce live set of statepoint we might choose to rematerialize
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002300 // some values instead of relocating them. This is purely an optimization and
Igor Laevskye0317182015-05-19 15:59:05 +00002301 // does not influence correctness.
2302 TargetTransformInfo &TTI =
2303 P->getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
2304
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002305 for (size_t i = 0; i < Records.size(); i++)
2306 rematerializeLiveValues(ToUpdate[i], Records[i], TTI);
Igor Laevskye0317182015-05-19 15:59:05 +00002307
Philip Reamesd16a9b12015-02-20 01:06:44 +00002308 // Now run through and replace the existing statepoints with new ones with
2309 // the live variables listed. We do not yet update uses of the values being
2310 // relocated. We have references to live variables that need to
2311 // survive to the last iteration of this loop. (By construction, the
2312 // previous statepoint can not be a live variable, thus we can and remove
2313 // the old statepoint calls as we go.)
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002314 for (size_t i = 0; i < Records.size(); i++)
2315 makeStatepointExplicit(DT, ToUpdate[i], Records[i]);
2316
2317 ToUpdate.clear(); // prevent accident use of invalid CallSites
Philip Reamesd16a9b12015-02-20 01:06:44 +00002318
Philip Reamesd16a9b12015-02-20 01:06:44 +00002319 // Do all the fixups of the original live variables to their relocated selves
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002320 SmallVector<Value *, 128> Live;
2321 for (size_t i = 0; i < Records.size(); i++) {
2322 PartiallyConstructedSafepointRecord &Info = Records[i];
Philip Reamesd16a9b12015-02-20 01:06:44 +00002323 // We can't simply save the live set from the original insertion. One of
2324 // the live values might be the result of a call which needs a safepoint.
2325 // That Value* no longer exists and we need to use the new gc_result.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002326 // Thankfully, the live set is embedded in the statepoint (and updated), so
Philip Reamesd16a9b12015-02-20 01:06:44 +00002327 // we just grab that.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002328 Statepoint Statepoint(Info.StatepointToken);
2329 Live.insert(Live.end(), Statepoint.gc_args_begin(),
2330 Statepoint.gc_args_end());
Philip Reames9a2e01d2015-04-13 17:35:55 +00002331#ifndef NDEBUG
2332 // Do some basic sanity checks on our liveness results before performing
2333 // relocation. Relocation can and will turn mistakes in liveness results
2334 // into non-sensical code which is must harder to debug.
2335 // TODO: It would be nice to test consistency as well
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002336 assert(DT.isReachableFromEntry(Info.StatepointToken->getParent()) &&
Philip Reames9a2e01d2015-04-13 17:35:55 +00002337 "statepoint must be reachable or liveness is meaningless");
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002338 for (Value *V : Statepoint.gc_args()) {
Philip Reames9a2e01d2015-04-13 17:35:55 +00002339 if (!isa<Instruction>(V))
2340 // Non-instruction values trivial dominate all possible uses
2341 continue;
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002342 auto *LiveInst = cast<Instruction>(V);
Philip Reames9a2e01d2015-04-13 17:35:55 +00002343 assert(DT.isReachableFromEntry(LiveInst->getParent()) &&
2344 "unreachable values should never be live");
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002345 assert(DT.dominates(LiveInst, Info.StatepointToken) &&
Philip Reames9a2e01d2015-04-13 17:35:55 +00002346 "basic SSA liveness expectation violated by liveness analysis");
2347 }
2348#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +00002349 }
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002350 unique_unsorted(Live);
Philip Reamesd16a9b12015-02-20 01:06:44 +00002351
Nick Lewyckyeb3231e2015-02-20 07:14:02 +00002352#ifndef NDEBUG
Philip Reamesd16a9b12015-02-20 01:06:44 +00002353 // sanity check
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002354 for (auto *Ptr : Live)
2355 assert(isGCPointerType(Ptr->getType()) && "must be a gc pointer type");
Nick Lewyckyeb3231e2015-02-20 07:14:02 +00002356#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +00002357
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002358 relocationViaAlloca(F, DT, Live, Records);
2359 return !Records.empty();
Philip Reamesd16a9b12015-02-20 01:06:44 +00002360}
2361
Sanjoy Das353a19e2015-06-02 22:33:37 +00002362// Handles both return values and arguments for Functions and CallSites.
2363template <typename AttrHolder>
2364static void RemoveDerefAttrAtIndex(LLVMContext &Ctx, AttrHolder &AH,
2365 unsigned Index) {
2366 AttrBuilder R;
2367 if (AH.getDereferenceableBytes(Index))
2368 R.addAttribute(Attribute::get(Ctx, Attribute::Dereferenceable,
2369 AH.getDereferenceableBytes(Index)));
2370 if (AH.getDereferenceableOrNullBytes(Index))
2371 R.addAttribute(Attribute::get(Ctx, Attribute::DereferenceableOrNull,
2372 AH.getDereferenceableOrNullBytes(Index)));
2373
2374 if (!R.empty())
2375 AH.setAttributes(AH.getAttributes().removeAttributes(
2376 Ctx, Index, AttributeSet::get(Ctx, Index, R)));
Vasileios Kalintiris9f77f612015-06-03 08:51:30 +00002377}
Sanjoy Das353a19e2015-06-02 22:33:37 +00002378
2379void
2380RewriteStatepointsForGC::stripDereferenceabilityInfoFromPrototype(Function &F) {
2381 LLVMContext &Ctx = F.getContext();
2382
2383 for (Argument &A : F.args())
2384 if (isa<PointerType>(A.getType()))
2385 RemoveDerefAttrAtIndex(Ctx, F, A.getArgNo() + 1);
2386
2387 if (isa<PointerType>(F.getReturnType()))
2388 RemoveDerefAttrAtIndex(Ctx, F, AttributeSet::ReturnIndex);
2389}
2390
2391void RewriteStatepointsForGC::stripDereferenceabilityInfoFromBody(Function &F) {
2392 if (F.empty())
2393 return;
2394
2395 LLVMContext &Ctx = F.getContext();
2396 MDBuilder Builder(Ctx);
2397
Nico Rieck78199512015-08-06 19:10:45 +00002398 for (Instruction &I : instructions(F)) {
Sanjoy Das353a19e2015-06-02 22:33:37 +00002399 if (const MDNode *MD = I.getMetadata(LLVMContext::MD_tbaa)) {
2400 assert(MD->getNumOperands() < 5 && "unrecognized metadata shape!");
2401 bool IsImmutableTBAA =
2402 MD->getNumOperands() == 4 &&
2403 mdconst::extract<ConstantInt>(MD->getOperand(3))->getValue() == 1;
2404
2405 if (!IsImmutableTBAA)
2406 continue; // no work to do, MD_tbaa is already marked mutable
2407
2408 MDNode *Base = cast<MDNode>(MD->getOperand(0));
2409 MDNode *Access = cast<MDNode>(MD->getOperand(1));
2410 uint64_t Offset =
2411 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue();
2412
2413 MDNode *MutableTBAA =
2414 Builder.createTBAAStructTagNode(Base, Access, Offset);
2415 I.setMetadata(LLVMContext::MD_tbaa, MutableTBAA);
2416 }
2417
2418 if (CallSite CS = CallSite(&I)) {
2419 for (int i = 0, e = CS.arg_size(); i != e; i++)
2420 if (isa<PointerType>(CS.getArgument(i)->getType()))
2421 RemoveDerefAttrAtIndex(Ctx, CS, i + 1);
2422 if (isa<PointerType>(CS.getType()))
2423 RemoveDerefAttrAtIndex(Ctx, CS, AttributeSet::ReturnIndex);
2424 }
2425 }
2426}
2427
Philip Reamesd16a9b12015-02-20 01:06:44 +00002428/// Returns true if this function should be rewritten by this pass. The main
2429/// point of this function is as an extension point for custom logic.
2430static bool shouldRewriteStatepointsIn(Function &F) {
2431 // TODO: This should check the GCStrategy
Philip Reames2ef029c2015-02-20 18:56:14 +00002432 if (F.hasGC()) {
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +00002433 const char *FunctionGCName = F.getGC();
2434 const StringRef StatepointExampleName("statepoint-example");
2435 const StringRef CoreCLRName("coreclr");
2436 return (StatepointExampleName == FunctionGCName) ||
NAKAMURA Takumi5582a6a2015-05-25 01:43:34 +00002437 (CoreCLRName == FunctionGCName);
2438 } else
Philip Reames2ef029c2015-02-20 18:56:14 +00002439 return false;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002440}
2441
Sanjoy Das353a19e2015-06-02 22:33:37 +00002442void RewriteStatepointsForGC::stripDereferenceabilityInfo(Module &M) {
2443#ifndef NDEBUG
2444 assert(std::any_of(M.begin(), M.end(), shouldRewriteStatepointsIn) &&
2445 "precondition!");
2446#endif
2447
2448 for (Function &F : M)
2449 stripDereferenceabilityInfoFromPrototype(F);
2450
2451 for (Function &F : M)
2452 stripDereferenceabilityInfoFromBody(F);
2453}
2454
Philip Reamesd16a9b12015-02-20 01:06:44 +00002455bool RewriteStatepointsForGC::runOnFunction(Function &F) {
2456 // Nothing to do for declarations.
2457 if (F.isDeclaration() || F.empty())
2458 return false;
2459
2460 // Policy choice says not to rewrite - the most common reason is that we're
2461 // compiling code without a GCStrategy.
2462 if (!shouldRewriteStatepointsIn(F))
2463 return false;
2464
Sanjoy Dasea45f0e2015-06-02 22:33:34 +00002465 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
Philip Reames704e78b2015-04-10 22:34:56 +00002466
Philip Reames85b36a82015-04-10 22:07:04 +00002467 // Gather all the statepoints which need rewritten. Be careful to only
2468 // consider those in reachable code since we need to ask dominance queries
2469 // when rewriting. We'll delete the unreachable ones in a moment.
Philip Reamesd2b66462015-02-20 22:39:41 +00002470 SmallVector<CallSite, 64> ParsePointNeeded;
Philip Reamesf66d7372015-04-10 22:16:58 +00002471 bool HasUnreachableStatepoint = false;
Nico Rieck78199512015-08-06 19:10:45 +00002472 for (Instruction &I : instructions(F)) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00002473 // TODO: only the ones with the flag set!
Philip Reames85b36a82015-04-10 22:07:04 +00002474 if (isStatepoint(I)) {
2475 if (DT.isReachableFromEntry(I.getParent()))
2476 ParsePointNeeded.push_back(CallSite(&I));
2477 else
Philip Reamesf66d7372015-04-10 22:16:58 +00002478 HasUnreachableStatepoint = true;
Philip Reames85b36a82015-04-10 22:07:04 +00002479 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00002480 }
2481
Philip Reames85b36a82015-04-10 22:07:04 +00002482 bool MadeChange = false;
Philip Reames704e78b2015-04-10 22:34:56 +00002483
Philip Reames85b36a82015-04-10 22:07:04 +00002484 // Delete any unreachable statepoints so that we don't have unrewritten
2485 // statepoints surviving this pass. This makes testing easier and the
2486 // resulting IR less confusing to human readers. Rather than be fancy, we
2487 // just reuse a utility function which removes the unreachable blocks.
Philip Reamesf66d7372015-04-10 22:16:58 +00002488 if (HasUnreachableStatepoint)
Philip Reames85b36a82015-04-10 22:07:04 +00002489 MadeChange |= removeUnreachableBlocks(F);
2490
Philip Reamesd16a9b12015-02-20 01:06:44 +00002491 // Return early if no work to do.
2492 if (ParsePointNeeded.empty())
Philip Reames85b36a82015-04-10 22:07:04 +00002493 return MadeChange;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002494
Philip Reames85b36a82015-04-10 22:07:04 +00002495 // As a prepass, go ahead and aggressively destroy single entry phi nodes.
2496 // These are created by LCSSA. They have the effect of increasing the size
2497 // of liveness sets for no good reason. It may be harder to do this post
2498 // insertion since relocations and base phis can confuse things.
2499 for (BasicBlock &BB : F)
2500 if (BB.getUniquePredecessor()) {
2501 MadeChange = true;
2502 FoldSingleEntryPHINodes(&BB);
2503 }
2504
Philip Reames971dc3a2015-08-12 22:11:45 +00002505 // Before we start introducing relocations, we want to tweak the IR a bit to
2506 // avoid unfortunate code generation effects. The main example is that we
2507 // want to try to make sure the comparison feeding a branch is after any
2508 // safepoints. Otherwise, we end up with a comparison of pre-relocation
2509 // values feeding a branch after relocation. This is semantically correct,
2510 // but results in extra register pressure since both the pre-relocation and
2511 // post-relocation copies must be available in registers. For code without
2512 // relocations this is handled elsewhere, but teaching the scheduler to
2513 // reverse the transform we're about to do would be slightly complex.
2514 // Note: This may extend the live range of the inputs to the icmp and thus
2515 // increase the liveset of any statepoint we move over. This is profitable
2516 // as long as all statepoints are in rare blocks. If we had in-register
2517 // lowering for live values this would be a much safer transform.
2518 auto getConditionInst = [](TerminatorInst *TI) -> Instruction* {
2519 if (auto *BI = dyn_cast<BranchInst>(TI))
2520 if (BI->isConditional())
2521 return dyn_cast<Instruction>(BI->getCondition());
2522 // TODO: Extend this to handle switches
2523 return nullptr;
2524 };
2525 for (BasicBlock &BB : F) {
2526 TerminatorInst *TI = BB.getTerminator();
2527 if (auto *Cond = getConditionInst(TI))
2528 // TODO: Handle more than just ICmps here. We should be able to move
2529 // most instructions without side effects or memory access.
2530 if (isa<ICmpInst>(Cond) && Cond->hasOneUse()) {
2531 MadeChange = true;
2532 Cond->moveBefore(TI);
2533 }
2534 }
2535
Philip Reames85b36a82015-04-10 22:07:04 +00002536 MadeChange |= insertParsePoints(F, DT, this, ParsePointNeeded);
2537 return MadeChange;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002538}
Philip Reamesdf1ef082015-04-10 22:53:14 +00002539
2540// liveness computation via standard dataflow
2541// -------------------------------------------------------------------
2542
2543// TODO: Consider using bitvectors for liveness, the set of potentially
2544// interesting values should be small and easy to pre-compute.
2545
Philip Reamesdf1ef082015-04-10 22:53:14 +00002546/// Compute the live-in set for the location rbegin starting from
2547/// the live-out set of the basic block
2548static void computeLiveInValues(BasicBlock::reverse_iterator rbegin,
2549 BasicBlock::reverse_iterator rend,
2550 DenseSet<Value *> &LiveTmp) {
2551
2552 for (BasicBlock::reverse_iterator ritr = rbegin; ritr != rend; ritr++) {
2553 Instruction *I = &*ritr;
2554
2555 // KILL/Def - Remove this definition from LiveIn
2556 LiveTmp.erase(I);
2557
2558 // Don't consider *uses* in PHI nodes, we handle their contribution to
2559 // predecessor blocks when we seed the LiveOut sets
2560 if (isa<PHINode>(I))
2561 continue;
2562
2563 // USE - Add to the LiveIn set for this instruction
2564 for (Value *V : I->operands()) {
2565 assert(!isUnhandledGCPointerType(V->getType()) &&
2566 "support for FCA unimplemented");
Philip Reames63294cb2015-04-26 19:48:03 +00002567 if (isHandledGCPointerType(V->getType()) && !isa<Constant>(V)) {
2568 // The choice to exclude all things constant here is slightly subtle.
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002569 // There are two independent reasons:
Philip Reames63294cb2015-04-26 19:48:03 +00002570 // - We assume that things which are constant (from LLVM's definition)
2571 // do not move at runtime. For example, the address of a global
2572 // variable is fixed, even though it's contents may not be.
2573 // - Second, we can't disallow arbitrary inttoptr constants even
2574 // if the language frontend does. Optimization passes are free to
2575 // locally exploit facts without respect to global reachability. This
2576 // can create sections of code which are dynamically unreachable and
2577 // contain just about anything. (see constants.ll in tests)
Philip Reamesdf1ef082015-04-10 22:53:14 +00002578 LiveTmp.insert(V);
2579 }
2580 }
2581 }
2582}
2583
2584static void computeLiveOutSeed(BasicBlock *BB, DenseSet<Value *> &LiveTmp) {
2585
2586 for (BasicBlock *Succ : successors(BB)) {
2587 const BasicBlock::iterator E(Succ->getFirstNonPHI());
2588 for (BasicBlock::iterator I = Succ->begin(); I != E; I++) {
2589 PHINode *Phi = cast<PHINode>(&*I);
2590 Value *V = Phi->getIncomingValueForBlock(BB);
2591 assert(!isUnhandledGCPointerType(V->getType()) &&
2592 "support for FCA unimplemented");
Philip Reames63294cb2015-04-26 19:48:03 +00002593 if (isHandledGCPointerType(V->getType()) && !isa<Constant>(V)) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00002594 LiveTmp.insert(V);
2595 }
2596 }
2597 }
2598}
2599
2600static DenseSet<Value *> computeKillSet(BasicBlock *BB) {
2601 DenseSet<Value *> KillSet;
2602 for (Instruction &I : *BB)
2603 if (isHandledGCPointerType(I.getType()))
2604 KillSet.insert(&I);
2605 return KillSet;
2606}
2607
Philip Reames9638ff92015-04-11 00:06:47 +00002608#ifndef NDEBUG
Philip Reamesdf1ef082015-04-10 22:53:14 +00002609/// Check that the items in 'Live' dominate 'TI'. This is used as a basic
2610/// sanity check for the liveness computation.
2611static void checkBasicSSA(DominatorTree &DT, DenseSet<Value *> &Live,
2612 TerminatorInst *TI, bool TermOkay = false) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00002613 for (Value *V : Live) {
2614 if (auto *I = dyn_cast<Instruction>(V)) {
2615 // The terminator can be a member of the LiveOut set. LLVM's definition
2616 // of instruction dominance states that V does not dominate itself. As
2617 // such, we need to special case this to allow it.
2618 if (TermOkay && TI == I)
2619 continue;
2620 assert(DT.dominates(I, TI) &&
2621 "basic SSA liveness expectation violated by liveness analysis");
2622 }
2623 }
Philip Reamesdf1ef082015-04-10 22:53:14 +00002624}
2625
2626/// Check that all the liveness sets used during the computation of liveness
2627/// obey basic SSA properties. This is useful for finding cases where we miss
2628/// a def.
2629static void checkBasicSSA(DominatorTree &DT, GCPtrLivenessData &Data,
2630 BasicBlock &BB) {
2631 checkBasicSSA(DT, Data.LiveSet[&BB], BB.getTerminator());
2632 checkBasicSSA(DT, Data.LiveOut[&BB], BB.getTerminator(), true);
2633 checkBasicSSA(DT, Data.LiveIn[&BB], BB.getTerminator());
2634}
Philip Reames9638ff92015-04-11 00:06:47 +00002635#endif
Philip Reamesdf1ef082015-04-10 22:53:14 +00002636
2637static void computeLiveInValues(DominatorTree &DT, Function &F,
2638 GCPtrLivenessData &Data) {
2639
Philip Reames4d80ede2015-04-10 23:11:26 +00002640 SmallSetVector<BasicBlock *, 200> Worklist;
Philip Reamesdf1ef082015-04-10 22:53:14 +00002641 auto AddPredsToWorklist = [&](BasicBlock *BB) {
Philip Reames4d80ede2015-04-10 23:11:26 +00002642 // We use a SetVector so that we don't have duplicates in the worklist.
2643 Worklist.insert(pred_begin(BB), pred_end(BB));
Philip Reamesdf1ef082015-04-10 22:53:14 +00002644 };
2645 auto NextItem = [&]() {
2646 BasicBlock *BB = Worklist.back();
2647 Worklist.pop_back();
Philip Reamesdf1ef082015-04-10 22:53:14 +00002648 return BB;
2649 };
2650
2651 // Seed the liveness for each individual block
2652 for (BasicBlock &BB : F) {
2653 Data.KillSet[&BB] = computeKillSet(&BB);
2654 Data.LiveSet[&BB].clear();
2655 computeLiveInValues(BB.rbegin(), BB.rend(), Data.LiveSet[&BB]);
2656
2657#ifndef NDEBUG
2658 for (Value *Kill : Data.KillSet[&BB])
2659 assert(!Data.LiveSet[&BB].count(Kill) && "live set contains kill");
2660#endif
2661
2662 Data.LiveOut[&BB] = DenseSet<Value *>();
2663 computeLiveOutSeed(&BB, Data.LiveOut[&BB]);
2664 Data.LiveIn[&BB] = Data.LiveSet[&BB];
2665 set_union(Data.LiveIn[&BB], Data.LiveOut[&BB]);
2666 set_subtract(Data.LiveIn[&BB], Data.KillSet[&BB]);
2667 if (!Data.LiveIn[&BB].empty())
2668 AddPredsToWorklist(&BB);
2669 }
2670
2671 // Propagate that liveness until stable
2672 while (!Worklist.empty()) {
2673 BasicBlock *BB = NextItem();
2674
2675 // Compute our new liveout set, then exit early if it hasn't changed
2676 // despite the contribution of our successor.
2677 DenseSet<Value *> LiveOut = Data.LiveOut[BB];
2678 const auto OldLiveOutSize = LiveOut.size();
2679 for (BasicBlock *Succ : successors(BB)) {
2680 assert(Data.LiveIn.count(Succ));
2681 set_union(LiveOut, Data.LiveIn[Succ]);
2682 }
2683 // assert OutLiveOut is a subset of LiveOut
2684 if (OldLiveOutSize == LiveOut.size()) {
2685 // If the sets are the same size, then we didn't actually add anything
2686 // when unioning our successors LiveIn Thus, the LiveIn of this block
2687 // hasn't changed.
2688 continue;
2689 }
2690 Data.LiveOut[BB] = LiveOut;
2691
2692 // Apply the effects of this basic block
2693 DenseSet<Value *> LiveTmp = LiveOut;
2694 set_union(LiveTmp, Data.LiveSet[BB]);
2695 set_subtract(LiveTmp, Data.KillSet[BB]);
2696
2697 assert(Data.LiveIn.count(BB));
2698 const DenseSet<Value *> &OldLiveIn = Data.LiveIn[BB];
2699 // assert: OldLiveIn is a subset of LiveTmp
2700 if (OldLiveIn.size() != LiveTmp.size()) {
2701 Data.LiveIn[BB] = LiveTmp;
2702 AddPredsToWorklist(BB);
2703 }
2704 } // while( !worklist.empty() )
2705
2706#ifndef NDEBUG
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002707 // Sanity check our output against SSA properties. This helps catch any
Philip Reamesdf1ef082015-04-10 22:53:14 +00002708 // missing kills during the above iteration.
2709 for (BasicBlock &BB : F) {
2710 checkBasicSSA(DT, Data, BB);
2711 }
2712#endif
2713}
2714
2715static void findLiveSetAtInst(Instruction *Inst, GCPtrLivenessData &Data,
2716 StatepointLiveSetTy &Out) {
2717
2718 BasicBlock *BB = Inst->getParent();
2719
2720 // Note: The copy is intentional and required
2721 assert(Data.LiveOut.count(BB));
2722 DenseSet<Value *> LiveOut = Data.LiveOut[BB];
2723
2724 // We want to handle the statepoint itself oddly. It's
2725 // call result is not live (normal), nor are it's arguments
2726 // (unless they're used again later). This adjustment is
2727 // specifically what we need to relocate
2728 BasicBlock::reverse_iterator rend(Inst);
2729 computeLiveInValues(BB->rbegin(), rend, LiveOut);
2730 LiveOut.erase(Inst);
2731 Out.insert(LiveOut.begin(), LiveOut.end());
2732}
2733
2734static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData,
2735 const CallSite &CS,
2736 PartiallyConstructedSafepointRecord &Info) {
2737 Instruction *Inst = CS.getInstruction();
2738 StatepointLiveSetTy Updated;
2739 findLiveSetAtInst(Inst, RevisedLivenessData, Updated);
2740
2741#ifndef NDEBUG
2742 DenseSet<Value *> Bases;
2743 for (auto KVPair : Info.PointerToBase) {
2744 Bases.insert(KVPair.second);
2745 }
2746#endif
2747 // We may have base pointers which are now live that weren't before. We need
2748 // to update the PointerToBase structure to reflect this.
2749 for (auto V : Updated)
2750 if (!Info.PointerToBase.count(V)) {
2751 assert(Bases.count(V) && "can't find base for unexpected live value");
2752 Info.PointerToBase[V] = V;
2753 continue;
2754 }
2755
2756#ifndef NDEBUG
2757 for (auto V : Updated) {
2758 assert(Info.PointerToBase.count(V) &&
2759 "must be able to find base for live value");
2760 }
2761#endif
2762
2763 // Remove any stale base mappings - this can happen since our liveness is
2764 // more precise then the one inherent in the base pointer analysis
2765 DenseSet<Value *> ToErase;
2766 for (auto KVPair : Info.PointerToBase)
2767 if (!Updated.count(KVPair.first))
2768 ToErase.insert(KVPair.first);
2769 for (auto V : ToErase)
2770 Info.PointerToBase.erase(V);
2771
2772#ifndef NDEBUG
2773 for (auto KVPair : Info.PointerToBase)
2774 assert(Updated.count(KVPair.first) && "record for non-live value");
2775#endif
2776
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002777 Info.LiveSet = Updated;
Philip Reamesdf1ef082015-04-10 22:53:14 +00002778}