blob: 4e165e24f49853cad67621c16b14ad4ed18c71bf [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"
17#include "llvm/ADT/SetOperations.h"
18#include "llvm/ADT/Statistic.h"
19#include "llvm/ADT/DenseSet.h"
20#include "llvm/IR/BasicBlock.h"
21#include "llvm/IR/CallSite.h"
22#include "llvm/IR/Dominators.h"
23#include "llvm/IR/Function.h"
24#include "llvm/IR/IRBuilder.h"
25#include "llvm/IR/InstIterator.h"
26#include "llvm/IR/Instructions.h"
27#include "llvm/IR/Intrinsics.h"
28#include "llvm/IR/IntrinsicInst.h"
29#include "llvm/IR/Module.h"
30#include "llvm/IR/Statepoint.h"
31#include "llvm/IR/Value.h"
32#include "llvm/IR/Verifier.h"
33#include "llvm/Support/Debug.h"
34#include "llvm/Support/CommandLine.h"
35#include "llvm/Transforms/Scalar.h"
36#include "llvm/Transforms/Utils/BasicBlockUtils.h"
37#include "llvm/Transforms/Utils/Cloning.h"
38#include "llvm/Transforms/Utils/Local.h"
39#include "llvm/Transforms/Utils/PromoteMemToReg.h"
40
41#define DEBUG_TYPE "rewrite-statepoints-for-gc"
42
43using namespace llvm;
44
45// Print tracing output
46static cl::opt<bool> TraceLSP("trace-rewrite-statepoints", cl::Hidden,
47 cl::init(false));
48
49// Print the liveset found at the insert location
50static cl::opt<bool> PrintLiveSet("spp-print-liveset", cl::Hidden,
51 cl::init(false));
52static cl::opt<bool> PrintLiveSetSize("spp-print-liveset-size",
53 cl::Hidden, cl::init(false));
54// Print out the base pointers for debugging
55static cl::opt<bool> PrintBasePointers("spp-print-base-pointers",
56 cl::Hidden, cl::init(false));
57
Benjamin Kramer6f665452015-02-20 14:00:58 +000058namespace {
Philip Reamesd16a9b12015-02-20 01:06:44 +000059struct RewriteStatepointsForGC : public FunctionPass {
60 static char ID; // Pass identification, replacement for typeid
61
62 RewriteStatepointsForGC() : FunctionPass(ID) {
63 initializeRewriteStatepointsForGCPass(*PassRegistry::getPassRegistry());
64 }
65 bool runOnFunction(Function &F) override;
66
67 void getAnalysisUsage(AnalysisUsage &AU) const override {
68 // We add and rewrite a bunch of instructions, but don't really do much
69 // else. We could in theory preserve a lot more analyses here.
70 AU.addRequired<DominatorTreeWrapperPass>();
71 }
72};
Benjamin Kramer6f665452015-02-20 14:00:58 +000073} // namespace
Philip Reamesd16a9b12015-02-20 01:06:44 +000074
75char RewriteStatepointsForGC::ID = 0;
76
77FunctionPass *llvm::createRewriteStatepointsForGCPass() {
78 return new RewriteStatepointsForGC();
79}
80
81INITIALIZE_PASS_BEGIN(RewriteStatepointsForGC, "rewrite-statepoints-for-gc",
82 "Make relocations explicit at statepoints", false, false)
83INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
84INITIALIZE_PASS_END(RewriteStatepointsForGC, "rewrite-statepoints-for-gc",
85 "Make relocations explicit at statepoints", false, false)
86
87namespace {
88// The type of the internal cache used inside the findBasePointers family
89// of functions. From the callers perspective, this is an opaque type and
90// should not be inspected.
91//
92// In the actual implementation this caches two relations:
93// - The base relation itself (i.e. this pointer is based on that one)
94// - The base defining value relation (i.e. before base_phi insertion)
95// Generally, after the execution of a full findBasePointer call, only the
96// base relation will remain. Internally, we add a mixture of the two
97// types, then update all the second type to the first type
Philip Reamese9c3b9b2015-02-20 22:48:20 +000098typedef DenseMap<Value *, Value *> DefiningValueMapTy;
Philip Reames1f017542015-02-20 23:16:52 +000099typedef DenseSet<llvm::Value *> StatepointLiveSetTy;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000100
Philip Reamesd16a9b12015-02-20 01:06:44 +0000101struct PartiallyConstructedSafepointRecord {
102 /// The set of values known to be live accross this safepoint
Philip Reames860660e2015-02-20 22:05:18 +0000103 StatepointLiveSetTy liveset;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000104
105 /// Mapping from live pointers to a base-defining-value
Philip Reamesf2041322015-02-20 19:26:04 +0000106 DenseMap<llvm::Value *, llvm::Value *> PointerToBase;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000107
108 /// Any new values which were added to the IR during base pointer analysis
109 /// for this safepoint
Philip Reamesf2041322015-02-20 19:26:04 +0000110 DenseSet<llvm::Value *> NewInsertedDefs;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000111
Philip Reames0a3240f2015-02-20 21:34:11 +0000112 /// The *new* gc.statepoint instruction itself. This produces the token
113 /// that normal path gc.relocates and the gc.result are tied to.
114 Instruction *StatepointToken;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000115
Philip Reamesf2041322015-02-20 19:26:04 +0000116 /// Instruction to which exceptional gc relocates are attached
117 /// Makes it easier to iterate through them during relocationViaAlloca.
118 Instruction *UnwindToken;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000119};
120}
121
122// TODO: Once we can get to the GCStrategy, this becomes
123// Optional<bool> isGCManagedPointer(const Value *V) const override {
124
125static bool isGCPointerType(const Type *T) {
126 if (const PointerType *PT = dyn_cast<PointerType>(T))
127 // For the sake of this example GC, we arbitrarily pick addrspace(1) as our
128 // GC managed heap. We know that a pointer into this heap needs to be
129 // updated and that no other pointer does.
130 return (1 == PT->getAddressSpace());
131 return false;
132}
133
134/// Return true if the Value is a gc reference type which is potentially used
135/// after the instruction 'loc'. This is only used with the edge reachability
136/// liveness code. Note: It is assumed the V dominates loc.
137static bool isLiveGCReferenceAt(Value &V, Instruction *loc, DominatorTree &DT,
138 LoopInfo *LI) {
139 if (!isGCPointerType(V.getType()))
140 return false;
141
142 if (V.use_empty())
143 return false;
144
145 // Given assumption that V dominates loc, this may be live
146 return true;
147}
Benjamin Kramerd4a3a552015-02-20 13:15:49 +0000148
149#ifndef NDEBUG
Philip Reamesd16a9b12015-02-20 01:06:44 +0000150static bool isAggWhichContainsGCPtrType(Type *Ty) {
151 if (VectorType *VT = dyn_cast<VectorType>(Ty))
152 return isGCPointerType(VT->getScalarType());
David Blaikie82ad7872015-02-20 23:44:24 +0000153 if (ArrayType *AT = dyn_cast<ArrayType>(Ty))
Philip Reamesd16a9b12015-02-20 01:06:44 +0000154 return isGCPointerType(AT->getElementType()) ||
155 isAggWhichContainsGCPtrType(AT->getElementType());
David Blaikie82ad7872015-02-20 23:44:24 +0000156 if (StructType *ST = dyn_cast<StructType>(Ty))
157 return std::any_of(ST->subtypes().begin(), ST->subtypes().end(),
158 [](Type *SubType) {
159 return isGCPointerType(SubType) ||
160 isAggWhichContainsGCPtrType(SubType);
161 });
162 return false;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000163}
Benjamin Kramerd4a3a552015-02-20 13:15:49 +0000164#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +0000165
166// Conservatively identifies any definitions which might be live at the
167// given instruction. The analysis is performed immediately before the
168// given instruction. Values defined by that instruction are not considered
169// live. Values used by that instruction are considered live.
170//
171// preconditions: valid IR graph, term is either a terminator instruction or
172// a call instruction, pred is the basic block of term, DT, LI are valid
173//
174// side effects: none, does not mutate IR
175//
176// postconditions: populates liveValues as discussed above
177static void findLiveGCValuesAtInst(Instruction *term, BasicBlock *pred,
178 DominatorTree &DT, LoopInfo *LI,
Philip Reames1f017542015-02-20 23:16:52 +0000179 StatepointLiveSetTy &liveValues) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000180 liveValues.clear();
181
182 assert(isa<CallInst>(term) || isa<InvokeInst>(term) || term->isTerminator());
183
184 Function *F = pred->getParent();
185
186 auto is_live_gc_reference =
187 [&](Value &V) { return isLiveGCReferenceAt(V, term, DT, LI); };
188
189 // Are there any gc pointer arguments live over this point? This needs to be
190 // special cased since arguments aren't defined in basic blocks.
191 for (Argument &arg : F->args()) {
192 assert(!isAggWhichContainsGCPtrType(arg.getType()) &&
193 "support for FCA unimplemented");
194
195 if (is_live_gc_reference(arg)) {
196 liveValues.insert(&arg);
197 }
198 }
199
200 // Walk through all dominating blocks - the ones which can contain
201 // definitions used in this block - and check to see if any of the values
202 // they define are used in locations potentially reachable from the
203 // interesting instruction.
204 BasicBlock *BBI = pred;
205 while (true) {
206 if (TraceLSP) {
207 errs() << "[LSP] Looking at dominating block " << pred->getName() << "\n";
208 }
209 assert(DT.dominates(BBI, pred));
210 assert(isPotentiallyReachable(BBI, pred, &DT) &&
211 "dominated block must be reachable");
212
213 // Walk through the instructions in dominating blocks and keep any
214 // that have a use potentially reachable from the block we're
215 // considering putting the safepoint in
216 for (Instruction &inst : *BBI) {
217 if (TraceLSP) {
218 errs() << "[LSP] Looking at instruction ";
219 inst.dump();
220 }
221
222 if (pred == BBI && (&inst) == term) {
223 if (TraceLSP) {
224 errs() << "[LSP] stopped because we encountered the safepoint "
225 "instruction.\n";
226 }
227
228 // If we're in the block which defines the interesting instruction,
229 // we don't want to include any values as live which are defined
230 // _after_ the interesting line or as part of the line itself
231 // i.e. "term" is the call instruction for a call safepoint, the
232 // results of the call should not be considered live in that stackmap
233 break;
234 }
235
236 assert(!isAggWhichContainsGCPtrType(inst.getType()) &&
237 "support for FCA unimplemented");
238
239 if (is_live_gc_reference(inst)) {
240 if (TraceLSP) {
241 errs() << "[LSP] found live value for this safepoint ";
242 inst.dump();
243 term->dump();
244 }
245 liveValues.insert(&inst);
246 }
247 }
248 if (!DT.getNode(BBI)->getIDom()) {
249 assert(BBI == &F->getEntryBlock() &&
250 "failed to find a dominator for something other than "
251 "the entry block");
252 break;
253 }
254 BBI = DT.getNode(BBI)->getIDom()->getBlock();
255 }
256}
257
258static bool order_by_name(llvm::Value *a, llvm::Value *b) {
259 if (a->hasName() && b->hasName()) {
260 return -1 == a->getName().compare(b->getName());
261 } else if (a->hasName() && !b->hasName()) {
262 return true;
263 } else if (!a->hasName() && b->hasName()) {
264 return false;
265 } else {
266 // Better than nothing, but not stable
267 return a < b;
268 }
269}
270
271/// Find the initial live set. Note that due to base pointer
272/// insertion, the live set may be incomplete.
273static void
274analyzeParsePointLiveness(DominatorTree &DT, const CallSite &CS,
275 PartiallyConstructedSafepointRecord &result) {
276 Instruction *inst = CS.getInstruction();
277
278 BasicBlock *BB = inst->getParent();
Philip Reames1f017542015-02-20 23:16:52 +0000279 StatepointLiveSetTy liveset;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000280 findLiveGCValuesAtInst(inst, BB, DT, nullptr, liveset);
281
282 if (PrintLiveSet) {
283 // Note: This output is used by several of the test cases
284 // The order of elemtns in a set is not stable, put them in a vec and sort
285 // by name
Philip Reames860660e2015-02-20 22:05:18 +0000286 SmallVector<Value *, 64> temp;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000287 temp.insert(temp.end(), liveset.begin(), liveset.end());
288 std::sort(temp.begin(), temp.end(), order_by_name);
289 errs() << "Live Variables:\n";
290 for (Value *V : temp) {
291 errs() << " " << V->getName(); // no newline
292 V->dump();
293 }
294 }
295 if (PrintLiveSetSize) {
296 errs() << "Safepoint For: " << CS.getCalledValue()->getName() << "\n";
297 errs() << "Number live values: " << liveset.size() << "\n";
298 }
299 result.liveset = liveset;
300}
301
302/// True iff this value is the null pointer constant (of any pointer type)
NAKAMURA Takumif7d08f62015-02-22 09:58:19 +0000303static bool LLVM_ATTRIBUTE_UNUSED isNullConstant(Value *V) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000304 return isa<Constant>(V) && isa<PointerType>(V->getType()) &&
305 cast<Constant>(V)->isNullValue();
306}
307
308/// Helper function for findBasePointer - Will return a value which either a)
309/// defines the base pointer for the input or b) blocks the simple search
310/// (i.e. a PHI or Select of two derived pointers)
311static Value *findBaseDefiningValue(Value *I) {
312 assert(I->getType()->isPointerTy() &&
313 "Illegal to ask for the base pointer of a non-pointer type");
314
315 // There are instructions which can never return gc pointer values. Sanity
316 // check
317 // that this is actually true.
318 assert(!isa<InsertElementInst>(I) && !isa<ExtractElementInst>(I) &&
319 !isa<ShuffleVectorInst>(I) && "Vector types are not gc pointers");
320 assert((!isa<Instruction>(I) || isa<InvokeInst>(I) ||
321 !cast<Instruction>(I)->isTerminator()) &&
322 "With the exception of invoke terminators don't define values");
323 assert(!isa<StoreInst>(I) && !isa<FenceInst>(I) &&
324 "Can't be definitions to start with");
325 assert(!isa<ICmpInst>(I) && !isa<FCmpInst>(I) &&
326 "Comparisons don't give ops");
327 // There's a bunch of instructions which just don't make sense to apply to
328 // a pointer. The only valid reason for this would be pointer bit
329 // twiddling which we're just not going to support.
330 assert((!isa<Instruction>(I) || !cast<Instruction>(I)->isBinaryOp()) &&
331 "Binary ops on pointer values are meaningless. Unless your "
332 "bit-twiddling which we don't support");
333
334 if (Argument *Arg = dyn_cast<Argument>(I)) {
335 // An incoming argument to the function is a base pointer
336 // We should have never reached here if this argument isn't an gc value
337 assert(Arg->getType()->isPointerTy() &&
338 "Base for pointer must be another pointer");
339 return Arg;
340 }
341
342 if (GlobalVariable *global = dyn_cast<GlobalVariable>(I)) {
343 // base case
344 assert(global->getType()->isPointerTy() &&
345 "Base for pointer must be another pointer");
346 return global;
347 }
348
349 // inlining could possibly introduce phi node that contains
350 // undef if callee has multiple returns
351 if (UndefValue *undef = dyn_cast<UndefValue>(I)) {
352 assert(undef->getType()->isPointerTy() &&
353 "Base for pointer must be another pointer");
354 return undef; // utterly meaningless, but useful for dealing with
355 // partially optimized code.
356 }
357
358 // Due to inheritance, this must be _after_ the global variable and undef
359 // checks
360 if (Constant *con = dyn_cast<Constant>(I)) {
361 assert(!isa<GlobalVariable>(I) && !isa<UndefValue>(I) &&
362 "order of checks wrong!");
363 // Note: Finding a constant base for something marked for relocation
364 // doesn't really make sense. The most likely case is either a) some
365 // screwed up the address space usage or b) your validating against
366 // compiled C++ code w/o the proper separation. The only real exception
367 // is a null pointer. You could have generic code written to index of
368 // off a potentially null value and have proven it null. We also use
369 // null pointers in dead paths of relocation phis (which we might later
370 // want to find a base pointer for).
371 assert(con->getType()->isPointerTy() &&
372 "Base for pointer must be another pointer");
373 assert(con->isNullValue() && "null is the only case which makes sense");
374 return con;
375 }
376
377 if (CastInst *CI = dyn_cast<CastInst>(I)) {
378 Value *def = CI->stripPointerCasts();
379 assert(def->getType()->isPointerTy() &&
380 "Base for pointer must be another pointer");
David Blaikie82ad7872015-02-20 23:44:24 +0000381 // If we find a cast instruction here, it means we've found a cast which is
382 // not simply a pointer cast (i.e. an inttoptr). We don't know how to
383 // handle int->ptr conversion.
Philip Reamesd16a9b12015-02-20 01:06:44 +0000384 assert(!isa<CastInst>(def) && "shouldn't find another cast here");
385 return findBaseDefiningValue(def);
386 }
387
388 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
389 if (LI->getType()->isPointerTy()) {
390 Value *Op = LI->getOperand(0);
Nick Lewyckyeb3231e2015-02-20 07:14:02 +0000391 (void)Op;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000392 // Has to be a pointer to an gc object, or possibly an array of such?
393 assert(Op->getType()->isPointerTy());
394 return LI; // The value loaded is an gc base itself
395 }
396 }
397 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
398 Value *Op = GEP->getOperand(0);
399 if (Op->getType()->isPointerTy()) {
400 return findBaseDefiningValue(Op); // The base of this GEP is the base
401 }
402 }
403
404 if (AllocaInst *alloc = dyn_cast<AllocaInst>(I)) {
405 // An alloca represents a conceptual stack slot. It's the slot itself
406 // that the GC needs to know about, not the value in the slot.
407 assert(alloc->getType()->isPointerTy() &&
408 "Base for pointer must be another pointer");
409 return alloc;
410 }
411
412 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
413 switch (II->getIntrinsicID()) {
414 default:
415 // fall through to general call handling
416 break;
417 case Intrinsic::experimental_gc_statepoint:
418 case Intrinsic::experimental_gc_result_float:
419 case Intrinsic::experimental_gc_result_int:
420 llvm_unreachable("these don't produce pointers");
421 case Intrinsic::experimental_gc_result_ptr:
422 // This is just a special case of the CallInst check below to handle a
423 // statepoint with deopt args which hasn't been rewritten for GC yet.
424 // TODO: Assert that the statepoint isn't rewritten yet.
425 return II;
426 case Intrinsic::experimental_gc_relocate: {
427 // Rerunning safepoint insertion after safepoints are already
428 // inserted is not supported. It could probably be made to work,
429 // but why are you doing this? There's no good reason.
430 llvm_unreachable("repeat safepoint insertion is not supported");
431 }
432 case Intrinsic::gcroot:
433 // Currently, this mechanism hasn't been extended to work with gcroot.
434 // There's no reason it couldn't be, but I haven't thought about the
435 // implications much.
436 llvm_unreachable(
437 "interaction with the gcroot mechanism is not supported");
438 }
439 }
440 // We assume that functions in the source language only return base
441 // pointers. This should probably be generalized via attributes to support
442 // both source language and internal functions.
443 if (CallInst *call = dyn_cast<CallInst>(I)) {
444 assert(call->getType()->isPointerTy() &&
445 "Base for pointer must be another pointer");
446 return call;
447 }
448 if (InvokeInst *invoke = dyn_cast<InvokeInst>(I)) {
449 assert(invoke->getType()->isPointerTy() &&
450 "Base for pointer must be another pointer");
451 return invoke;
452 }
453
454 // I have absolutely no idea how to implement this part yet. It's not
455 // neccessarily hard, I just haven't really looked at it yet.
456 assert(!isa<LandingPadInst>(I) && "Landing Pad is unimplemented");
457
458 if (AtomicCmpXchgInst *cas = dyn_cast<AtomicCmpXchgInst>(I)) {
459 // A CAS is effectively a atomic store and load combined under a
460 // predicate. From the perspective of base pointers, we just treat it
461 // like a load. We loaded a pointer from a address in memory, that value
462 // had better be a valid base pointer.
463 return cas->getPointerOperand();
464 }
465 if (AtomicRMWInst *atomic = dyn_cast<AtomicRMWInst>(I)) {
466 assert(AtomicRMWInst::Xchg == atomic->getOperation() &&
467 "All others are binary ops which don't apply to base pointers");
468 // semantically, a load, store pair. Treat it the same as a standard load
469 return atomic->getPointerOperand();
470 }
471
472 // The aggregate ops. Aggregates can either be in the heap or on the
473 // stack, but in either case, this is simply a field load. As a result,
474 // this is a defining definition of the base just like a load is.
475 if (ExtractValueInst *ev = dyn_cast<ExtractValueInst>(I)) {
476 return ev;
477 }
478
479 // We should never see an insert vector since that would require we be
480 // tracing back a struct value not a pointer value.
481 assert(!isa<InsertValueInst>(I) &&
482 "Base pointer for a struct is meaningless");
483
484 // The last two cases here don't return a base pointer. Instead, they
485 // return a value which dynamically selects from amoung several base
486 // derived pointers (each with it's own base potentially). It's the job of
487 // the caller to resolve these.
488 if (SelectInst *select = dyn_cast<SelectInst>(I)) {
489 return select;
490 }
Philip Reamesd16a9b12015-02-20 01:06:44 +0000491
David Blaikie82ad7872015-02-20 23:44:24 +0000492 return cast<PHINode>(I);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000493}
494
495/// Returns the base defining value for this value.
Benjamin Kramer6f665452015-02-20 14:00:58 +0000496static Value *findBaseDefiningValueCached(Value *I, DefiningValueMapTy &cache) {
497 Value *&Cached = cache[I];
498 if (!Cached) {
499 Cached = findBaseDefiningValue(I);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000500 }
Benjamin Kramer6f665452015-02-20 14:00:58 +0000501 assert(cache[I] != nullptr);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000502
503 if (TraceLSP) {
Benjamin Kramer6f665452015-02-20 14:00:58 +0000504 errs() << "fBDV-cached: " << I->getName() << " -> " << Cached->getName()
Philip Reamesd16a9b12015-02-20 01:06:44 +0000505 << "\n";
506 }
Benjamin Kramer6f665452015-02-20 14:00:58 +0000507 return Cached;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000508}
509
510/// Return a base pointer for this value if known. Otherwise, return it's
511/// base defining value.
512static Value *findBaseOrBDV(Value *I, DefiningValueMapTy &cache) {
513 Value *def = findBaseDefiningValueCached(I, cache);
Benjamin Kramer6f665452015-02-20 14:00:58 +0000514 auto Found = cache.find(def);
515 if (Found != cache.end()) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000516 // Either a base-of relation, or a self reference. Caller must check.
Benjamin Kramer6f665452015-02-20 14:00:58 +0000517 return Found->second;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000518 }
519 // Only a BDV available
520 return def;
521}
522
523/// Given the result of a call to findBaseDefiningValue, or findBaseOrBDV,
524/// is it known to be a base pointer? Or do we need to continue searching.
525static bool isKnownBaseResult(Value *v) {
526 if (!isa<PHINode>(v) && !isa<SelectInst>(v)) {
527 // no recursion possible
528 return true;
529 }
530 if (cast<Instruction>(v)->getMetadata("is_base_value")) {
531 // This is a previously inserted base phi or select. We know
532 // that this is a base value.
533 return true;
534 }
535
536 // We need to keep searching
537 return false;
538}
539
540// TODO: find a better name for this
541namespace {
542class PhiState {
543public:
544 enum Status { Unknown, Base, Conflict };
545
546 PhiState(Status s, Value *b = nullptr) : status(s), base(b) {
547 assert(status != Base || b);
548 }
549 PhiState(Value *b) : status(Base), base(b) {}
550 PhiState() : status(Unknown), base(nullptr) {}
551 PhiState(const PhiState &other) : status(other.status), base(other.base) {
552 assert(status != Base || base);
553 }
554
555 Status getStatus() const { return status; }
556 Value *getBase() const { return base; }
557
558 bool isBase() const { return getStatus() == Base; }
559 bool isUnknown() const { return getStatus() == Unknown; }
560 bool isConflict() const { return getStatus() == Conflict; }
561
562 bool operator==(const PhiState &other) const {
563 return base == other.base && status == other.status;
564 }
565
566 bool operator!=(const PhiState &other) const { return !(*this == other); }
567
568 void dump() {
569 errs() << status << " (" << base << " - "
570 << (base ? base->getName() : "nullptr") << "): ";
571 }
572
573private:
574 Status status;
575 Value *base; // non null only if status == base
576};
577
Philip Reamese9c3b9b2015-02-20 22:48:20 +0000578typedef DenseMap<Value *, PhiState> ConflictStateMapTy;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000579// Values of type PhiState form a lattice, and this is a helper
580// class that implementes the meet operation. The meat of the meet
581// operation is implemented in MeetPhiStates::pureMeet
582class MeetPhiStates {
583public:
584 // phiStates is a mapping from PHINodes and SelectInst's to PhiStates.
Philip Reames860660e2015-02-20 22:05:18 +0000585 explicit MeetPhiStates(const ConflictStateMapTy &phiStates)
Philip Reamesd16a9b12015-02-20 01:06:44 +0000586 : phiStates(phiStates) {}
587
588 // Destructively meet the current result with the base V. V can
589 // either be a merge instruction (SelectInst / PHINode), in which
590 // case its status is looked up in the phiStates map; or a regular
591 // SSA value, in which case it is assumed to be a base.
592 void meetWith(Value *V) {
593 PhiState otherState = getStateForBDV(V);
594 assert((MeetPhiStates::pureMeet(otherState, currentResult) ==
595 MeetPhiStates::pureMeet(currentResult, otherState)) &&
596 "math is wrong: meet does not commute!");
597 currentResult = MeetPhiStates::pureMeet(otherState, currentResult);
598 }
599
600 PhiState getResult() const { return currentResult; }
601
602private:
Philip Reames860660e2015-02-20 22:05:18 +0000603 const ConflictStateMapTy &phiStates;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000604 PhiState currentResult;
605
606 /// Return a phi state for a base defining value. We'll generate a new
607 /// base state for known bases and expect to find a cached state otherwise
608 PhiState getStateForBDV(Value *baseValue) {
609 if (isKnownBaseResult(baseValue)) {
610 return PhiState(baseValue);
611 } else {
612 return lookupFromMap(baseValue);
613 }
614 }
615
616 PhiState lookupFromMap(Value *V) {
617 auto I = phiStates.find(V);
618 assert(I != phiStates.end() && "lookup failed!");
619 return I->second;
620 }
621
622 static PhiState pureMeet(const PhiState &stateA, const PhiState &stateB) {
623 switch (stateA.getStatus()) {
624 case PhiState::Unknown:
625 return stateB;
626
627 case PhiState::Base:
628 assert(stateA.getBase() && "can't be null");
David Blaikie82ad7872015-02-20 23:44:24 +0000629 if (stateB.isUnknown())
Philip Reamesd16a9b12015-02-20 01:06:44 +0000630 return stateA;
David Blaikie82ad7872015-02-20 23:44:24 +0000631
632 if (stateB.isBase()) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000633 if (stateA.getBase() == stateB.getBase()) {
634 assert(stateA == stateB && "equality broken!");
635 return stateA;
636 }
637 return PhiState(PhiState::Conflict);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000638 }
David Blaikie82ad7872015-02-20 23:44:24 +0000639 assert(stateB.isConflict() && "only three states!");
640 return PhiState(PhiState::Conflict);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000641
642 case PhiState::Conflict:
643 return stateA;
644 }
Reid Klecknera070ee52015-02-20 19:46:02 +0000645 llvm_unreachable("only three states!");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000646 }
647};
648}
649/// For a given value or instruction, figure out what base ptr it's derived
650/// from. For gc objects, this is simply itself. On success, returns a value
651/// which is the base pointer. (This is reliable and can be used for
652/// relocation.) On failure, returns nullptr.
653static Value *findBasePointer(Value *I, DefiningValueMapTy &cache,
Philip Reamesf2041322015-02-20 19:26:04 +0000654 DenseSet<llvm::Value *> &NewInsertedDefs) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000655 Value *def = findBaseOrBDV(I, cache);
656
657 if (isKnownBaseResult(def)) {
658 return def;
659 }
660
661 // Here's the rough algorithm:
662 // - For every SSA value, construct a mapping to either an actual base
663 // pointer or a PHI which obscures the base pointer.
664 // - Construct a mapping from PHI to unknown TOP state. Use an
665 // optimistic algorithm to propagate base pointer information. Lattice
666 // looks like:
667 // UNKNOWN
668 // b1 b2 b3 b4
669 // CONFLICT
670 // When algorithm terminates, all PHIs will either have a single concrete
671 // base or be in a conflict state.
672 // - For every conflict, insert a dummy PHI node without arguments. Add
673 // these to the base[Instruction] = BasePtr mapping. For every
674 // non-conflict, add the actual base.
675 // - For every conflict, add arguments for the base[a] of each input
676 // arguments.
677 //
678 // Note: A simpler form of this would be to add the conflict form of all
679 // PHIs without running the optimistic algorithm. This would be
680 // analougous to pessimistic data flow and would likely lead to an
681 // overall worse solution.
682
Philip Reames860660e2015-02-20 22:05:18 +0000683 ConflictStateMapTy states;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000684 states[def] = PhiState();
685 // Recursively fill in all phis & selects reachable from the initial one
686 // for which we don't already know a definite base value for
Philip Reamesa226e612015-02-28 00:47:50 +0000687 // TODO: This should be rewritten with a worklist
Philip Reamesd16a9b12015-02-20 01:06:44 +0000688 bool done = false;
689 while (!done) {
690 done = true;
Philip Reamesa226e612015-02-28 00:47:50 +0000691 // Since we're adding elements to 'states' as we run, we can't keep
692 // iterators into the set.
693 SmallVector<Value*, 16> Keys;
694 Keys.reserve(states.size());
Philip Reamesd16a9b12015-02-20 01:06:44 +0000695 for (auto Pair : states) {
Philip Reamesa226e612015-02-28 00:47:50 +0000696 Value *V = Pair.first;
697 Keys.push_back(V);
698 }
699 for (Value *v : Keys) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000700 assert(!isKnownBaseResult(v) && "why did it get added?");
701 if (PHINode *phi = dyn_cast<PHINode>(v)) {
David Blaikie82ad7872015-02-20 23:44:24 +0000702 assert(phi->getNumIncomingValues() > 0 &&
703 "zero input phis are illegal");
704 for (Value *InVal : phi->incoming_values()) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000705 Value *local = findBaseOrBDV(InVal, cache);
706 if (!isKnownBaseResult(local) && states.find(local) == states.end()) {
707 states[local] = PhiState();
708 done = false;
709 }
710 }
711 } else if (SelectInst *sel = dyn_cast<SelectInst>(v)) {
712 Value *local = findBaseOrBDV(sel->getTrueValue(), cache);
713 if (!isKnownBaseResult(local) && states.find(local) == states.end()) {
714 states[local] = PhiState();
715 done = false;
716 }
717 local = findBaseOrBDV(sel->getFalseValue(), cache);
718 if (!isKnownBaseResult(local) && states.find(local) == states.end()) {
719 states[local] = PhiState();
720 done = false;
721 }
722 }
723 }
724 }
725
726 if (TraceLSP) {
727 errs() << "States after initialization:\n";
728 for (auto Pair : states) {
729 Instruction *v = cast<Instruction>(Pair.first);
730 PhiState state = Pair.second;
731 state.dump();
732 v->dump();
733 }
734 }
735
736 // TODO: come back and revisit the state transitions around inputs which
737 // have reached conflict state. The current version seems too conservative.
738
739 bool progress = true;
740 size_t oldSize = 0;
741 while (progress) {
742 oldSize = states.size();
743 progress = false;
Philip Reamesa226e612015-02-28 00:47:50 +0000744 // We're only changing keys in this loop, thus safe to keep iterators
Philip Reamesd16a9b12015-02-20 01:06:44 +0000745 for (auto Pair : states) {
746 MeetPhiStates calculateMeet(states);
747 Value *v = Pair.first;
748 assert(!isKnownBaseResult(v) && "why did it get added?");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000749 if (SelectInst *select = dyn_cast<SelectInst>(v)) {
750 calculateMeet.meetWith(findBaseOrBDV(select->getTrueValue(), cache));
751 calculateMeet.meetWith(findBaseOrBDV(select->getFalseValue(), cache));
David Blaikie82ad7872015-02-20 23:44:24 +0000752 } else
753 for (Value *Val : cast<PHINode>(v)->incoming_values())
754 calculateMeet.meetWith(findBaseOrBDV(Val, cache));
Philip Reamesd16a9b12015-02-20 01:06:44 +0000755
756 PhiState oldState = states[v];
757 PhiState newState = calculateMeet.getResult();
758 if (oldState != newState) {
759 progress = true;
760 states[v] = newState;
761 }
762 }
763
764 assert(oldSize <= states.size());
765 assert(oldSize == states.size() || progress);
766 }
767
768 if (TraceLSP) {
769 errs() << "States after meet iteration:\n";
770 for (auto Pair : states) {
771 Instruction *v = cast<Instruction>(Pair.first);
772 PhiState state = Pair.second;
773 state.dump();
774 v->dump();
775 }
776 }
777
778 // Insert Phis for all conflicts
Philip Reames2e5bcbe2015-02-28 01:52:09 +0000779 // We want to keep naming deterministic in the loop that follows, so
780 // sort the keys before iteration. This is useful in allowing us to
781 // write stable tests. Note that there is no invalidation issue here.
782 SmallVector<Value*, 16> Keys;
783 Keys.reserve(states.size());
Philip Reamesd16a9b12015-02-20 01:06:44 +0000784 for (auto Pair : states) {
Philip Reames2e5bcbe2015-02-28 01:52:09 +0000785 Value *V = Pair.first;
786 Keys.push_back(V);
787 }
788 std::sort(Keys.begin(), Keys.end(), order_by_name);
789 // TODO: adjust naming patterns to avoid this order of iteration dependency
790 for (Value *V : Keys) {
791 Instruction *v = cast<Instruction>(V);
792 PhiState state = states[V];
Philip Reamesd16a9b12015-02-20 01:06:44 +0000793 assert(!isKnownBaseResult(v) && "why did it get added?");
794 assert(!state.isUnknown() && "Optimistic algorithm didn't complete!");
Philip Reamesf986d682015-02-28 00:54:41 +0000795 if (!state.isConflict())
796 continue;
797
798 if (isa<PHINode>(v)) {
799 int num_preds =
800 std::distance(pred_begin(v->getParent()), pred_end(v->getParent()));
801 assert(num_preds > 0 && "how did we reach here");
802 PHINode *phi = PHINode::Create(v->getType(), num_preds, "base_phi", v);
803 NewInsertedDefs.insert(phi);
804 // Add metadata marking this as a base value
805 auto *const_1 = ConstantInt::get(
806 Type::getInt32Ty(
807 v->getParent()->getParent()->getParent()->getContext()),
808 1);
809 auto MDConst = ConstantAsMetadata::get(const_1);
810 MDNode *md = MDNode::get(
811 v->getParent()->getParent()->getParent()->getContext(), MDConst);
812 phi->setMetadata("is_base_value", md);
813 states[v] = PhiState(PhiState::Conflict, phi);
814 } else {
815 SelectInst *sel = cast<SelectInst>(v);
816 // The undef will be replaced later
817 UndefValue *undef = UndefValue::get(sel->getType());
818 SelectInst *basesel = SelectInst::Create(sel->getCondition(), undef,
819 undef, "base_select", sel);
820 NewInsertedDefs.insert(basesel);
821 // Add metadata marking this as a base value
822 auto *const_1 = ConstantInt::get(
823 Type::getInt32Ty(
824 v->getParent()->getParent()->getParent()->getContext()),
825 1);
826 auto MDConst = ConstantAsMetadata::get(const_1);
827 MDNode *md = MDNode::get(
828 v->getParent()->getParent()->getParent()->getContext(), MDConst);
829 basesel->setMetadata("is_base_value", md);
830 states[v] = PhiState(PhiState::Conflict, basesel);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000831 }
832 }
833
834 // Fixup all the inputs of the new PHIs
835 for (auto Pair : states) {
836 Instruction *v = cast<Instruction>(Pair.first);
837 PhiState state = Pair.second;
838
839 assert(!isKnownBaseResult(v) && "why did it get added?");
840 assert(!state.isUnknown() && "Optimistic algorithm didn't complete!");
Philip Reames28e61ce2015-02-28 01:57:44 +0000841 if (!state.isConflict())
842 continue;
843
844 if (PHINode *basephi = dyn_cast<PHINode>(state.getBase())) {
845 PHINode *phi = cast<PHINode>(v);
846 unsigned NumPHIValues = phi->getNumIncomingValues();
847 for (unsigned i = 0; i < NumPHIValues; i++) {
848 Value *InVal = phi->getIncomingValue(i);
849 BasicBlock *InBB = phi->getIncomingBlock(i);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000850
Philip Reames28e61ce2015-02-28 01:57:44 +0000851 // If we've already seen InBB, add the same incoming value
852 // we added for it earlier. The IR verifier requires phi
853 // nodes with multiple entries from the same basic block
854 // to have the same incoming value for each of those
855 // entries. If we don't do this check here and basephi
856 // has a different type than base, we'll end up adding two
857 // bitcasts (and hence two distinct values) as incoming
858 // values for the same basic block.
Philip Reamesd16a9b12015-02-20 01:06:44 +0000859
Philip Reames28e61ce2015-02-28 01:57:44 +0000860 int blockIndex = basephi->getBasicBlockIndex(InBB);
861 if (blockIndex != -1) {
862 Value *oldBase = basephi->getIncomingValue(blockIndex);
863 basephi->addIncoming(oldBase, InBB);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000864#ifndef NDEBUG
Philip Reames28e61ce2015-02-28 01:57:44 +0000865 Value *base = findBaseOrBDV(InVal, cache);
866 if (!isKnownBaseResult(base)) {
867 // Either conflict or base.
868 assert(states.count(base));
869 base = states[base].getBase();
870 assert(base != nullptr && "unknown PhiState!");
871 assert(NewInsertedDefs.count(base) &&
872 "should have already added this in a prev. iteration!");
873 }
Philip Reamesd16a9b12015-02-20 01:06:44 +0000874
Philip Reames28e61ce2015-02-28 01:57:44 +0000875 // In essense this assert states: the only way two
876 // values incoming from the same basic block may be
877 // different is by being different bitcasts of the same
878 // value. A cleanup that remains TODO is changing
879 // findBaseOrBDV to return an llvm::Value of the correct
880 // type (and still remain pure). This will remove the
881 // need to add bitcasts.
882 assert(base->stripPointerCasts() == oldBase->stripPointerCasts() &&
883 "sanity -- findBaseOrBDV should be pure!");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000884#endif
Philip Reames28e61ce2015-02-28 01:57:44 +0000885 continue;
886 }
Philip Reamesd16a9b12015-02-20 01:06:44 +0000887
Philip Reames28e61ce2015-02-28 01:57:44 +0000888 // Find either the defining value for the PHI or the normal base for
889 // a non-phi node
890 Value *base = findBaseOrBDV(InVal, cache);
891 if (!isKnownBaseResult(base)) {
892 // Either conflict or base.
893 assert(states.count(base));
894 base = states[base].getBase();
895 assert(base != nullptr && "unknown PhiState!");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000896 }
Philip Reames28e61ce2015-02-28 01:57:44 +0000897 assert(base && "can't be null");
898 // Must use original input BB since base may not be Instruction
899 // The cast is needed since base traversal may strip away bitcasts
900 if (base->getType() != basephi->getType()) {
901 base = new BitCastInst(base, basephi->getType(), "cast",
902 InBB->getTerminator());
903 NewInsertedDefs.insert(base);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000904 }
Philip Reames28e61ce2015-02-28 01:57:44 +0000905 basephi->addIncoming(base, InBB);
906 }
907 assert(basephi->getNumIncomingValues() == NumPHIValues);
908 } else {
909 SelectInst *basesel = cast<SelectInst>(state.getBase());
910 SelectInst *sel = cast<SelectInst>(v);
911 // Operand 1 & 2 are true, false path respectively. TODO: refactor to
912 // something more safe and less hacky.
913 for (int i = 1; i <= 2; i++) {
914 Value *InVal = sel->getOperand(i);
915 // Find either the defining value for the PHI or the normal base for
916 // a non-phi node
917 Value *base = findBaseOrBDV(InVal, cache);
918 if (!isKnownBaseResult(base)) {
919 // Either conflict or base.
920 assert(states.count(base));
921 base = states[base].getBase();
922 assert(base != nullptr && "unknown PhiState!");
923 }
924 assert(base && "can't be null");
925 // Must use original input BB since base may not be Instruction
926 // The cast is needed since base traversal may strip away bitcasts
927 if (base->getType() != basesel->getType()) {
928 base = new BitCastInst(base, basesel->getType(), "cast", basesel);
929 NewInsertedDefs.insert(base);
930 }
931 basesel->setOperand(i, base);
932 }
Philip Reamesd16a9b12015-02-20 01:06:44 +0000933 }
934 }
935
936 // Cache all of our results so we can cheaply reuse them
937 // NOTE: This is actually two caches: one of the base defining value
938 // relation and one of the base pointer relation! FIXME
939 for (auto item : states) {
940 Value *v = item.first;
941 Value *base = item.second.getBase();
942 assert(v && base);
943 assert(!isKnownBaseResult(v) && "why did it get added?");
944
945 if (TraceLSP) {
946 std::string fromstr =
947 cache.count(v) ? (cache[v]->hasName() ? cache[v]->getName() : "")
948 : "none";
949 errs() << "Updating base value cache"
950 << " for: " << (v->hasName() ? v->getName() : "")
951 << " from: " << fromstr
952 << " to: " << (base->hasName() ? base->getName() : "") << "\n";
953 }
954
955 assert(isKnownBaseResult(base) &&
956 "must be something we 'know' is a base pointer");
957 if (cache.count(v)) {
958 // Once we transition from the BDV relation being store in the cache to
959 // the base relation being stored, it must be stable
960 assert((!isKnownBaseResult(cache[v]) || cache[v] == base) &&
961 "base relation should be stable");
962 }
963 cache[v] = base;
964 }
965 assert(cache.find(def) != cache.end());
966 return cache[def];
967}
968
969// For a set of live pointers (base and/or derived), identify the base
970// pointer of the object which they are derived from. This routine will
971// mutate the IR graph as needed to make the 'base' pointer live at the
972// definition site of 'derived'. This ensures that any use of 'derived' can
973// also use 'base'. This may involve the insertion of a number of
974// additional PHI nodes.
975//
976// preconditions: live is a set of pointer type Values
977//
978// side effects: may insert PHI nodes into the existing CFG, will preserve
979// CFG, will not remove or mutate any existing nodes
980//
Philip Reamesf2041322015-02-20 19:26:04 +0000981// post condition: PointerToBase contains one (derived, base) pair for every
Philip Reamesd16a9b12015-02-20 01:06:44 +0000982// pointer in live. Note that derived can be equal to base if the original
983// pointer was a base pointer.
Philip Reames1f017542015-02-20 23:16:52 +0000984static void findBasePointers(const StatepointLiveSetTy &live,
Philip Reamesf2041322015-02-20 19:26:04 +0000985 DenseMap<llvm::Value *, llvm::Value *> &PointerToBase,
Philip Reamesd16a9b12015-02-20 01:06:44 +0000986 DominatorTree *DT, DefiningValueMapTy &DVCache,
Philip Reamesf2041322015-02-20 19:26:04 +0000987 DenseSet<llvm::Value *> &NewInsertedDefs) {
Philip Reames2e5bcbe2015-02-28 01:52:09 +0000988 // For the naming of values inserted to be deterministic - which makes for
989 // much cleaner and more stable tests - we need to assign an order to the
990 // live values. DenseSets do not provide a deterministic order across runs.
991 SmallVector<Value*, 64> Temp;
992 Temp.insert(Temp.end(), live.begin(), live.end());
993 std::sort(Temp.begin(), Temp.end(), order_by_name);
994 for (Value *ptr : Temp) {
Philip Reamesf2041322015-02-20 19:26:04 +0000995 Value *base = findBasePointer(ptr, DVCache, NewInsertedDefs);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000996 assert(base && "failed to find base pointer");
Philip Reamesf2041322015-02-20 19:26:04 +0000997 PointerToBase[ptr] = base;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000998 assert((!isa<Instruction>(base) || !isa<Instruction>(ptr) ||
999 DT->dominates(cast<Instruction>(base)->getParent(),
1000 cast<Instruction>(ptr)->getParent())) &&
1001 "The base we found better dominate the derived pointer");
1002
David Blaikie82ad7872015-02-20 23:44:24 +00001003 // If you see this trip and like to live really dangerously, the code should
1004 // be correct, just with idioms the verifier can't handle. You can try
1005 // disabling the verifier at your own substaintial risk.
1006 assert(!isNullConstant(base) && "the relocation code needs adjustment to "
1007 "handle the relocation of a null pointer "
1008 "constant without causing false positives "
1009 "in the safepoint ir verifier.");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001010 }
1011}
1012
1013/// Find the required based pointers (and adjust the live set) for the given
1014/// parse point.
1015static void findBasePointers(DominatorTree &DT, DefiningValueMapTy &DVCache,
1016 const CallSite &CS,
1017 PartiallyConstructedSafepointRecord &result) {
Philip Reamesf2041322015-02-20 19:26:04 +00001018 DenseMap<llvm::Value *, llvm::Value *> PointerToBase;
1019 DenseSet<llvm::Value *> NewInsertedDefs;
1020 findBasePointers(result.liveset, PointerToBase, &DT, DVCache, NewInsertedDefs);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001021
1022 if (PrintBasePointers) {
Philip Reamesa5aeaf42015-02-28 00:20:48 +00001023 // Note: Need to print these in a stable order since this is checked in
1024 // some tests.
Philip Reamesd16a9b12015-02-20 01:06:44 +00001025 errs() << "Base Pairs (w/o Relocation):\n";
Philip Reamesa5aeaf42015-02-28 00:20:48 +00001026 SmallVector<Value*, 64> Temp;
1027 Temp.reserve(PointerToBase.size());
Philip Reamesf2041322015-02-20 19:26:04 +00001028 for (auto Pair : PointerToBase) {
Philip Reamesa5aeaf42015-02-28 00:20:48 +00001029 Temp.push_back(Pair.first);
1030 }
1031 std::sort(Temp.begin(), Temp.end(), order_by_name);
1032 for (Value *Ptr : Temp) {
1033 Value *Base = PointerToBase[Ptr];
1034 errs() << " derived %" << Ptr->getName() << " base %"
1035 << Base->getName() << "\n";
Philip Reamesd16a9b12015-02-20 01:06:44 +00001036 }
1037 }
1038
Philip Reamesf2041322015-02-20 19:26:04 +00001039 result.PointerToBase = PointerToBase;
1040 result.NewInsertedDefs = NewInsertedDefs;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001041}
1042
1043/// Check for liveness of items in the insert defs and add them to the live
1044/// and base pointer sets
1045static void fixupLiveness(DominatorTree &DT, const CallSite &CS,
Philip Reames1f017542015-02-20 23:16:52 +00001046 const DenseSet<Value *> &allInsertedDefs,
Philip Reamesd16a9b12015-02-20 01:06:44 +00001047 PartiallyConstructedSafepointRecord &result) {
1048 Instruction *inst = CS.getInstruction();
1049
Philip Reamesf2041322015-02-20 19:26:04 +00001050 auto liveset = result.liveset;
1051 auto PointerToBase = result.PointerToBase;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001052
1053 auto is_live_gc_reference =
1054 [&](Value &V) { return isLiveGCReferenceAt(V, inst, DT, nullptr); };
1055
1056 // For each new definition, check to see if a) the definition dominates the
1057 // instruction we're interested in, and b) one of the uses of that definition
1058 // is edge-reachable from the instruction we're interested in. This is the
1059 // same definition of liveness we used in the intial liveness analysis
1060 for (Value *newDef : allInsertedDefs) {
1061 if (liveset.count(newDef)) {
1062 // already live, no action needed
1063 continue;
1064 }
1065
1066 // PERF: Use DT to check instruction domination might not be good for
1067 // compilation time, and we could change to optimal solution if this
1068 // turn to be a issue
1069 if (!DT.dominates(cast<Instruction>(newDef), inst)) {
1070 // can't possibly be live at inst
1071 continue;
1072 }
1073
1074 if (is_live_gc_reference(*newDef)) {
Philip Reamesf2041322015-02-20 19:26:04 +00001075 // Add the live new defs into liveset and PointerToBase
Philip Reamesd16a9b12015-02-20 01:06:44 +00001076 liveset.insert(newDef);
Philip Reamesf2041322015-02-20 19:26:04 +00001077 PointerToBase[newDef] = newDef;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001078 }
1079 }
1080
1081 result.liveset = liveset;
Philip Reamesf2041322015-02-20 19:26:04 +00001082 result.PointerToBase = PointerToBase;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001083}
1084
1085static void fixupLiveReferences(
1086 Function &F, DominatorTree &DT, Pass *P,
Philip Reames1f017542015-02-20 23:16:52 +00001087 const DenseSet<llvm::Value *> &allInsertedDefs,
Philip Reamesd2b66462015-02-20 22:39:41 +00001088 ArrayRef<CallSite> toUpdate,
1089 MutableArrayRef<struct PartiallyConstructedSafepointRecord> records) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001090 for (size_t i = 0; i < records.size(); i++) {
1091 struct PartiallyConstructedSafepointRecord &info = records[i];
Philip Reamesd2b66462015-02-20 22:39:41 +00001092 const CallSite &CS = toUpdate[i];
Philip Reamesd16a9b12015-02-20 01:06:44 +00001093 fixupLiveness(DT, CS, allInsertedDefs, info);
1094 }
1095}
1096
1097// Normalize basic block to make it ready to be target of invoke statepoint.
1098// It means spliting it to have single predecessor. Return newly created BB
1099// ready to be successor of invoke statepoint.
1100static BasicBlock *normalizeBBForInvokeSafepoint(BasicBlock *BB,
1101 BasicBlock *InvokeParent,
1102 Pass *P) {
1103 BasicBlock *ret = BB;
1104
1105 if (!BB->getUniquePredecessor()) {
1106 ret = SplitBlockPredecessors(BB, InvokeParent, "");
1107 }
1108
1109 // Another requirement for such basic blocks is to not have any phi nodes.
1110 // Since we just ensured that new BB will have single predecessor,
1111 // all phi nodes in it will have one value. Here it would be naturall place
1112 // to
1113 // remove them all. But we can not do this because we are risking to remove
1114 // one of the values stored in liveset of another statepoint. We will do it
1115 // later after placing all safepoints.
1116
1117 return ret;
1118}
1119
Philip Reamesd2b66462015-02-20 22:39:41 +00001120static int find_index(ArrayRef<Value *> livevec, Value *val) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001121 auto itr = std::find(livevec.begin(), livevec.end(), val);
1122 assert(livevec.end() != itr);
1123 size_t index = std::distance(livevec.begin(), itr);
1124 assert(index < livevec.size());
1125 return index;
1126}
1127
1128// Create new attribute set containing only attributes which can be transfered
1129// from original call to the safepoint.
1130static AttributeSet legalizeCallAttributes(AttributeSet AS) {
1131 AttributeSet ret;
1132
1133 for (unsigned Slot = 0; Slot < AS.getNumSlots(); Slot++) {
1134 unsigned index = AS.getSlotIndex(Slot);
1135
1136 if (index == AttributeSet::ReturnIndex ||
1137 index == AttributeSet::FunctionIndex) {
1138
1139 for (auto it = AS.begin(Slot), it_end = AS.end(Slot); it != it_end;
1140 ++it) {
1141 Attribute attr = *it;
1142
1143 // Do not allow certain attributes - just skip them
1144 // Safepoint can not be read only or read none.
1145 if (attr.hasAttribute(Attribute::ReadNone) ||
1146 attr.hasAttribute(Attribute::ReadOnly))
1147 continue;
1148
1149 ret = ret.addAttributes(
1150 AS.getContext(), index,
1151 AttributeSet::get(AS.getContext(), index, AttrBuilder(attr)));
1152 }
1153 }
1154
1155 // Just skip parameter attributes for now
1156 }
1157
1158 return ret;
1159}
1160
1161/// Helper function to place all gc relocates necessary for the given
1162/// statepoint.
1163/// Inputs:
1164/// liveVariables - list of variables to be relocated.
1165/// liveStart - index of the first live variable.
1166/// basePtrs - base pointers.
1167/// statepointToken - statepoint instruction to which relocates should be
1168/// bound.
1169/// Builder - Llvm IR builder to be used to construct new calls.
Philip Reamesd2b66462015-02-20 22:39:41 +00001170void CreateGCRelocates(ArrayRef<llvm::Value *> liveVariables,
1171 const int liveStart,
1172 ArrayRef<llvm::Value *> basePtrs,
1173 Instruction *statepointToken, IRBuilder<> Builder) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001174
Philip Reamesd2b66462015-02-20 22:39:41 +00001175 SmallVector<Instruction *, 64> NewDefs;
1176 NewDefs.reserve(liveVariables.size());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001177
1178 Module *M = statepointToken->getParent()->getParent()->getParent();
1179
1180 for (unsigned i = 0; i < liveVariables.size(); i++) {
1181 // We generate a (potentially) unique declaration for every pointer type
1182 // combination. This results is some blow up the function declarations in
1183 // the IR, but removes the need for argument bitcasts which shrinks the IR
1184 // greatly and makes it much more readable.
Philip Reamesd2b66462015-02-20 22:39:41 +00001185 SmallVector<Type *, 1> types; // one per 'any' type
Philip Reamesd16a9b12015-02-20 01:06:44 +00001186 types.push_back(liveVariables[i]->getType()); // result type
1187 Value *gc_relocate_decl = Intrinsic::getDeclaration(
1188 M, Intrinsic::experimental_gc_relocate, types);
1189
1190 // Generate the gc.relocate call and save the result
1191 Value *baseIdx =
1192 ConstantInt::get(Type::getInt32Ty(M->getContext()),
1193 liveStart + find_index(liveVariables, basePtrs[i]));
1194 Value *liveIdx = ConstantInt::get(
1195 Type::getInt32Ty(M->getContext()),
1196 liveStart + find_index(liveVariables, liveVariables[i]));
1197
1198 // only specify a debug name if we can give a useful one
1199 Value *reloc = Builder.CreateCall3(
1200 gc_relocate_decl, statepointToken, baseIdx, liveIdx,
1201 liveVariables[i]->hasName() ? liveVariables[i]->getName() + ".relocated"
1202 : "");
1203 // Trick CodeGen into thinking there are lots of free registers at this
1204 // fake call.
1205 cast<CallInst>(reloc)->setCallingConv(CallingConv::Cold);
1206
Philip Reamesd2b66462015-02-20 22:39:41 +00001207 NewDefs.push_back(cast<Instruction>(reloc));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001208 }
Philip Reamesd2b66462015-02-20 22:39:41 +00001209 assert(NewDefs.size() == liveVariables.size() &&
Philip Reamesd16a9b12015-02-20 01:06:44 +00001210 "missing or extra redefinition at safepoint");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001211}
1212
1213static void
1214makeStatepointExplicitImpl(const CallSite &CS, /* to replace */
1215 const SmallVectorImpl<llvm::Value *> &basePtrs,
1216 const SmallVectorImpl<llvm::Value *> &liveVariables,
1217 Pass *P,
1218 PartiallyConstructedSafepointRecord &result) {
1219 assert(basePtrs.size() == liveVariables.size());
1220 assert(isStatepoint(CS) &&
1221 "This method expects to be rewriting a statepoint");
1222
1223 BasicBlock *BB = CS.getInstruction()->getParent();
1224 assert(BB);
1225 Function *F = BB->getParent();
1226 assert(F && "must be set");
1227 Module *M = F->getParent();
Nick Lewyckyeb3231e2015-02-20 07:14:02 +00001228 (void)M;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001229 assert(M && "must be set");
1230
1231 // We're not changing the function signature of the statepoint since the gc
1232 // arguments go into the var args section.
1233 Function *gc_statepoint_decl = CS.getCalledFunction();
1234
1235 // Then go ahead and use the builder do actually do the inserts. We insert
1236 // immediately before the previous instruction under the assumption that all
1237 // arguments will be available here. We can't insert afterwards since we may
1238 // be replacing a terminator.
1239 Instruction *insertBefore = CS.getInstruction();
1240 IRBuilder<> Builder(insertBefore);
1241 // Copy all of the arguments from the original statepoint - this includes the
1242 // target, call args, and deopt args
Philip Reamesd2b66462015-02-20 22:39:41 +00001243 SmallVector<llvm::Value *, 64> args;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001244 args.insert(args.end(), CS.arg_begin(), CS.arg_end());
1245 // TODO: Clear the 'needs rewrite' flag
1246
1247 // add all the pointers to be relocated (gc arguments)
1248 // Capture the start of the live variable list for use in the gc_relocates
1249 const int live_start = args.size();
1250 args.insert(args.end(), liveVariables.begin(), liveVariables.end());
1251
1252 // Create the statepoint given all the arguments
1253 Instruction *token = nullptr;
1254 AttributeSet return_attributes;
1255 if (CS.isCall()) {
1256 CallInst *toReplace = cast<CallInst>(CS.getInstruction());
1257 CallInst *call =
1258 Builder.CreateCall(gc_statepoint_decl, args, "safepoint_token");
1259 call->setTailCall(toReplace->isTailCall());
1260 call->setCallingConv(toReplace->getCallingConv());
1261
1262 // Currently we will fail on parameter attributes and on certain
1263 // function attributes.
1264 AttributeSet new_attrs = legalizeCallAttributes(toReplace->getAttributes());
1265 // In case if we can handle this set of sttributes - set up function attrs
1266 // directly on statepoint and return attrs later for gc_result intrinsic.
1267 call->setAttributes(new_attrs.getFnAttributes());
1268 return_attributes = new_attrs.getRetAttributes();
1269
1270 token = call;
1271
1272 // Put the following gc_result and gc_relocate calls immediately after the
1273 // the old call (which we're about to delete)
1274 BasicBlock::iterator next(toReplace);
1275 assert(BB->end() != next && "not a terminator, must have next");
1276 next++;
1277 Instruction *IP = &*(next);
1278 Builder.SetInsertPoint(IP);
1279 Builder.SetCurrentDebugLocation(IP->getDebugLoc());
1280
David Blaikie82ad7872015-02-20 23:44:24 +00001281 } else {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001282 InvokeInst *toReplace = cast<InvokeInst>(CS.getInstruction());
1283
1284 // Insert the new invoke into the old block. We'll remove the old one in a
1285 // moment at which point this will become the new terminator for the
1286 // original block.
1287 InvokeInst *invoke = InvokeInst::Create(
1288 gc_statepoint_decl, toReplace->getNormalDest(),
1289 toReplace->getUnwindDest(), args, "", toReplace->getParent());
1290 invoke->setCallingConv(toReplace->getCallingConv());
1291
1292 // Currently we will fail on parameter attributes and on certain
1293 // function attributes.
1294 AttributeSet new_attrs = legalizeCallAttributes(toReplace->getAttributes());
1295 // In case if we can handle this set of sttributes - set up function attrs
1296 // directly on statepoint and return attrs later for gc_result intrinsic.
1297 invoke->setAttributes(new_attrs.getFnAttributes());
1298 return_attributes = new_attrs.getRetAttributes();
1299
1300 token = invoke;
1301
1302 // Generate gc relocates in exceptional path
1303 BasicBlock *unwindBlock = normalizeBBForInvokeSafepoint(
1304 toReplace->getUnwindDest(), invoke->getParent(), P);
1305
1306 Instruction *IP = &*(unwindBlock->getFirstInsertionPt());
1307 Builder.SetInsertPoint(IP);
1308 Builder.SetCurrentDebugLocation(toReplace->getDebugLoc());
1309
1310 // Extract second element from landingpad return value. We will attach
1311 // exceptional gc relocates to it.
1312 const unsigned idx = 1;
1313 Instruction *exceptional_token =
1314 cast<Instruction>(Builder.CreateExtractValue(
1315 unwindBlock->getLandingPadInst(), idx, "relocate_token"));
Philip Reamesf2041322015-02-20 19:26:04 +00001316 result.UnwindToken = exceptional_token;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001317
1318 // Just throw away return value. We will use the one we got for normal
1319 // block.
1320 (void)CreateGCRelocates(liveVariables, live_start, basePtrs,
1321 exceptional_token, Builder);
1322
1323 // Generate gc relocates and returns for normal block
1324 BasicBlock *normalDest = normalizeBBForInvokeSafepoint(
1325 toReplace->getNormalDest(), invoke->getParent(), P);
1326
1327 IP = &*(normalDest->getFirstInsertionPt());
1328 Builder.SetInsertPoint(IP);
1329
1330 // gc relocates will be generated later as if it were regular call
1331 // statepoint
Philip Reamesd16a9b12015-02-20 01:06:44 +00001332 }
1333 assert(token);
1334
1335 // Take the name of the original value call if it had one.
1336 token->takeName(CS.getInstruction());
1337
1338 // The GCResult is already inserted, we just need to find it
David Blaikie5e5d7842015-02-22 20:58:38 +00001339#ifndef NDEBUG
1340 Instruction *toReplace = CS.getInstruction();
1341 assert((toReplace->hasNUses(0) || toReplace->hasNUses(1)) &&
1342 "only valid use before rewrite is gc.result");
1343 assert(!toReplace->hasOneUse() ||
1344 isGCResult(cast<Instruction>(*toReplace->user_begin())));
1345#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +00001346
1347 // Update the gc.result of the original statepoint (if any) to use the newly
1348 // inserted statepoint. This is safe to do here since the token can't be
1349 // considered a live reference.
1350 CS.getInstruction()->replaceAllUsesWith(token);
1351
Philip Reames0a3240f2015-02-20 21:34:11 +00001352 result.StatepointToken = token;
1353
Philip Reamesd16a9b12015-02-20 01:06:44 +00001354 // Second, create a gc.relocate for every live variable
Philip Reames0a3240f2015-02-20 21:34:11 +00001355 CreateGCRelocates(liveVariables, live_start, basePtrs, token, Builder);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001356
Philip Reamesd16a9b12015-02-20 01:06:44 +00001357}
1358
1359namespace {
1360struct name_ordering {
1361 Value *base;
1362 Value *derived;
1363 bool operator()(name_ordering const &a, name_ordering const &b) {
1364 return -1 == a.derived->getName().compare(b.derived->getName());
1365 }
1366};
1367}
1368static void stablize_order(SmallVectorImpl<Value *> &basevec,
1369 SmallVectorImpl<Value *> &livevec) {
1370 assert(basevec.size() == livevec.size());
1371
Philip Reames860660e2015-02-20 22:05:18 +00001372 SmallVector<name_ordering, 64> temp;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001373 for (size_t i = 0; i < basevec.size(); i++) {
1374 name_ordering v;
1375 v.base = basevec[i];
1376 v.derived = livevec[i];
1377 temp.push_back(v);
1378 }
1379 std::sort(temp.begin(), temp.end(), name_ordering());
1380 for (size_t i = 0; i < basevec.size(); i++) {
1381 basevec[i] = temp[i].base;
1382 livevec[i] = temp[i].derived;
1383 }
1384}
1385
1386// Replace an existing gc.statepoint with a new one and a set of gc.relocates
1387// which make the relocations happening at this safepoint explicit.
1388//
1389// WARNING: Does not do any fixup to adjust users of the original live
1390// values. That's the callers responsibility.
1391static void
1392makeStatepointExplicit(DominatorTree &DT, const CallSite &CS, Pass *P,
1393 PartiallyConstructedSafepointRecord &result) {
Philip Reamesf2041322015-02-20 19:26:04 +00001394 auto liveset = result.liveset;
1395 auto PointerToBase = result.PointerToBase;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001396
1397 // Convert to vector for efficient cross referencing.
1398 SmallVector<Value *, 64> basevec, livevec;
1399 livevec.reserve(liveset.size());
1400 basevec.reserve(liveset.size());
1401 for (Value *L : liveset) {
1402 livevec.push_back(L);
1403
Philip Reamesf2041322015-02-20 19:26:04 +00001404 assert(PointerToBase.find(L) != PointerToBase.end());
1405 Value *base = PointerToBase[L];
Philip Reamesd16a9b12015-02-20 01:06:44 +00001406 basevec.push_back(base);
1407 }
1408 assert(livevec.size() == basevec.size());
1409
1410 // To make the output IR slightly more stable (for use in diffs), ensure a
1411 // fixed order of the values in the safepoint (by sorting the value name).
1412 // The order is otherwise meaningless.
1413 stablize_order(basevec, livevec);
1414
1415 // Do the actual rewriting and delete the old statepoint
1416 makeStatepointExplicitImpl(CS, basevec, livevec, P, result);
1417 CS.getInstruction()->eraseFromParent();
1418}
1419
1420// Helper function for the relocationViaAlloca.
1421// It receives iterator to the statepoint gc relocates and emits store to the
1422// assigned
1423// location (via allocaMap) for the each one of them.
1424// Add visited values into the visitedLiveValues set we will later use them
1425// for sanity check.
1426static void
1427insertRelocationStores(iterator_range<Value::user_iterator> gcRelocs,
1428 DenseMap<Value *, Value *> &allocaMap,
1429 DenseSet<Value *> &visitedLiveValues) {
1430
1431 for (User *U : gcRelocs) {
1432 if (!isa<IntrinsicInst>(U))
1433 continue;
1434
1435 IntrinsicInst *relocatedValue = cast<IntrinsicInst>(U);
1436
1437 // We only care about relocates
1438 if (relocatedValue->getIntrinsicID() !=
1439 Intrinsic::experimental_gc_relocate) {
1440 continue;
1441 }
1442
1443 GCRelocateOperands relocateOperands(relocatedValue);
1444 Value *originalValue = const_cast<Value *>(relocateOperands.derivedPtr());
1445 assert(allocaMap.count(originalValue));
1446 Value *alloca = allocaMap[originalValue];
1447
1448 // Emit store into the related alloca
1449 StoreInst *store = new StoreInst(relocatedValue, alloca);
1450 store->insertAfter(relocatedValue);
1451
1452#ifndef NDEBUG
1453 visitedLiveValues.insert(originalValue);
1454#endif
1455 }
1456}
1457
1458/// do all the relocation update via allocas and mem2reg
1459static void relocationViaAlloca(
Philip Reamesd2b66462015-02-20 22:39:41 +00001460 Function &F, DominatorTree &DT, ArrayRef<Value *> live,
1461 ArrayRef<struct PartiallyConstructedSafepointRecord> records) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001462#ifndef NDEBUG
1463 int initialAllocaNum = 0;
1464
1465 // record initial number of allocas
1466 for (inst_iterator itr = inst_begin(F), end = inst_end(F); itr != end;
1467 itr++) {
1468 if (isa<AllocaInst>(*itr))
1469 initialAllocaNum++;
1470 }
1471#endif
1472
1473 // TODO-PERF: change data structures, reserve
1474 DenseMap<Value *, Value *> allocaMap;
1475 SmallVector<AllocaInst *, 200> PromotableAllocas;
1476 PromotableAllocas.reserve(live.size());
1477
1478 // emit alloca for each live gc pointer
1479 for (unsigned i = 0; i < live.size(); i++) {
1480 Value *liveValue = live[i];
1481 AllocaInst *alloca = new AllocaInst(liveValue->getType(), "",
1482 F.getEntryBlock().getFirstNonPHI());
1483 allocaMap[liveValue] = alloca;
1484 PromotableAllocas.push_back(alloca);
1485 }
1486
1487 // The next two loops are part of the same conceptual operation. We need to
1488 // insert a store to the alloca after the original def and at each
1489 // redefinition. We need to insert a load before each use. These are split
1490 // into distinct loops for performance reasons.
1491
1492 // update gc pointer after each statepoint
1493 // either store a relocated value or null (if no relocated value found for
1494 // this gc pointer and it is not a gc_result)
1495 // this must happen before we update the statepoint with load of alloca
1496 // otherwise we lose the link between statepoint and old def
1497 for (size_t i = 0; i < records.size(); i++) {
1498 const struct PartiallyConstructedSafepointRecord &info = records[i];
Philip Reames0a3240f2015-02-20 21:34:11 +00001499 Value *Statepoint = info.StatepointToken;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001500
1501 // This will be used for consistency check
1502 DenseSet<Value *> visitedLiveValues;
1503
1504 // Insert stores for normal statepoint gc relocates
Philip Reames0a3240f2015-02-20 21:34:11 +00001505 insertRelocationStores(Statepoint->users(), allocaMap, visitedLiveValues);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001506
1507 // In case if it was invoke statepoint
1508 // we will insert stores for exceptional path gc relocates.
Philip Reames0a3240f2015-02-20 21:34:11 +00001509 if (isa<InvokeInst>(Statepoint)) {
Philip Reamesf2041322015-02-20 19:26:04 +00001510 insertRelocationStores(info.UnwindToken->users(),
Philip Reamesd16a9b12015-02-20 01:06:44 +00001511 allocaMap, visitedLiveValues);
1512 }
1513
1514#ifndef NDEBUG
Philip Reamesf2041322015-02-20 19:26:04 +00001515 // As a debuging aid, pretend that an unrelocated pointer becomes null at
1516 // the gc.statepoint. This will turn some subtle GC problems into slightly
Philip Reamesfa2fcf172015-02-20 19:51:56 +00001517 // easier to debug SEGVs
1518 SmallVector<AllocaInst *, 64> ToClobber;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001519 for (auto Pair : allocaMap) {
Philip Reamesfa2fcf172015-02-20 19:51:56 +00001520 Value *Def = Pair.first;
1521 AllocaInst *Alloca = cast<AllocaInst>(Pair.second);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001522
1523 // This value was relocated
Philip Reamesfa2fcf172015-02-20 19:51:56 +00001524 if (visitedLiveValues.count(Def)) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001525 continue;
1526 }
Philip Reamesfa2fcf172015-02-20 19:51:56 +00001527 ToClobber.push_back(Alloca);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001528 }
Philip Reamesfa2fcf172015-02-20 19:51:56 +00001529
Philip Reamesfa2fcf172015-02-20 19:51:56 +00001530 auto InsertClobbersAt = [&](Instruction *IP) {
1531 for (auto *AI : ToClobber) {
1532 auto AIType = cast<PointerType>(AI->getType());
1533 auto PT = cast<PointerType>(AIType->getElementType());
1534 Constant *CPN = ConstantPointerNull::get(PT);
1535 StoreInst *store = new StoreInst(CPN, AI);
1536 store->insertBefore(IP);
1537 }
1538 };
1539
1540 // Insert the clobbering stores. These may get intermixed with the
1541 // gc.results and gc.relocates, but that's fine.
1542 if (auto II = dyn_cast<InvokeInst>(Statepoint)) {
1543 InsertClobbersAt(II->getNormalDest()->getFirstInsertionPt());
1544 InsertClobbersAt(II->getUnwindDest()->getFirstInsertionPt());
David Blaikie82ad7872015-02-20 23:44:24 +00001545 } else {
1546 BasicBlock::iterator Next(cast<CallInst>(Statepoint));
Philip Reamesfa2fcf172015-02-20 19:51:56 +00001547 Next++;
1548 InsertClobbersAt(Next);
David Blaikie82ad7872015-02-20 23:44:24 +00001549 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00001550#endif
1551 }
1552 // update use with load allocas and add store for gc_relocated
1553 for (auto Pair : allocaMap) {
1554 Value *def = Pair.first;
1555 Value *alloca = Pair.second;
1556
1557 // we pre-record the uses of allocas so that we dont have to worry about
1558 // later update
1559 // that change the user information.
1560 SmallVector<Instruction *, 20> uses;
1561 // PERF: trade a linear scan for repeated reallocation
1562 uses.reserve(std::distance(def->user_begin(), def->user_end()));
1563 for (User *U : def->users()) {
1564 if (!isa<ConstantExpr>(U)) {
1565 // If the def has a ConstantExpr use, then the def is either a
1566 // ConstantExpr use itself or null. In either case
1567 // (recursively in the first, directly in the second), the oop
1568 // it is ultimately dependent on is null and this particular
1569 // use does not need to be fixed up.
1570 uses.push_back(cast<Instruction>(U));
1571 }
1572 }
1573
1574 std::sort(uses.begin(), uses.end());
1575 auto last = std::unique(uses.begin(), uses.end());
1576 uses.erase(last, uses.end());
1577
1578 for (Instruction *use : uses) {
1579 if (isa<PHINode>(use)) {
1580 PHINode *phi = cast<PHINode>(use);
1581 for (unsigned i = 0; i < phi->getNumIncomingValues(); i++) {
1582 if (def == phi->getIncomingValue(i)) {
1583 LoadInst *load = new LoadInst(
1584 alloca, "", phi->getIncomingBlock(i)->getTerminator());
1585 phi->setIncomingValue(i, load);
1586 }
1587 }
1588 } else {
1589 LoadInst *load = new LoadInst(alloca, "", use);
1590 use->replaceUsesOfWith(def, load);
1591 }
1592 }
1593
1594 // emit store for the initial gc value
1595 // store must be inserted after load, otherwise store will be in alloca's
1596 // use list and an extra load will be inserted before it
1597 StoreInst *store = new StoreInst(def, alloca);
1598 if (isa<Instruction>(def)) {
1599 store->insertAfter(cast<Instruction>(def));
1600 } else {
1601 assert((isa<Argument>(def) || isa<GlobalVariable>(def) ||
1602 (isa<Constant>(def) && cast<Constant>(def)->isNullValue())) &&
1603 "Must be argument or global");
1604 store->insertAfter(cast<Instruction>(alloca));
1605 }
1606 }
1607
1608 assert(PromotableAllocas.size() == live.size() &&
1609 "we must have the same allocas with lives");
1610 if (!PromotableAllocas.empty()) {
1611 // apply mem2reg to promote alloca to SSA
1612 PromoteMemToReg(PromotableAllocas, DT);
1613 }
1614
1615#ifndef NDEBUG
1616 for (inst_iterator itr = inst_begin(F), end = inst_end(F); itr != end;
1617 itr++) {
1618 if (isa<AllocaInst>(*itr))
1619 initialAllocaNum--;
1620 }
1621 assert(initialAllocaNum == 0 && "We must not introduce any extra allocas");
1622#endif
1623}
1624
1625/// Implement a unique function which doesn't require we sort the input
1626/// vector. Doing so has the effect of changing the output of a couple of
1627/// tests in ways which make them less useful in testing fused safepoints.
Philip Reamesd2b66462015-02-20 22:39:41 +00001628template <typename T> static void unique_unsorted(SmallVectorImpl<T> &Vec) {
1629 DenseSet<T> Seen;
1630 SmallVector<T, 128> TempVec;
1631 TempVec.reserve(Vec.size());
1632 for (auto Element : Vec)
1633 TempVec.push_back(Element);
1634 Vec.clear();
1635 for (auto V : TempVec) {
1636 if (Seen.insert(V).second) {
1637 Vec.push_back(V);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001638 }
1639 }
1640}
1641
1642static Function *getUseHolder(Module &M) {
1643 FunctionType *ftype =
1644 FunctionType::get(Type::getVoidTy(M.getContext()), true);
1645 Function *Func = cast<Function>(M.getOrInsertFunction("__tmp_use", ftype));
1646 return Func;
1647}
1648
1649/// Insert holders so that each Value is obviously live through the entire
1650/// liftetime of the call.
1651static void insertUseHolderAfter(CallSite &CS, const ArrayRef<Value *> Values,
Philip Reamesd2b66462015-02-20 22:39:41 +00001652 SmallVectorImpl<CallInst *> &holders) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001653 Module *M = CS.getInstruction()->getParent()->getParent()->getParent();
1654 Function *Func = getUseHolder(*M);
1655 if (CS.isCall()) {
1656 // For call safepoints insert dummy calls right after safepoint
1657 BasicBlock::iterator next(CS.getInstruction());
1658 next++;
1659 CallInst *base_holder = CallInst::Create(Func, Values, "", next);
1660 holders.push_back(base_holder);
1661 } else if (CS.isInvoke()) {
1662 // For invoke safepooints insert dummy calls both in normal and
1663 // exceptional destination blocks
1664 InvokeInst *invoke = cast<InvokeInst>(CS.getInstruction());
1665 CallInst *normal_holder = CallInst::Create(
1666 Func, Values, "", invoke->getNormalDest()->getFirstInsertionPt());
1667 CallInst *unwind_holder = CallInst::Create(
1668 Func, Values, "", invoke->getUnwindDest()->getFirstInsertionPt());
1669 holders.push_back(normal_holder);
1670 holders.push_back(unwind_holder);
Philip Reames860660e2015-02-20 22:05:18 +00001671 } else
1672 llvm_unreachable("unsupported call type");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001673}
1674
1675static void findLiveReferences(
Philip Reamesd2b66462015-02-20 22:39:41 +00001676 Function &F, DominatorTree &DT, Pass *P, ArrayRef<CallSite> toUpdate,
1677 MutableArrayRef<struct PartiallyConstructedSafepointRecord> records) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001678 for (size_t i = 0; i < records.size(); i++) {
1679 struct PartiallyConstructedSafepointRecord &info = records[i];
Philip Reamesd2b66462015-02-20 22:39:41 +00001680 const CallSite &CS = toUpdate[i];
Philip Reamesd16a9b12015-02-20 01:06:44 +00001681 analyzeParsePointLiveness(DT, CS, info);
1682 }
1683}
1684
Philip Reames1f017542015-02-20 23:16:52 +00001685static void addBasesAsLiveValues(StatepointLiveSetTy &liveset,
Philip Reamesf2041322015-02-20 19:26:04 +00001686 DenseMap<Value *, Value *> &PointerToBase) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001687 // Identify any base pointers which are used in this safepoint, but not
1688 // themselves relocated. We need to relocate them so that later inserted
1689 // safepoints can get the properly relocated base register.
1690 DenseSet<Value *> missing;
1691 for (Value *L : liveset) {
Philip Reamesf2041322015-02-20 19:26:04 +00001692 assert(PointerToBase.find(L) != PointerToBase.end());
1693 Value *base = PointerToBase[L];
Philip Reamesd16a9b12015-02-20 01:06:44 +00001694 assert(base);
1695 if (liveset.find(base) == liveset.end()) {
Philip Reamesf2041322015-02-20 19:26:04 +00001696 assert(PointerToBase.find(base) == PointerToBase.end());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001697 // uniqued by set insert
1698 missing.insert(base);
1699 }
1700 }
1701
1702 // Note that we want these at the end of the list, otherwise
1703 // register placement gets screwed up once we lower to STATEPOINT
1704 // instructions. This is an utter hack, but there doesn't seem to be a
1705 // better one.
1706 for (Value *base : missing) {
1707 assert(base);
1708 liveset.insert(base);
Philip Reamesf2041322015-02-20 19:26:04 +00001709 PointerToBase[base] = base;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001710 }
Philip Reamesf2041322015-02-20 19:26:04 +00001711 assert(liveset.size() == PointerToBase.size());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001712}
1713
1714static bool insertParsePoints(Function &F, DominatorTree &DT, Pass *P,
Philip Reamesd2b66462015-02-20 22:39:41 +00001715 SmallVectorImpl<CallSite> &toUpdate) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001716#ifndef NDEBUG
1717 // sanity check the input
1718 std::set<CallSite> uniqued;
1719 uniqued.insert(toUpdate.begin(), toUpdate.end());
1720 assert(uniqued.size() == toUpdate.size() && "no duplicates please!");
1721
1722 for (size_t i = 0; i < toUpdate.size(); i++) {
1723 CallSite &CS = toUpdate[i];
1724 assert(CS.getInstruction()->getParent()->getParent() == &F);
1725 assert(isStatepoint(CS) && "expected to already be a deopt statepoint");
1726 }
1727#endif
1728
1729 // A list of dummy calls added to the IR to keep various values obviously
1730 // live in the IR. We'll remove all of these when done.
Philip Reamesd2b66462015-02-20 22:39:41 +00001731 SmallVector<CallInst *, 64> holders;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001732
1733 // Insert a dummy call with all of the arguments to the vm_state we'll need
1734 // for the actual safepoint insertion. This ensures reference arguments in
1735 // the deopt argument list are considered live through the safepoint (and
1736 // thus makes sure they get relocated.)
1737 for (size_t i = 0; i < toUpdate.size(); i++) {
1738 CallSite &CS = toUpdate[i];
1739 Statepoint StatepointCS(CS);
1740
1741 SmallVector<Value *, 64> DeoptValues;
1742 for (Use &U : StatepointCS.vm_state_args()) {
1743 Value *Arg = cast<Value>(&U);
1744 if (isGCPointerType(Arg->getType()))
1745 DeoptValues.push_back(Arg);
1746 }
1747 insertUseHolderAfter(CS, DeoptValues, holders);
1748 }
1749
Philip Reamesd2b66462015-02-20 22:39:41 +00001750 SmallVector<struct PartiallyConstructedSafepointRecord, 64> records;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001751 records.reserve(toUpdate.size());
1752 for (size_t i = 0; i < toUpdate.size(); i++) {
1753 struct PartiallyConstructedSafepointRecord info;
1754 records.push_back(info);
1755 }
1756 assert(records.size() == toUpdate.size());
1757
1758 // A) Identify all gc pointers which are staticly live at the given call
1759 // site.
1760 findLiveReferences(F, DT, P, toUpdate, records);
1761
1762 // B) Find the base pointers for each live pointer
1763 /* scope for caching */ {
1764 // Cache the 'defining value' relation used in the computation and
1765 // insertion of base phis and selects. This ensures that we don't insert
1766 // large numbers of duplicate base_phis.
1767 DefiningValueMapTy DVCache;
1768
1769 for (size_t i = 0; i < records.size(); i++) {
1770 struct PartiallyConstructedSafepointRecord &info = records[i];
1771 CallSite &CS = toUpdate[i];
1772 findBasePointers(DT, DVCache, CS, info);
1773 }
1774 } // end of cache scope
1775
1776 // The base phi insertion logic (for any safepoint) may have inserted new
1777 // instructions which are now live at some safepoint. The simplest such
1778 // example is:
1779 // loop:
1780 // phi a <-- will be a new base_phi here
1781 // safepoint 1 <-- that needs to be live here
1782 // gep a + 1
1783 // safepoint 2
1784 // br loop
Philip Reames1f017542015-02-20 23:16:52 +00001785 DenseSet<llvm::Value *> allInsertedDefs;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001786 for (size_t i = 0; i < records.size(); i++) {
1787 struct PartiallyConstructedSafepointRecord &info = records[i];
Philip Reamesf2041322015-02-20 19:26:04 +00001788 allInsertedDefs.insert(info.NewInsertedDefs.begin(),
1789 info.NewInsertedDefs.end());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001790 }
1791
1792 // We insert some dummy calls after each safepoint to definitely hold live
1793 // the base pointers which were identified for that safepoint. We'll then
1794 // ask liveness for _every_ base inserted to see what is now live. Then we
1795 // remove the dummy calls.
1796 holders.reserve(holders.size() + records.size());
1797 for (size_t i = 0; i < records.size(); i++) {
1798 struct PartiallyConstructedSafepointRecord &info = records[i];
1799 CallSite &CS = toUpdate[i];
1800
1801 SmallVector<Value *, 128> Bases;
Philip Reamesf2041322015-02-20 19:26:04 +00001802 for (auto Pair : info.PointerToBase) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001803 Bases.push_back(Pair.second);
1804 }
1805 insertUseHolderAfter(CS, Bases, holders);
1806 }
1807
1808 // Add the bases explicitly to the live vector set. This may result in a few
1809 // extra relocations, but the base has to be available whenever a pointer
1810 // derived from it is used. Thus, we need it to be part of the statepoint's
1811 // gc arguments list. TODO: Introduce an explicit notion (in the following
1812 // code) of the GC argument list as seperate from the live Values at a
1813 // given statepoint.
1814 for (size_t i = 0; i < records.size(); i++) {
1815 struct PartiallyConstructedSafepointRecord &info = records[i];
Philip Reamesf2041322015-02-20 19:26:04 +00001816 addBasesAsLiveValues(info.liveset, info.PointerToBase);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001817 }
1818
1819 // If we inserted any new values, we need to adjust our notion of what is
1820 // live at a particular safepoint.
1821 if (!allInsertedDefs.empty()) {
1822 fixupLiveReferences(F, DT, P, allInsertedDefs, toUpdate, records);
1823 }
1824 if (PrintBasePointers) {
1825 for (size_t i = 0; i < records.size(); i++) {
1826 struct PartiallyConstructedSafepointRecord &info = records[i];
1827 errs() << "Base Pairs: (w/Relocation)\n";
Philip Reamesf2041322015-02-20 19:26:04 +00001828 for (auto Pair : info.PointerToBase) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001829 errs() << " derived %" << Pair.first->getName() << " base %"
1830 << Pair.second->getName() << "\n";
1831 }
1832 }
1833 }
1834 for (size_t i = 0; i < holders.size(); i++) {
1835 holders[i]->eraseFromParent();
1836 holders[i] = nullptr;
1837 }
1838 holders.clear();
1839
1840 // Now run through and replace the existing statepoints with new ones with
1841 // the live variables listed. We do not yet update uses of the values being
1842 // relocated. We have references to live variables that need to
1843 // survive to the last iteration of this loop. (By construction, the
1844 // previous statepoint can not be a live variable, thus we can and remove
1845 // the old statepoint calls as we go.)
1846 for (size_t i = 0; i < records.size(); i++) {
1847 struct PartiallyConstructedSafepointRecord &info = records[i];
1848 CallSite &CS = toUpdate[i];
1849 makeStatepointExplicit(DT, CS, P, info);
1850 }
1851 toUpdate.clear(); // prevent accident use of invalid CallSites
1852
1853 // In case if we inserted relocates in a different basic block than the
1854 // original safepoint (this can happen for invokes). We need to be sure that
1855 // original values were not used in any of the phi nodes at the
1856 // beginning of basic block containing them. Because we know that all such
1857 // blocks will have single predecessor we can safely assume that all phi
1858 // nodes have single entry (because of normalizeBBForInvokeSafepoint).
1859 // Just remove them all here.
1860 for (size_t i = 0; i < records.size(); i++) {
Philip Reames0a3240f2015-02-20 21:34:11 +00001861 Instruction *I = records[i].StatepointToken;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001862
1863 if (InvokeInst *invoke = dyn_cast<InvokeInst>(I)) {
1864 FoldSingleEntryPHINodes(invoke->getNormalDest());
1865 assert(!isa<PHINode>(invoke->getNormalDest()->begin()));
1866
1867 FoldSingleEntryPHINodes(invoke->getUnwindDest());
1868 assert(!isa<PHINode>(invoke->getUnwindDest()->begin()));
1869 }
1870 }
1871
1872 // Do all the fixups of the original live variables to their relocated selves
Philip Reamesd2b66462015-02-20 22:39:41 +00001873 SmallVector<Value *, 128> live;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001874 for (size_t i = 0; i < records.size(); i++) {
1875 struct PartiallyConstructedSafepointRecord &info = records[i];
1876 // We can't simply save the live set from the original insertion. One of
1877 // the live values might be the result of a call which needs a safepoint.
1878 // That Value* no longer exists and we need to use the new gc_result.
1879 // Thankfully, the liveset is embedded in the statepoint (and updated), so
1880 // we just grab that.
Philip Reames0a3240f2015-02-20 21:34:11 +00001881 Statepoint statepoint(info.StatepointToken);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001882 live.insert(live.end(), statepoint.gc_args_begin(),
1883 statepoint.gc_args_end());
1884 }
1885 unique_unsorted(live);
1886
Nick Lewyckyeb3231e2015-02-20 07:14:02 +00001887#ifndef NDEBUG
Philip Reamesd16a9b12015-02-20 01:06:44 +00001888 // sanity check
1889 for (auto ptr : live) {
1890 assert(isGCPointerType(ptr->getType()) && "must be a gc pointer type");
1891 }
Nick Lewyckyeb3231e2015-02-20 07:14:02 +00001892#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +00001893
1894 relocationViaAlloca(F, DT, live, records);
1895 return !records.empty();
1896}
1897
1898/// Returns true if this function should be rewritten by this pass. The main
1899/// point of this function is as an extension point for custom logic.
1900static bool shouldRewriteStatepointsIn(Function &F) {
1901 // TODO: This should check the GCStrategy
Philip Reames2ef029c2015-02-20 18:56:14 +00001902 if (F.hasGC()) {
1903 const std::string StatepointExampleName("statepoint-example");
1904 return StatepointExampleName == F.getGC();
1905 } else
1906 return false;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001907}
1908
1909bool RewriteStatepointsForGC::runOnFunction(Function &F) {
1910 // Nothing to do for declarations.
1911 if (F.isDeclaration() || F.empty())
1912 return false;
1913
1914 // Policy choice says not to rewrite - the most common reason is that we're
1915 // compiling code without a GCStrategy.
1916 if (!shouldRewriteStatepointsIn(F))
1917 return false;
1918
1919 // Gather all the statepoints which need rewritten.
Philip Reamesd2b66462015-02-20 22:39:41 +00001920 SmallVector<CallSite, 64> ParsePointNeeded;
1921 for (Instruction &I : inst_range(F)) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001922 // TODO: only the ones with the flag set!
Philip Reamesd2b66462015-02-20 22:39:41 +00001923 if (isStatepoint(I))
1924 ParsePointNeeded.push_back(CallSite(&I));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001925 }
1926
1927 // Return early if no work to do.
1928 if (ParsePointNeeded.empty())
1929 return false;
1930
1931 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1932 return insertParsePoints(F, DT, this, ParsePointNeeded);
1933}