blob: 062fba5cdad8a6c12bfa850b989384564e089cae [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
Sanjoy Das25ec1a32015-10-16 02:41:00 +000075static cl::opt<bool> UseDeoptBundles("rs4gc-use-deopt-bundles", cl::Hidden,
76 cl::init(false));
77static cl::opt<bool>
78 AllowStatepointWithNoDeoptInfo("rs4gc-allow-statepoint-with-no-deopt-info",
79 cl::Hidden, cl::init(true));
80
Benjamin Kramer6f665452015-02-20 14:00:58 +000081namespace {
Sanjoy Dasea45f0e2015-06-02 22:33:34 +000082struct RewriteStatepointsForGC : public ModulePass {
Philip Reamesd16a9b12015-02-20 01:06:44 +000083 static char ID; // Pass identification, replacement for typeid
84
Sanjoy Dasea45f0e2015-06-02 22:33:34 +000085 RewriteStatepointsForGC() : ModulePass(ID) {
Philip Reamesd16a9b12015-02-20 01:06:44 +000086 initializeRewriteStatepointsForGCPass(*PassRegistry::getPassRegistry());
87 }
Sanjoy Dasea45f0e2015-06-02 22:33:34 +000088 bool runOnFunction(Function &F);
89 bool runOnModule(Module &M) override {
90 bool Changed = false;
91 for (Function &F : M)
92 Changed |= runOnFunction(F);
Sanjoy Das353a19e2015-06-02 22:33:37 +000093
94 if (Changed) {
Igor Laevskydde00292015-10-23 22:42:44 +000095 // stripNonValidAttributes asserts that shouldRewriteStatepointsIn
Sanjoy Das353a19e2015-06-02 22:33:37 +000096 // returns true for at least one function in the module. Since at least
97 // one function changed, we know that the precondition is satisfied.
Igor Laevskydde00292015-10-23 22:42:44 +000098 stripNonValidAttributes(M);
Sanjoy Das353a19e2015-06-02 22:33:37 +000099 }
100
Sanjoy Dasea45f0e2015-06-02 22:33:34 +0000101 return Changed;
102 }
Philip Reamesd16a9b12015-02-20 01:06:44 +0000103
104 void getAnalysisUsage(AnalysisUsage &AU) const override {
105 // We add and rewrite a bunch of instructions, but don't really do much
106 // else. We could in theory preserve a lot more analyses here.
107 AU.addRequired<DominatorTreeWrapperPass>();
Igor Laevskye0317182015-05-19 15:59:05 +0000108 AU.addRequired<TargetTransformInfoWrapperPass>();
Philip Reamesd16a9b12015-02-20 01:06:44 +0000109 }
Sanjoy Das353a19e2015-06-02 22:33:37 +0000110
111 /// The IR fed into RewriteStatepointsForGC may have had attributes implying
112 /// dereferenceability that are no longer valid/correct after
113 /// RewriteStatepointsForGC has run. This is because semantically, after
114 /// RewriteStatepointsForGC runs, all calls to gc.statepoint "free" the entire
Igor Laevskydde00292015-10-23 22:42:44 +0000115 /// heap. stripNonValidAttributes (conservatively) restores correctness
Sanjoy Das353a19e2015-06-02 22:33:37 +0000116 /// by erasing all attributes in the module that externally imply
117 /// dereferenceability.
Igor Laevsky1ef06552015-10-26 19:06:01 +0000118 /// Similar reasoning also applies to the noalias attributes. gc.statepoint
119 /// can touch the entire heap including noalias objects.
Igor Laevskydde00292015-10-23 22:42:44 +0000120 void stripNonValidAttributes(Module &M);
Sanjoy Das353a19e2015-06-02 22:33:37 +0000121
Igor Laevskydde00292015-10-23 22:42:44 +0000122 // Helpers for stripNonValidAttributes
123 void stripNonValidAttributesFromBody(Function &F);
124 void stripNonValidAttributesFromPrototype(Function &F);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000125};
Benjamin Kramer6f665452015-02-20 14:00:58 +0000126} // namespace
Philip Reamesd16a9b12015-02-20 01:06:44 +0000127
128char RewriteStatepointsForGC::ID = 0;
129
Sanjoy Dasea45f0e2015-06-02 22:33:34 +0000130ModulePass *llvm::createRewriteStatepointsForGCPass() {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000131 return new RewriteStatepointsForGC();
132}
133
134INITIALIZE_PASS_BEGIN(RewriteStatepointsForGC, "rewrite-statepoints-for-gc",
135 "Make relocations explicit at statepoints", false, false)
136INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
137INITIALIZE_PASS_END(RewriteStatepointsForGC, "rewrite-statepoints-for-gc",
138 "Make relocations explicit at statepoints", false, false)
139
140namespace {
Philip Reamesdf1ef082015-04-10 22:53:14 +0000141struct GCPtrLivenessData {
142 /// Values defined in this block.
143 DenseMap<BasicBlock *, DenseSet<Value *>> KillSet;
144 /// Values used in this block (and thus live); does not included values
145 /// killed within this block.
146 DenseMap<BasicBlock *, DenseSet<Value *>> LiveSet;
147
148 /// Values live into this basic block (i.e. used by any
149 /// instruction in this basic block or ones reachable from here)
150 DenseMap<BasicBlock *, DenseSet<Value *>> LiveIn;
151
152 /// Values live out of this basic block (i.e. live into
153 /// any successor block)
154 DenseMap<BasicBlock *, DenseSet<Value *>> LiveOut;
155};
156
Philip Reamesd16a9b12015-02-20 01:06:44 +0000157// The type of the internal cache used inside the findBasePointers family
158// of functions. From the callers perspective, this is an opaque type and
159// should not be inspected.
160//
161// In the actual implementation this caches two relations:
162// - The base relation itself (i.e. this pointer is based on that one)
163// - The base defining value relation (i.e. before base_phi insertion)
164// Generally, after the execution of a full findBasePointer call, only the
165// base relation will remain. Internally, we add a mixture of the two
166// types, then update all the second type to the first type
Philip Reamese9c3b9b2015-02-20 22:48:20 +0000167typedef DenseMap<Value *, Value *> DefiningValueMapTy;
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +0000168typedef DenseSet<Value *> StatepointLiveSetTy;
Sanjoy Das40bdd042015-10-07 21:32:35 +0000169typedef DenseMap<AssertingVH<Instruction>, AssertingVH<Value>>
170 RematerializedValueMapTy;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000171
Philip Reamesd16a9b12015-02-20 01:06:44 +0000172struct PartiallyConstructedSafepointRecord {
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000173 /// The set of values known to be live across this safepoint
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +0000174 StatepointLiveSetTy LiveSet;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000175
176 /// Mapping from live pointers to a base-defining-value
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +0000177 DenseMap<Value *, Value *> PointerToBase;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000178
Philip Reames0a3240f2015-02-20 21:34:11 +0000179 /// The *new* gc.statepoint instruction itself. This produces the token
180 /// that normal path gc.relocates and the gc.result are tied to.
181 Instruction *StatepointToken;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000182
Philip Reamesf2041322015-02-20 19:26:04 +0000183 /// Instruction to which exceptional gc relocates are attached
184 /// Makes it easier to iterate through them during relocationViaAlloca.
185 Instruction *UnwindToken;
Igor Laevskye0317182015-05-19 15:59:05 +0000186
187 /// Record live values we are rematerialized instead of relocating.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +0000188 /// They are not included into 'LiveSet' field.
Igor Laevskye0317182015-05-19 15:59:05 +0000189 /// Maps rematerialized copy to it's original value.
190 RematerializedValueMapTy RematerializedValues;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000191};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000192}
Philip Reamesd16a9b12015-02-20 01:06:44 +0000193
Sanjoy Das25ec1a32015-10-16 02:41:00 +0000194static ArrayRef<Use> GetDeoptBundleOperands(ImmutableCallSite CS) {
195 assert(UseDeoptBundles && "Should not be called otherwise!");
196
197 Optional<OperandBundleUse> DeoptBundle = CS.getOperandBundle("deopt");
198
199 if (!DeoptBundle.hasValue()) {
200 assert(AllowStatepointWithNoDeoptInfo &&
201 "Found non-leaf call without deopt info!");
202 return None;
203 }
204
205 return DeoptBundle.getValue().Inputs;
206}
207
Philip Reamesdf1ef082015-04-10 22:53:14 +0000208/// Compute the live-in set for every basic block in the function
209static void computeLiveInValues(DominatorTree &DT, Function &F,
210 GCPtrLivenessData &Data);
211
212/// Given results from the dataflow liveness computation, find the set of live
213/// Values at a particular instruction.
214static void findLiveSetAtInst(Instruction *inst, GCPtrLivenessData &Data,
215 StatepointLiveSetTy &out);
216
Philip Reamesd16a9b12015-02-20 01:06:44 +0000217// TODO: Once we can get to the GCStrategy, this becomes
218// Optional<bool> isGCManagedPointer(const Value *V) const override {
219
Craig Toppere3dcce92015-08-01 22:20:21 +0000220static bool isGCPointerType(Type *T) {
221 if (auto *PT = dyn_cast<PointerType>(T))
Philip Reamesd16a9b12015-02-20 01:06:44 +0000222 // For the sake of this example GC, we arbitrarily pick addrspace(1) as our
223 // GC managed heap. We know that a pointer into this heap needs to be
224 // updated and that no other pointer does.
225 return (1 == PT->getAddressSpace());
226 return false;
227}
228
Philip Reames8531d8c2015-04-10 21:48:25 +0000229// Return true if this type is one which a) is a gc pointer or contains a GC
230// pointer and b) is of a type this code expects to encounter as a live value.
231// (The insertion code will assert that a type which matches (a) and not (b)
Philip Reames704e78b2015-04-10 22:34:56 +0000232// is not encountered.)
Philip Reames8531d8c2015-04-10 21:48:25 +0000233static bool isHandledGCPointerType(Type *T) {
234 // We fully support gc pointers
235 if (isGCPointerType(T))
236 return true;
237 // We partially support vectors of gc pointers. The code will assert if it
238 // can't handle something.
239 if (auto VT = dyn_cast<VectorType>(T))
240 if (isGCPointerType(VT->getElementType()))
241 return true;
242 return false;
243}
244
245#ifndef NDEBUG
246/// Returns true if this type contains a gc pointer whether we know how to
247/// handle that type or not.
248static bool containsGCPtrType(Type *Ty) {
Philip Reames704e78b2015-04-10 22:34:56 +0000249 if (isGCPointerType(Ty))
Philip Reames8531d8c2015-04-10 21:48:25 +0000250 return true;
251 if (VectorType *VT = dyn_cast<VectorType>(Ty))
252 return isGCPointerType(VT->getScalarType());
253 if (ArrayType *AT = dyn_cast<ArrayType>(Ty))
254 return containsGCPtrType(AT->getElementType());
255 if (StructType *ST = dyn_cast<StructType>(Ty))
Craig Topperd896b032015-11-29 05:38:08 +0000256 return std::any_of(ST->subtypes().begin(), ST->subtypes().end(),
257 containsGCPtrType);
Philip Reames8531d8c2015-04-10 21:48:25 +0000258 return false;
259}
260
261// Returns true if this is a type which a) is a gc pointer or contains a GC
262// pointer and b) is of a type which the code doesn't expect (i.e. first class
263// aggregates). Used to trip assertions.
264static bool isUnhandledGCPointerType(Type *Ty) {
265 return containsGCPtrType(Ty) && !isHandledGCPointerType(Ty);
266}
267#endif
268
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +0000269static bool order_by_name(Value *a, Value *b) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000270 if (a->hasName() && b->hasName()) {
271 return -1 == a->getName().compare(b->getName());
272 } else if (a->hasName() && !b->hasName()) {
273 return true;
274 } else if (!a->hasName() && b->hasName()) {
275 return false;
276 } else {
277 // Better than nothing, but not stable
278 return a < b;
279 }
280}
281
Philip Reamesece70b82015-09-09 23:57:18 +0000282// Return the name of the value suffixed with the provided value, or if the
283// value didn't have a name, the default value specified.
284static std::string suffixed_name_or(Value *V, StringRef Suffix,
285 StringRef DefaultName) {
286 return V->hasName() ? (V->getName() + Suffix).str() : DefaultName.str();
287}
288
Philip Reamesdf1ef082015-04-10 22:53:14 +0000289// Conservatively identifies any definitions which might be live at the
290// given instruction. The analysis is performed immediately before the
291// given instruction. Values defined by that instruction are not considered
292// live. Values used by that instruction are considered live.
293static void analyzeParsePointLiveness(
294 DominatorTree &DT, GCPtrLivenessData &OriginalLivenessData,
295 const CallSite &CS, PartiallyConstructedSafepointRecord &result) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000296 Instruction *inst = CS.getInstruction();
297
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +0000298 StatepointLiveSetTy LiveSet;
299 findLiveSetAtInst(inst, OriginalLivenessData, LiveSet);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000300
301 if (PrintLiveSet) {
302 // Note: This output is used by several of the test cases
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000303 // The order of elements in a set is not stable, put them in a vec and sort
Philip Reamesd16a9b12015-02-20 01:06:44 +0000304 // by name
Philip Reamesdab35f32015-09-02 21:11:44 +0000305 SmallVector<Value *, 64> Temp;
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +0000306 Temp.insert(Temp.end(), LiveSet.begin(), LiveSet.end());
Philip Reamesdab35f32015-09-02 21:11:44 +0000307 std::sort(Temp.begin(), Temp.end(), order_by_name);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000308 errs() << "Live Variables:\n";
Philip Reamesdab35f32015-09-02 21:11:44 +0000309 for (Value *V : Temp)
310 dbgs() << " " << V->getName() << " " << *V << "\n";
Philip Reamesd16a9b12015-02-20 01:06:44 +0000311 }
312 if (PrintLiveSetSize) {
313 errs() << "Safepoint For: " << CS.getCalledValue()->getName() << "\n";
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +0000314 errs() << "Number live values: " << LiveSet.size() << "\n";
Philip Reamesd16a9b12015-02-20 01:06:44 +0000315 }
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +0000316 result.LiveSet = LiveSet;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000317}
318
Philip Reamesf5b8e472015-09-03 21:34:30 +0000319static bool isKnownBaseResult(Value *V);
320namespace {
321/// A single base defining value - An immediate base defining value for an
322/// instruction 'Def' is an input to 'Def' whose base is also a base of 'Def'.
323/// For instructions which have multiple pointer [vector] inputs or that
324/// transition between vector and scalar types, there is no immediate base
325/// defining value. The 'base defining value' for 'Def' is the transitive
326/// closure of this relation stopping at the first instruction which has no
327/// immediate base defining value. The b.d.v. might itself be a base pointer,
328/// but it can also be an arbitrary derived pointer.
329struct BaseDefiningValueResult {
330 /// Contains the value which is the base defining value.
331 Value * const BDV;
332 /// True if the base defining value is also known to be an actual base
333 /// pointer.
334 const bool IsKnownBase;
335 BaseDefiningValueResult(Value *BDV, bool IsKnownBase)
336 : BDV(BDV), IsKnownBase(IsKnownBase) {
337#ifndef NDEBUG
338 // Check consistency between new and old means of checking whether a BDV is
339 // a base.
340 bool MustBeBase = isKnownBaseResult(BDV);
341 assert(!MustBeBase || MustBeBase == IsKnownBase);
342#endif
343 }
344};
345}
346
347static BaseDefiningValueResult findBaseDefiningValue(Value *I);
Philip Reames311f7102015-05-12 22:19:52 +0000348
Philip Reames8fe7f132015-06-26 22:47:37 +0000349/// Return a base defining value for the 'Index' element of the given vector
350/// instruction 'I'. If Index is null, returns a BDV for the entire vector
351/// 'I'. As an optimization, this method will try to determine when the
352/// element is known to already be a base pointer. If this can be established,
353/// the second value in the returned pair will be true. Note that either a
354/// vector or a pointer typed value can be returned. For the former, the
355/// vector returned is a BDV (and possibly a base) of the entire vector 'I'.
356/// If the later, the return pointer is a BDV (or possibly a base) for the
357/// particular element in 'I'.
Philip Reamesf5b8e472015-09-03 21:34:30 +0000358static BaseDefiningValueResult
Philip Reames66287132015-09-09 23:40:12 +0000359findBaseDefiningValueOfVector(Value *I) {
Philip Reames8531d8c2015-04-10 21:48:25 +0000360 assert(I->getType()->isVectorTy() &&
361 cast<VectorType>(I->getType())->getElementType()->isPointerTy() &&
362 "Illegal to ask for the base pointer of a non-pointer type");
363
364 // Each case parallels findBaseDefiningValue below, see that code for
365 // detailed motivation.
366
367 if (isa<Argument>(I))
368 // An incoming argument to the function is a base pointer
Philip Reamesf5b8e472015-09-03 21:34:30 +0000369 return BaseDefiningValueResult(I, true);
Philip Reames8531d8c2015-04-10 21:48:25 +0000370
371 // We shouldn't see the address of a global as a vector value?
372 assert(!isa<GlobalVariable>(I) &&
373 "unexpected global variable found in base of vector");
374
375 // inlining could possibly introduce phi node that contains
376 // undef if callee has multiple returns
377 if (isa<UndefValue>(I))
378 // utterly meaningless, but useful for dealing with partially optimized
379 // code.
Philip Reamesf5b8e472015-09-03 21:34:30 +0000380 return BaseDefiningValueResult(I, true);
Philip Reames8531d8c2015-04-10 21:48:25 +0000381
382 // Due to inheritance, this must be _after_ the global variable and undef
383 // checks
384 if (Constant *Con = dyn_cast<Constant>(I)) {
385 assert(!isa<GlobalVariable>(I) && !isa<UndefValue>(I) &&
386 "order of checks wrong!");
387 assert(Con->isNullValue() && "null is the only case which makes sense");
Philip Reamesf5b8e472015-09-03 21:34:30 +0000388 return BaseDefiningValueResult(Con, true);
Philip Reames8531d8c2015-04-10 21:48:25 +0000389 }
Philip Reames8fe7f132015-06-26 22:47:37 +0000390
Philip Reames8531d8c2015-04-10 21:48:25 +0000391 if (isa<LoadInst>(I))
Philip Reamesf5b8e472015-09-03 21:34:30 +0000392 return BaseDefiningValueResult(I, true);
Philip Reamesf5b8e472015-09-03 21:34:30 +0000393
Philip Reames66287132015-09-09 23:40:12 +0000394 if (isa<InsertElementInst>(I))
Philip Reames8fe7f132015-06-26 22:47:37 +0000395 // We don't know whether this vector contains entirely base pointers or
396 // not. To be conservatively correct, we treat it as a BDV and will
397 // duplicate code as needed to construct a parallel vector of bases.
Philip Reames66287132015-09-09 23:40:12 +0000398 return BaseDefiningValueResult(I, false);
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +0000399
Philip Reames8fe7f132015-06-26 22:47:37 +0000400 if (isa<ShuffleVectorInst>(I))
401 // We don't know whether this vector contains entirely base pointers or
402 // not. To be conservatively correct, we treat it as a BDV and will
403 // duplicate code as needed to construct a parallel vector of bases.
404 // TODO: There a number of local optimizations which could be applied here
405 // for particular sufflevector patterns.
Philip Reamesf5b8e472015-09-03 21:34:30 +0000406 return BaseDefiningValueResult(I, false);
Philip Reames8fe7f132015-06-26 22:47:37 +0000407
408 // A PHI or Select is a base defining value. The outer findBasePointer
409 // algorithm is responsible for constructing a base value for this BDV.
410 assert((isa<SelectInst>(I) || isa<PHINode>(I)) &&
411 "unknown vector instruction - no base found for vector element");
Philip Reamesf5b8e472015-09-03 21:34:30 +0000412 return BaseDefiningValueResult(I, false);
Philip Reames8531d8c2015-04-10 21:48:25 +0000413}
414
Philip Reamesd16a9b12015-02-20 01:06:44 +0000415/// Helper function for findBasePointer - Will return a value which either a)
Philip Reames9ac4e382015-08-12 21:00:20 +0000416/// defines the base pointer for the input, b) blocks the simple search
417/// (i.e. a PHI or Select of two derived pointers), or c) involves a change
418/// from pointer to vector type or back.
Philip Reamesf5b8e472015-09-03 21:34:30 +0000419static BaseDefiningValueResult findBaseDefiningValue(Value *I) {
Philip Reames8fe7f132015-06-26 22:47:37 +0000420 if (I->getType()->isVectorTy())
Philip Reamesf5b8e472015-09-03 21:34:30 +0000421 return findBaseDefiningValueOfVector(I);
Philip Reames8fe7f132015-06-26 22:47:37 +0000422
Philip Reamesd16a9b12015-02-20 01:06:44 +0000423 assert(I->getType()->isPointerTy() &&
424 "Illegal to ask for the base pointer of a non-pointer type");
425
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000426 if (isa<Argument>(I))
Philip Reamesd16a9b12015-02-20 01:06:44 +0000427 // An incoming argument to the function is a base pointer
428 // We should have never reached here if this argument isn't an gc value
Philip Reamesf5b8e472015-09-03 21:34:30 +0000429 return BaseDefiningValueResult(I, true);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000430
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000431 if (isa<GlobalVariable>(I))
Philip Reamesd16a9b12015-02-20 01:06:44 +0000432 // base case
Philip Reamesf5b8e472015-09-03 21:34:30 +0000433 return BaseDefiningValueResult(I, true);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000434
435 // inlining could possibly introduce phi node that contains
436 // undef if callee has multiple returns
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000437 if (isa<UndefValue>(I))
438 // utterly meaningless, but useful for dealing with
439 // partially optimized code.
Philip Reamesf5b8e472015-09-03 21:34:30 +0000440 return BaseDefiningValueResult(I, true);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000441
442 // Due to inheritance, this must be _after_ the global variable and undef
443 // checks
Philip Reames3ea15892015-09-03 21:57:40 +0000444 if (isa<Constant>(I)) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000445 assert(!isa<GlobalVariable>(I) && !isa<UndefValue>(I) &&
446 "order of checks wrong!");
Philip Reames5d546892015-12-19 02:38:22 +0000447 // Note: Even for frontends which don't have constant references, we can
448 // see constants appearing after optimizations. A simple example is
449 // specialization of an address computation on null feeding into a merge
450 // point where the actual use of the now-constant input is protected by
451 // another null check. (e.g. test4 in constants.ll)
Philip Reamesf5b8e472015-09-03 21:34:30 +0000452 return BaseDefiningValueResult(I, true);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000453 }
454
455 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000456 Value *Def = CI->stripPointerCasts();
Manuel Jacob8050a492015-12-21 01:26:46 +0000457 // If stripping pointer casts changes the address space there is an
458 // addrspacecast in between.
459 assert(cast<PointerType>(Def->getType())->getAddressSpace() ==
460 cast<PointerType>(CI->getType())->getAddressSpace() &&
461 "unsupported addrspacecast");
David Blaikie82ad7872015-02-20 23:44:24 +0000462 // If we find a cast instruction here, it means we've found a cast which is
463 // not simply a pointer cast (i.e. an inttoptr). We don't know how to
464 // handle int->ptr conversion.
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000465 assert(!isa<CastInst>(Def) && "shouldn't find another cast here");
466 return findBaseDefiningValue(Def);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000467 }
468
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000469 if (isa<LoadInst>(I))
Philip Reamesf5b8e472015-09-03 21:34:30 +0000470 // The value loaded is an gc base itself
471 return BaseDefiningValueResult(I, true);
472
Philip Reamesd16a9b12015-02-20 01:06:44 +0000473
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000474 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I))
475 // The base of this GEP is the base
476 return findBaseDefiningValue(GEP->getPointerOperand());
Philip Reamesd16a9b12015-02-20 01:06:44 +0000477
478 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
479 switch (II->getIntrinsicID()) {
480 default:
481 // fall through to general call handling
482 break;
483 case Intrinsic::experimental_gc_statepoint:
Manuel Jacob4e4f60d2015-12-22 18:44:45 +0000484 llvm_unreachable("statepoints don't produce pointers");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000485 case Intrinsic::experimental_gc_relocate: {
486 // Rerunning safepoint insertion after safepoints are already
487 // inserted is not supported. It could probably be made to work,
488 // but why are you doing this? There's no good reason.
489 llvm_unreachable("repeat safepoint insertion is not supported");
490 }
491 case Intrinsic::gcroot:
492 // Currently, this mechanism hasn't been extended to work with gcroot.
493 // There's no reason it couldn't be, but I haven't thought about the
494 // implications much.
495 llvm_unreachable(
496 "interaction with the gcroot mechanism is not supported");
497 }
498 }
499 // We assume that functions in the source language only return base
500 // pointers. This should probably be generalized via attributes to support
501 // both source language and internal functions.
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000502 if (isa<CallInst>(I) || isa<InvokeInst>(I))
Philip Reamesf5b8e472015-09-03 21:34:30 +0000503 return BaseDefiningValueResult(I, true);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000504
505 // I have absolutely no idea how to implement this part yet. It's not
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000506 // necessarily hard, I just haven't really looked at it yet.
Philip Reamesd16a9b12015-02-20 01:06:44 +0000507 assert(!isa<LandingPadInst>(I) && "Landing Pad is unimplemented");
508
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000509 if (isa<AtomicCmpXchgInst>(I))
Philip Reamesd16a9b12015-02-20 01:06:44 +0000510 // A CAS is effectively a atomic store and load combined under a
511 // predicate. From the perspective of base pointers, we just treat it
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000512 // like a load.
Philip Reamesf5b8e472015-09-03 21:34:30 +0000513 return BaseDefiningValueResult(I, true);
Philip Reames704e78b2015-04-10 22:34:56 +0000514
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000515 assert(!isa<AtomicRMWInst>(I) && "Xchg handled above, all others are "
Philip Reames704e78b2015-04-10 22:34:56 +0000516 "binary ops which don't apply to pointers");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000517
518 // The aggregate ops. Aggregates can either be in the heap or on the
519 // stack, but in either case, this is simply a field load. As a result,
520 // this is a defining definition of the base just like a load is.
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000521 if (isa<ExtractValueInst>(I))
Philip Reamesf5b8e472015-09-03 21:34:30 +0000522 return BaseDefiningValueResult(I, true);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000523
524 // We should never see an insert vector since that would require we be
525 // tracing back a struct value not a pointer value.
526 assert(!isa<InsertValueInst>(I) &&
527 "Base pointer for a struct is meaningless");
528
Philip Reames9ac4e382015-08-12 21:00:20 +0000529 // An extractelement produces a base result exactly when it's input does.
530 // We may need to insert a parallel instruction to extract the appropriate
531 // element out of the base vector corresponding to the input. Given this,
532 // it's analogous to the phi and select case even though it's not a merge.
Philip Reames66287132015-09-09 23:40:12 +0000533 if (isa<ExtractElementInst>(I))
534 // Note: There a lot of obvious peephole cases here. This are deliberately
535 // handled after the main base pointer inference algorithm to make writing
536 // test cases to exercise that code easier.
537 return BaseDefiningValueResult(I, false);
Philip Reames9ac4e382015-08-12 21:00:20 +0000538
Philip Reamesd16a9b12015-02-20 01:06:44 +0000539 // The last two cases here don't return a base pointer. Instead, they
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000540 // return a value which dynamically selects from among several base
Philip Reamesd16a9b12015-02-20 01:06:44 +0000541 // derived pointers (each with it's own base potentially). It's the job of
542 // the caller to resolve these.
Philip Reames704e78b2015-04-10 22:34:56 +0000543 assert((isa<SelectInst>(I) || isa<PHINode>(I)) &&
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000544 "missing instruction case in findBaseDefiningValing");
Philip Reamesf5b8e472015-09-03 21:34:30 +0000545 return BaseDefiningValueResult(I, false);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000546}
547
548/// Returns the base defining value for this value.
Philip Reames18d0feb2015-03-27 05:39:32 +0000549static Value *findBaseDefiningValueCached(Value *I, DefiningValueMapTy &Cache) {
550 Value *&Cached = Cache[I];
Benjamin Kramer6f665452015-02-20 14:00:58 +0000551 if (!Cached) {
Philip Reamesf5b8e472015-09-03 21:34:30 +0000552 Cached = findBaseDefiningValue(I).BDV;
Philip Reames2a892a62015-07-23 22:25:26 +0000553 DEBUG(dbgs() << "fBDV-cached: " << I->getName() << " -> "
554 << Cached->getName() << "\n");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000555 }
Philip Reames18d0feb2015-03-27 05:39:32 +0000556 assert(Cache[I] != nullptr);
Benjamin Kramer6f665452015-02-20 14:00:58 +0000557 return Cached;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000558}
559
560/// Return a base pointer for this value if known. Otherwise, return it's
561/// base defining value.
Philip Reames18d0feb2015-03-27 05:39:32 +0000562static Value *findBaseOrBDV(Value *I, DefiningValueMapTy &Cache) {
563 Value *Def = findBaseDefiningValueCached(I, Cache);
564 auto Found = Cache.find(Def);
565 if (Found != Cache.end()) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000566 // Either a base-of relation, or a self reference. Caller must check.
Benjamin Kramer6f665452015-02-20 14:00:58 +0000567 return Found->second;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000568 }
569 // Only a BDV available
Philip Reames18d0feb2015-03-27 05:39:32 +0000570 return Def;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000571}
572
573/// Given the result of a call to findBaseDefiningValue, or findBaseOrBDV,
574/// is it known to be a base pointer? Or do we need to continue searching.
Philip Reames18d0feb2015-03-27 05:39:32 +0000575static bool isKnownBaseResult(Value *V) {
Philip Reames66287132015-09-09 23:40:12 +0000576 if (!isa<PHINode>(V) && !isa<SelectInst>(V) &&
577 !isa<ExtractElementInst>(V) && !isa<InsertElementInst>(V) &&
578 !isa<ShuffleVectorInst>(V)) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000579 // no recursion possible
580 return true;
581 }
Philip Reames18d0feb2015-03-27 05:39:32 +0000582 if (isa<Instruction>(V) &&
583 cast<Instruction>(V)->getMetadata("is_base_value")) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000584 // This is a previously inserted base phi or select. We know
585 // that this is a base value.
586 return true;
587 }
588
589 // We need to keep searching
590 return false;
591}
592
Philip Reamesd16a9b12015-02-20 01:06:44 +0000593namespace {
Philip Reames9b141ed2015-07-23 22:49:14 +0000594/// Models the state of a single base defining value in the findBasePointer
595/// algorithm for determining where a new instruction is needed to propagate
596/// the base of this BDV.
597class BDVState {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000598public:
599 enum Status { Unknown, Base, Conflict };
600
Philip Reames9b141ed2015-07-23 22:49:14 +0000601 BDVState(Status s, Value *b = nullptr) : status(s), base(b) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000602 assert(status != Base || b);
603 }
Philip Reames9b141ed2015-07-23 22:49:14 +0000604 explicit BDVState(Value *b) : status(Base), base(b) {}
605 BDVState() : status(Unknown), base(nullptr) {}
Philip Reamesd16a9b12015-02-20 01:06:44 +0000606
607 Status getStatus() const { return status; }
608 Value *getBase() const { return base; }
609
610 bool isBase() const { return getStatus() == Base; }
611 bool isUnknown() const { return getStatus() == Unknown; }
612 bool isConflict() const { return getStatus() == Conflict; }
613
Philip Reames9b141ed2015-07-23 22:49:14 +0000614 bool operator==(const BDVState &other) const {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000615 return base == other.base && status == other.status;
616 }
617
Philip Reames9b141ed2015-07-23 22:49:14 +0000618 bool operator!=(const BDVState &other) const { return !(*this == other); }
Philip Reamesd16a9b12015-02-20 01:06:44 +0000619
Philip Reames2a892a62015-07-23 22:25:26 +0000620 LLVM_DUMP_METHOD
621 void dump() const { print(dbgs()); dbgs() << '\n'; }
622
623 void print(raw_ostream &OS) const {
Philip Reamesdab35f32015-09-02 21:11:44 +0000624 switch (status) {
625 case Unknown:
626 OS << "U";
627 break;
628 case Base:
629 OS << "B";
630 break;
631 case Conflict:
632 OS << "C";
633 break;
634 };
635 OS << " (" << base << " - "
Philip Reames2a892a62015-07-23 22:25:26 +0000636 << (base ? base->getName() : "nullptr") << "): ";
Philip Reamesd16a9b12015-02-20 01:06:44 +0000637 }
638
639private:
640 Status status;
Philip Reamesdd0948a2015-12-18 03:53:28 +0000641 AssertingVH<Value> base; // non null only if status == base
Philip Reamesd16a9b12015-02-20 01:06:44 +0000642};
Philip Reamesb3967cd2015-09-02 22:30:53 +0000643}
Philip Reamesd16a9b12015-02-20 01:06:44 +0000644
Philip Reames6906e922015-09-02 21:57:17 +0000645#ifndef NDEBUG
Philip Reamesb3967cd2015-09-02 22:30:53 +0000646static raw_ostream &operator<<(raw_ostream &OS, const BDVState &State) {
Philip Reames2a892a62015-07-23 22:25:26 +0000647 State.print(OS);
648 return OS;
649}
Philip Reames6906e922015-09-02 21:57:17 +0000650#endif
Philip Reames2a892a62015-07-23 22:25:26 +0000651
Philip Reamesb3967cd2015-09-02 22:30:53 +0000652namespace {
Philip Reames9b141ed2015-07-23 22:49:14 +0000653// Values of type BDVState form a lattice, and this is a helper
Philip Reamesd16a9b12015-02-20 01:06:44 +0000654// class that implementes the meet operation. The meat of the meet
Philip Reames9b141ed2015-07-23 22:49:14 +0000655// operation is implemented in MeetBDVStates::pureMeet
656class MeetBDVStates {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000657public:
Philip Reames273e6bb2015-07-23 21:41:27 +0000658 /// Initializes the currentResult to the TOP state so that if can be met with
659 /// any other state to produce that state.
Philip Reames9b141ed2015-07-23 22:49:14 +0000660 MeetBDVStates() {}
Philip Reamesd16a9b12015-02-20 01:06:44 +0000661
Philip Reames9b141ed2015-07-23 22:49:14 +0000662 // Destructively meet the current result with the given BDVState
663 void meetWith(BDVState otherState) {
Philip Reames273e6bb2015-07-23 21:41:27 +0000664 currentResult = meet(otherState, currentResult);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000665 }
666
Philip Reames9b141ed2015-07-23 22:49:14 +0000667 BDVState getResult() const { return currentResult; }
Philip Reamesd16a9b12015-02-20 01:06:44 +0000668
669private:
Philip Reames9b141ed2015-07-23 22:49:14 +0000670 BDVState currentResult;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000671
Philip Reames9b141ed2015-07-23 22:49:14 +0000672 /// Perform a meet operation on two elements of the BDVState lattice.
673 static BDVState meet(BDVState LHS, BDVState RHS) {
Philip Reames273e6bb2015-07-23 21:41:27 +0000674 assert((pureMeet(LHS, RHS) == pureMeet(RHS, LHS)) &&
675 "math is wrong: meet does not commute!");
Philip Reames9b141ed2015-07-23 22:49:14 +0000676 BDVState Result = pureMeet(LHS, RHS);
Philip Reames2a892a62015-07-23 22:25:26 +0000677 DEBUG(dbgs() << "meet of " << LHS << " with " << RHS
678 << " produced " << Result << "\n");
679 return Result;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000680 }
681
Philip Reames9b141ed2015-07-23 22:49:14 +0000682 static BDVState pureMeet(const BDVState &stateA, const BDVState &stateB) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000683 switch (stateA.getStatus()) {
Philip Reames9b141ed2015-07-23 22:49:14 +0000684 case BDVState::Unknown:
Philip Reamesd16a9b12015-02-20 01:06:44 +0000685 return stateB;
686
Philip Reames9b141ed2015-07-23 22:49:14 +0000687 case BDVState::Base:
Philip Reamesd16a9b12015-02-20 01:06:44 +0000688 assert(stateA.getBase() && "can't be null");
David Blaikie82ad7872015-02-20 23:44:24 +0000689 if (stateB.isUnknown())
Philip Reamesd16a9b12015-02-20 01:06:44 +0000690 return stateA;
David Blaikie82ad7872015-02-20 23:44:24 +0000691
692 if (stateB.isBase()) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000693 if (stateA.getBase() == stateB.getBase()) {
694 assert(stateA == stateB && "equality broken!");
695 return stateA;
696 }
Philip Reames9b141ed2015-07-23 22:49:14 +0000697 return BDVState(BDVState::Conflict);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000698 }
David Blaikie82ad7872015-02-20 23:44:24 +0000699 assert(stateB.isConflict() && "only three states!");
Philip Reames9b141ed2015-07-23 22:49:14 +0000700 return BDVState(BDVState::Conflict);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000701
Philip Reames9b141ed2015-07-23 22:49:14 +0000702 case BDVState::Conflict:
Philip Reamesd16a9b12015-02-20 01:06:44 +0000703 return stateA;
704 }
Reid Klecknera070ee52015-02-20 19:46:02 +0000705 llvm_unreachable("only three states!");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000706 }
707};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000708}
Philip Reamesb3967cd2015-09-02 22:30:53 +0000709
710
Philip Reamesd16a9b12015-02-20 01:06:44 +0000711/// For a given value or instruction, figure out what base ptr it's derived
712/// from. For gc objects, this is simply itself. On success, returns a value
713/// which is the base pointer. (This is reliable and can be used for
714/// relocation.) On failure, returns nullptr.
Philip Reamesba198492015-04-14 00:41:34 +0000715static Value *findBasePointer(Value *I, DefiningValueMapTy &cache) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000716 Value *def = findBaseOrBDV(I, cache);
717
718 if (isKnownBaseResult(def)) {
719 return def;
720 }
721
722 // Here's the rough algorithm:
723 // - For every SSA value, construct a mapping to either an actual base
724 // pointer or a PHI which obscures the base pointer.
725 // - Construct a mapping from PHI to unknown TOP state. Use an
726 // optimistic algorithm to propagate base pointer information. Lattice
727 // looks like:
728 // UNKNOWN
729 // b1 b2 b3 b4
730 // CONFLICT
731 // When algorithm terminates, all PHIs will either have a single concrete
732 // base or be in a conflict state.
733 // - For every conflict, insert a dummy PHI node without arguments. Add
734 // these to the base[Instruction] = BasePtr mapping. For every
735 // non-conflict, add the actual base.
736 // - For every conflict, add arguments for the base[a] of each input
737 // arguments.
738 //
739 // Note: A simpler form of this would be to add the conflict form of all
740 // PHIs without running the optimistic algorithm. This would be
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000741 // analogous to pessimistic data flow and would likely lead to an
Philip Reamesd16a9b12015-02-20 01:06:44 +0000742 // overall worse solution.
743
Philip Reames29e9ae72015-07-24 00:42:55 +0000744#ifndef NDEBUG
Philip Reames88958b22015-07-24 00:02:11 +0000745 auto isExpectedBDVType = [](Value *BDV) {
Philip Reames66287132015-09-09 23:40:12 +0000746 return isa<PHINode>(BDV) || isa<SelectInst>(BDV) ||
747 isa<ExtractElementInst>(BDV) || isa<InsertElementInst>(BDV);
Philip Reames88958b22015-07-24 00:02:11 +0000748 };
Philip Reames29e9ae72015-07-24 00:42:55 +0000749#endif
Philip Reames88958b22015-07-24 00:02:11 +0000750
751 // Once populated, will contain a mapping from each potentially non-base BDV
752 // to a lattice value (described above) which corresponds to that BDV.
Philip Reames15d55632015-09-09 23:26:08 +0000753 // We use the order of insertion (DFS over the def/use graph) to provide a
754 // stable deterministic ordering for visiting DenseMaps (which are unordered)
755 // below. This is important for deterministic compilation.
Philip Reames34d7a742015-09-10 00:22:49 +0000756 MapVector<Value *, BDVState> States;
Philip Reames15d55632015-09-09 23:26:08 +0000757
758 // Recursively fill in all base defining values reachable from the initial
759 // one for which we don't already know a definite base value for
Philip Reames88958b22015-07-24 00:02:11 +0000760 /* scope */ {
Philip Reames88958b22015-07-24 00:02:11 +0000761 SmallVector<Value*, 16> Worklist;
762 Worklist.push_back(def);
Philip Reames34d7a742015-09-10 00:22:49 +0000763 States.insert(std::make_pair(def, BDVState()));
Philip Reames88958b22015-07-24 00:02:11 +0000764 while (!Worklist.empty()) {
765 Value *Current = Worklist.pop_back_val();
766 assert(!isKnownBaseResult(Current) && "why did it get added?");
767
768 auto visitIncomingValue = [&](Value *InVal) {
769 Value *Base = findBaseOrBDV(InVal, cache);
770 if (isKnownBaseResult(Base))
771 // Known bases won't need new instructions introduced and can be
772 // ignored safely
773 return;
774 assert(isExpectedBDVType(Base) && "the only non-base values "
775 "we see should be base defining values");
Philip Reames34d7a742015-09-10 00:22:49 +0000776 if (States.insert(std::make_pair(Base, BDVState())).second)
Philip Reames88958b22015-07-24 00:02:11 +0000777 Worklist.push_back(Base);
778 };
779 if (PHINode *Phi = dyn_cast<PHINode>(Current)) {
780 for (Value *InVal : Phi->incoming_values())
781 visitIncomingValue(InVal);
Philip Reames9ac4e382015-08-12 21:00:20 +0000782 } else if (SelectInst *Sel = dyn_cast<SelectInst>(Current)) {
Philip Reames88958b22015-07-24 00:02:11 +0000783 visitIncomingValue(Sel->getTrueValue());
784 visitIncomingValue(Sel->getFalseValue());
Philip Reames9ac4e382015-08-12 21:00:20 +0000785 } else if (auto *EE = dyn_cast<ExtractElementInst>(Current)) {
786 visitIncomingValue(EE->getVectorOperand());
Philip Reames66287132015-09-09 23:40:12 +0000787 } else if (auto *IE = dyn_cast<InsertElementInst>(Current)) {
788 visitIncomingValue(IE->getOperand(0)); // vector operand
789 visitIncomingValue(IE->getOperand(1)); // scalar operand
Philip Reames9ac4e382015-08-12 21:00:20 +0000790 } else {
Philip Reames66287132015-09-09 23:40:12 +0000791 // There is one known class of instructions we know we don't handle.
792 assert(isa<ShuffleVectorInst>(Current));
Philip Reames9ac4e382015-08-12 21:00:20 +0000793 llvm_unreachable("unimplemented instruction case");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000794 }
795 }
796 }
797
Philip Reamesdab35f32015-09-02 21:11:44 +0000798#ifndef NDEBUG
799 DEBUG(dbgs() << "States after initialization:\n");
Philip Reames34d7a742015-09-10 00:22:49 +0000800 for (auto Pair : States) {
Philip Reamesdab35f32015-09-02 21:11:44 +0000801 DEBUG(dbgs() << " " << Pair.second << " for " << *Pair.first << "\n");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000802 }
Philip Reamesdab35f32015-09-02 21:11:44 +0000803#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +0000804
Philip Reames273e6bb2015-07-23 21:41:27 +0000805 // Return a phi state for a base defining value. We'll generate a new
806 // base state for known bases and expect to find a cached state otherwise.
807 auto getStateForBDV = [&](Value *baseValue) {
808 if (isKnownBaseResult(baseValue))
Philip Reames9b141ed2015-07-23 22:49:14 +0000809 return BDVState(baseValue);
Philip Reames34d7a742015-09-10 00:22:49 +0000810 auto I = States.find(baseValue);
811 assert(I != States.end() && "lookup failed!");
Philip Reames273e6bb2015-07-23 21:41:27 +0000812 return I->second;
813 };
814
Philip Reamesd16a9b12015-02-20 01:06:44 +0000815 bool progress = true;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000816 while (progress) {
Yaron Keren42a7adf2015-02-28 13:11:24 +0000817#ifndef NDEBUG
Philip Reamesb4e55f32015-09-10 00:32:56 +0000818 const size_t oldSize = States.size();
Yaron Keren42a7adf2015-02-28 13:11:24 +0000819#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +0000820 progress = false;
Philip Reames15d55632015-09-09 23:26:08 +0000821 // We're only changing values in this loop, thus safe to keep iterators.
822 // Since this is computing a fixed point, the order of visit does not
823 // effect the result. TODO: We could use a worklist here and make this run
824 // much faster.
Philip Reames34d7a742015-09-10 00:22:49 +0000825 for (auto Pair : States) {
Philip Reamesece70b82015-09-09 23:57:18 +0000826 Value *BDV = Pair.first;
827 assert(!isKnownBaseResult(BDV) && "why did it get added?");
Philip Reames273e6bb2015-07-23 21:41:27 +0000828
Philip Reames9b141ed2015-07-23 22:49:14 +0000829 // Given an input value for the current instruction, return a BDVState
Philip Reames273e6bb2015-07-23 21:41:27 +0000830 // instance which represents the BDV of that value.
831 auto getStateForInput = [&](Value *V) mutable {
832 Value *BDV = findBaseOrBDV(V, cache);
833 return getStateForBDV(BDV);
834 };
835
Philip Reames9b141ed2015-07-23 22:49:14 +0000836 MeetBDVStates calculateMeet;
Philip Reamesece70b82015-09-09 23:57:18 +0000837 if (SelectInst *select = dyn_cast<SelectInst>(BDV)) {
Philip Reames273e6bb2015-07-23 21:41:27 +0000838 calculateMeet.meetWith(getStateForInput(select->getTrueValue()));
839 calculateMeet.meetWith(getStateForInput(select->getFalseValue()));
Philip Reamesece70b82015-09-09 23:57:18 +0000840 } else if (PHINode *Phi = dyn_cast<PHINode>(BDV)) {
Philip Reames9ac4e382015-08-12 21:00:20 +0000841 for (Value *Val : Phi->incoming_values())
Philip Reames273e6bb2015-07-23 21:41:27 +0000842 calculateMeet.meetWith(getStateForInput(Val));
Philip Reamesece70b82015-09-09 23:57:18 +0000843 } else if (auto *EE = dyn_cast<ExtractElementInst>(BDV)) {
Philip Reames9ac4e382015-08-12 21:00:20 +0000844 // The 'meet' for an extractelement is slightly trivial, but it's still
845 // useful in that it drives us to conflict if our input is.
Philip Reames9ac4e382015-08-12 21:00:20 +0000846 calculateMeet.meetWith(getStateForInput(EE->getVectorOperand()));
Philip Reames66287132015-09-09 23:40:12 +0000847 } else {
848 // Given there's a inherent type mismatch between the operands, will
849 // *always* produce Conflict.
Philip Reamesece70b82015-09-09 23:57:18 +0000850 auto *IE = cast<InsertElementInst>(BDV);
Philip Reames66287132015-09-09 23:40:12 +0000851 calculateMeet.meetWith(getStateForInput(IE->getOperand(0)));
852 calculateMeet.meetWith(getStateForInput(IE->getOperand(1)));
Philip Reames9ac4e382015-08-12 21:00:20 +0000853 }
854
Philip Reames34d7a742015-09-10 00:22:49 +0000855 BDVState oldState = States[BDV];
Philip Reames9b141ed2015-07-23 22:49:14 +0000856 BDVState newState = calculateMeet.getResult();
Philip Reamesd16a9b12015-02-20 01:06:44 +0000857 if (oldState != newState) {
858 progress = true;
Philip Reames34d7a742015-09-10 00:22:49 +0000859 States[BDV] = newState;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000860 }
861 }
862
Philip Reamesb4e55f32015-09-10 00:32:56 +0000863 assert(oldSize == States.size() &&
864 "fixed point shouldn't be adding any new nodes to state");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000865 }
866
Philip Reamesdab35f32015-09-02 21:11:44 +0000867#ifndef NDEBUG
868 DEBUG(dbgs() << "States after meet iteration:\n");
Philip Reames34d7a742015-09-10 00:22:49 +0000869 for (auto Pair : States) {
Philip Reamesdab35f32015-09-02 21:11:44 +0000870 DEBUG(dbgs() << " " << Pair.second << " for " << *Pair.first << "\n");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000871 }
Philip Reamesdab35f32015-09-02 21:11:44 +0000872#endif
873
Philip Reamesd16a9b12015-02-20 01:06:44 +0000874 // Insert Phis for all conflicts
Philip Reames2e5bcbe2015-02-28 01:52:09 +0000875 // TODO: adjust naming patterns to avoid this order of iteration dependency
Philip Reames34d7a742015-09-10 00:22:49 +0000876 for (auto Pair : States) {
Philip Reames15d55632015-09-09 23:26:08 +0000877 Instruction *I = cast<Instruction>(Pair.first);
878 BDVState State = Pair.second;
Philip Reames6ff1a1e32015-07-21 19:04:38 +0000879 assert(!isKnownBaseResult(I) && "why did it get added?");
880 assert(!State.isUnknown() && "Optimistic algorithm didn't complete!");
Philip Reames9ac4e382015-08-12 21:00:20 +0000881
882 // extractelement instructions are a bit special in that we may need to
883 // insert an extract even when we know an exact base for the instruction.
884 // The problem is that we need to convert from a vector base to a scalar
885 // base for the particular indice we're interested in.
886 if (State.isBase() && isa<ExtractElementInst>(I) &&
887 isa<VectorType>(State.getBase()->getType())) {
888 auto *EE = cast<ExtractElementInst>(I);
889 // TODO: In many cases, the new instruction is just EE itself. We should
890 // exploit this, but can't do it here since it would break the invariant
891 // about the BDV not being known to be a base.
892 auto *BaseInst = ExtractElementInst::Create(State.getBase(),
893 EE->getIndexOperand(),
894 "base_ee", EE);
895 BaseInst->setMetadata("is_base_value", MDNode::get(I->getContext(), {}));
Philip Reames34d7a742015-09-10 00:22:49 +0000896 States[I] = BDVState(BDVState::Base, BaseInst);
Philip Reames9ac4e382015-08-12 21:00:20 +0000897 }
Philip Reames66287132015-09-09 23:40:12 +0000898
899 // Since we're joining a vector and scalar base, they can never be the
900 // same. As a result, we should always see insert element having reached
901 // the conflict state.
902 if (isa<InsertElementInst>(I)) {
903 assert(State.isConflict());
904 }
Philip Reames9ac4e382015-08-12 21:00:20 +0000905
Philip Reames6ff1a1e32015-07-21 19:04:38 +0000906 if (!State.isConflict())
Philip Reamesf986d682015-02-28 00:54:41 +0000907 continue;
Philip Reames704e78b2015-04-10 22:34:56 +0000908
Philip Reames6ff1a1e32015-07-21 19:04:38 +0000909 /// Create and insert a new instruction which will represent the base of
910 /// the given instruction 'I'.
911 auto MakeBaseInstPlaceholder = [](Instruction *I) -> Instruction* {
912 if (isa<PHINode>(I)) {
913 BasicBlock *BB = I->getParent();
914 int NumPreds = std::distance(pred_begin(BB), pred_end(BB));
915 assert(NumPreds > 0 && "how did we reach here");
Philip Reamesece70b82015-09-09 23:57:18 +0000916 std::string Name = suffixed_name_or(I, ".base", "base_phi");
Philip Reamesfa2c6302015-07-24 19:01:39 +0000917 return PHINode::Create(I->getType(), NumPreds, Name, I);
Philip Reames9ac4e382015-08-12 21:00:20 +0000918 } else if (SelectInst *Sel = dyn_cast<SelectInst>(I)) {
919 // The undef will be replaced later
920 UndefValue *Undef = UndefValue::get(Sel->getType());
Philip Reamesece70b82015-09-09 23:57:18 +0000921 std::string Name = suffixed_name_or(I, ".base", "base_select");
Philip Reames9ac4e382015-08-12 21:00:20 +0000922 return SelectInst::Create(Sel->getCondition(), Undef,
923 Undef, Name, Sel);
Philip Reames66287132015-09-09 23:40:12 +0000924 } else if (auto *EE = dyn_cast<ExtractElementInst>(I)) {
Philip Reames9ac4e382015-08-12 21:00:20 +0000925 UndefValue *Undef = UndefValue::get(EE->getVectorOperand()->getType());
Philip Reamesece70b82015-09-09 23:57:18 +0000926 std::string Name = suffixed_name_or(I, ".base", "base_ee");
Philip Reames9ac4e382015-08-12 21:00:20 +0000927 return ExtractElementInst::Create(Undef, EE->getIndexOperand(), Name,
928 EE);
Philip Reames66287132015-09-09 23:40:12 +0000929 } else {
930 auto *IE = cast<InsertElementInst>(I);
931 UndefValue *VecUndef = UndefValue::get(IE->getOperand(0)->getType());
932 UndefValue *ScalarUndef = UndefValue::get(IE->getOperand(1)->getType());
Philip Reamesece70b82015-09-09 23:57:18 +0000933 std::string Name = suffixed_name_or(I, ".base", "base_ie");
Philip Reames66287132015-09-09 23:40:12 +0000934 return InsertElementInst::Create(VecUndef, ScalarUndef,
935 IE->getOperand(2), Name, IE);
Philip Reames6ff1a1e32015-07-21 19:04:38 +0000936 }
Philip Reames66287132015-09-09 23:40:12 +0000937
Philip Reames6ff1a1e32015-07-21 19:04:38 +0000938 };
939 Instruction *BaseInst = MakeBaseInstPlaceholder(I);
940 // Add metadata marking this as a base value
941 BaseInst->setMetadata("is_base_value", MDNode::get(I->getContext(), {}));
Philip Reames34d7a742015-09-10 00:22:49 +0000942 States[I] = BDVState(BDVState::Conflict, BaseInst);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000943 }
944
Philip Reames3ea15892015-09-03 21:57:40 +0000945 // Returns a instruction which produces the base pointer for a given
946 // instruction. The instruction is assumed to be an input to one of the BDVs
947 // seen in the inference algorithm above. As such, we must either already
948 // know it's base defining value is a base, or have inserted a new
949 // instruction to propagate the base of it's BDV and have entered that newly
950 // introduced instruction into the state table. In either case, we are
951 // assured to be able to determine an instruction which produces it's base
952 // pointer.
953 auto getBaseForInput = [&](Value *Input, Instruction *InsertPt) {
954 Value *BDV = findBaseOrBDV(Input, cache);
955 Value *Base = nullptr;
956 if (isKnownBaseResult(BDV)) {
957 Base = BDV;
958 } else {
959 // Either conflict or base.
Philip Reames34d7a742015-09-10 00:22:49 +0000960 assert(States.count(BDV));
961 Base = States[BDV].getBase();
Philip Reames3ea15892015-09-03 21:57:40 +0000962 }
963 assert(Base && "can't be null");
964 // The cast is needed since base traversal may strip away bitcasts
965 if (Base->getType() != Input->getType() &&
966 InsertPt) {
967 Base = new BitCastInst(Base, Input->getType(), "cast",
968 InsertPt);
969 }
970 return Base;
971 };
972
Philip Reames15d55632015-09-09 23:26:08 +0000973 // Fixup all the inputs of the new PHIs. Visit order needs to be
974 // deterministic and predictable because we're naming newly created
975 // instructions.
Philip Reames34d7a742015-09-10 00:22:49 +0000976 for (auto Pair : States) {
Philip Reames7540e3a2015-09-10 00:01:53 +0000977 Instruction *BDV = cast<Instruction>(Pair.first);
Philip Reamesc8ded462015-09-10 00:27:50 +0000978 BDVState State = Pair.second;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000979
Philip Reames7540e3a2015-09-10 00:01:53 +0000980 assert(!isKnownBaseResult(BDV) && "why did it get added?");
Philip Reamesc8ded462015-09-10 00:27:50 +0000981 assert(!State.isUnknown() && "Optimistic algorithm didn't complete!");
982 if (!State.isConflict())
Philip Reames28e61ce2015-02-28 01:57:44 +0000983 continue;
Philip Reames704e78b2015-04-10 22:34:56 +0000984
Philip Reamesc8ded462015-09-10 00:27:50 +0000985 if (PHINode *basephi = dyn_cast<PHINode>(State.getBase())) {
Philip Reames7540e3a2015-09-10 00:01:53 +0000986 PHINode *phi = cast<PHINode>(BDV);
Philip Reames28e61ce2015-02-28 01:57:44 +0000987 unsigned NumPHIValues = phi->getNumIncomingValues();
988 for (unsigned i = 0; i < NumPHIValues; i++) {
989 Value *InVal = phi->getIncomingValue(i);
990 BasicBlock *InBB = phi->getIncomingBlock(i);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000991
Philip Reames28e61ce2015-02-28 01:57:44 +0000992 // If we've already seen InBB, add the same incoming value
993 // we added for it earlier. The IR verifier requires phi
994 // nodes with multiple entries from the same basic block
995 // to have the same incoming value for each of those
996 // entries. If we don't do this check here and basephi
997 // has a different type than base, we'll end up adding two
998 // bitcasts (and hence two distinct values) as incoming
999 // values for the same basic block.
Philip Reamesd16a9b12015-02-20 01:06:44 +00001000
Philip Reames28e61ce2015-02-28 01:57:44 +00001001 int blockIndex = basephi->getBasicBlockIndex(InBB);
1002 if (blockIndex != -1) {
1003 Value *oldBase = basephi->getIncomingValue(blockIndex);
1004 basephi->addIncoming(oldBase, InBB);
Philip Reames3ea15892015-09-03 21:57:40 +00001005
Philip Reamesd16a9b12015-02-20 01:06:44 +00001006#ifndef NDEBUG
Philip Reames3ea15892015-09-03 21:57:40 +00001007 Value *Base = getBaseForInput(InVal, nullptr);
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001008 // In essence this assert states: the only way two
Philip Reames28e61ce2015-02-28 01:57:44 +00001009 // values incoming from the same basic block may be
1010 // different is by being different bitcasts of the same
1011 // value. A cleanup that remains TODO is changing
1012 // findBaseOrBDV to return an llvm::Value of the correct
1013 // type (and still remain pure). This will remove the
1014 // need to add bitcasts.
Philip Reames3ea15892015-09-03 21:57:40 +00001015 assert(Base->stripPointerCasts() == oldBase->stripPointerCasts() &&
Philip Reames28e61ce2015-02-28 01:57:44 +00001016 "sanity -- findBaseOrBDV should be pure!");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001017#endif
Philip Reames28e61ce2015-02-28 01:57:44 +00001018 continue;
1019 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00001020
Philip Reames3ea15892015-09-03 21:57:40 +00001021 // Find the instruction which produces the base for each input. We may
1022 // need to insert a bitcast in the incoming block.
1023 // TODO: Need to split critical edges if insertion is needed
1024 Value *Base = getBaseForInput(InVal, InBB->getTerminator());
1025 basephi->addIncoming(Base, InBB);
Philip Reames28e61ce2015-02-28 01:57:44 +00001026 }
1027 assert(basephi->getNumIncomingValues() == NumPHIValues);
Philip Reamesc8ded462015-09-10 00:27:50 +00001028 } else if (SelectInst *BaseSel = dyn_cast<SelectInst>(State.getBase())) {
Philip Reames7540e3a2015-09-10 00:01:53 +00001029 SelectInst *Sel = cast<SelectInst>(BDV);
Philip Reames28e61ce2015-02-28 01:57:44 +00001030 // Operand 1 & 2 are true, false path respectively. TODO: refactor to
1031 // something more safe and less hacky.
1032 for (int i = 1; i <= 2; i++) {
Philip Reames3ea15892015-09-03 21:57:40 +00001033 Value *InVal = Sel->getOperand(i);
1034 // Find the instruction which produces the base for each input. We may
1035 // need to insert a bitcast.
1036 Value *Base = getBaseForInput(InVal, BaseSel);
1037 BaseSel->setOperand(i, Base);
Philip Reames28e61ce2015-02-28 01:57:44 +00001038 }
Philip Reamesc8ded462015-09-10 00:27:50 +00001039 } else if (auto *BaseEE = dyn_cast<ExtractElementInst>(State.getBase())) {
Philip Reames7540e3a2015-09-10 00:01:53 +00001040 Value *InVal = cast<ExtractElementInst>(BDV)->getVectorOperand();
Philip Reames3ea15892015-09-03 21:57:40 +00001041 // Find the instruction which produces the base for each input. We may
1042 // need to insert a bitcast.
1043 Value *Base = getBaseForInput(InVal, BaseEE);
Philip Reames9ac4e382015-08-12 21:00:20 +00001044 BaseEE->setOperand(0, Base);
Philip Reames66287132015-09-09 23:40:12 +00001045 } else {
Philip Reamesc8ded462015-09-10 00:27:50 +00001046 auto *BaseIE = cast<InsertElementInst>(State.getBase());
Philip Reames7540e3a2015-09-10 00:01:53 +00001047 auto *BdvIE = cast<InsertElementInst>(BDV);
Philip Reames66287132015-09-09 23:40:12 +00001048 auto UpdateOperand = [&](int OperandIdx) {
1049 Value *InVal = BdvIE->getOperand(OperandIdx);
Philip Reames953817b2015-09-10 00:44:10 +00001050 Value *Base = getBaseForInput(InVal, BaseIE);
Philip Reames66287132015-09-09 23:40:12 +00001051 BaseIE->setOperand(OperandIdx, Base);
1052 };
1053 UpdateOperand(0); // vector operand
1054 UpdateOperand(1); // scalar operand
Philip Reamesd16a9b12015-02-20 01:06:44 +00001055 }
Philip Reames66287132015-09-09 23:40:12 +00001056
Philip Reamesd16a9b12015-02-20 01:06:44 +00001057 }
1058
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001059 // Now that we're done with the algorithm, see if we can optimize the
1060 // results slightly by reducing the number of new instructions needed.
1061 // Arguably, this should be integrated into the algorithm above, but
1062 // doing as a post process step is easier to reason about for the moment.
1063 DenseMap<Value *, Value *> ReverseMap;
1064 SmallPtrSet<Instruction *, 16> NewInsts;
Philip Reames9546f362015-09-02 22:25:07 +00001065 SmallSetVector<AssertingVH<Instruction>, 16> Worklist;
Philip Reames246e6182015-09-03 20:24:29 +00001066 // Note: We need to visit the states in a deterministic order. We uses the
1067 // Keys we sorted above for this purpose. Note that we are papering over a
1068 // bigger problem with the algorithm above - it's visit order is not
1069 // deterministic. A larger change is needed to fix this.
Philip Reames34d7a742015-09-10 00:22:49 +00001070 for (auto Pair : States) {
Philip Reames15d55632015-09-09 23:26:08 +00001071 auto *BDV = Pair.first;
1072 auto State = Pair.second;
Philip Reames246e6182015-09-03 20:24:29 +00001073 Value *Base = State.getBase();
Philip Reames15d55632015-09-09 23:26:08 +00001074 assert(BDV && Base);
1075 assert(!isKnownBaseResult(BDV) && "why did it get added?");
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001076 assert(isKnownBaseResult(Base) &&
1077 "must be something we 'know' is a base pointer");
Philip Reames246e6182015-09-03 20:24:29 +00001078 if (!State.isConflict())
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001079 continue;
1080
Philip Reames15d55632015-09-09 23:26:08 +00001081 ReverseMap[Base] = BDV;
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001082 if (auto *BaseI = dyn_cast<Instruction>(Base)) {
1083 NewInsts.insert(BaseI);
1084 Worklist.insert(BaseI);
1085 }
1086 }
Philip Reames9546f362015-09-02 22:25:07 +00001087 auto ReplaceBaseInstWith = [&](Value *BDV, Instruction *BaseI,
1088 Value *Replacement) {
1089 // Add users which are new instructions (excluding self references)
1090 for (User *U : BaseI->users())
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001091 if (auto *UI = dyn_cast<Instruction>(U))
Philip Reames9546f362015-09-02 22:25:07 +00001092 if (NewInsts.count(UI) && UI != BaseI)
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001093 Worklist.insert(UI);
Philip Reames9546f362015-09-02 22:25:07 +00001094 // Then do the actual replacement
1095 NewInsts.erase(BaseI);
1096 ReverseMap.erase(BaseI);
1097 BaseI->replaceAllUsesWith(Replacement);
Philip Reames34d7a742015-09-10 00:22:49 +00001098 assert(States.count(BDV));
1099 assert(States[BDV].isConflict() && States[BDV].getBase() == BaseI);
1100 States[BDV] = BDVState(BDVState::Conflict, Replacement);
Philip Reamesdd0948a2015-12-18 03:53:28 +00001101 BaseI->eraseFromParent();
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001102 };
1103 const DataLayout &DL = cast<Instruction>(def)->getModule()->getDataLayout();
1104 while (!Worklist.empty()) {
1105 Instruction *BaseI = Worklist.pop_back_val();
Philip Reamesdab35f32015-09-02 21:11:44 +00001106 assert(NewInsts.count(BaseI));
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001107 Value *Bdv = ReverseMap[BaseI];
1108 if (auto *BdvI = dyn_cast<Instruction>(Bdv))
1109 if (BaseI->isIdenticalTo(BdvI)) {
1110 DEBUG(dbgs() << "Identical Base: " << *BaseI << "\n");
Philip Reames9546f362015-09-02 22:25:07 +00001111 ReplaceBaseInstWith(Bdv, BaseI, Bdv);
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001112 continue;
1113 }
1114 if (Value *V = SimplifyInstruction(BaseI, DL)) {
1115 DEBUG(dbgs() << "Base " << *BaseI << " simplified to " << *V << "\n");
Philip Reames9546f362015-09-02 22:25:07 +00001116 ReplaceBaseInstWith(Bdv, BaseI, V);
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001117 continue;
1118 }
1119 }
1120
Philip Reamesd16a9b12015-02-20 01:06:44 +00001121 // Cache all of our results so we can cheaply reuse them
1122 // NOTE: This is actually two caches: one of the base defining value
1123 // relation and one of the base pointer relation! FIXME
Philip Reames34d7a742015-09-10 00:22:49 +00001124 for (auto Pair : States) {
Philip Reames15d55632015-09-09 23:26:08 +00001125 auto *BDV = Pair.first;
1126 Value *base = Pair.second.getBase();
1127 assert(BDV && base);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001128
Philip Reamesece70b82015-09-09 23:57:18 +00001129 std::string fromstr = cache.count(BDV) ? cache[BDV]->getName() : "none";
Philip Reamesdab35f32015-09-02 21:11:44 +00001130 DEBUG(dbgs() << "Updating base value cache"
Philip Reamesece70b82015-09-09 23:57:18 +00001131 << " for: " << BDV->getName()
Philip Reamesdab35f32015-09-02 21:11:44 +00001132 << " from: " << fromstr
Philip Reamesece70b82015-09-09 23:57:18 +00001133 << " to: " << base->getName() << "\n");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001134
Philip Reames15d55632015-09-09 23:26:08 +00001135 if (cache.count(BDV)) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001136 // Once we transition from the BDV relation being store in the cache to
1137 // the base relation being stored, it must be stable
Philip Reames15d55632015-09-09 23:26:08 +00001138 assert((!isKnownBaseResult(cache[BDV]) || cache[BDV] == base) &&
Philip Reamesd16a9b12015-02-20 01:06:44 +00001139 "base relation should be stable");
1140 }
Philip Reames15d55632015-09-09 23:26:08 +00001141 cache[BDV] = base;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001142 }
1143 assert(cache.find(def) != cache.end());
1144 return cache[def];
1145}
1146
1147// For a set of live pointers (base and/or derived), identify the base
1148// pointer of the object which they are derived from. This routine will
1149// mutate the IR graph as needed to make the 'base' pointer live at the
1150// definition site of 'derived'. This ensures that any use of 'derived' can
1151// also use 'base'. This may involve the insertion of a number of
1152// additional PHI nodes.
1153//
1154// preconditions: live is a set of pointer type Values
1155//
1156// side effects: may insert PHI nodes into the existing CFG, will preserve
1157// CFG, will not remove or mutate any existing nodes
1158//
Philip Reamesf2041322015-02-20 19:26:04 +00001159// post condition: PointerToBase contains one (derived, base) pair for every
Philip Reamesd16a9b12015-02-20 01:06:44 +00001160// pointer in live. Note that derived can be equal to base if the original
1161// pointer was a base pointer.
Philip Reames704e78b2015-04-10 22:34:56 +00001162static void
1163findBasePointers(const StatepointLiveSetTy &live,
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001164 DenseMap<Value *, Value *> &PointerToBase,
Philip Reamesba198492015-04-14 00:41:34 +00001165 DominatorTree *DT, DefiningValueMapTy &DVCache) {
Philip Reames2e5bcbe2015-02-28 01:52:09 +00001166 // For the naming of values inserted to be deterministic - which makes for
1167 // much cleaner and more stable tests - we need to assign an order to the
1168 // live values. DenseSets do not provide a deterministic order across runs.
Philip Reames704e78b2015-04-10 22:34:56 +00001169 SmallVector<Value *, 64> Temp;
Philip Reames2e5bcbe2015-02-28 01:52:09 +00001170 Temp.insert(Temp.end(), live.begin(), live.end());
1171 std::sort(Temp.begin(), Temp.end(), order_by_name);
1172 for (Value *ptr : Temp) {
Philip Reamesba198492015-04-14 00:41:34 +00001173 Value *base = findBasePointer(ptr, DVCache);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001174 assert(base && "failed to find base pointer");
Philip Reamesf2041322015-02-20 19:26:04 +00001175 PointerToBase[ptr] = base;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001176 assert((!isa<Instruction>(base) || !isa<Instruction>(ptr) ||
1177 DT->dominates(cast<Instruction>(base)->getParent(),
1178 cast<Instruction>(ptr)->getParent())) &&
1179 "The base we found better dominate the derived pointer");
1180
David Blaikie82ad7872015-02-20 23:44:24 +00001181 // If you see this trip and like to live really dangerously, the code should
1182 // be correct, just with idioms the verifier can't handle. You can try
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001183 // disabling the verifier at your own substantial risk.
Philip Reames704e78b2015-04-10 22:34:56 +00001184 assert(!isa<ConstantPointerNull>(base) &&
Philip Reames24c6cd52015-03-27 05:47:00 +00001185 "the relocation code needs adjustment to handle the relocation of "
1186 "a null pointer constant without causing false positives in the "
1187 "safepoint ir verifier.");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001188 }
1189}
1190
1191/// Find the required based pointers (and adjust the live set) for the given
1192/// parse point.
1193static void findBasePointers(DominatorTree &DT, DefiningValueMapTy &DVCache,
1194 const CallSite &CS,
1195 PartiallyConstructedSafepointRecord &result) {
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001196 DenseMap<Value *, Value *> PointerToBase;
1197 findBasePointers(result.LiveSet, PointerToBase, &DT, DVCache);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001198
1199 if (PrintBasePointers) {
Philip Reamesa5aeaf42015-02-28 00:20:48 +00001200 // Note: Need to print these in a stable order since this is checked in
1201 // some tests.
Philip Reamesd16a9b12015-02-20 01:06:44 +00001202 errs() << "Base Pairs (w/o Relocation):\n";
Philip Reames704e78b2015-04-10 22:34:56 +00001203 SmallVector<Value *, 64> Temp;
Philip Reamesa5aeaf42015-02-28 00:20:48 +00001204 Temp.reserve(PointerToBase.size());
Philip Reamesf2041322015-02-20 19:26:04 +00001205 for (auto Pair : PointerToBase) {
Philip Reamesa5aeaf42015-02-28 00:20:48 +00001206 Temp.push_back(Pair.first);
1207 }
1208 std::sort(Temp.begin(), Temp.end(), order_by_name);
1209 for (Value *Ptr : Temp) {
1210 Value *Base = PointerToBase[Ptr];
Manuel Jacoba4efd8a2015-12-23 00:19:45 +00001211 errs() << " derived ";
1212 Ptr->printAsOperand(errs(), false);
1213 errs() << " base ";
1214 Base->printAsOperand(errs(), false);
1215 errs() << "\n";;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001216 }
1217 }
1218
Philip Reamesf2041322015-02-20 19:26:04 +00001219 result.PointerToBase = PointerToBase;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001220}
1221
Philip Reamesdf1ef082015-04-10 22:53:14 +00001222/// Given an updated version of the dataflow liveness results, update the
1223/// liveset and base pointer maps for the call site CS.
1224static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData,
1225 const CallSite &CS,
1226 PartiallyConstructedSafepointRecord &result);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001227
Philip Reamesdf1ef082015-04-10 22:53:14 +00001228static void recomputeLiveInValues(
Justin Bogner843fb202015-12-15 19:40:57 +00001229 Function &F, DominatorTree &DT, ArrayRef<CallSite> toUpdate,
Philip Reamesd2b66462015-02-20 22:39:41 +00001230 MutableArrayRef<struct PartiallyConstructedSafepointRecord> records) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00001231 // TODO-PERF: reuse the original liveness, then simply run the dataflow
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001232 // again. The old values are still live and will help it stabilize quickly.
Philip Reamesdf1ef082015-04-10 22:53:14 +00001233 GCPtrLivenessData RevisedLivenessData;
1234 computeLiveInValues(DT, F, RevisedLivenessData);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001235 for (size_t i = 0; i < records.size(); i++) {
1236 struct PartiallyConstructedSafepointRecord &info = records[i];
Philip Reamesd2b66462015-02-20 22:39:41 +00001237 const CallSite &CS = toUpdate[i];
Philip Reamesdf1ef082015-04-10 22:53:14 +00001238 recomputeLiveInValues(RevisedLivenessData, CS, info);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001239 }
1240}
1241
Sanjoy Das7ad67642015-10-20 01:06:24 +00001242// When inserting gc.relocate and gc.result calls, we need to ensure there are
1243// no uses of the original value / return value between the gc.statepoint and
1244// the gc.relocate / gc.result call. One case which can arise is a phi node
1245// starting one of the successor blocks. We also need to be able to insert the
1246// gc.relocates only on the path which goes through the statepoint. We might
1247// need to split an edge to make this possible.
Philip Reamesf209a152015-04-13 20:00:30 +00001248static BasicBlock *
Sanjoy Dasea45f0e2015-06-02 22:33:34 +00001249normalizeForInvokeSafepoint(BasicBlock *BB, BasicBlock *InvokeParent,
1250 DominatorTree &DT) {
Philip Reames69e51ca2015-04-13 18:07:21 +00001251 BasicBlock *Ret = BB;
Sanjoy Dasff3dba72015-10-20 01:06:17 +00001252 if (!BB->getUniquePredecessor())
Chandler Carruth96ada252015-07-22 09:52:54 +00001253 Ret = SplitBlockPredecessors(BB, InvokeParent, "", &DT);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001254
Sanjoy Das7ad67642015-10-20 01:06:24 +00001255 // Now that 'Ret' has unique predecessor we can safely remove all phi nodes
Philip Reames69e51ca2015-04-13 18:07:21 +00001256 // from it
1257 FoldSingleEntryPHINodes(Ret);
Sanjoy Dasff3dba72015-10-20 01:06:17 +00001258 assert(!isa<PHINode>(Ret->begin()) &&
1259 "All PHI nodes should have been removed!");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001260
Sanjoy Das7ad67642015-10-20 01:06:24 +00001261 // At this point, we can safely insert a gc.relocate or gc.result as the first
1262 // instruction in Ret if needed.
Philip Reames69e51ca2015-04-13 18:07:21 +00001263 return Ret;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001264}
1265
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001266// Create new attribute set containing only attributes which can be transferred
Philip Reamesd16a9b12015-02-20 01:06:44 +00001267// from original call to the safepoint.
1268static AttributeSet legalizeCallAttributes(AttributeSet AS) {
Sanjoy Das810a59d2015-10-16 02:41:11 +00001269 AttributeSet Ret;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001270
1271 for (unsigned Slot = 0; Slot < AS.getNumSlots(); Slot++) {
Sanjoy Das810a59d2015-10-16 02:41:11 +00001272 unsigned Index = AS.getSlotIndex(Slot);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001273
Sanjoy Das810a59d2015-10-16 02:41:11 +00001274 if (Index == AttributeSet::ReturnIndex ||
1275 Index == AttributeSet::FunctionIndex) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001276
Sanjoy Das810a59d2015-10-16 02:41:11 +00001277 for (Attribute Attr : make_range(AS.begin(Slot), AS.end(Slot))) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001278
1279 // Do not allow certain attributes - just skip them
1280 // Safepoint can not be read only or read none.
Sanjoy Das810a59d2015-10-16 02:41:11 +00001281 if (Attr.hasAttribute(Attribute::ReadNone) ||
1282 Attr.hasAttribute(Attribute::ReadOnly))
Philip Reamesd16a9b12015-02-20 01:06:44 +00001283 continue;
1284
Sanjoy Das58fae7c2015-10-16 02:41:23 +00001285 // These attributes control the generation of the gc.statepoint call /
1286 // invoke itself; and once the gc.statepoint is in place, they're of no
1287 // use.
1288 if (Attr.hasAttribute("statepoint-num-patch-bytes") ||
1289 Attr.hasAttribute("statepoint-id"))
1290 continue;
1291
Sanjoy Das810a59d2015-10-16 02:41:11 +00001292 Ret = Ret.addAttributes(
1293 AS.getContext(), Index,
1294 AttributeSet::get(AS.getContext(), Index, AttrBuilder(Attr)));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001295 }
1296 }
1297
1298 // Just skip parameter attributes for now
1299 }
1300
Sanjoy Das810a59d2015-10-16 02:41:11 +00001301 return Ret;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001302}
1303
1304/// Helper function to place all gc relocates necessary for the given
1305/// statepoint.
1306/// Inputs:
1307/// liveVariables - list of variables to be relocated.
1308/// liveStart - index of the first live variable.
1309/// basePtrs - base pointers.
1310/// statepointToken - statepoint instruction to which relocates should be
1311/// bound.
1312/// Builder - Llvm IR builder to be used to construct new calls.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001313static void CreateGCRelocates(ArrayRef<Value *> LiveVariables,
Sanjoy Das5665c992015-05-11 23:47:27 +00001314 const int LiveStart,
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001315 ArrayRef<Value *> BasePtrs,
Sanjoy Das5665c992015-05-11 23:47:27 +00001316 Instruction *StatepointToken,
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00001317 IRBuilder<> Builder) {
Philip Reames94babb72015-07-21 17:18:03 +00001318 if (LiveVariables.empty())
1319 return;
Sanjoy Dasb1942f12015-10-20 01:06:28 +00001320
1321 auto FindIndex = [](ArrayRef<Value *> LiveVec, Value *Val) {
1322 auto ValIt = std::find(LiveVec.begin(), LiveVec.end(), Val);
1323 assert(ValIt != LiveVec.end() && "Val not found in LiveVec!");
1324 size_t Index = std::distance(LiveVec.begin(), ValIt);
1325 assert(Index < LiveVec.size() && "Bug in std::find?");
1326 return Index;
1327 };
1328
Philip Reames94babb72015-07-21 17:18:03 +00001329 // All gc_relocate are set to i8 addrspace(1)* type. We originally generated
1330 // unique declarations for each pointer type, but this proved problematic
1331 // because the intrinsic mangling code is incomplete and fragile. Since
1332 // we're moving towards a single unified pointer type anyways, we can just
1333 // cast everything to an i8* of the right address space. A bitcast is added
1334 // later to convert gc_relocate to the actual value's type.
Philip Reames74ce2e72015-07-21 16:51:17 +00001335 Module *M = StatepointToken->getModule();
Philip Reames94babb72015-07-21 17:18:03 +00001336 auto AS = cast<PointerType>(LiveVariables[0]->getType())->getAddressSpace();
1337 Type *Types[] = {Type::getInt8PtrTy(M->getContext(), AS)};
1338 Value *GCRelocateDecl =
1339 Intrinsic::getDeclaration(M, Intrinsic::experimental_gc_relocate, Types);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001340
Sanjoy Das5665c992015-05-11 23:47:27 +00001341 for (unsigned i = 0; i < LiveVariables.size(); i++) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001342 // Generate the gc.relocate call and save the result
Sanjoy Das5665c992015-05-11 23:47:27 +00001343 Value *BaseIdx =
Sanjoy Dasb1942f12015-10-20 01:06:28 +00001344 Builder.getInt32(LiveStart + FindIndex(LiveVariables, BasePtrs[i]));
Sanjoy Das3020b1b2015-10-20 01:06:31 +00001345 Value *LiveIdx = Builder.getInt32(LiveStart + i);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001346
1347 // only specify a debug name if we can give a useful one
Philip Reames74ce2e72015-07-21 16:51:17 +00001348 CallInst *Reloc = Builder.CreateCall(
David Blaikieff6409d2015-05-18 22:13:54 +00001349 GCRelocateDecl, {StatepointToken, BaseIdx, LiveIdx},
Philip Reamesece70b82015-09-09 23:57:18 +00001350 suffixed_name_or(LiveVariables[i], ".relocated", ""));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001351 // Trick CodeGen into thinking there are lots of free registers at this
1352 // fake call.
Philip Reames74ce2e72015-07-21 16:51:17 +00001353 Reloc->setCallingConv(CallingConv::Cold);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001354 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00001355}
1356
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001357namespace {
1358
1359/// This struct is used to defer RAUWs and `eraseFromParent` s. Using this
1360/// avoids having to worry about keeping around dangling pointers to Values.
1361class DeferredReplacement {
1362 AssertingVH<Instruction> Old;
1363 AssertingVH<Instruction> New;
1364
1365public:
1366 explicit DeferredReplacement(Instruction *Old, Instruction *New) :
1367 Old(Old), New(New) {
1368 assert(Old != New && "Not allowed!");
1369 }
1370
1371 /// Does the task represented by this instance.
1372 void doReplacement() {
1373 Instruction *OldI = Old;
1374 Instruction *NewI = New;
1375
1376 assert(OldI != NewI && "Disallowed at construction?!");
1377
1378 Old = nullptr;
1379 New = nullptr;
1380
1381 if (NewI)
1382 OldI->replaceAllUsesWith(NewI);
1383 OldI->eraseFromParent();
1384 }
1385};
1386}
1387
Philip Reamesd16a9b12015-02-20 01:06:44 +00001388static void
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001389makeStatepointExplicitImpl(const CallSite CS, /* to replace */
1390 const SmallVectorImpl<Value *> &BasePtrs,
1391 const SmallVectorImpl<Value *> &LiveVariables,
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001392 PartiallyConstructedSafepointRecord &Result,
1393 std::vector<DeferredReplacement> &Replacements) {
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001394 assert(BasePtrs.size() == LiveVariables.size());
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001395 assert((UseDeoptBundles || isStatepoint(CS)) &&
Philip Reamesd16a9b12015-02-20 01:06:44 +00001396 "This method expects to be rewriting a statepoint");
1397
Philip Reamesd16a9b12015-02-20 01:06:44 +00001398 // Then go ahead and use the builder do actually do the inserts. We insert
1399 // immediately before the previous instruction under the assumption that all
1400 // arguments will be available here. We can't insert afterwards since we may
1401 // be replacing a terminator.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001402 Instruction *InsertBefore = CS.getInstruction();
1403 IRBuilder<> Builder(InsertBefore);
1404
Sanjoy Das3c520a12015-10-08 23:18:38 +00001405 ArrayRef<Value *> GCArgs(LiveVariables);
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001406 uint64_t StatepointID = 0xABCDEF00;
1407 uint32_t NumPatchBytes = 0;
1408 uint32_t Flags = uint32_t(StatepointFlags::None);
Sanjoy Das3c520a12015-10-08 23:18:38 +00001409
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001410 ArrayRef<Use> CallArgs;
1411 ArrayRef<Use> DeoptArgs;
1412 ArrayRef<Use> TransitionArgs;
1413
1414 Value *CallTarget = nullptr;
1415
1416 if (UseDeoptBundles) {
1417 CallArgs = {CS.arg_begin(), CS.arg_end()};
1418 DeoptArgs = GetDeoptBundleOperands(CS);
1419 // TODO: we don't fill in TransitionArgs or Flags in this branch, but we
1420 // could have an operand bundle for that too.
1421 AttributeSet OriginalAttrs = CS.getAttributes();
1422
1423 Attribute AttrID = OriginalAttrs.getAttribute(AttributeSet::FunctionIndex,
1424 "statepoint-id");
1425 if (AttrID.isStringAttribute())
1426 AttrID.getValueAsString().getAsInteger(10, StatepointID);
1427
1428 Attribute AttrNumPatchBytes = OriginalAttrs.getAttribute(
1429 AttributeSet::FunctionIndex, "statepoint-num-patch-bytes");
1430 if (AttrNumPatchBytes.isStringAttribute())
1431 AttrNumPatchBytes.getValueAsString().getAsInteger(10, NumPatchBytes);
1432
1433 CallTarget = CS.getCalledValue();
1434 } else {
1435 // This branch will be gone soon, and we will soon only support the
1436 // UseDeoptBundles == true configuration.
1437 Statepoint OldSP(CS);
1438 StatepointID = OldSP.getID();
1439 NumPatchBytes = OldSP.getNumPatchBytes();
1440 Flags = OldSP.getFlags();
1441
1442 CallArgs = {OldSP.arg_begin(), OldSP.arg_end()};
1443 DeoptArgs = {OldSP.vm_state_begin(), OldSP.vm_state_end()};
1444 TransitionArgs = {OldSP.gc_transition_args_begin(),
1445 OldSP.gc_transition_args_end()};
1446 CallTarget = OldSP.getCalledValue();
1447 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00001448
1449 // Create the statepoint given all the arguments
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001450 Instruction *Token = nullptr;
1451 AttributeSet ReturnAttrs;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001452 if (CS.isCall()) {
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001453 CallInst *ToReplace = cast<CallInst>(CS.getInstruction());
Sanjoy Das3c520a12015-10-08 23:18:38 +00001454 CallInst *Call = Builder.CreateGCStatepointCall(
1455 StatepointID, NumPatchBytes, CallTarget, Flags, CallArgs,
1456 TransitionArgs, DeoptArgs, GCArgs, "safepoint_token");
1457
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001458 Call->setTailCall(ToReplace->isTailCall());
1459 Call->setCallingConv(ToReplace->getCallingConv());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001460
1461 // Currently we will fail on parameter attributes and on certain
1462 // function attributes.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001463 AttributeSet NewAttrs = legalizeCallAttributes(ToReplace->getAttributes());
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001464 // In case if we can handle this set of attributes - set up function attrs
Philip Reamesd16a9b12015-02-20 01:06:44 +00001465 // directly on statepoint and return attrs later for gc_result intrinsic.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001466 Call->setAttributes(NewAttrs.getFnAttributes());
1467 ReturnAttrs = NewAttrs.getRetAttributes();
Philip Reamesd16a9b12015-02-20 01:06:44 +00001468
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001469 Token = Call;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001470
1471 // Put the following gc_result and gc_relocate calls immediately after the
1472 // the old call (which we're about to delete)
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001473 assert(ToReplace->getNextNode() && "Not a terminator, must have next!");
1474 Builder.SetInsertPoint(ToReplace->getNextNode());
1475 Builder.SetCurrentDebugLocation(ToReplace->getNextNode()->getDebugLoc());
David Blaikie82ad7872015-02-20 23:44:24 +00001476 } else {
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001477 InvokeInst *ToReplace = cast<InvokeInst>(CS.getInstruction());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001478
1479 // Insert the new invoke into the old block. We'll remove the old one in a
1480 // moment at which point this will become the new terminator for the
1481 // original block.
Sanjoy Das3c520a12015-10-08 23:18:38 +00001482 InvokeInst *Invoke = Builder.CreateGCStatepointInvoke(
1483 StatepointID, NumPatchBytes, CallTarget, ToReplace->getNormalDest(),
1484 ToReplace->getUnwindDest(), Flags, CallArgs, TransitionArgs, DeoptArgs,
1485 GCArgs, "statepoint_token");
1486
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001487 Invoke->setCallingConv(ToReplace->getCallingConv());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001488
1489 // Currently we will fail on parameter attributes and on certain
1490 // function attributes.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001491 AttributeSet NewAttrs = legalizeCallAttributes(ToReplace->getAttributes());
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001492 // In case if we can handle this set of attributes - set up function attrs
Philip Reamesd16a9b12015-02-20 01:06:44 +00001493 // directly on statepoint and return attrs later for gc_result intrinsic.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001494 Invoke->setAttributes(NewAttrs.getFnAttributes());
1495 ReturnAttrs = NewAttrs.getRetAttributes();
Philip Reamesd16a9b12015-02-20 01:06:44 +00001496
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001497 Token = Invoke;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001498
1499 // Generate gc relocates in exceptional path
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001500 BasicBlock *UnwindBlock = ToReplace->getUnwindDest();
1501 assert(!isa<PHINode>(UnwindBlock->begin()) &&
1502 UnwindBlock->getUniquePredecessor() &&
Philip Reames69e51ca2015-04-13 18:07:21 +00001503 "can't safely insert in this block!");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001504
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001505 Builder.SetInsertPoint(&*UnwindBlock->getFirstInsertionPt());
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001506 Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001507
1508 // Extract second element from landingpad return value. We will attach
1509 // exceptional gc relocates to it.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001510 Instruction *ExceptionalToken =
Philip Reamesd16a9b12015-02-20 01:06:44 +00001511 cast<Instruction>(Builder.CreateExtractValue(
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001512 UnwindBlock->getLandingPadInst(), 1, "relocate_token"));
1513 Result.UnwindToken = ExceptionalToken;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001514
Sanjoy Das3c520a12015-10-08 23:18:38 +00001515 const unsigned LiveStartIdx = Statepoint(Token).gcArgsStartIdx();
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001516 CreateGCRelocates(LiveVariables, LiveStartIdx, BasePtrs, ExceptionalToken,
1517 Builder);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001518
1519 // Generate gc relocates and returns for normal block
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001520 BasicBlock *NormalDest = ToReplace->getNormalDest();
1521 assert(!isa<PHINode>(NormalDest->begin()) &&
1522 NormalDest->getUniquePredecessor() &&
Philip Reames69e51ca2015-04-13 18:07:21 +00001523 "can't safely insert in this block!");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001524
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001525 Builder.SetInsertPoint(&*NormalDest->getFirstInsertionPt());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001526
1527 // gc relocates will be generated later as if it were regular call
1528 // statepoint
Philip Reamesd16a9b12015-02-20 01:06:44 +00001529 }
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001530 assert(Token && "Should be set in one of the above branches!");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001531
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001532 if (UseDeoptBundles) {
1533 Token->setName("statepoint_token");
1534 if (!CS.getType()->isVoidTy() && !CS.getInstruction()->use_empty()) {
1535 StringRef Name =
1536 CS.getInstruction()->hasName() ? CS.getInstruction()->getName() : "";
1537 CallInst *GCResult = Builder.CreateGCResult(Token, CS.getType(), Name);
1538 GCResult->setAttributes(CS.getAttributes().getRetAttributes());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001539
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001540 // We cannot RAUW or delete CS.getInstruction() because it could be in the
1541 // live set of some other safepoint, in which case that safepoint's
1542 // PartiallyConstructedSafepointRecord will hold a raw pointer to this
1543 // llvm::Instruction. Instead, we defer the replacement and deletion to
1544 // after the live sets have been made explicit in the IR, and we no longer
1545 // have raw pointers to worry about.
1546 Replacements.emplace_back(CS.getInstruction(), GCResult);
1547 } else {
1548 Replacements.emplace_back(CS.getInstruction(), nullptr);
1549 }
1550 } else {
1551 assert(!CS.getInstruction()->hasNUsesOrMore(2) &&
1552 "only valid use before rewrite is gc.result");
1553 assert(!CS.getInstruction()->hasOneUse() ||
1554 isGCResult(cast<Instruction>(*CS.getInstruction()->user_begin())));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001555
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001556 // Take the name of the original statepoint token if there was one.
1557 Token->takeName(CS.getInstruction());
1558
1559 // Update the gc.result of the original statepoint (if any) to use the newly
1560 // inserted statepoint. This is safe to do here since the token can't be
1561 // considered a live reference.
1562 CS.getInstruction()->replaceAllUsesWith(Token);
1563 CS.getInstruction()->eraseFromParent();
1564 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00001565
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001566 Result.StatepointToken = Token;
Philip Reames0a3240f2015-02-20 21:34:11 +00001567
Philip Reamesd16a9b12015-02-20 01:06:44 +00001568 // Second, create a gc.relocate for every live variable
Sanjoy Das3c520a12015-10-08 23:18:38 +00001569 const unsigned LiveStartIdx = Statepoint(Token).gcArgsStartIdx();
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001570 CreateGCRelocates(LiveVariables, LiveStartIdx, BasePtrs, Token, Builder);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001571}
1572
1573namespace {
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001574struct NameOrdering {
1575 Value *Base;
1576 Value *Derived;
1577
1578 bool operator()(NameOrdering const &a, NameOrdering const &b) {
1579 return -1 == a.Derived->getName().compare(b.Derived->getName());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001580 }
1581};
1582}
Philip Reamesd16a9b12015-02-20 01:06:44 +00001583
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001584static void StabilizeOrder(SmallVectorImpl<Value *> &BaseVec,
1585 SmallVectorImpl<Value *> &LiveVec) {
1586 assert(BaseVec.size() == LiveVec.size());
1587
1588 SmallVector<NameOrdering, 64> Temp;
1589 for (size_t i = 0; i < BaseVec.size(); i++) {
1590 NameOrdering v;
1591 v.Base = BaseVec[i];
1592 v.Derived = LiveVec[i];
1593 Temp.push_back(v);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001594 }
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001595
1596 std::sort(Temp.begin(), Temp.end(), NameOrdering());
1597 for (size_t i = 0; i < BaseVec.size(); i++) {
1598 BaseVec[i] = Temp[i].Base;
1599 LiveVec[i] = Temp[i].Derived;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001600 }
1601}
1602
1603// Replace an existing gc.statepoint with a new one and a set of gc.relocates
1604// which make the relocations happening at this safepoint explicit.
Philip Reames704e78b2015-04-10 22:34:56 +00001605//
Philip Reamesd16a9b12015-02-20 01:06:44 +00001606// WARNING: Does not do any fixup to adjust users of the original live
1607// values. That's the callers responsibility.
1608static void
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001609makeStatepointExplicit(DominatorTree &DT, const CallSite &CS,
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001610 PartiallyConstructedSafepointRecord &Result,
1611 std::vector<DeferredReplacement> &Replacements) {
Sanjoy Das1ede5362015-10-08 23:18:22 +00001612 const auto &LiveSet = Result.LiveSet;
1613 const auto &PointerToBase = Result.PointerToBase;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001614
1615 // Convert to vector for efficient cross referencing.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001616 SmallVector<Value *, 64> BaseVec, LiveVec;
1617 LiveVec.reserve(LiveSet.size());
1618 BaseVec.reserve(LiveSet.size());
1619 for (Value *L : LiveSet) {
1620 LiveVec.push_back(L);
Philip Reames74ce2e72015-07-21 16:51:17 +00001621 assert(PointerToBase.count(L));
Sanjoy Das1ede5362015-10-08 23:18:22 +00001622 Value *Base = PointerToBase.find(L)->second;
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001623 BaseVec.push_back(Base);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001624 }
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001625 assert(LiveVec.size() == BaseVec.size());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001626
1627 // To make the output IR slightly more stable (for use in diffs), ensure a
1628 // fixed order of the values in the safepoint (by sorting the value name).
1629 // The order is otherwise meaningless.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001630 StabilizeOrder(BaseVec, LiveVec);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001631
1632 // Do the actual rewriting and delete the old statepoint
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001633 makeStatepointExplicitImpl(CS, BaseVec, LiveVec, Result, Replacements);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001634}
1635
1636// Helper function for the relocationViaAlloca.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001637//
1638// It receives iterator to the statepoint gc relocates and emits a store to the
1639// assigned location (via allocaMap) for the each one of them. It adds the
1640// visited values into the visitedLiveValues set, which we will later use them
1641// for sanity checking.
Philip Reamesd16a9b12015-02-20 01:06:44 +00001642static void
Sanjoy Das5665c992015-05-11 23:47:27 +00001643insertRelocationStores(iterator_range<Value::user_iterator> GCRelocs,
1644 DenseMap<Value *, Value *> &AllocaMap,
1645 DenseSet<Value *> &VisitedLiveValues) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001646
Sanjoy Das5665c992015-05-11 23:47:27 +00001647 for (User *U : GCRelocs) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001648 if (!isa<IntrinsicInst>(U))
1649 continue;
1650
Sanjoy Das5665c992015-05-11 23:47:27 +00001651 IntrinsicInst *RelocatedValue = cast<IntrinsicInst>(U);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001652
1653 // We only care about relocates
Sanjoy Das5665c992015-05-11 23:47:27 +00001654 if (RelocatedValue->getIntrinsicID() !=
Philip Reamesd16a9b12015-02-20 01:06:44 +00001655 Intrinsic::experimental_gc_relocate) {
1656 continue;
1657 }
1658
Sanjoy Das5665c992015-05-11 23:47:27 +00001659 GCRelocateOperands RelocateOperands(RelocatedValue);
1660 Value *OriginalValue =
1661 const_cast<Value *>(RelocateOperands.getDerivedPtr());
1662 assert(AllocaMap.count(OriginalValue));
1663 Value *Alloca = AllocaMap[OriginalValue];
Philip Reamesd16a9b12015-02-20 01:06:44 +00001664
1665 // Emit store into the related alloca
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001666 // All gc_relocates are i8 addrspace(1)* typed, and it must be bitcasted to
Sanjoy Das89c54912015-05-11 18:49:34 +00001667 // the correct type according to alloca.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001668 assert(RelocatedValue->getNextNode() &&
1669 "Should always have one since it's not a terminator");
Sanjoy Das5665c992015-05-11 23:47:27 +00001670 IRBuilder<> Builder(RelocatedValue->getNextNode());
Sanjoy Das89c54912015-05-11 18:49:34 +00001671 Value *CastedRelocatedValue =
Philip Reamesece70b82015-09-09 23:57:18 +00001672 Builder.CreateBitCast(RelocatedValue,
1673 cast<AllocaInst>(Alloca)->getAllocatedType(),
1674 suffixed_name_or(RelocatedValue, ".casted", ""));
Sanjoy Das89c54912015-05-11 18:49:34 +00001675
Sanjoy Das5665c992015-05-11 23:47:27 +00001676 StoreInst *Store = new StoreInst(CastedRelocatedValue, Alloca);
1677 Store->insertAfter(cast<Instruction>(CastedRelocatedValue));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001678
1679#ifndef NDEBUG
Sanjoy Das5665c992015-05-11 23:47:27 +00001680 VisitedLiveValues.insert(OriginalValue);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001681#endif
1682 }
1683}
1684
Igor Laevskye0317182015-05-19 15:59:05 +00001685// Helper function for the "relocationViaAlloca". Similar to the
1686// "insertRelocationStores" but works for rematerialized values.
1687static void
1688insertRematerializationStores(
1689 RematerializedValueMapTy RematerializedValues,
1690 DenseMap<Value *, Value *> &AllocaMap,
1691 DenseSet<Value *> &VisitedLiveValues) {
1692
1693 for (auto RematerializedValuePair: RematerializedValues) {
1694 Instruction *RematerializedValue = RematerializedValuePair.first;
1695 Value *OriginalValue = RematerializedValuePair.second;
1696
1697 assert(AllocaMap.count(OriginalValue) &&
1698 "Can not find alloca for rematerialized value");
1699 Value *Alloca = AllocaMap[OriginalValue];
1700
1701 StoreInst *Store = new StoreInst(RematerializedValue, Alloca);
1702 Store->insertAfter(RematerializedValue);
1703
1704#ifndef NDEBUG
1705 VisitedLiveValues.insert(OriginalValue);
1706#endif
1707 }
1708}
1709
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001710/// Do all the relocation update via allocas and mem2reg
Philip Reamesd16a9b12015-02-20 01:06:44 +00001711static void relocationViaAlloca(
Igor Laevsky285fe842015-05-19 16:29:43 +00001712 Function &F, DominatorTree &DT, ArrayRef<Value *> Live,
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001713 ArrayRef<PartiallyConstructedSafepointRecord> Records) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001714#ifndef NDEBUG
Philip Reamesa6ebf072015-03-27 05:53:16 +00001715 // record initial number of (static) allocas; we'll check we have the same
1716 // number when we get done.
1717 int InitialAllocaNum = 0;
Philip Reames704e78b2015-04-10 22:34:56 +00001718 for (auto I = F.getEntryBlock().begin(), E = F.getEntryBlock().end(); I != E;
1719 I++)
Philip Reamesa6ebf072015-03-27 05:53:16 +00001720 if (isa<AllocaInst>(*I))
1721 InitialAllocaNum++;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001722#endif
1723
1724 // TODO-PERF: change data structures, reserve
Igor Laevsky285fe842015-05-19 16:29:43 +00001725 DenseMap<Value *, Value *> AllocaMap;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001726 SmallVector<AllocaInst *, 200> PromotableAllocas;
Igor Laevskye0317182015-05-19 15:59:05 +00001727 // Used later to chack that we have enough allocas to store all values
1728 std::size_t NumRematerializedValues = 0;
Igor Laevsky285fe842015-05-19 16:29:43 +00001729 PromotableAllocas.reserve(Live.size());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001730
Igor Laevskye0317182015-05-19 15:59:05 +00001731 // Emit alloca for "LiveValue" and record it in "allocaMap" and
1732 // "PromotableAllocas"
1733 auto emitAllocaFor = [&](Value *LiveValue) {
1734 AllocaInst *Alloca = new AllocaInst(LiveValue->getType(), "",
1735 F.getEntryBlock().getFirstNonPHI());
Igor Laevsky285fe842015-05-19 16:29:43 +00001736 AllocaMap[LiveValue] = Alloca;
Igor Laevskye0317182015-05-19 15:59:05 +00001737 PromotableAllocas.push_back(Alloca);
1738 };
1739
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001740 // Emit alloca for each live gc pointer
1741 for (Value *V : Live)
1742 emitAllocaFor(V);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001743
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001744 // Emit allocas for rematerialized values
1745 for (const auto &Info : Records)
Igor Laevsky285fe842015-05-19 16:29:43 +00001746 for (auto RematerializedValuePair : Info.RematerializedValues) {
Igor Laevskye0317182015-05-19 15:59:05 +00001747 Value *OriginalValue = RematerializedValuePair.second;
Igor Laevsky285fe842015-05-19 16:29:43 +00001748 if (AllocaMap.count(OriginalValue) != 0)
Igor Laevskye0317182015-05-19 15:59:05 +00001749 continue;
1750
1751 emitAllocaFor(OriginalValue);
1752 ++NumRematerializedValues;
1753 }
Igor Laevsky285fe842015-05-19 16:29:43 +00001754
Philip Reamesd16a9b12015-02-20 01:06:44 +00001755 // The next two loops are part of the same conceptual operation. We need to
1756 // insert a store to the alloca after the original def and at each
1757 // redefinition. We need to insert a load before each use. These are split
1758 // into distinct loops for performance reasons.
1759
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001760 // Update gc pointer after each statepoint: either store a relocated value or
1761 // null (if no relocated value was found for this gc pointer and it is not a
1762 // gc_result). This must happen before we update the statepoint with load of
1763 // alloca otherwise we lose the link between statepoint and old def.
1764 for (const auto &Info : Records) {
Igor Laevsky285fe842015-05-19 16:29:43 +00001765 Value *Statepoint = Info.StatepointToken;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001766
1767 // This will be used for consistency check
Igor Laevsky285fe842015-05-19 16:29:43 +00001768 DenseSet<Value *> VisitedLiveValues;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001769
1770 // Insert stores for normal statepoint gc relocates
Igor Laevsky285fe842015-05-19 16:29:43 +00001771 insertRelocationStores(Statepoint->users(), AllocaMap, VisitedLiveValues);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001772
1773 // In case if it was invoke statepoint
1774 // we will insert stores for exceptional path gc relocates.
Philip Reames0a3240f2015-02-20 21:34:11 +00001775 if (isa<InvokeInst>(Statepoint)) {
Igor Laevsky285fe842015-05-19 16:29:43 +00001776 insertRelocationStores(Info.UnwindToken->users(), AllocaMap,
1777 VisitedLiveValues);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001778 }
1779
Igor Laevskye0317182015-05-19 15:59:05 +00001780 // Do similar thing with rematerialized values
Igor Laevsky285fe842015-05-19 16:29:43 +00001781 insertRematerializationStores(Info.RematerializedValues, AllocaMap,
1782 VisitedLiveValues);
Igor Laevskye0317182015-05-19 15:59:05 +00001783
Philip Reamese73300b2015-04-13 16:41:32 +00001784 if (ClobberNonLive) {
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001785 // As a debugging aid, pretend that an unrelocated pointer becomes null at
Philip Reamese73300b2015-04-13 16:41:32 +00001786 // the gc.statepoint. This will turn some subtle GC problems into
1787 // slightly easier to debug SEGVs. Note that on large IR files with
1788 // lots of gc.statepoints this is extremely costly both memory and time
1789 // wise.
1790 SmallVector<AllocaInst *, 64> ToClobber;
Igor Laevsky285fe842015-05-19 16:29:43 +00001791 for (auto Pair : AllocaMap) {
Philip Reamese73300b2015-04-13 16:41:32 +00001792 Value *Def = Pair.first;
1793 AllocaInst *Alloca = cast<AllocaInst>(Pair.second);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001794
Philip Reamese73300b2015-04-13 16:41:32 +00001795 // This value was relocated
Igor Laevsky285fe842015-05-19 16:29:43 +00001796 if (VisitedLiveValues.count(Def)) {
Philip Reamese73300b2015-04-13 16:41:32 +00001797 continue;
1798 }
1799 ToClobber.push_back(Alloca);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001800 }
Philip Reamesfa2fcf172015-02-20 19:51:56 +00001801
Philip Reamese73300b2015-04-13 16:41:32 +00001802 auto InsertClobbersAt = [&](Instruction *IP) {
1803 for (auto *AI : ToClobber) {
1804 auto AIType = cast<PointerType>(AI->getType());
1805 auto PT = cast<PointerType>(AIType->getElementType());
1806 Constant *CPN = ConstantPointerNull::get(PT);
Igor Laevsky285fe842015-05-19 16:29:43 +00001807 StoreInst *Store = new StoreInst(CPN, AI);
1808 Store->insertBefore(IP);
Philip Reamese73300b2015-04-13 16:41:32 +00001809 }
1810 };
1811
1812 // Insert the clobbering stores. These may get intermixed with the
1813 // gc.results and gc.relocates, but that's fine.
1814 if (auto II = dyn_cast<InvokeInst>(Statepoint)) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001815 InsertClobbersAt(&*II->getNormalDest()->getFirstInsertionPt());
1816 InsertClobbersAt(&*II->getUnwindDest()->getFirstInsertionPt());
Philip Reamese73300b2015-04-13 16:41:32 +00001817 } else {
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001818 InsertClobbersAt(cast<Instruction>(Statepoint)->getNextNode());
Philip Reamesfa2fcf172015-02-20 19:51:56 +00001819 }
David Blaikie82ad7872015-02-20 23:44:24 +00001820 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00001821 }
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001822
1823 // Update use with load allocas and add store for gc_relocated.
Igor Laevsky285fe842015-05-19 16:29:43 +00001824 for (auto Pair : AllocaMap) {
1825 Value *Def = Pair.first;
1826 Value *Alloca = Pair.second;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001827
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001828 // We pre-record the uses of allocas so that we dont have to worry about
1829 // later update that changes the user information..
1830
Igor Laevsky285fe842015-05-19 16:29:43 +00001831 SmallVector<Instruction *, 20> Uses;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001832 // PERF: trade a linear scan for repeated reallocation
Igor Laevsky285fe842015-05-19 16:29:43 +00001833 Uses.reserve(std::distance(Def->user_begin(), Def->user_end()));
1834 for (User *U : Def->users()) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001835 if (!isa<ConstantExpr>(U)) {
1836 // If the def has a ConstantExpr use, then the def is either a
1837 // ConstantExpr use itself or null. In either case
1838 // (recursively in the first, directly in the second), the oop
1839 // it is ultimately dependent on is null and this particular
1840 // use does not need to be fixed up.
Igor Laevsky285fe842015-05-19 16:29:43 +00001841 Uses.push_back(cast<Instruction>(U));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001842 }
1843 }
1844
Igor Laevsky285fe842015-05-19 16:29:43 +00001845 std::sort(Uses.begin(), Uses.end());
1846 auto Last = std::unique(Uses.begin(), Uses.end());
1847 Uses.erase(Last, Uses.end());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001848
Igor Laevsky285fe842015-05-19 16:29:43 +00001849 for (Instruction *Use : Uses) {
1850 if (isa<PHINode>(Use)) {
1851 PHINode *Phi = cast<PHINode>(Use);
1852 for (unsigned i = 0; i < Phi->getNumIncomingValues(); i++) {
1853 if (Def == Phi->getIncomingValue(i)) {
1854 LoadInst *Load = new LoadInst(
1855 Alloca, "", Phi->getIncomingBlock(i)->getTerminator());
1856 Phi->setIncomingValue(i, Load);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001857 }
1858 }
1859 } else {
Igor Laevsky285fe842015-05-19 16:29:43 +00001860 LoadInst *Load = new LoadInst(Alloca, "", Use);
1861 Use->replaceUsesOfWith(Def, Load);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001862 }
1863 }
1864
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001865 // Emit store for the initial gc value. Store must be inserted after load,
1866 // otherwise store will be in alloca's use list and an extra load will be
1867 // inserted before it.
Igor Laevsky285fe842015-05-19 16:29:43 +00001868 StoreInst *Store = new StoreInst(Def, Alloca);
1869 if (Instruction *Inst = dyn_cast<Instruction>(Def)) {
1870 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(Inst)) {
Philip Reames6da37852015-03-04 00:13:52 +00001871 // InvokeInst is a TerminatorInst so the store need to be inserted
1872 // into its normal destination block.
Igor Laevsky285fe842015-05-19 16:29:43 +00001873 BasicBlock *NormalDest = Invoke->getNormalDest();
1874 Store->insertBefore(NormalDest->getFirstNonPHI());
Philip Reames6da37852015-03-04 00:13:52 +00001875 } else {
Igor Laevsky285fe842015-05-19 16:29:43 +00001876 assert(!Inst->isTerminator() &&
Philip Reames6da37852015-03-04 00:13:52 +00001877 "The only TerminatorInst that can produce a value is "
1878 "InvokeInst which is handled above.");
Igor Laevsky285fe842015-05-19 16:29:43 +00001879 Store->insertAfter(Inst);
Philip Reames6da37852015-03-04 00:13:52 +00001880 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00001881 } else {
Igor Laevsky285fe842015-05-19 16:29:43 +00001882 assert(isa<Argument>(Def));
1883 Store->insertAfter(cast<Instruction>(Alloca));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001884 }
1885 }
1886
Igor Laevsky285fe842015-05-19 16:29:43 +00001887 assert(PromotableAllocas.size() == Live.size() + NumRematerializedValues &&
Philip Reamesd16a9b12015-02-20 01:06:44 +00001888 "we must have the same allocas with lives");
1889 if (!PromotableAllocas.empty()) {
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001890 // Apply mem2reg to promote alloca to SSA
Philip Reamesd16a9b12015-02-20 01:06:44 +00001891 PromoteMemToReg(PromotableAllocas, DT);
1892 }
1893
1894#ifndef NDEBUG
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001895 for (auto &I : F.getEntryBlock())
1896 if (isa<AllocaInst>(I))
Philip Reamesa6ebf072015-03-27 05:53:16 +00001897 InitialAllocaNum--;
1898 assert(InitialAllocaNum == 0 && "We must not introduce any extra allocas");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001899#endif
1900}
1901
1902/// Implement a unique function which doesn't require we sort the input
1903/// vector. Doing so has the effect of changing the output of a couple of
1904/// tests in ways which make them less useful in testing fused safepoints.
Philip Reamesd2b66462015-02-20 22:39:41 +00001905template <typename T> static void unique_unsorted(SmallVectorImpl<T> &Vec) {
Benjamin Kramer258ea0d2015-06-13 19:50:38 +00001906 SmallSet<T, 8> Seen;
1907 Vec.erase(std::remove_if(Vec.begin(), Vec.end(), [&](const T &V) {
1908 return !Seen.insert(V).second;
1909 }), Vec.end());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001910}
1911
Philip Reamesd16a9b12015-02-20 01:06:44 +00001912/// Insert holders so that each Value is obviously live through the entire
Philip Reamesf209a152015-04-13 20:00:30 +00001913/// lifetime of the call.
Philip Reamesd16a9b12015-02-20 01:06:44 +00001914static void insertUseHolderAfter(CallSite &CS, const ArrayRef<Value *> Values,
Philip Reamesf209a152015-04-13 20:00:30 +00001915 SmallVectorImpl<CallInst *> &Holders) {
Philip Reames21142752015-04-13 19:07:47 +00001916 if (Values.empty())
1917 // No values to hold live, might as well not insert the empty holder
1918 return;
1919
Sanjay Patelaf674fb2015-12-14 17:24:23 +00001920 Module *M = CS.getInstruction()->getModule();
Philip Reamesf209a152015-04-13 20:00:30 +00001921 // Use a dummy vararg function to actually hold the values live
1922 Function *Func = cast<Function>(M->getOrInsertFunction(
1923 "__tmp_use", FunctionType::get(Type::getVoidTy(M->getContext()), true)));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001924 if (CS.isCall()) {
1925 // For call safepoints insert dummy calls right after safepoint
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001926 Holders.push_back(CallInst::Create(Func, Values, "",
1927 &*++CS.getInstruction()->getIterator()));
Philip Reamesf209a152015-04-13 20:00:30 +00001928 return;
1929 }
1930 // For invoke safepooints insert dummy calls both in normal and
1931 // exceptional destination blocks
1932 auto *II = cast<InvokeInst>(CS.getInstruction());
1933 Holders.push_back(CallInst::Create(
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001934 Func, Values, "", &*II->getNormalDest()->getFirstInsertionPt()));
Philip Reamesf209a152015-04-13 20:00:30 +00001935 Holders.push_back(CallInst::Create(
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001936 Func, Values, "", &*II->getUnwindDest()->getFirstInsertionPt()));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001937}
1938
1939static void findLiveReferences(
Justin Bogner843fb202015-12-15 19:40:57 +00001940 Function &F, DominatorTree &DT, ArrayRef<CallSite> toUpdate,
Philip Reamesd2b66462015-02-20 22:39:41 +00001941 MutableArrayRef<struct PartiallyConstructedSafepointRecord> records) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00001942 GCPtrLivenessData OriginalLivenessData;
1943 computeLiveInValues(DT, F, OriginalLivenessData);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001944 for (size_t i = 0; i < records.size(); i++) {
1945 struct PartiallyConstructedSafepointRecord &info = records[i];
Philip Reamesd2b66462015-02-20 22:39:41 +00001946 const CallSite &CS = toUpdate[i];
Philip Reamesdf1ef082015-04-10 22:53:14 +00001947 analyzeParsePointLiveness(DT, OriginalLivenessData, CS, info);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001948 }
1949}
1950
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001951/// Remove any vector of pointers from the live set by scalarizing them over the
1952/// statepoint instruction. Adds the scalarized pieces to the live set. It
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001953/// would be preferable to include the vector in the statepoint itself, but
Philip Reames8531d8c2015-04-10 21:48:25 +00001954/// the lowering code currently does not handle that. Extending it would be
1955/// slightly non-trivial since it requires a format change. Given how rare
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001956/// such cases are (for the moment?) scalarizing is an acceptable compromise.
Philip Reames8531d8c2015-04-10 21:48:25 +00001957static void splitVectorValues(Instruction *StatepointInst,
Philip Reames8fe7f132015-06-26 22:47:37 +00001958 StatepointLiveSetTy &LiveSet,
1959 DenseMap<Value *, Value *>& PointerToBase,
1960 DominatorTree &DT) {
Philip Reames8531d8c2015-04-10 21:48:25 +00001961 SmallVector<Value *, 16> ToSplit;
1962 for (Value *V : LiveSet)
1963 if (isa<VectorType>(V->getType()))
1964 ToSplit.push_back(V);
1965
1966 if (ToSplit.empty())
1967 return;
1968
Philip Reames8fe7f132015-06-26 22:47:37 +00001969 DenseMap<Value *, SmallVector<Value *, 16>> ElementMapping;
1970
Philip Reames8531d8c2015-04-10 21:48:25 +00001971 Function &F = *(StatepointInst->getParent()->getParent());
1972
Philip Reames704e78b2015-04-10 22:34:56 +00001973 DenseMap<Value *, AllocaInst *> AllocaMap;
Philip Reames8531d8c2015-04-10 21:48:25 +00001974 // First is normal return, second is exceptional return (invoke only)
Philip Reames704e78b2015-04-10 22:34:56 +00001975 DenseMap<Value *, std::pair<Value *, Value *>> Replacements;
Philip Reames8531d8c2015-04-10 21:48:25 +00001976 for (Value *V : ToSplit) {
Philip Reames704e78b2015-04-10 22:34:56 +00001977 AllocaInst *Alloca =
1978 new AllocaInst(V->getType(), "", F.getEntryBlock().getFirstNonPHI());
Philip Reames8531d8c2015-04-10 21:48:25 +00001979 AllocaMap[V] = Alloca;
1980
1981 VectorType *VT = cast<VectorType>(V->getType());
1982 IRBuilder<> Builder(StatepointInst);
Philip Reames704e78b2015-04-10 22:34:56 +00001983 SmallVector<Value *, 16> Elements;
Philip Reames8531d8c2015-04-10 21:48:25 +00001984 for (unsigned i = 0; i < VT->getNumElements(); i++)
1985 Elements.push_back(Builder.CreateExtractElement(V, Builder.getInt32(i)));
Philip Reames8fe7f132015-06-26 22:47:37 +00001986 ElementMapping[V] = Elements;
Philip Reames8531d8c2015-04-10 21:48:25 +00001987
1988 auto InsertVectorReform = [&](Instruction *IP) {
1989 Builder.SetInsertPoint(IP);
1990 Builder.SetCurrentDebugLocation(IP->getDebugLoc());
1991 Value *ResultVec = UndefValue::get(VT);
1992 for (unsigned i = 0; i < VT->getNumElements(); i++)
1993 ResultVec = Builder.CreateInsertElement(ResultVec, Elements[i],
1994 Builder.getInt32(i));
1995 return ResultVec;
1996 };
1997
1998 if (isa<CallInst>(StatepointInst)) {
1999 BasicBlock::iterator Next(StatepointInst);
2000 Next++;
2001 Instruction *IP = &*(Next);
2002 Replacements[V].first = InsertVectorReform(IP);
2003 Replacements[V].second = nullptr;
2004 } else {
2005 InvokeInst *Invoke = cast<InvokeInst>(StatepointInst);
2006 // We've already normalized - check that we don't have shared destination
Philip Reames704e78b2015-04-10 22:34:56 +00002007 // blocks
Philip Reames8531d8c2015-04-10 21:48:25 +00002008 BasicBlock *NormalDest = Invoke->getNormalDest();
2009 assert(!isa<PHINode>(NormalDest->begin()));
2010 BasicBlock *UnwindDest = Invoke->getUnwindDest();
2011 assert(!isa<PHINode>(UnwindDest->begin()));
2012 // Insert insert element sequences in both successors
2013 Instruction *IP = &*(NormalDest->getFirstInsertionPt());
2014 Replacements[V].first = InsertVectorReform(IP);
2015 IP = &*(UnwindDest->getFirstInsertionPt());
2016 Replacements[V].second = InsertVectorReform(IP);
2017 }
2018 }
Philip Reames8fe7f132015-06-26 22:47:37 +00002019
Philip Reames8531d8c2015-04-10 21:48:25 +00002020 for (Value *V : ToSplit) {
2021 AllocaInst *Alloca = AllocaMap[V];
2022
2023 // Capture all users before we start mutating use lists
Philip Reames704e78b2015-04-10 22:34:56 +00002024 SmallVector<Instruction *, 16> Users;
Philip Reames8531d8c2015-04-10 21:48:25 +00002025 for (User *U : V->users())
2026 Users.push_back(cast<Instruction>(U));
2027
2028 for (Instruction *I : Users) {
2029 if (auto Phi = dyn_cast<PHINode>(I)) {
2030 for (unsigned i = 0; i < Phi->getNumIncomingValues(); i++)
2031 if (V == Phi->getIncomingValue(i)) {
Philip Reames704e78b2015-04-10 22:34:56 +00002032 LoadInst *Load = new LoadInst(
2033 Alloca, "", Phi->getIncomingBlock(i)->getTerminator());
Philip Reames8531d8c2015-04-10 21:48:25 +00002034 Phi->setIncomingValue(i, Load);
2035 }
2036 } else {
2037 LoadInst *Load = new LoadInst(Alloca, "", I);
2038 I->replaceUsesOfWith(V, Load);
2039 }
2040 }
2041
2042 // Store the original value and the replacement value into the alloca
2043 StoreInst *Store = new StoreInst(V, Alloca);
2044 if (auto I = dyn_cast<Instruction>(V))
2045 Store->insertAfter(I);
2046 else
2047 Store->insertAfter(Alloca);
Philip Reames704e78b2015-04-10 22:34:56 +00002048
Philip Reames8531d8c2015-04-10 21:48:25 +00002049 // Normal return for invoke, or call return
2050 Instruction *Replacement = cast<Instruction>(Replacements[V].first);
2051 (new StoreInst(Replacement, Alloca))->insertAfter(Replacement);
2052 // Unwind return for invoke only
2053 Replacement = cast_or_null<Instruction>(Replacements[V].second);
2054 if (Replacement)
2055 (new StoreInst(Replacement, Alloca))->insertAfter(Replacement);
2056 }
2057
2058 // apply mem2reg to promote alloca to SSA
Philip Reames704e78b2015-04-10 22:34:56 +00002059 SmallVector<AllocaInst *, 16> Allocas;
Philip Reames8531d8c2015-04-10 21:48:25 +00002060 for (Value *V : ToSplit)
2061 Allocas.push_back(AllocaMap[V]);
2062 PromoteMemToReg(Allocas, DT);
Philip Reames8fe7f132015-06-26 22:47:37 +00002063
2064 // Update our tracking of live pointers and base mappings to account for the
2065 // changes we just made.
2066 for (Value *V : ToSplit) {
2067 auto &Elements = ElementMapping[V];
2068
2069 LiveSet.erase(V);
2070 LiveSet.insert(Elements.begin(), Elements.end());
2071 // We need to update the base mapping as well.
2072 assert(PointerToBase.count(V));
2073 Value *OldBase = PointerToBase[V];
2074 auto &BaseElements = ElementMapping[OldBase];
2075 PointerToBase.erase(V);
2076 assert(Elements.size() == BaseElements.size());
2077 for (unsigned i = 0; i < Elements.size(); i++) {
2078 Value *Elem = Elements[i];
2079 PointerToBase[Elem] = BaseElements[i];
2080 }
2081 }
Philip Reames8531d8c2015-04-10 21:48:25 +00002082}
2083
Igor Laevskye0317182015-05-19 15:59:05 +00002084// Helper function for the "rematerializeLiveValues". It walks use chain
2085// starting from the "CurrentValue" until it meets "BaseValue". Only "simple"
2086// values are visited (currently it is GEP's and casts). Returns true if it
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002087// successfully reached "BaseValue" and false otherwise.
Igor Laevskye0317182015-05-19 15:59:05 +00002088// Fills "ChainToBase" array with all visited values. "BaseValue" is not
2089// recorded.
2090static bool findRematerializableChainToBasePointer(
2091 SmallVectorImpl<Instruction*> &ChainToBase,
2092 Value *CurrentValue, Value *BaseValue) {
2093
2094 // We have found a base value
2095 if (CurrentValue == BaseValue) {
2096 return true;
2097 }
2098
2099 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurrentValue)) {
2100 ChainToBase.push_back(GEP);
2101 return findRematerializableChainToBasePointer(ChainToBase,
2102 GEP->getPointerOperand(),
2103 BaseValue);
2104 }
2105
2106 if (CastInst *CI = dyn_cast<CastInst>(CurrentValue)) {
2107 Value *Def = CI->stripPointerCasts();
2108
2109 // This two checks are basically similar. First one is here for the
2110 // consistency with findBasePointers logic.
2111 assert(!isa<CastInst>(Def) && "not a pointer cast found");
2112 if (!CI->isNoopCast(CI->getModule()->getDataLayout()))
2113 return false;
2114
2115 ChainToBase.push_back(CI);
2116 return findRematerializableChainToBasePointer(ChainToBase, Def, BaseValue);
2117 }
2118
2119 // Not supported instruction in the chain
2120 return false;
2121}
2122
2123// Helper function for the "rematerializeLiveValues". Compute cost of the use
2124// chain we are going to rematerialize.
2125static unsigned
2126chainToBasePointerCost(SmallVectorImpl<Instruction*> &Chain,
2127 TargetTransformInfo &TTI) {
2128 unsigned Cost = 0;
2129
2130 for (Instruction *Instr : Chain) {
2131 if (CastInst *CI = dyn_cast<CastInst>(Instr)) {
2132 assert(CI->isNoopCast(CI->getModule()->getDataLayout()) &&
2133 "non noop cast is found during rematerialization");
2134
2135 Type *SrcTy = CI->getOperand(0)->getType();
2136 Cost += TTI.getCastInstrCost(CI->getOpcode(), CI->getType(), SrcTy);
2137
2138 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Instr)) {
2139 // Cost of the address calculation
2140 Type *ValTy = GEP->getPointerOperandType()->getPointerElementType();
2141 Cost += TTI.getAddressComputationCost(ValTy);
2142
2143 // And cost of the GEP itself
2144 // TODO: Use TTI->getGEPCost here (it exists, but appears to be not
2145 // allowed for the external usage)
2146 if (!GEP->hasAllConstantIndices())
2147 Cost += 2;
2148
2149 } else {
2150 llvm_unreachable("unsupported instruciton type during rematerialization");
2151 }
2152 }
2153
2154 return Cost;
2155}
2156
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002157// From the statepoint live set pick values that are cheaper to recompute then
2158// to relocate. Remove this values from the live set, rematerialize them after
Igor Laevskye0317182015-05-19 15:59:05 +00002159// statepoint and record them in "Info" structure. Note that similar to
2160// relocated values we don't do any user adjustments here.
2161static void rematerializeLiveValues(CallSite CS,
2162 PartiallyConstructedSafepointRecord &Info,
2163 TargetTransformInfo &TTI) {
Aaron Ballmanff7d4fa2015-05-20 14:53:50 +00002164 const unsigned int ChainLengthThreshold = 10;
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +00002165
Igor Laevskye0317182015-05-19 15:59:05 +00002166 // Record values we are going to delete from this statepoint live set.
2167 // We can not di this in following loop due to iterator invalidation.
2168 SmallVector<Value *, 32> LiveValuesToBeDeleted;
2169
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002170 for (Value *LiveValue: Info.LiveSet) {
Igor Laevskye0317182015-05-19 15:59:05 +00002171 // For each live pointer find it's defining chain
2172 SmallVector<Instruction *, 3> ChainToBase;
Philip Reames74ce2e72015-07-21 16:51:17 +00002173 assert(Info.PointerToBase.count(LiveValue));
Igor Laevskye0317182015-05-19 15:59:05 +00002174 bool FoundChain =
2175 findRematerializableChainToBasePointer(ChainToBase,
2176 LiveValue,
2177 Info.PointerToBase[LiveValue]);
2178 // Nothing to do, or chain is too long
2179 if (!FoundChain ||
2180 ChainToBase.size() == 0 ||
2181 ChainToBase.size() > ChainLengthThreshold)
2182 continue;
2183
2184 // Compute cost of this chain
2185 unsigned Cost = chainToBasePointerCost(ChainToBase, TTI);
2186 // TODO: We can also account for cases when we will be able to remove some
2187 // of the rematerialized values by later optimization passes. I.e if
2188 // we rematerialized several intersecting chains. Or if original values
2189 // don't have any uses besides this statepoint.
2190
2191 // For invokes we need to rematerialize each chain twice - for normal and
2192 // for unwind basic blocks. Model this by multiplying cost by two.
2193 if (CS.isInvoke()) {
2194 Cost *= 2;
2195 }
2196 // If it's too expensive - skip it
2197 if (Cost >= RematerializationThreshold)
2198 continue;
2199
2200 // Remove value from the live set
2201 LiveValuesToBeDeleted.push_back(LiveValue);
2202
2203 // Clone instructions and record them inside "Info" structure
2204
2205 // Walk backwards to visit top-most instructions first
2206 std::reverse(ChainToBase.begin(), ChainToBase.end());
2207
2208 // Utility function which clones all instructions from "ChainToBase"
2209 // and inserts them before "InsertBefore". Returns rematerialized value
2210 // which should be used after statepoint.
2211 auto rematerializeChain = [&ChainToBase](Instruction *InsertBefore) {
2212 Instruction *LastClonedValue = nullptr;
2213 Instruction *LastValue = nullptr;
2214 for (Instruction *Instr: ChainToBase) {
2215 // Only GEP's and casts are suported as we need to be careful to not
2216 // introduce any new uses of pointers not in the liveset.
2217 // Note that it's fine to introduce new uses of pointers which were
2218 // otherwise not used after this statepoint.
2219 assert(isa<GetElementPtrInst>(Instr) || isa<CastInst>(Instr));
2220
2221 Instruction *ClonedValue = Instr->clone();
2222 ClonedValue->insertBefore(InsertBefore);
2223 ClonedValue->setName(Instr->getName() + ".remat");
2224
2225 // If it is not first instruction in the chain then it uses previously
2226 // cloned value. We should update it to use cloned value.
2227 if (LastClonedValue) {
2228 assert(LastValue);
2229 ClonedValue->replaceUsesOfWith(LastValue, LastClonedValue);
2230#ifndef NDEBUG
Igor Laevskyd83f6972015-05-21 13:02:14 +00002231 // Assert that cloned instruction does not use any instructions from
2232 // this chain other than LastClonedValue
2233 for (auto OpValue : ClonedValue->operand_values()) {
2234 assert(std::find(ChainToBase.begin(), ChainToBase.end(), OpValue) ==
2235 ChainToBase.end() &&
2236 "incorrect use in rematerialization chain");
Igor Laevskye0317182015-05-19 15:59:05 +00002237 }
2238#endif
2239 }
2240
2241 LastClonedValue = ClonedValue;
2242 LastValue = Instr;
2243 }
2244 assert(LastClonedValue);
2245 return LastClonedValue;
2246 };
2247
2248 // Different cases for calls and invokes. For invokes we need to clone
2249 // instructions both on normal and unwind path.
2250 if (CS.isCall()) {
2251 Instruction *InsertBefore = CS.getInstruction()->getNextNode();
2252 assert(InsertBefore);
2253 Instruction *RematerializedValue = rematerializeChain(InsertBefore);
2254 Info.RematerializedValues[RematerializedValue] = LiveValue;
2255 } else {
2256 InvokeInst *Invoke = cast<InvokeInst>(CS.getInstruction());
2257
2258 Instruction *NormalInsertBefore =
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00002259 &*Invoke->getNormalDest()->getFirstInsertionPt();
Igor Laevskye0317182015-05-19 15:59:05 +00002260 Instruction *UnwindInsertBefore =
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00002261 &*Invoke->getUnwindDest()->getFirstInsertionPt();
Igor Laevskye0317182015-05-19 15:59:05 +00002262
2263 Instruction *NormalRematerializedValue =
2264 rematerializeChain(NormalInsertBefore);
2265 Instruction *UnwindRematerializedValue =
2266 rematerializeChain(UnwindInsertBefore);
2267
2268 Info.RematerializedValues[NormalRematerializedValue] = LiveValue;
2269 Info.RematerializedValues[UnwindRematerializedValue] = LiveValue;
2270 }
2271 }
2272
2273 // Remove rematerializaed values from the live set
2274 for (auto LiveValue: LiveValuesToBeDeleted) {
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002275 Info.LiveSet.erase(LiveValue);
Igor Laevskye0317182015-05-19 15:59:05 +00002276 }
2277}
2278
Justin Bogner843fb202015-12-15 19:40:57 +00002279static bool insertParsePoints(Function &F, DominatorTree &DT,
2280 TargetTransformInfo &TTI,
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002281 SmallVectorImpl<CallSite> &ToUpdate) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00002282#ifndef NDEBUG
2283 // sanity check the input
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002284 std::set<CallSite> Uniqued;
2285 Uniqued.insert(ToUpdate.begin(), ToUpdate.end());
2286 assert(Uniqued.size() == ToUpdate.size() && "no duplicates please!");
Philip Reamesd16a9b12015-02-20 01:06:44 +00002287
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002288 for (CallSite CS : ToUpdate) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00002289 assert(CS.getInstruction()->getParent()->getParent() == &F);
Sanjoy Das25ec1a32015-10-16 02:41:00 +00002290 assert((UseDeoptBundles || isStatepoint(CS)) &&
2291 "expected to already be a deopt statepoint");
Philip Reamesd16a9b12015-02-20 01:06:44 +00002292 }
2293#endif
2294
Philip Reames69e51ca2015-04-13 18:07:21 +00002295 // When inserting gc.relocates for invokes, we need to be able to insert at
2296 // the top of the successor blocks. See the comment on
2297 // normalForInvokeSafepoint on exactly what is needed. Note that this step
Philip Reamesf209a152015-04-13 20:00:30 +00002298 // may restructure the CFG.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002299 for (CallSite CS : ToUpdate) {
Philip Reamesf209a152015-04-13 20:00:30 +00002300 if (!CS.isInvoke())
2301 continue;
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002302 auto *II = cast<InvokeInst>(CS.getInstruction());
2303 normalizeForInvokeSafepoint(II->getNormalDest(), II->getParent(), DT);
2304 normalizeForInvokeSafepoint(II->getUnwindDest(), II->getParent(), DT);
Philip Reamesf209a152015-04-13 20:00:30 +00002305 }
Philip Reames69e51ca2015-04-13 18:07:21 +00002306
Philip Reamesd16a9b12015-02-20 01:06:44 +00002307 // A list of dummy calls added to the IR to keep various values obviously
2308 // live in the IR. We'll remove all of these when done.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002309 SmallVector<CallInst *, 64> Holders;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002310
2311 // Insert a dummy call with all of the arguments to the vm_state we'll need
2312 // for the actual safepoint insertion. This ensures reference arguments in
2313 // the deopt argument list are considered live through the safepoint (and
2314 // thus makes sure they get relocated.)
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002315 for (CallSite CS : ToUpdate) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00002316 SmallVector<Value *, 64> DeoptValues;
Sanjoy Das25ec1a32015-10-16 02:41:00 +00002317
2318 iterator_range<const Use *> DeoptStateRange =
2319 UseDeoptBundles
2320 ? iterator_range<const Use *>(GetDeoptBundleOperands(CS))
2321 : iterator_range<const Use *>(Statepoint(CS).vm_state_args());
2322
2323 for (Value *Arg : DeoptStateRange) {
Philip Reames8531d8c2015-04-10 21:48:25 +00002324 assert(!isUnhandledGCPointerType(Arg->getType()) &&
2325 "support for FCA unimplemented");
2326 if (isHandledGCPointerType(Arg->getType()))
Philip Reamesd16a9b12015-02-20 01:06:44 +00002327 DeoptValues.push_back(Arg);
2328 }
Sanjoy Das25ec1a32015-10-16 02:41:00 +00002329
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002330 insertUseHolderAfter(CS, DeoptValues, Holders);
Philip Reamesd16a9b12015-02-20 01:06:44 +00002331 }
2332
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002333 SmallVector<PartiallyConstructedSafepointRecord, 64> Records(ToUpdate.size());
Philip Reamesd16a9b12015-02-20 01:06:44 +00002334
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002335 // A) Identify all gc pointers which are statically live at the given call
Philip Reamesd16a9b12015-02-20 01:06:44 +00002336 // site.
Justin Bogner843fb202015-12-15 19:40:57 +00002337 findLiveReferences(F, DT, ToUpdate, Records);
Philip Reamesd16a9b12015-02-20 01:06:44 +00002338
2339 // B) Find the base pointers for each live pointer
2340 /* scope for caching */ {
2341 // Cache the 'defining value' relation used in the computation and
2342 // insertion of base phis and selects. This ensures that we don't insert
2343 // large numbers of duplicate base_phis.
2344 DefiningValueMapTy DVCache;
2345
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002346 for (size_t i = 0; i < Records.size(); i++) {
2347 PartiallyConstructedSafepointRecord &info = Records[i];
2348 findBasePointers(DT, DVCache, ToUpdate[i], info);
Philip Reamesd16a9b12015-02-20 01:06:44 +00002349 }
2350 } // end of cache scope
2351
2352 // The base phi insertion logic (for any safepoint) may have inserted new
2353 // instructions which are now live at some safepoint. The simplest such
2354 // example is:
2355 // loop:
2356 // phi a <-- will be a new base_phi here
2357 // safepoint 1 <-- that needs to be live here
2358 // gep a + 1
2359 // safepoint 2
2360 // br loop
Philip Reamesd16a9b12015-02-20 01:06:44 +00002361 // We insert some dummy calls after each safepoint to definitely hold live
2362 // the base pointers which were identified for that safepoint. We'll then
2363 // ask liveness for _every_ base inserted to see what is now live. Then we
2364 // remove the dummy calls.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002365 Holders.reserve(Holders.size() + Records.size());
2366 for (size_t i = 0; i < Records.size(); i++) {
2367 PartiallyConstructedSafepointRecord &Info = Records[i];
Philip Reamesd16a9b12015-02-20 01:06:44 +00002368
2369 SmallVector<Value *, 128> Bases;
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002370 for (auto Pair : Info.PointerToBase)
Philip Reamesd16a9b12015-02-20 01:06:44 +00002371 Bases.push_back(Pair.second);
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002372
2373 insertUseHolderAfter(ToUpdate[i], Bases, Holders);
Philip Reamesd16a9b12015-02-20 01:06:44 +00002374 }
2375
Philip Reamesdf1ef082015-04-10 22:53:14 +00002376 // By selecting base pointers, we've effectively inserted new uses. Thus, we
2377 // need to rerun liveness. We may *also* have inserted new defs, but that's
2378 // not the key issue.
Justin Bogner843fb202015-12-15 19:40:57 +00002379 recomputeLiveInValues(F, DT, ToUpdate, Records);
Philip Reamesd16a9b12015-02-20 01:06:44 +00002380
Philip Reamesd16a9b12015-02-20 01:06:44 +00002381 if (PrintBasePointers) {
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002382 for (auto &Info : Records) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00002383 errs() << "Base Pairs: (w/Relocation)\n";
Manuel Jacoba4efd8a2015-12-23 00:19:45 +00002384 for (auto Pair : Info.PointerToBase) {
2385 errs() << " derived ";
2386 Pair.first->printAsOperand(errs(), false);
2387 errs() << " base ";
2388 Pair.second->printAsOperand(errs(), false);
2389 errs() << "\n";
2390 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00002391 }
2392 }
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002393
Manuel Jacob990dfa62015-12-22 16:50:44 +00002394 // It is possible that non-constant live variables have a constant base. For
2395 // example, a GEP with a variable offset from a global. In this case we can
2396 // remove it from the liveset. We already don't add constants to the liveset
2397 // because we assume they won't move at runtime and the GC doesn't need to be
2398 // informed about them. The same reasoning applies if the base is constant.
2399 // Note that the relocation placement code relies on this filtering for
2400 // correctness as it expects the base to be in the liveset, which isn't true
2401 // if the base is constant.
2402 for (auto &Info : Records)
2403 for (auto &BasePair : Info.PointerToBase)
2404 if (isa<Constant>(BasePair.second))
2405 Info.LiveSet.erase(BasePair.first);
2406
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002407 for (CallInst *CI : Holders)
2408 CI->eraseFromParent();
2409
2410 Holders.clear();
Philip Reamesd16a9b12015-02-20 01:06:44 +00002411
Philip Reames8fe7f132015-06-26 22:47:37 +00002412 // Do a limited scalarization of any live at safepoint vector values which
2413 // contain pointers. This enables this pass to run after vectorization at
2414 // the cost of some possible performance loss. TODO: it would be nice to
2415 // natively support vectors all the way through the backend so we don't need
2416 // to scalarize here.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002417 for (size_t i = 0; i < Records.size(); i++) {
2418 PartiallyConstructedSafepointRecord &Info = Records[i];
2419 Instruction *Statepoint = ToUpdate[i].getInstruction();
2420 splitVectorValues(cast<Instruction>(Statepoint), Info.LiveSet,
2421 Info.PointerToBase, DT);
Philip Reames8fe7f132015-06-26 22:47:37 +00002422 }
2423
Igor Laevskye0317182015-05-19 15:59:05 +00002424 // In order to reduce live set of statepoint we might choose to rematerialize
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002425 // some values instead of relocating them. This is purely an optimization and
Igor Laevskye0317182015-05-19 15:59:05 +00002426 // does not influence correctness.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002427 for (size_t i = 0; i < Records.size(); i++)
2428 rematerializeLiveValues(ToUpdate[i], Records[i], TTI);
Igor Laevskye0317182015-05-19 15:59:05 +00002429
Sanjoy Das25ec1a32015-10-16 02:41:00 +00002430 // We need this to safely RAUW and delete call or invoke return values that
2431 // may themselves be live over a statepoint. For details, please see usage in
2432 // makeStatepointExplicitImpl.
2433 std::vector<DeferredReplacement> Replacements;
2434
Philip Reamesd16a9b12015-02-20 01:06:44 +00002435 // Now run through and replace the existing statepoints with new ones with
2436 // the live variables listed. We do not yet update uses of the values being
2437 // relocated. We have references to live variables that need to
2438 // survive to the last iteration of this loop. (By construction, the
2439 // previous statepoint can not be a live variable, thus we can and remove
2440 // the old statepoint calls as we go.)
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002441 for (size_t i = 0; i < Records.size(); i++)
Sanjoy Das25ec1a32015-10-16 02:41:00 +00002442 makeStatepointExplicit(DT, ToUpdate[i], Records[i], Replacements);
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002443
2444 ToUpdate.clear(); // prevent accident use of invalid CallSites
Philip Reamesd16a9b12015-02-20 01:06:44 +00002445
Sanjoy Das25ec1a32015-10-16 02:41:00 +00002446 for (auto &PR : Replacements)
2447 PR.doReplacement();
2448
2449 Replacements.clear();
2450
2451 for (auto &Info : Records) {
2452 // These live sets may contain state Value pointers, since we replaced calls
2453 // with operand bundles with calls wrapped in gc.statepoint, and some of
2454 // those calls may have been def'ing live gc pointers. Clear these out to
2455 // avoid accidentally using them.
2456 //
2457 // TODO: We should create a separate data structure that does not contain
2458 // these live sets, and migrate to using that data structure from this point
2459 // onward.
2460 Info.LiveSet.clear();
2461 Info.PointerToBase.clear();
2462 }
2463
Philip Reamesd16a9b12015-02-20 01:06:44 +00002464 // Do all the fixups of the original live variables to their relocated selves
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002465 SmallVector<Value *, 128> Live;
2466 for (size_t i = 0; i < Records.size(); i++) {
2467 PartiallyConstructedSafepointRecord &Info = Records[i];
Sanjoy Das25ec1a32015-10-16 02:41:00 +00002468
Philip Reamesd16a9b12015-02-20 01:06:44 +00002469 // We can't simply save the live set from the original insertion. One of
2470 // the live values might be the result of a call which needs a safepoint.
2471 // That Value* no longer exists and we need to use the new gc_result.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002472 // Thankfully, the live set is embedded in the statepoint (and updated), so
Philip Reamesd16a9b12015-02-20 01:06:44 +00002473 // we just grab that.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002474 Statepoint Statepoint(Info.StatepointToken);
2475 Live.insert(Live.end(), Statepoint.gc_args_begin(),
2476 Statepoint.gc_args_end());
Philip Reames9a2e01d2015-04-13 17:35:55 +00002477#ifndef NDEBUG
2478 // Do some basic sanity checks on our liveness results before performing
2479 // relocation. Relocation can and will turn mistakes in liveness results
2480 // into non-sensical code which is must harder to debug.
2481 // TODO: It would be nice to test consistency as well
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002482 assert(DT.isReachableFromEntry(Info.StatepointToken->getParent()) &&
Philip Reames9a2e01d2015-04-13 17:35:55 +00002483 "statepoint must be reachable or liveness is meaningless");
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002484 for (Value *V : Statepoint.gc_args()) {
Philip Reames9a2e01d2015-04-13 17:35:55 +00002485 if (!isa<Instruction>(V))
2486 // Non-instruction values trivial dominate all possible uses
2487 continue;
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002488 auto *LiveInst = cast<Instruction>(V);
Philip Reames9a2e01d2015-04-13 17:35:55 +00002489 assert(DT.isReachableFromEntry(LiveInst->getParent()) &&
2490 "unreachable values should never be live");
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002491 assert(DT.dominates(LiveInst, Info.StatepointToken) &&
Philip Reames9a2e01d2015-04-13 17:35:55 +00002492 "basic SSA liveness expectation violated by liveness analysis");
2493 }
2494#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +00002495 }
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002496 unique_unsorted(Live);
Philip Reamesd16a9b12015-02-20 01:06:44 +00002497
Nick Lewyckyeb3231e2015-02-20 07:14:02 +00002498#ifndef NDEBUG
Philip Reamesd16a9b12015-02-20 01:06:44 +00002499 // sanity check
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002500 for (auto *Ptr : Live)
2501 assert(isGCPointerType(Ptr->getType()) && "must be a gc pointer type");
Nick Lewyckyeb3231e2015-02-20 07:14:02 +00002502#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +00002503
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002504 relocationViaAlloca(F, DT, Live, Records);
2505 return !Records.empty();
Philip Reamesd16a9b12015-02-20 01:06:44 +00002506}
2507
Sanjoy Das353a19e2015-06-02 22:33:37 +00002508// Handles both return values and arguments for Functions and CallSites.
2509template <typename AttrHolder>
Igor Laevskydde00292015-10-23 22:42:44 +00002510static void RemoveNonValidAttrAtIndex(LLVMContext &Ctx, AttrHolder &AH,
2511 unsigned Index) {
Sanjoy Das353a19e2015-06-02 22:33:37 +00002512 AttrBuilder R;
2513 if (AH.getDereferenceableBytes(Index))
2514 R.addAttribute(Attribute::get(Ctx, Attribute::Dereferenceable,
2515 AH.getDereferenceableBytes(Index)));
2516 if (AH.getDereferenceableOrNullBytes(Index))
2517 R.addAttribute(Attribute::get(Ctx, Attribute::DereferenceableOrNull,
2518 AH.getDereferenceableOrNullBytes(Index)));
Igor Laevsky1ef06552015-10-26 19:06:01 +00002519 if (AH.doesNotAlias(Index))
2520 R.addAttribute(Attribute::NoAlias);
Sanjoy Das353a19e2015-06-02 22:33:37 +00002521
2522 if (!R.empty())
2523 AH.setAttributes(AH.getAttributes().removeAttributes(
2524 Ctx, Index, AttributeSet::get(Ctx, Index, R)));
Vasileios Kalintiris9f77f612015-06-03 08:51:30 +00002525}
Sanjoy Das353a19e2015-06-02 22:33:37 +00002526
2527void
Igor Laevskydde00292015-10-23 22:42:44 +00002528RewriteStatepointsForGC::stripNonValidAttributesFromPrototype(Function &F) {
Sanjoy Das353a19e2015-06-02 22:33:37 +00002529 LLVMContext &Ctx = F.getContext();
2530
2531 for (Argument &A : F.args())
2532 if (isa<PointerType>(A.getType()))
Igor Laevskydde00292015-10-23 22:42:44 +00002533 RemoveNonValidAttrAtIndex(Ctx, F, A.getArgNo() + 1);
Sanjoy Das353a19e2015-06-02 22:33:37 +00002534
2535 if (isa<PointerType>(F.getReturnType()))
Igor Laevskydde00292015-10-23 22:42:44 +00002536 RemoveNonValidAttrAtIndex(Ctx, F, AttributeSet::ReturnIndex);
Sanjoy Das353a19e2015-06-02 22:33:37 +00002537}
2538
Igor Laevskydde00292015-10-23 22:42:44 +00002539void RewriteStatepointsForGC::stripNonValidAttributesFromBody(Function &F) {
Sanjoy Das353a19e2015-06-02 22:33:37 +00002540 if (F.empty())
2541 return;
2542
2543 LLVMContext &Ctx = F.getContext();
2544 MDBuilder Builder(Ctx);
2545
Nico Rieck78199512015-08-06 19:10:45 +00002546 for (Instruction &I : instructions(F)) {
Sanjoy Das353a19e2015-06-02 22:33:37 +00002547 if (const MDNode *MD = I.getMetadata(LLVMContext::MD_tbaa)) {
2548 assert(MD->getNumOperands() < 5 && "unrecognized metadata shape!");
2549 bool IsImmutableTBAA =
2550 MD->getNumOperands() == 4 &&
2551 mdconst::extract<ConstantInt>(MD->getOperand(3))->getValue() == 1;
2552
2553 if (!IsImmutableTBAA)
2554 continue; // no work to do, MD_tbaa is already marked mutable
2555
2556 MDNode *Base = cast<MDNode>(MD->getOperand(0));
2557 MDNode *Access = cast<MDNode>(MD->getOperand(1));
2558 uint64_t Offset =
2559 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue();
2560
2561 MDNode *MutableTBAA =
2562 Builder.createTBAAStructTagNode(Base, Access, Offset);
2563 I.setMetadata(LLVMContext::MD_tbaa, MutableTBAA);
2564 }
2565
2566 if (CallSite CS = CallSite(&I)) {
2567 for (int i = 0, e = CS.arg_size(); i != e; i++)
2568 if (isa<PointerType>(CS.getArgument(i)->getType()))
Igor Laevskydde00292015-10-23 22:42:44 +00002569 RemoveNonValidAttrAtIndex(Ctx, CS, i + 1);
Sanjoy Das353a19e2015-06-02 22:33:37 +00002570 if (isa<PointerType>(CS.getType()))
Igor Laevskydde00292015-10-23 22:42:44 +00002571 RemoveNonValidAttrAtIndex(Ctx, CS, AttributeSet::ReturnIndex);
Sanjoy Das353a19e2015-06-02 22:33:37 +00002572 }
2573 }
2574}
2575
Philip Reamesd16a9b12015-02-20 01:06:44 +00002576/// Returns true if this function should be rewritten by this pass. The main
2577/// point of this function is as an extension point for custom logic.
2578static bool shouldRewriteStatepointsIn(Function &F) {
2579 // TODO: This should check the GCStrategy
Philip Reames2ef029c2015-02-20 18:56:14 +00002580 if (F.hasGC()) {
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +00002581 const char *FunctionGCName = F.getGC();
2582 const StringRef StatepointExampleName("statepoint-example");
2583 const StringRef CoreCLRName("coreclr");
2584 return (StatepointExampleName == FunctionGCName) ||
NAKAMURA Takumi5582a6a2015-05-25 01:43:34 +00002585 (CoreCLRName == FunctionGCName);
2586 } else
Philip Reames2ef029c2015-02-20 18:56:14 +00002587 return false;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002588}
2589
Igor Laevskydde00292015-10-23 22:42:44 +00002590void RewriteStatepointsForGC::stripNonValidAttributes(Module &M) {
Sanjoy Das353a19e2015-06-02 22:33:37 +00002591#ifndef NDEBUG
2592 assert(std::any_of(M.begin(), M.end(), shouldRewriteStatepointsIn) &&
2593 "precondition!");
2594#endif
2595
2596 for (Function &F : M)
Igor Laevskydde00292015-10-23 22:42:44 +00002597 stripNonValidAttributesFromPrototype(F);
Sanjoy Das353a19e2015-06-02 22:33:37 +00002598
2599 for (Function &F : M)
Igor Laevskydde00292015-10-23 22:42:44 +00002600 stripNonValidAttributesFromBody(F);
Sanjoy Das353a19e2015-06-02 22:33:37 +00002601}
2602
Philip Reamesd16a9b12015-02-20 01:06:44 +00002603bool RewriteStatepointsForGC::runOnFunction(Function &F) {
2604 // Nothing to do for declarations.
2605 if (F.isDeclaration() || F.empty())
2606 return false;
2607
2608 // Policy choice says not to rewrite - the most common reason is that we're
2609 // compiling code without a GCStrategy.
2610 if (!shouldRewriteStatepointsIn(F))
2611 return false;
2612
Sanjoy Dasea45f0e2015-06-02 22:33:34 +00002613 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
Justin Bogner843fb202015-12-15 19:40:57 +00002614 TargetTransformInfo &TTI =
2615 getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
Philip Reames704e78b2015-04-10 22:34:56 +00002616
Sanjoy Das25ec1a32015-10-16 02:41:00 +00002617 auto NeedsRewrite = [](Instruction &I) {
2618 if (UseDeoptBundles) {
2619 if (ImmutableCallSite CS = ImmutableCallSite(&I))
2620 return !callsGCLeafFunction(CS);
2621 return false;
2622 }
2623
2624 return isStatepoint(I);
2625 };
2626
Philip Reames85b36a82015-04-10 22:07:04 +00002627 // Gather all the statepoints which need rewritten. Be careful to only
2628 // consider those in reachable code since we need to ask dominance queries
2629 // when rewriting. We'll delete the unreachable ones in a moment.
Philip Reamesd2b66462015-02-20 22:39:41 +00002630 SmallVector<CallSite, 64> ParsePointNeeded;
Philip Reamesf66d7372015-04-10 22:16:58 +00002631 bool HasUnreachableStatepoint = false;
Nico Rieck78199512015-08-06 19:10:45 +00002632 for (Instruction &I : instructions(F)) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00002633 // TODO: only the ones with the flag set!
Sanjoy Das25ec1a32015-10-16 02:41:00 +00002634 if (NeedsRewrite(I)) {
Philip Reames85b36a82015-04-10 22:07:04 +00002635 if (DT.isReachableFromEntry(I.getParent()))
2636 ParsePointNeeded.push_back(CallSite(&I));
2637 else
Philip Reamesf66d7372015-04-10 22:16:58 +00002638 HasUnreachableStatepoint = true;
Philip Reames85b36a82015-04-10 22:07:04 +00002639 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00002640 }
2641
Philip Reames85b36a82015-04-10 22:07:04 +00002642 bool MadeChange = false;
Philip Reames704e78b2015-04-10 22:34:56 +00002643
Philip Reames85b36a82015-04-10 22:07:04 +00002644 // Delete any unreachable statepoints so that we don't have unrewritten
2645 // statepoints surviving this pass. This makes testing easier and the
2646 // resulting IR less confusing to human readers. Rather than be fancy, we
2647 // just reuse a utility function which removes the unreachable blocks.
Philip Reamesf66d7372015-04-10 22:16:58 +00002648 if (HasUnreachableStatepoint)
Philip Reames85b36a82015-04-10 22:07:04 +00002649 MadeChange |= removeUnreachableBlocks(F);
2650
Philip Reamesd16a9b12015-02-20 01:06:44 +00002651 // Return early if no work to do.
2652 if (ParsePointNeeded.empty())
Philip Reames85b36a82015-04-10 22:07:04 +00002653 return MadeChange;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002654
Philip Reames85b36a82015-04-10 22:07:04 +00002655 // As a prepass, go ahead and aggressively destroy single entry phi nodes.
2656 // These are created by LCSSA. They have the effect of increasing the size
2657 // of liveness sets for no good reason. It may be harder to do this post
2658 // insertion since relocations and base phis can confuse things.
2659 for (BasicBlock &BB : F)
2660 if (BB.getUniquePredecessor()) {
2661 MadeChange = true;
2662 FoldSingleEntryPHINodes(&BB);
2663 }
2664
Philip Reames971dc3a2015-08-12 22:11:45 +00002665 // Before we start introducing relocations, we want to tweak the IR a bit to
2666 // avoid unfortunate code generation effects. The main example is that we
2667 // want to try to make sure the comparison feeding a branch is after any
2668 // safepoints. Otherwise, we end up with a comparison of pre-relocation
2669 // values feeding a branch after relocation. This is semantically correct,
2670 // but results in extra register pressure since both the pre-relocation and
2671 // post-relocation copies must be available in registers. For code without
2672 // relocations this is handled elsewhere, but teaching the scheduler to
2673 // reverse the transform we're about to do would be slightly complex.
2674 // Note: This may extend the live range of the inputs to the icmp and thus
2675 // increase the liveset of any statepoint we move over. This is profitable
2676 // as long as all statepoints are in rare blocks. If we had in-register
2677 // lowering for live values this would be a much safer transform.
2678 auto getConditionInst = [](TerminatorInst *TI) -> Instruction* {
2679 if (auto *BI = dyn_cast<BranchInst>(TI))
2680 if (BI->isConditional())
2681 return dyn_cast<Instruction>(BI->getCondition());
2682 // TODO: Extend this to handle switches
2683 return nullptr;
2684 };
2685 for (BasicBlock &BB : F) {
2686 TerminatorInst *TI = BB.getTerminator();
2687 if (auto *Cond = getConditionInst(TI))
2688 // TODO: Handle more than just ICmps here. We should be able to move
2689 // most instructions without side effects or memory access.
2690 if (isa<ICmpInst>(Cond) && Cond->hasOneUse()) {
2691 MadeChange = true;
2692 Cond->moveBefore(TI);
2693 }
2694 }
2695
Justin Bogner843fb202015-12-15 19:40:57 +00002696 MadeChange |= insertParsePoints(F, DT, TTI, ParsePointNeeded);
Philip Reames85b36a82015-04-10 22:07:04 +00002697 return MadeChange;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002698}
Philip Reamesdf1ef082015-04-10 22:53:14 +00002699
2700// liveness computation via standard dataflow
2701// -------------------------------------------------------------------
2702
2703// TODO: Consider using bitvectors for liveness, the set of potentially
2704// interesting values should be small and easy to pre-compute.
2705
Philip Reamesdf1ef082015-04-10 22:53:14 +00002706/// Compute the live-in set for the location rbegin starting from
2707/// the live-out set of the basic block
2708static void computeLiveInValues(BasicBlock::reverse_iterator rbegin,
2709 BasicBlock::reverse_iterator rend,
2710 DenseSet<Value *> &LiveTmp) {
2711
2712 for (BasicBlock::reverse_iterator ritr = rbegin; ritr != rend; ritr++) {
2713 Instruction *I = &*ritr;
2714
2715 // KILL/Def - Remove this definition from LiveIn
2716 LiveTmp.erase(I);
2717
2718 // Don't consider *uses* in PHI nodes, we handle their contribution to
2719 // predecessor blocks when we seed the LiveOut sets
2720 if (isa<PHINode>(I))
2721 continue;
2722
2723 // USE - Add to the LiveIn set for this instruction
2724 for (Value *V : I->operands()) {
2725 assert(!isUnhandledGCPointerType(V->getType()) &&
2726 "support for FCA unimplemented");
Philip Reames63294cb2015-04-26 19:48:03 +00002727 if (isHandledGCPointerType(V->getType()) && !isa<Constant>(V)) {
2728 // The choice to exclude all things constant here is slightly subtle.
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002729 // There are two independent reasons:
Philip Reames63294cb2015-04-26 19:48:03 +00002730 // - We assume that things which are constant (from LLVM's definition)
2731 // do not move at runtime. For example, the address of a global
2732 // variable is fixed, even though it's contents may not be.
2733 // - Second, we can't disallow arbitrary inttoptr constants even
2734 // if the language frontend does. Optimization passes are free to
2735 // locally exploit facts without respect to global reachability. This
2736 // can create sections of code which are dynamically unreachable and
2737 // contain just about anything. (see constants.ll in tests)
Philip Reamesdf1ef082015-04-10 22:53:14 +00002738 LiveTmp.insert(V);
2739 }
2740 }
2741 }
2742}
2743
2744static void computeLiveOutSeed(BasicBlock *BB, DenseSet<Value *> &LiveTmp) {
2745
2746 for (BasicBlock *Succ : successors(BB)) {
2747 const BasicBlock::iterator E(Succ->getFirstNonPHI());
2748 for (BasicBlock::iterator I = Succ->begin(); I != E; I++) {
2749 PHINode *Phi = cast<PHINode>(&*I);
2750 Value *V = Phi->getIncomingValueForBlock(BB);
2751 assert(!isUnhandledGCPointerType(V->getType()) &&
2752 "support for FCA unimplemented");
Philip Reames63294cb2015-04-26 19:48:03 +00002753 if (isHandledGCPointerType(V->getType()) && !isa<Constant>(V)) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00002754 LiveTmp.insert(V);
2755 }
2756 }
2757 }
2758}
2759
2760static DenseSet<Value *> computeKillSet(BasicBlock *BB) {
2761 DenseSet<Value *> KillSet;
2762 for (Instruction &I : *BB)
2763 if (isHandledGCPointerType(I.getType()))
2764 KillSet.insert(&I);
2765 return KillSet;
2766}
2767
Philip Reames9638ff92015-04-11 00:06:47 +00002768#ifndef NDEBUG
Philip Reamesdf1ef082015-04-10 22:53:14 +00002769/// Check that the items in 'Live' dominate 'TI'. This is used as a basic
2770/// sanity check for the liveness computation.
2771static void checkBasicSSA(DominatorTree &DT, DenseSet<Value *> &Live,
2772 TerminatorInst *TI, bool TermOkay = false) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00002773 for (Value *V : Live) {
2774 if (auto *I = dyn_cast<Instruction>(V)) {
2775 // The terminator can be a member of the LiveOut set. LLVM's definition
2776 // of instruction dominance states that V does not dominate itself. As
2777 // such, we need to special case this to allow it.
2778 if (TermOkay && TI == I)
2779 continue;
2780 assert(DT.dominates(I, TI) &&
2781 "basic SSA liveness expectation violated by liveness analysis");
2782 }
2783 }
Philip Reamesdf1ef082015-04-10 22:53:14 +00002784}
2785
2786/// Check that all the liveness sets used during the computation of liveness
2787/// obey basic SSA properties. This is useful for finding cases where we miss
2788/// a def.
2789static void checkBasicSSA(DominatorTree &DT, GCPtrLivenessData &Data,
2790 BasicBlock &BB) {
2791 checkBasicSSA(DT, Data.LiveSet[&BB], BB.getTerminator());
2792 checkBasicSSA(DT, Data.LiveOut[&BB], BB.getTerminator(), true);
2793 checkBasicSSA(DT, Data.LiveIn[&BB], BB.getTerminator());
2794}
Philip Reames9638ff92015-04-11 00:06:47 +00002795#endif
Philip Reamesdf1ef082015-04-10 22:53:14 +00002796
2797static void computeLiveInValues(DominatorTree &DT, Function &F,
2798 GCPtrLivenessData &Data) {
2799
Philip Reames4d80ede2015-04-10 23:11:26 +00002800 SmallSetVector<BasicBlock *, 200> Worklist;
Philip Reamesdf1ef082015-04-10 22:53:14 +00002801 auto AddPredsToWorklist = [&](BasicBlock *BB) {
Philip Reames4d80ede2015-04-10 23:11:26 +00002802 // We use a SetVector so that we don't have duplicates in the worklist.
2803 Worklist.insert(pred_begin(BB), pred_end(BB));
Philip Reamesdf1ef082015-04-10 22:53:14 +00002804 };
2805 auto NextItem = [&]() {
2806 BasicBlock *BB = Worklist.back();
2807 Worklist.pop_back();
Philip Reamesdf1ef082015-04-10 22:53:14 +00002808 return BB;
2809 };
2810
2811 // Seed the liveness for each individual block
2812 for (BasicBlock &BB : F) {
2813 Data.KillSet[&BB] = computeKillSet(&BB);
2814 Data.LiveSet[&BB].clear();
2815 computeLiveInValues(BB.rbegin(), BB.rend(), Data.LiveSet[&BB]);
2816
2817#ifndef NDEBUG
2818 for (Value *Kill : Data.KillSet[&BB])
2819 assert(!Data.LiveSet[&BB].count(Kill) && "live set contains kill");
2820#endif
2821
2822 Data.LiveOut[&BB] = DenseSet<Value *>();
2823 computeLiveOutSeed(&BB, Data.LiveOut[&BB]);
2824 Data.LiveIn[&BB] = Data.LiveSet[&BB];
2825 set_union(Data.LiveIn[&BB], Data.LiveOut[&BB]);
2826 set_subtract(Data.LiveIn[&BB], Data.KillSet[&BB]);
2827 if (!Data.LiveIn[&BB].empty())
2828 AddPredsToWorklist(&BB);
2829 }
2830
2831 // Propagate that liveness until stable
2832 while (!Worklist.empty()) {
2833 BasicBlock *BB = NextItem();
2834
2835 // Compute our new liveout set, then exit early if it hasn't changed
2836 // despite the contribution of our successor.
2837 DenseSet<Value *> LiveOut = Data.LiveOut[BB];
2838 const auto OldLiveOutSize = LiveOut.size();
2839 for (BasicBlock *Succ : successors(BB)) {
2840 assert(Data.LiveIn.count(Succ));
2841 set_union(LiveOut, Data.LiveIn[Succ]);
2842 }
2843 // assert OutLiveOut is a subset of LiveOut
2844 if (OldLiveOutSize == LiveOut.size()) {
2845 // If the sets are the same size, then we didn't actually add anything
2846 // when unioning our successors LiveIn Thus, the LiveIn of this block
2847 // hasn't changed.
2848 continue;
2849 }
2850 Data.LiveOut[BB] = LiveOut;
2851
2852 // Apply the effects of this basic block
2853 DenseSet<Value *> LiveTmp = LiveOut;
2854 set_union(LiveTmp, Data.LiveSet[BB]);
2855 set_subtract(LiveTmp, Data.KillSet[BB]);
2856
2857 assert(Data.LiveIn.count(BB));
2858 const DenseSet<Value *> &OldLiveIn = Data.LiveIn[BB];
2859 // assert: OldLiveIn is a subset of LiveTmp
2860 if (OldLiveIn.size() != LiveTmp.size()) {
2861 Data.LiveIn[BB] = LiveTmp;
2862 AddPredsToWorklist(BB);
2863 }
2864 } // while( !worklist.empty() )
2865
2866#ifndef NDEBUG
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002867 // Sanity check our output against SSA properties. This helps catch any
Philip Reamesdf1ef082015-04-10 22:53:14 +00002868 // missing kills during the above iteration.
2869 for (BasicBlock &BB : F) {
2870 checkBasicSSA(DT, Data, BB);
2871 }
2872#endif
2873}
2874
2875static void findLiveSetAtInst(Instruction *Inst, GCPtrLivenessData &Data,
2876 StatepointLiveSetTy &Out) {
2877
2878 BasicBlock *BB = Inst->getParent();
2879
2880 // Note: The copy is intentional and required
2881 assert(Data.LiveOut.count(BB));
2882 DenseSet<Value *> LiveOut = Data.LiveOut[BB];
2883
2884 // We want to handle the statepoint itself oddly. It's
2885 // call result is not live (normal), nor are it's arguments
2886 // (unless they're used again later). This adjustment is
2887 // specifically what we need to relocate
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00002888 BasicBlock::reverse_iterator rend(Inst->getIterator());
Philip Reamesdf1ef082015-04-10 22:53:14 +00002889 computeLiveInValues(BB->rbegin(), rend, LiveOut);
2890 LiveOut.erase(Inst);
2891 Out.insert(LiveOut.begin(), LiveOut.end());
2892}
2893
2894static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData,
2895 const CallSite &CS,
2896 PartiallyConstructedSafepointRecord &Info) {
2897 Instruction *Inst = CS.getInstruction();
2898 StatepointLiveSetTy Updated;
2899 findLiveSetAtInst(Inst, RevisedLivenessData, Updated);
2900
2901#ifndef NDEBUG
2902 DenseSet<Value *> Bases;
2903 for (auto KVPair : Info.PointerToBase) {
2904 Bases.insert(KVPair.second);
2905 }
2906#endif
2907 // We may have base pointers which are now live that weren't before. We need
2908 // to update the PointerToBase structure to reflect this.
2909 for (auto V : Updated)
2910 if (!Info.PointerToBase.count(V)) {
2911 assert(Bases.count(V) && "can't find base for unexpected live value");
2912 Info.PointerToBase[V] = V;
2913 continue;
2914 }
2915
2916#ifndef NDEBUG
2917 for (auto V : Updated) {
2918 assert(Info.PointerToBase.count(V) &&
2919 "must be able to find base for live value");
2920 }
2921#endif
2922
2923 // Remove any stale base mappings - this can happen since our liveness is
2924 // more precise then the one inherent in the base pointer analysis
2925 DenseSet<Value *> ToErase;
2926 for (auto KVPair : Info.PointerToBase)
2927 if (!Updated.count(KVPair.first))
2928 ToErase.insert(KVPair.first);
2929 for (auto V : ToErase)
2930 Info.PointerToBase.erase(V);
2931
2932#ifndef NDEBUG
2933 for (auto KVPair : Info.PointerToBase)
2934 assert(Updated.count(KVPair.first) && "record for non-live value");
2935#endif
2936
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002937 Info.LiveSet = Updated;
Philip Reamesdf1ef082015-04-10 22:53:14 +00002938}