blob: ed8029b8a37c00362bd78dd7e27d4eb0263b4d91 [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) {}
Philip Reamesd16a9b12015-02-20 01:06:44 +0000551
552 Status getStatus() const { return status; }
553 Value *getBase() const { return base; }
554
555 bool isBase() const { return getStatus() == Base; }
556 bool isUnknown() const { return getStatus() == Unknown; }
557 bool isConflict() const { return getStatus() == Conflict; }
558
559 bool operator==(const PhiState &other) const {
560 return base == other.base && status == other.status;
561 }
562
563 bool operator!=(const PhiState &other) const { return !(*this == other); }
564
565 void dump() {
566 errs() << status << " (" << base << " - "
567 << (base ? base->getName() : "nullptr") << "): ";
568 }
569
570private:
571 Status status;
572 Value *base; // non null only if status == base
573};
574
Philip Reamese9c3b9b2015-02-20 22:48:20 +0000575typedef DenseMap<Value *, PhiState> ConflictStateMapTy;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000576// Values of type PhiState form a lattice, and this is a helper
577// class that implementes the meet operation. The meat of the meet
578// operation is implemented in MeetPhiStates::pureMeet
579class MeetPhiStates {
580public:
581 // phiStates is a mapping from PHINodes and SelectInst's to PhiStates.
Philip Reames860660e2015-02-20 22:05:18 +0000582 explicit MeetPhiStates(const ConflictStateMapTy &phiStates)
Philip Reamesd16a9b12015-02-20 01:06:44 +0000583 : phiStates(phiStates) {}
584
585 // Destructively meet the current result with the base V. V can
586 // either be a merge instruction (SelectInst / PHINode), in which
587 // case its status is looked up in the phiStates map; or a regular
588 // SSA value, in which case it is assumed to be a base.
589 void meetWith(Value *V) {
590 PhiState otherState = getStateForBDV(V);
591 assert((MeetPhiStates::pureMeet(otherState, currentResult) ==
592 MeetPhiStates::pureMeet(currentResult, otherState)) &&
593 "math is wrong: meet does not commute!");
594 currentResult = MeetPhiStates::pureMeet(otherState, currentResult);
595 }
596
597 PhiState getResult() const { return currentResult; }
598
599private:
Philip Reames860660e2015-02-20 22:05:18 +0000600 const ConflictStateMapTy &phiStates;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000601 PhiState currentResult;
602
603 /// Return a phi state for a base defining value. We'll generate a new
604 /// base state for known bases and expect to find a cached state otherwise
605 PhiState getStateForBDV(Value *baseValue) {
606 if (isKnownBaseResult(baseValue)) {
607 return PhiState(baseValue);
608 } else {
609 return lookupFromMap(baseValue);
610 }
611 }
612
613 PhiState lookupFromMap(Value *V) {
614 auto I = phiStates.find(V);
615 assert(I != phiStates.end() && "lookup failed!");
616 return I->second;
617 }
618
619 static PhiState pureMeet(const PhiState &stateA, const PhiState &stateB) {
620 switch (stateA.getStatus()) {
621 case PhiState::Unknown:
622 return stateB;
623
624 case PhiState::Base:
625 assert(stateA.getBase() && "can't be null");
David Blaikie82ad7872015-02-20 23:44:24 +0000626 if (stateB.isUnknown())
Philip Reamesd16a9b12015-02-20 01:06:44 +0000627 return stateA;
David Blaikie82ad7872015-02-20 23:44:24 +0000628
629 if (stateB.isBase()) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000630 if (stateA.getBase() == stateB.getBase()) {
631 assert(stateA == stateB && "equality broken!");
632 return stateA;
633 }
634 return PhiState(PhiState::Conflict);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000635 }
David Blaikie82ad7872015-02-20 23:44:24 +0000636 assert(stateB.isConflict() && "only three states!");
637 return PhiState(PhiState::Conflict);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000638
639 case PhiState::Conflict:
640 return stateA;
641 }
Reid Klecknera070ee52015-02-20 19:46:02 +0000642 llvm_unreachable("only three states!");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000643 }
644};
645}
646/// For a given value or instruction, figure out what base ptr it's derived
647/// from. For gc objects, this is simply itself. On success, returns a value
648/// which is the base pointer. (This is reliable and can be used for
649/// relocation.) On failure, returns nullptr.
650static Value *findBasePointer(Value *I, DefiningValueMapTy &cache,
Philip Reamesf2041322015-02-20 19:26:04 +0000651 DenseSet<llvm::Value *> &NewInsertedDefs) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000652 Value *def = findBaseOrBDV(I, cache);
653
654 if (isKnownBaseResult(def)) {
655 return def;
656 }
657
658 // Here's the rough algorithm:
659 // - For every SSA value, construct a mapping to either an actual base
660 // pointer or a PHI which obscures the base pointer.
661 // - Construct a mapping from PHI to unknown TOP state. Use an
662 // optimistic algorithm to propagate base pointer information. Lattice
663 // looks like:
664 // UNKNOWN
665 // b1 b2 b3 b4
666 // CONFLICT
667 // When algorithm terminates, all PHIs will either have a single concrete
668 // base or be in a conflict state.
669 // - For every conflict, insert a dummy PHI node without arguments. Add
670 // these to the base[Instruction] = BasePtr mapping. For every
671 // non-conflict, add the actual base.
672 // - For every conflict, add arguments for the base[a] of each input
673 // arguments.
674 //
675 // Note: A simpler form of this would be to add the conflict form of all
676 // PHIs without running the optimistic algorithm. This would be
677 // analougous to pessimistic data flow and would likely lead to an
678 // overall worse solution.
679
Philip Reames860660e2015-02-20 22:05:18 +0000680 ConflictStateMapTy states;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000681 states[def] = PhiState();
682 // Recursively fill in all phis & selects reachable from the initial one
683 // for which we don't already know a definite base value for
Philip Reamesa226e612015-02-28 00:47:50 +0000684 // TODO: This should be rewritten with a worklist
Philip Reamesd16a9b12015-02-20 01:06:44 +0000685 bool done = false;
686 while (!done) {
687 done = true;
Philip Reamesa226e612015-02-28 00:47:50 +0000688 // Since we're adding elements to 'states' as we run, we can't keep
689 // iterators into the set.
690 SmallVector<Value*, 16> Keys;
691 Keys.reserve(states.size());
Philip Reamesd16a9b12015-02-20 01:06:44 +0000692 for (auto Pair : states) {
Philip Reamesa226e612015-02-28 00:47:50 +0000693 Value *V = Pair.first;
694 Keys.push_back(V);
695 }
696 for (Value *v : Keys) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000697 assert(!isKnownBaseResult(v) && "why did it get added?");
698 if (PHINode *phi = dyn_cast<PHINode>(v)) {
David Blaikie82ad7872015-02-20 23:44:24 +0000699 assert(phi->getNumIncomingValues() > 0 &&
700 "zero input phis are illegal");
701 for (Value *InVal : phi->incoming_values()) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000702 Value *local = findBaseOrBDV(InVal, cache);
703 if (!isKnownBaseResult(local) && states.find(local) == states.end()) {
704 states[local] = PhiState();
705 done = false;
706 }
707 }
708 } else if (SelectInst *sel = dyn_cast<SelectInst>(v)) {
709 Value *local = findBaseOrBDV(sel->getTrueValue(), cache);
710 if (!isKnownBaseResult(local) && states.find(local) == states.end()) {
711 states[local] = PhiState();
712 done = false;
713 }
714 local = findBaseOrBDV(sel->getFalseValue(), cache);
715 if (!isKnownBaseResult(local) && states.find(local) == states.end()) {
716 states[local] = PhiState();
717 done = false;
718 }
719 }
720 }
721 }
722
723 if (TraceLSP) {
724 errs() << "States after initialization:\n";
725 for (auto Pair : states) {
726 Instruction *v = cast<Instruction>(Pair.first);
727 PhiState state = Pair.second;
728 state.dump();
729 v->dump();
730 }
731 }
732
733 // TODO: come back and revisit the state transitions around inputs which
734 // have reached conflict state. The current version seems too conservative.
735
736 bool progress = true;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000737 while (progress) {
Yaron Keren42a7adf2015-02-28 13:11:24 +0000738#ifndef NDEBUG
739 size_t oldSize = states.size();
740#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +0000741 progress = false;
Philip Reamesa226e612015-02-28 00:47:50 +0000742 // We're only changing keys in this loop, thus safe to keep iterators
Philip Reamesd16a9b12015-02-20 01:06:44 +0000743 for (auto Pair : states) {
744 MeetPhiStates calculateMeet(states);
745 Value *v = Pair.first;
746 assert(!isKnownBaseResult(v) && "why did it get added?");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000747 if (SelectInst *select = dyn_cast<SelectInst>(v)) {
748 calculateMeet.meetWith(findBaseOrBDV(select->getTrueValue(), cache));
749 calculateMeet.meetWith(findBaseOrBDV(select->getFalseValue(), cache));
David Blaikie82ad7872015-02-20 23:44:24 +0000750 } else
751 for (Value *Val : cast<PHINode>(v)->incoming_values())
752 calculateMeet.meetWith(findBaseOrBDV(Val, cache));
Philip Reamesd16a9b12015-02-20 01:06:44 +0000753
754 PhiState oldState = states[v];
755 PhiState newState = calculateMeet.getResult();
756 if (oldState != newState) {
757 progress = true;
758 states[v] = newState;
759 }
760 }
761
762 assert(oldSize <= states.size());
763 assert(oldSize == states.size() || progress);
764 }
765
766 if (TraceLSP) {
767 errs() << "States after meet iteration:\n";
768 for (auto Pair : states) {
769 Instruction *v = cast<Instruction>(Pair.first);
770 PhiState state = Pair.second;
771 state.dump();
772 v->dump();
773 }
774 }
775
776 // Insert Phis for all conflicts
Philip Reames2e5bcbe2015-02-28 01:52:09 +0000777 // We want to keep naming deterministic in the loop that follows, so
778 // sort the keys before iteration. This is useful in allowing us to
779 // write stable tests. Note that there is no invalidation issue here.
780 SmallVector<Value*, 16> Keys;
781 Keys.reserve(states.size());
Philip Reamesd16a9b12015-02-20 01:06:44 +0000782 for (auto Pair : states) {
Philip Reames2e5bcbe2015-02-28 01:52:09 +0000783 Value *V = Pair.first;
784 Keys.push_back(V);
785 }
786 std::sort(Keys.begin(), Keys.end(), order_by_name);
787 // TODO: adjust naming patterns to avoid this order of iteration dependency
788 for (Value *V : Keys) {
789 Instruction *v = cast<Instruction>(V);
790 PhiState state = states[V];
Philip Reamesd16a9b12015-02-20 01:06:44 +0000791 assert(!isKnownBaseResult(v) && "why did it get added?");
792 assert(!state.isUnknown() && "Optimistic algorithm didn't complete!");
Philip Reamesf986d682015-02-28 00:54:41 +0000793 if (!state.isConflict())
794 continue;
795
796 if (isa<PHINode>(v)) {
797 int num_preds =
798 std::distance(pred_begin(v->getParent()), pred_end(v->getParent()));
799 assert(num_preds > 0 && "how did we reach here");
800 PHINode *phi = PHINode::Create(v->getType(), num_preds, "base_phi", v);
801 NewInsertedDefs.insert(phi);
802 // Add metadata marking this as a base value
803 auto *const_1 = ConstantInt::get(
804 Type::getInt32Ty(
805 v->getParent()->getParent()->getParent()->getContext()),
806 1);
807 auto MDConst = ConstantAsMetadata::get(const_1);
808 MDNode *md = MDNode::get(
809 v->getParent()->getParent()->getParent()->getContext(), MDConst);
810 phi->setMetadata("is_base_value", md);
811 states[v] = PhiState(PhiState::Conflict, phi);
812 } else {
813 SelectInst *sel = cast<SelectInst>(v);
814 // The undef will be replaced later
815 UndefValue *undef = UndefValue::get(sel->getType());
816 SelectInst *basesel = SelectInst::Create(sel->getCondition(), undef,
817 undef, "base_select", sel);
818 NewInsertedDefs.insert(basesel);
819 // Add metadata marking this as a base value
820 auto *const_1 = ConstantInt::get(
821 Type::getInt32Ty(
822 v->getParent()->getParent()->getParent()->getContext()),
823 1);
824 auto MDConst = ConstantAsMetadata::get(const_1);
825 MDNode *md = MDNode::get(
826 v->getParent()->getParent()->getParent()->getContext(), MDConst);
827 basesel->setMetadata("is_base_value", md);
828 states[v] = PhiState(PhiState::Conflict, basesel);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000829 }
830 }
831
832 // Fixup all the inputs of the new PHIs
833 for (auto Pair : states) {
834 Instruction *v = cast<Instruction>(Pair.first);
835 PhiState state = Pair.second;
836
837 assert(!isKnownBaseResult(v) && "why did it get added?");
838 assert(!state.isUnknown() && "Optimistic algorithm didn't complete!");
Philip Reames28e61ce2015-02-28 01:57:44 +0000839 if (!state.isConflict())
840 continue;
841
842 if (PHINode *basephi = dyn_cast<PHINode>(state.getBase())) {
843 PHINode *phi = cast<PHINode>(v);
844 unsigned NumPHIValues = phi->getNumIncomingValues();
845 for (unsigned i = 0; i < NumPHIValues; i++) {
846 Value *InVal = phi->getIncomingValue(i);
847 BasicBlock *InBB = phi->getIncomingBlock(i);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000848
Philip Reames28e61ce2015-02-28 01:57:44 +0000849 // If we've already seen InBB, add the same incoming value
850 // we added for it earlier. The IR verifier requires phi
851 // nodes with multiple entries from the same basic block
852 // to have the same incoming value for each of those
853 // entries. If we don't do this check here and basephi
854 // has a different type than base, we'll end up adding two
855 // bitcasts (and hence two distinct values) as incoming
856 // values for the same basic block.
Philip Reamesd16a9b12015-02-20 01:06:44 +0000857
Philip Reames28e61ce2015-02-28 01:57:44 +0000858 int blockIndex = basephi->getBasicBlockIndex(InBB);
859 if (blockIndex != -1) {
860 Value *oldBase = basephi->getIncomingValue(blockIndex);
861 basephi->addIncoming(oldBase, InBB);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000862#ifndef NDEBUG
Philip Reames28e61ce2015-02-28 01:57:44 +0000863 Value *base = findBaseOrBDV(InVal, cache);
864 if (!isKnownBaseResult(base)) {
865 // Either conflict or base.
866 assert(states.count(base));
867 base = states[base].getBase();
868 assert(base != nullptr && "unknown PhiState!");
869 assert(NewInsertedDefs.count(base) &&
870 "should have already added this in a prev. iteration!");
871 }
Philip Reamesd16a9b12015-02-20 01:06:44 +0000872
Philip Reames28e61ce2015-02-28 01:57:44 +0000873 // In essense this assert states: the only way two
874 // values incoming from the same basic block may be
875 // different is by being different bitcasts of the same
876 // value. A cleanup that remains TODO is changing
877 // findBaseOrBDV to return an llvm::Value of the correct
878 // type (and still remain pure). This will remove the
879 // need to add bitcasts.
880 assert(base->stripPointerCasts() == oldBase->stripPointerCasts() &&
881 "sanity -- findBaseOrBDV should be pure!");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000882#endif
Philip Reames28e61ce2015-02-28 01:57:44 +0000883 continue;
884 }
Philip Reamesd16a9b12015-02-20 01:06:44 +0000885
Philip Reames28e61ce2015-02-28 01:57:44 +0000886 // Find either the defining value for the PHI or the normal base for
887 // a non-phi node
888 Value *base = findBaseOrBDV(InVal, cache);
889 if (!isKnownBaseResult(base)) {
890 // Either conflict or base.
891 assert(states.count(base));
892 base = states[base].getBase();
893 assert(base != nullptr && "unknown PhiState!");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000894 }
Philip Reames28e61ce2015-02-28 01:57:44 +0000895 assert(base && "can't be null");
896 // Must use original input BB since base may not be Instruction
897 // The cast is needed since base traversal may strip away bitcasts
898 if (base->getType() != basephi->getType()) {
899 base = new BitCastInst(base, basephi->getType(), "cast",
900 InBB->getTerminator());
901 NewInsertedDefs.insert(base);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000902 }
Philip Reames28e61ce2015-02-28 01:57:44 +0000903 basephi->addIncoming(base, InBB);
904 }
905 assert(basephi->getNumIncomingValues() == NumPHIValues);
906 } else {
907 SelectInst *basesel = cast<SelectInst>(state.getBase());
908 SelectInst *sel = cast<SelectInst>(v);
909 // Operand 1 & 2 are true, false path respectively. TODO: refactor to
910 // something more safe and less hacky.
911 for (int i = 1; i <= 2; i++) {
912 Value *InVal = sel->getOperand(i);
913 // Find either the defining value for the PHI or the normal base for
914 // a non-phi node
915 Value *base = findBaseOrBDV(InVal, cache);
916 if (!isKnownBaseResult(base)) {
917 // Either conflict or base.
918 assert(states.count(base));
919 base = states[base].getBase();
920 assert(base != nullptr && "unknown PhiState!");
921 }
922 assert(base && "can't be null");
923 // Must use original input BB since base may not be Instruction
924 // The cast is needed since base traversal may strip away bitcasts
925 if (base->getType() != basesel->getType()) {
926 base = new BitCastInst(base, basesel->getType(), "cast", basesel);
927 NewInsertedDefs.insert(base);
928 }
929 basesel->setOperand(i, base);
930 }
Philip Reamesd16a9b12015-02-20 01:06:44 +0000931 }
932 }
933
934 // Cache all of our results so we can cheaply reuse them
935 // NOTE: This is actually two caches: one of the base defining value
936 // relation and one of the base pointer relation! FIXME
937 for (auto item : states) {
938 Value *v = item.first;
939 Value *base = item.second.getBase();
940 assert(v && base);
941 assert(!isKnownBaseResult(v) && "why did it get added?");
942
943 if (TraceLSP) {
944 std::string fromstr =
945 cache.count(v) ? (cache[v]->hasName() ? cache[v]->getName() : "")
946 : "none";
947 errs() << "Updating base value cache"
948 << " for: " << (v->hasName() ? v->getName() : "")
949 << " from: " << fromstr
950 << " to: " << (base->hasName() ? base->getName() : "") << "\n";
951 }
952
953 assert(isKnownBaseResult(base) &&
954 "must be something we 'know' is a base pointer");
955 if (cache.count(v)) {
956 // Once we transition from the BDV relation being store in the cache to
957 // the base relation being stored, it must be stable
958 assert((!isKnownBaseResult(cache[v]) || cache[v] == base) &&
959 "base relation should be stable");
960 }
961 cache[v] = base;
962 }
963 assert(cache.find(def) != cache.end());
964 return cache[def];
965}
966
967// For a set of live pointers (base and/or derived), identify the base
968// pointer of the object which they are derived from. This routine will
969// mutate the IR graph as needed to make the 'base' pointer live at the
970// definition site of 'derived'. This ensures that any use of 'derived' can
971// also use 'base'. This may involve the insertion of a number of
972// additional PHI nodes.
973//
974// preconditions: live is a set of pointer type Values
975//
976// side effects: may insert PHI nodes into the existing CFG, will preserve
977// CFG, will not remove or mutate any existing nodes
978//
Philip Reamesf2041322015-02-20 19:26:04 +0000979// post condition: PointerToBase contains one (derived, base) pair for every
Philip Reamesd16a9b12015-02-20 01:06:44 +0000980// pointer in live. Note that derived can be equal to base if the original
981// pointer was a base pointer.
Philip Reames1f017542015-02-20 23:16:52 +0000982static void findBasePointers(const StatepointLiveSetTy &live,
Philip Reamesf2041322015-02-20 19:26:04 +0000983 DenseMap<llvm::Value *, llvm::Value *> &PointerToBase,
Philip Reamesd16a9b12015-02-20 01:06:44 +0000984 DominatorTree *DT, DefiningValueMapTy &DVCache,
Philip Reamesf2041322015-02-20 19:26:04 +0000985 DenseSet<llvm::Value *> &NewInsertedDefs) {
Philip Reames2e5bcbe2015-02-28 01:52:09 +0000986 // For the naming of values inserted to be deterministic - which makes for
987 // much cleaner and more stable tests - we need to assign an order to the
988 // live values. DenseSets do not provide a deterministic order across runs.
989 SmallVector<Value*, 64> Temp;
990 Temp.insert(Temp.end(), live.begin(), live.end());
991 std::sort(Temp.begin(), Temp.end(), order_by_name);
992 for (Value *ptr : Temp) {
Philip Reamesf2041322015-02-20 19:26:04 +0000993 Value *base = findBasePointer(ptr, DVCache, NewInsertedDefs);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000994 assert(base && "failed to find base pointer");
Philip Reamesf2041322015-02-20 19:26:04 +0000995 PointerToBase[ptr] = base;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000996 assert((!isa<Instruction>(base) || !isa<Instruction>(ptr) ||
997 DT->dominates(cast<Instruction>(base)->getParent(),
998 cast<Instruction>(ptr)->getParent())) &&
999 "The base we found better dominate the derived pointer");
1000
David Blaikie82ad7872015-02-20 23:44:24 +00001001 // If you see this trip and like to live really dangerously, the code should
1002 // be correct, just with idioms the verifier can't handle. You can try
1003 // disabling the verifier at your own substaintial risk.
1004 assert(!isNullConstant(base) && "the relocation code needs adjustment to "
1005 "handle the relocation of a null pointer "
1006 "constant without causing false positives "
1007 "in the safepoint ir verifier.");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001008 }
1009}
1010
1011/// Find the required based pointers (and adjust the live set) for the given
1012/// parse point.
1013static void findBasePointers(DominatorTree &DT, DefiningValueMapTy &DVCache,
1014 const CallSite &CS,
1015 PartiallyConstructedSafepointRecord &result) {
Philip Reamesf2041322015-02-20 19:26:04 +00001016 DenseMap<llvm::Value *, llvm::Value *> PointerToBase;
1017 DenseSet<llvm::Value *> NewInsertedDefs;
1018 findBasePointers(result.liveset, PointerToBase, &DT, DVCache, NewInsertedDefs);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001019
1020 if (PrintBasePointers) {
Philip Reamesa5aeaf42015-02-28 00:20:48 +00001021 // Note: Need to print these in a stable order since this is checked in
1022 // some tests.
Philip Reamesd16a9b12015-02-20 01:06:44 +00001023 errs() << "Base Pairs (w/o Relocation):\n";
Philip Reamesa5aeaf42015-02-28 00:20:48 +00001024 SmallVector<Value*, 64> Temp;
1025 Temp.reserve(PointerToBase.size());
Philip Reamesf2041322015-02-20 19:26:04 +00001026 for (auto Pair : PointerToBase) {
Philip Reamesa5aeaf42015-02-28 00:20:48 +00001027 Temp.push_back(Pair.first);
1028 }
1029 std::sort(Temp.begin(), Temp.end(), order_by_name);
1030 for (Value *Ptr : Temp) {
1031 Value *Base = PointerToBase[Ptr];
1032 errs() << " derived %" << Ptr->getName() << " base %"
1033 << Base->getName() << "\n";
Philip Reamesd16a9b12015-02-20 01:06:44 +00001034 }
1035 }
1036
Philip Reamesf2041322015-02-20 19:26:04 +00001037 result.PointerToBase = PointerToBase;
1038 result.NewInsertedDefs = NewInsertedDefs;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001039}
1040
1041/// Check for liveness of items in the insert defs and add them to the live
1042/// and base pointer sets
1043static void fixupLiveness(DominatorTree &DT, const CallSite &CS,
Philip Reames1f017542015-02-20 23:16:52 +00001044 const DenseSet<Value *> &allInsertedDefs,
Philip Reamesd16a9b12015-02-20 01:06:44 +00001045 PartiallyConstructedSafepointRecord &result) {
1046 Instruction *inst = CS.getInstruction();
1047
Philip Reamesf2041322015-02-20 19:26:04 +00001048 auto liveset = result.liveset;
1049 auto PointerToBase = result.PointerToBase;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001050
1051 auto is_live_gc_reference =
1052 [&](Value &V) { return isLiveGCReferenceAt(V, inst, DT, nullptr); };
1053
1054 // For each new definition, check to see if a) the definition dominates the
1055 // instruction we're interested in, and b) one of the uses of that definition
1056 // is edge-reachable from the instruction we're interested in. This is the
1057 // same definition of liveness we used in the intial liveness analysis
1058 for (Value *newDef : allInsertedDefs) {
1059 if (liveset.count(newDef)) {
1060 // already live, no action needed
1061 continue;
1062 }
1063
1064 // PERF: Use DT to check instruction domination might not be good for
1065 // compilation time, and we could change to optimal solution if this
1066 // turn to be a issue
1067 if (!DT.dominates(cast<Instruction>(newDef), inst)) {
1068 // can't possibly be live at inst
1069 continue;
1070 }
1071
1072 if (is_live_gc_reference(*newDef)) {
Philip Reamesf2041322015-02-20 19:26:04 +00001073 // Add the live new defs into liveset and PointerToBase
Philip Reamesd16a9b12015-02-20 01:06:44 +00001074 liveset.insert(newDef);
Philip Reamesf2041322015-02-20 19:26:04 +00001075 PointerToBase[newDef] = newDef;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001076 }
1077 }
1078
1079 result.liveset = liveset;
Philip Reamesf2041322015-02-20 19:26:04 +00001080 result.PointerToBase = PointerToBase;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001081}
1082
1083static void fixupLiveReferences(
1084 Function &F, DominatorTree &DT, Pass *P,
Philip Reames1f017542015-02-20 23:16:52 +00001085 const DenseSet<llvm::Value *> &allInsertedDefs,
Philip Reamesd2b66462015-02-20 22:39:41 +00001086 ArrayRef<CallSite> toUpdate,
1087 MutableArrayRef<struct PartiallyConstructedSafepointRecord> records) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001088 for (size_t i = 0; i < records.size(); i++) {
1089 struct PartiallyConstructedSafepointRecord &info = records[i];
Philip Reamesd2b66462015-02-20 22:39:41 +00001090 const CallSite &CS = toUpdate[i];
Philip Reamesd16a9b12015-02-20 01:06:44 +00001091 fixupLiveness(DT, CS, allInsertedDefs, info);
1092 }
1093}
1094
1095// Normalize basic block to make it ready to be target of invoke statepoint.
1096// It means spliting it to have single predecessor. Return newly created BB
1097// ready to be successor of invoke statepoint.
1098static BasicBlock *normalizeBBForInvokeSafepoint(BasicBlock *BB,
1099 BasicBlock *InvokeParent,
1100 Pass *P) {
1101 BasicBlock *ret = BB;
1102
1103 if (!BB->getUniquePredecessor()) {
1104 ret = SplitBlockPredecessors(BB, InvokeParent, "");
1105 }
1106
1107 // Another requirement for such basic blocks is to not have any phi nodes.
1108 // Since we just ensured that new BB will have single predecessor,
1109 // all phi nodes in it will have one value. Here it would be naturall place
1110 // to
1111 // remove them all. But we can not do this because we are risking to remove
1112 // one of the values stored in liveset of another statepoint. We will do it
1113 // later after placing all safepoints.
1114
1115 return ret;
1116}
1117
Philip Reamesd2b66462015-02-20 22:39:41 +00001118static int find_index(ArrayRef<Value *> livevec, Value *val) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001119 auto itr = std::find(livevec.begin(), livevec.end(), val);
1120 assert(livevec.end() != itr);
1121 size_t index = std::distance(livevec.begin(), itr);
1122 assert(index < livevec.size());
1123 return index;
1124}
1125
1126// Create new attribute set containing only attributes which can be transfered
1127// from original call to the safepoint.
1128static AttributeSet legalizeCallAttributes(AttributeSet AS) {
1129 AttributeSet ret;
1130
1131 for (unsigned Slot = 0; Slot < AS.getNumSlots(); Slot++) {
1132 unsigned index = AS.getSlotIndex(Slot);
1133
1134 if (index == AttributeSet::ReturnIndex ||
1135 index == AttributeSet::FunctionIndex) {
1136
1137 for (auto it = AS.begin(Slot), it_end = AS.end(Slot); it != it_end;
1138 ++it) {
1139 Attribute attr = *it;
1140
1141 // Do not allow certain attributes - just skip them
1142 // Safepoint can not be read only or read none.
1143 if (attr.hasAttribute(Attribute::ReadNone) ||
1144 attr.hasAttribute(Attribute::ReadOnly))
1145 continue;
1146
1147 ret = ret.addAttributes(
1148 AS.getContext(), index,
1149 AttributeSet::get(AS.getContext(), index, AttrBuilder(attr)));
1150 }
1151 }
1152
1153 // Just skip parameter attributes for now
1154 }
1155
1156 return ret;
1157}
1158
1159/// Helper function to place all gc relocates necessary for the given
1160/// statepoint.
1161/// Inputs:
1162/// liveVariables - list of variables to be relocated.
1163/// liveStart - index of the first live variable.
1164/// basePtrs - base pointers.
1165/// statepointToken - statepoint instruction to which relocates should be
1166/// bound.
1167/// Builder - Llvm IR builder to be used to construct new calls.
Philip Reamesd2b66462015-02-20 22:39:41 +00001168void CreateGCRelocates(ArrayRef<llvm::Value *> liveVariables,
1169 const int liveStart,
1170 ArrayRef<llvm::Value *> basePtrs,
1171 Instruction *statepointToken, IRBuilder<> Builder) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001172
Philip Reamesd2b66462015-02-20 22:39:41 +00001173 SmallVector<Instruction *, 64> NewDefs;
1174 NewDefs.reserve(liveVariables.size());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001175
1176 Module *M = statepointToken->getParent()->getParent()->getParent();
1177
1178 for (unsigned i = 0; i < liveVariables.size(); i++) {
1179 // We generate a (potentially) unique declaration for every pointer type
1180 // combination. This results is some blow up the function declarations in
1181 // the IR, but removes the need for argument bitcasts which shrinks the IR
1182 // greatly and makes it much more readable.
Philip Reamesd2b66462015-02-20 22:39:41 +00001183 SmallVector<Type *, 1> types; // one per 'any' type
Philip Reamesd16a9b12015-02-20 01:06:44 +00001184 types.push_back(liveVariables[i]->getType()); // result type
1185 Value *gc_relocate_decl = Intrinsic::getDeclaration(
1186 M, Intrinsic::experimental_gc_relocate, types);
1187
1188 // Generate the gc.relocate call and save the result
1189 Value *baseIdx =
1190 ConstantInt::get(Type::getInt32Ty(M->getContext()),
1191 liveStart + find_index(liveVariables, basePtrs[i]));
1192 Value *liveIdx = ConstantInt::get(
1193 Type::getInt32Ty(M->getContext()),
1194 liveStart + find_index(liveVariables, liveVariables[i]));
1195
1196 // only specify a debug name if we can give a useful one
1197 Value *reloc = Builder.CreateCall3(
1198 gc_relocate_decl, statepointToken, baseIdx, liveIdx,
1199 liveVariables[i]->hasName() ? liveVariables[i]->getName() + ".relocated"
1200 : "");
1201 // Trick CodeGen into thinking there are lots of free registers at this
1202 // fake call.
1203 cast<CallInst>(reloc)->setCallingConv(CallingConv::Cold);
1204
Philip Reamesd2b66462015-02-20 22:39:41 +00001205 NewDefs.push_back(cast<Instruction>(reloc));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001206 }
Philip Reamesd2b66462015-02-20 22:39:41 +00001207 assert(NewDefs.size() == liveVariables.size() &&
Philip Reamesd16a9b12015-02-20 01:06:44 +00001208 "missing or extra redefinition at safepoint");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001209}
1210
1211static void
1212makeStatepointExplicitImpl(const CallSite &CS, /* to replace */
1213 const SmallVectorImpl<llvm::Value *> &basePtrs,
1214 const SmallVectorImpl<llvm::Value *> &liveVariables,
1215 Pass *P,
1216 PartiallyConstructedSafepointRecord &result) {
1217 assert(basePtrs.size() == liveVariables.size());
1218 assert(isStatepoint(CS) &&
1219 "This method expects to be rewriting a statepoint");
1220
1221 BasicBlock *BB = CS.getInstruction()->getParent();
1222 assert(BB);
1223 Function *F = BB->getParent();
1224 assert(F && "must be set");
1225 Module *M = F->getParent();
Nick Lewyckyeb3231e2015-02-20 07:14:02 +00001226 (void)M;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001227 assert(M && "must be set");
1228
1229 // We're not changing the function signature of the statepoint since the gc
1230 // arguments go into the var args section.
1231 Function *gc_statepoint_decl = CS.getCalledFunction();
1232
1233 // Then go ahead and use the builder do actually do the inserts. We insert
1234 // immediately before the previous instruction under the assumption that all
1235 // arguments will be available here. We can't insert afterwards since we may
1236 // be replacing a terminator.
1237 Instruction *insertBefore = CS.getInstruction();
1238 IRBuilder<> Builder(insertBefore);
1239 // Copy all of the arguments from the original statepoint - this includes the
1240 // target, call args, and deopt args
Philip Reamesd2b66462015-02-20 22:39:41 +00001241 SmallVector<llvm::Value *, 64> args;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001242 args.insert(args.end(), CS.arg_begin(), CS.arg_end());
1243 // TODO: Clear the 'needs rewrite' flag
1244
1245 // add all the pointers to be relocated (gc arguments)
1246 // Capture the start of the live variable list for use in the gc_relocates
1247 const int live_start = args.size();
1248 args.insert(args.end(), liveVariables.begin(), liveVariables.end());
1249
1250 // Create the statepoint given all the arguments
1251 Instruction *token = nullptr;
1252 AttributeSet return_attributes;
1253 if (CS.isCall()) {
1254 CallInst *toReplace = cast<CallInst>(CS.getInstruction());
1255 CallInst *call =
1256 Builder.CreateCall(gc_statepoint_decl, args, "safepoint_token");
1257 call->setTailCall(toReplace->isTailCall());
1258 call->setCallingConv(toReplace->getCallingConv());
1259
1260 // Currently we will fail on parameter attributes and on certain
1261 // function attributes.
1262 AttributeSet new_attrs = legalizeCallAttributes(toReplace->getAttributes());
1263 // In case if we can handle this set of sttributes - set up function attrs
1264 // directly on statepoint and return attrs later for gc_result intrinsic.
1265 call->setAttributes(new_attrs.getFnAttributes());
1266 return_attributes = new_attrs.getRetAttributes();
1267
1268 token = call;
1269
1270 // Put the following gc_result and gc_relocate calls immediately after the
1271 // the old call (which we're about to delete)
1272 BasicBlock::iterator next(toReplace);
1273 assert(BB->end() != next && "not a terminator, must have next");
1274 next++;
1275 Instruction *IP = &*(next);
1276 Builder.SetInsertPoint(IP);
1277 Builder.SetCurrentDebugLocation(IP->getDebugLoc());
1278
David Blaikie82ad7872015-02-20 23:44:24 +00001279 } else {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001280 InvokeInst *toReplace = cast<InvokeInst>(CS.getInstruction());
1281
1282 // Insert the new invoke into the old block. We'll remove the old one in a
1283 // moment at which point this will become the new terminator for the
1284 // original block.
1285 InvokeInst *invoke = InvokeInst::Create(
1286 gc_statepoint_decl, toReplace->getNormalDest(),
1287 toReplace->getUnwindDest(), args, "", toReplace->getParent());
1288 invoke->setCallingConv(toReplace->getCallingConv());
1289
1290 // Currently we will fail on parameter attributes and on certain
1291 // function attributes.
1292 AttributeSet new_attrs = legalizeCallAttributes(toReplace->getAttributes());
1293 // In case if we can handle this set of sttributes - set up function attrs
1294 // directly on statepoint and return attrs later for gc_result intrinsic.
1295 invoke->setAttributes(new_attrs.getFnAttributes());
1296 return_attributes = new_attrs.getRetAttributes();
1297
1298 token = invoke;
1299
1300 // Generate gc relocates in exceptional path
1301 BasicBlock *unwindBlock = normalizeBBForInvokeSafepoint(
1302 toReplace->getUnwindDest(), invoke->getParent(), P);
1303
1304 Instruction *IP = &*(unwindBlock->getFirstInsertionPt());
1305 Builder.SetInsertPoint(IP);
1306 Builder.SetCurrentDebugLocation(toReplace->getDebugLoc());
1307
1308 // Extract second element from landingpad return value. We will attach
1309 // exceptional gc relocates to it.
1310 const unsigned idx = 1;
1311 Instruction *exceptional_token =
1312 cast<Instruction>(Builder.CreateExtractValue(
1313 unwindBlock->getLandingPadInst(), idx, "relocate_token"));
Philip Reamesf2041322015-02-20 19:26:04 +00001314 result.UnwindToken = exceptional_token;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001315
1316 // Just throw away return value. We will use the one we got for normal
1317 // block.
1318 (void)CreateGCRelocates(liveVariables, live_start, basePtrs,
1319 exceptional_token, Builder);
1320
1321 // Generate gc relocates and returns for normal block
1322 BasicBlock *normalDest = normalizeBBForInvokeSafepoint(
1323 toReplace->getNormalDest(), invoke->getParent(), P);
1324
1325 IP = &*(normalDest->getFirstInsertionPt());
1326 Builder.SetInsertPoint(IP);
1327
1328 // gc relocates will be generated later as if it were regular call
1329 // statepoint
Philip Reamesd16a9b12015-02-20 01:06:44 +00001330 }
1331 assert(token);
1332
1333 // Take the name of the original value call if it had one.
1334 token->takeName(CS.getInstruction());
1335
1336 // The GCResult is already inserted, we just need to find it
David Blaikie5e5d7842015-02-22 20:58:38 +00001337#ifndef NDEBUG
1338 Instruction *toReplace = CS.getInstruction();
1339 assert((toReplace->hasNUses(0) || toReplace->hasNUses(1)) &&
1340 "only valid use before rewrite is gc.result");
1341 assert(!toReplace->hasOneUse() ||
1342 isGCResult(cast<Instruction>(*toReplace->user_begin())));
1343#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +00001344
1345 // Update the gc.result of the original statepoint (if any) to use the newly
1346 // inserted statepoint. This is safe to do here since the token can't be
1347 // considered a live reference.
1348 CS.getInstruction()->replaceAllUsesWith(token);
1349
Philip Reames0a3240f2015-02-20 21:34:11 +00001350 result.StatepointToken = token;
1351
Philip Reamesd16a9b12015-02-20 01:06:44 +00001352 // Second, create a gc.relocate for every live variable
Philip Reames0a3240f2015-02-20 21:34:11 +00001353 CreateGCRelocates(liveVariables, live_start, basePtrs, token, Builder);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001354
Philip Reamesd16a9b12015-02-20 01:06:44 +00001355}
1356
1357namespace {
1358struct name_ordering {
1359 Value *base;
1360 Value *derived;
1361 bool operator()(name_ordering const &a, name_ordering const &b) {
1362 return -1 == a.derived->getName().compare(b.derived->getName());
1363 }
1364};
1365}
1366static void stablize_order(SmallVectorImpl<Value *> &basevec,
1367 SmallVectorImpl<Value *> &livevec) {
1368 assert(basevec.size() == livevec.size());
1369
Philip Reames860660e2015-02-20 22:05:18 +00001370 SmallVector<name_ordering, 64> temp;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001371 for (size_t i = 0; i < basevec.size(); i++) {
1372 name_ordering v;
1373 v.base = basevec[i];
1374 v.derived = livevec[i];
1375 temp.push_back(v);
1376 }
1377 std::sort(temp.begin(), temp.end(), name_ordering());
1378 for (size_t i = 0; i < basevec.size(); i++) {
1379 basevec[i] = temp[i].base;
1380 livevec[i] = temp[i].derived;
1381 }
1382}
1383
1384// Replace an existing gc.statepoint with a new one and a set of gc.relocates
1385// which make the relocations happening at this safepoint explicit.
1386//
1387// WARNING: Does not do any fixup to adjust users of the original live
1388// values. That's the callers responsibility.
1389static void
1390makeStatepointExplicit(DominatorTree &DT, const CallSite &CS, Pass *P,
1391 PartiallyConstructedSafepointRecord &result) {
Philip Reamesf2041322015-02-20 19:26:04 +00001392 auto liveset = result.liveset;
1393 auto PointerToBase = result.PointerToBase;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001394
1395 // Convert to vector for efficient cross referencing.
1396 SmallVector<Value *, 64> basevec, livevec;
1397 livevec.reserve(liveset.size());
1398 basevec.reserve(liveset.size());
1399 for (Value *L : liveset) {
1400 livevec.push_back(L);
1401
Philip Reamesf2041322015-02-20 19:26:04 +00001402 assert(PointerToBase.find(L) != PointerToBase.end());
1403 Value *base = PointerToBase[L];
Philip Reamesd16a9b12015-02-20 01:06:44 +00001404 basevec.push_back(base);
1405 }
1406 assert(livevec.size() == basevec.size());
1407
1408 // To make the output IR slightly more stable (for use in diffs), ensure a
1409 // fixed order of the values in the safepoint (by sorting the value name).
1410 // The order is otherwise meaningless.
1411 stablize_order(basevec, livevec);
1412
1413 // Do the actual rewriting and delete the old statepoint
1414 makeStatepointExplicitImpl(CS, basevec, livevec, P, result);
1415 CS.getInstruction()->eraseFromParent();
1416}
1417
1418// Helper function for the relocationViaAlloca.
1419// It receives iterator to the statepoint gc relocates and emits store to the
1420// assigned
1421// location (via allocaMap) for the each one of them.
1422// Add visited values into the visitedLiveValues set we will later use them
1423// for sanity check.
1424static void
1425insertRelocationStores(iterator_range<Value::user_iterator> gcRelocs,
1426 DenseMap<Value *, Value *> &allocaMap,
1427 DenseSet<Value *> &visitedLiveValues) {
1428
1429 for (User *U : gcRelocs) {
1430 if (!isa<IntrinsicInst>(U))
1431 continue;
1432
1433 IntrinsicInst *relocatedValue = cast<IntrinsicInst>(U);
1434
1435 // We only care about relocates
1436 if (relocatedValue->getIntrinsicID() !=
1437 Intrinsic::experimental_gc_relocate) {
1438 continue;
1439 }
1440
1441 GCRelocateOperands relocateOperands(relocatedValue);
1442 Value *originalValue = const_cast<Value *>(relocateOperands.derivedPtr());
1443 assert(allocaMap.count(originalValue));
1444 Value *alloca = allocaMap[originalValue];
1445
1446 // Emit store into the related alloca
1447 StoreInst *store = new StoreInst(relocatedValue, alloca);
1448 store->insertAfter(relocatedValue);
1449
1450#ifndef NDEBUG
1451 visitedLiveValues.insert(originalValue);
1452#endif
1453 }
1454}
1455
1456/// do all the relocation update via allocas and mem2reg
1457static void relocationViaAlloca(
Philip Reamesd2b66462015-02-20 22:39:41 +00001458 Function &F, DominatorTree &DT, ArrayRef<Value *> live,
1459 ArrayRef<struct PartiallyConstructedSafepointRecord> records) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001460#ifndef NDEBUG
1461 int initialAllocaNum = 0;
1462
1463 // record initial number of allocas
1464 for (inst_iterator itr = inst_begin(F), end = inst_end(F); itr != end;
1465 itr++) {
1466 if (isa<AllocaInst>(*itr))
1467 initialAllocaNum++;
1468 }
1469#endif
1470
1471 // TODO-PERF: change data structures, reserve
1472 DenseMap<Value *, Value *> allocaMap;
1473 SmallVector<AllocaInst *, 200> PromotableAllocas;
1474 PromotableAllocas.reserve(live.size());
1475
1476 // emit alloca for each live gc pointer
1477 for (unsigned i = 0; i < live.size(); i++) {
1478 Value *liveValue = live[i];
1479 AllocaInst *alloca = new AllocaInst(liveValue->getType(), "",
1480 F.getEntryBlock().getFirstNonPHI());
1481 allocaMap[liveValue] = alloca;
1482 PromotableAllocas.push_back(alloca);
1483 }
1484
1485 // The next two loops are part of the same conceptual operation. We need to
1486 // insert a store to the alloca after the original def and at each
1487 // redefinition. We need to insert a load before each use. These are split
1488 // into distinct loops for performance reasons.
1489
1490 // update gc pointer after each statepoint
1491 // either store a relocated value or null (if no relocated value found for
1492 // this gc pointer and it is not a gc_result)
1493 // this must happen before we update the statepoint with load of alloca
1494 // otherwise we lose the link between statepoint and old def
1495 for (size_t i = 0; i < records.size(); i++) {
1496 const struct PartiallyConstructedSafepointRecord &info = records[i];
Philip Reames0a3240f2015-02-20 21:34:11 +00001497 Value *Statepoint = info.StatepointToken;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001498
1499 // This will be used for consistency check
1500 DenseSet<Value *> visitedLiveValues;
1501
1502 // Insert stores for normal statepoint gc relocates
Philip Reames0a3240f2015-02-20 21:34:11 +00001503 insertRelocationStores(Statepoint->users(), allocaMap, visitedLiveValues);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001504
1505 // In case if it was invoke statepoint
1506 // we will insert stores for exceptional path gc relocates.
Philip Reames0a3240f2015-02-20 21:34:11 +00001507 if (isa<InvokeInst>(Statepoint)) {
Philip Reamesf2041322015-02-20 19:26:04 +00001508 insertRelocationStores(info.UnwindToken->users(),
Philip Reamesd16a9b12015-02-20 01:06:44 +00001509 allocaMap, visitedLiveValues);
1510 }
1511
1512#ifndef NDEBUG
Philip Reamesf2041322015-02-20 19:26:04 +00001513 // As a debuging aid, pretend that an unrelocated pointer becomes null at
1514 // the gc.statepoint. This will turn some subtle GC problems into slightly
Philip Reamesfa2fcf172015-02-20 19:51:56 +00001515 // easier to debug SEGVs
1516 SmallVector<AllocaInst *, 64> ToClobber;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001517 for (auto Pair : allocaMap) {
Philip Reamesfa2fcf172015-02-20 19:51:56 +00001518 Value *Def = Pair.first;
1519 AllocaInst *Alloca = cast<AllocaInst>(Pair.second);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001520
1521 // This value was relocated
Philip Reamesfa2fcf172015-02-20 19:51:56 +00001522 if (visitedLiveValues.count(Def)) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001523 continue;
1524 }
Philip Reamesfa2fcf172015-02-20 19:51:56 +00001525 ToClobber.push_back(Alloca);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001526 }
Philip Reamesfa2fcf172015-02-20 19:51:56 +00001527
Philip Reamesfa2fcf172015-02-20 19:51:56 +00001528 auto InsertClobbersAt = [&](Instruction *IP) {
1529 for (auto *AI : ToClobber) {
1530 auto AIType = cast<PointerType>(AI->getType());
1531 auto PT = cast<PointerType>(AIType->getElementType());
1532 Constant *CPN = ConstantPointerNull::get(PT);
1533 StoreInst *store = new StoreInst(CPN, AI);
1534 store->insertBefore(IP);
1535 }
1536 };
1537
1538 // Insert the clobbering stores. These may get intermixed with the
1539 // gc.results and gc.relocates, but that's fine.
1540 if (auto II = dyn_cast<InvokeInst>(Statepoint)) {
1541 InsertClobbersAt(II->getNormalDest()->getFirstInsertionPt());
1542 InsertClobbersAt(II->getUnwindDest()->getFirstInsertionPt());
David Blaikie82ad7872015-02-20 23:44:24 +00001543 } else {
1544 BasicBlock::iterator Next(cast<CallInst>(Statepoint));
Philip Reamesfa2fcf172015-02-20 19:51:56 +00001545 Next++;
1546 InsertClobbersAt(Next);
David Blaikie82ad7872015-02-20 23:44:24 +00001547 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00001548#endif
1549 }
1550 // update use with load allocas and add store for gc_relocated
1551 for (auto Pair : allocaMap) {
1552 Value *def = Pair.first;
1553 Value *alloca = Pair.second;
1554
1555 // we pre-record the uses of allocas so that we dont have to worry about
1556 // later update
1557 // that change the user information.
1558 SmallVector<Instruction *, 20> uses;
1559 // PERF: trade a linear scan for repeated reallocation
1560 uses.reserve(std::distance(def->user_begin(), def->user_end()));
1561 for (User *U : def->users()) {
1562 if (!isa<ConstantExpr>(U)) {
1563 // If the def has a ConstantExpr use, then the def is either a
1564 // ConstantExpr use itself or null. In either case
1565 // (recursively in the first, directly in the second), the oop
1566 // it is ultimately dependent on is null and this particular
1567 // use does not need to be fixed up.
1568 uses.push_back(cast<Instruction>(U));
1569 }
1570 }
1571
1572 std::sort(uses.begin(), uses.end());
1573 auto last = std::unique(uses.begin(), uses.end());
1574 uses.erase(last, uses.end());
1575
1576 for (Instruction *use : uses) {
1577 if (isa<PHINode>(use)) {
1578 PHINode *phi = cast<PHINode>(use);
1579 for (unsigned i = 0; i < phi->getNumIncomingValues(); i++) {
1580 if (def == phi->getIncomingValue(i)) {
1581 LoadInst *load = new LoadInst(
1582 alloca, "", phi->getIncomingBlock(i)->getTerminator());
1583 phi->setIncomingValue(i, load);
1584 }
1585 }
1586 } else {
1587 LoadInst *load = new LoadInst(alloca, "", use);
1588 use->replaceUsesOfWith(def, load);
1589 }
1590 }
1591
1592 // emit store for the initial gc value
1593 // store must be inserted after load, otherwise store will be in alloca's
1594 // use list and an extra load will be inserted before it
1595 StoreInst *store = new StoreInst(def, alloca);
Philip Reames6da37852015-03-04 00:13:52 +00001596 if (Instruction *inst = dyn_cast<Instruction>(def)) {
1597 if (InvokeInst *invoke = dyn_cast<InvokeInst>(inst)) {
1598 // InvokeInst is a TerminatorInst so the store need to be inserted
1599 // into its normal destination block.
1600 BasicBlock *normalDest = invoke->getNormalDest();
1601 store->insertBefore(normalDest->getFirstNonPHI());
1602 } else {
1603 assert(!inst->isTerminator() &&
1604 "The only TerminatorInst that can produce a value is "
1605 "InvokeInst which is handled above.");
1606 store->insertAfter(inst);
1607 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00001608 } else {
1609 assert((isa<Argument>(def) || isa<GlobalVariable>(def) ||
1610 (isa<Constant>(def) && cast<Constant>(def)->isNullValue())) &&
1611 "Must be argument or global");
1612 store->insertAfter(cast<Instruction>(alloca));
1613 }
1614 }
1615
1616 assert(PromotableAllocas.size() == live.size() &&
1617 "we must have the same allocas with lives");
1618 if (!PromotableAllocas.empty()) {
1619 // apply mem2reg to promote alloca to SSA
1620 PromoteMemToReg(PromotableAllocas, DT);
1621 }
1622
1623#ifndef NDEBUG
1624 for (inst_iterator itr = inst_begin(F), end = inst_end(F); itr != end;
1625 itr++) {
1626 if (isa<AllocaInst>(*itr))
1627 initialAllocaNum--;
1628 }
1629 assert(initialAllocaNum == 0 && "We must not introduce any extra allocas");
1630#endif
1631}
1632
1633/// Implement a unique function which doesn't require we sort the input
1634/// vector. Doing so has the effect of changing the output of a couple of
1635/// tests in ways which make them less useful in testing fused safepoints.
Philip Reamesd2b66462015-02-20 22:39:41 +00001636template <typename T> static void unique_unsorted(SmallVectorImpl<T> &Vec) {
1637 DenseSet<T> Seen;
1638 SmallVector<T, 128> TempVec;
1639 TempVec.reserve(Vec.size());
1640 for (auto Element : Vec)
1641 TempVec.push_back(Element);
1642 Vec.clear();
1643 for (auto V : TempVec) {
1644 if (Seen.insert(V).second) {
1645 Vec.push_back(V);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001646 }
1647 }
1648}
1649
1650static Function *getUseHolder(Module &M) {
1651 FunctionType *ftype =
1652 FunctionType::get(Type::getVoidTy(M.getContext()), true);
1653 Function *Func = cast<Function>(M.getOrInsertFunction("__tmp_use", ftype));
1654 return Func;
1655}
1656
1657/// Insert holders so that each Value is obviously live through the entire
1658/// liftetime of the call.
1659static void insertUseHolderAfter(CallSite &CS, const ArrayRef<Value *> Values,
Philip Reamesd2b66462015-02-20 22:39:41 +00001660 SmallVectorImpl<CallInst *> &holders) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001661 Module *M = CS.getInstruction()->getParent()->getParent()->getParent();
1662 Function *Func = getUseHolder(*M);
1663 if (CS.isCall()) {
1664 // For call safepoints insert dummy calls right after safepoint
1665 BasicBlock::iterator next(CS.getInstruction());
1666 next++;
1667 CallInst *base_holder = CallInst::Create(Func, Values, "", next);
1668 holders.push_back(base_holder);
1669 } else if (CS.isInvoke()) {
1670 // For invoke safepooints insert dummy calls both in normal and
1671 // exceptional destination blocks
1672 InvokeInst *invoke = cast<InvokeInst>(CS.getInstruction());
1673 CallInst *normal_holder = CallInst::Create(
1674 Func, Values, "", invoke->getNormalDest()->getFirstInsertionPt());
1675 CallInst *unwind_holder = CallInst::Create(
1676 Func, Values, "", invoke->getUnwindDest()->getFirstInsertionPt());
1677 holders.push_back(normal_holder);
1678 holders.push_back(unwind_holder);
Philip Reames860660e2015-02-20 22:05:18 +00001679 } else
1680 llvm_unreachable("unsupported call type");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001681}
1682
1683static void findLiveReferences(
Philip Reamesd2b66462015-02-20 22:39:41 +00001684 Function &F, DominatorTree &DT, Pass *P, ArrayRef<CallSite> toUpdate,
1685 MutableArrayRef<struct PartiallyConstructedSafepointRecord> records) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001686 for (size_t i = 0; i < records.size(); i++) {
1687 struct PartiallyConstructedSafepointRecord &info = records[i];
Philip Reamesd2b66462015-02-20 22:39:41 +00001688 const CallSite &CS = toUpdate[i];
Philip Reamesd16a9b12015-02-20 01:06:44 +00001689 analyzeParsePointLiveness(DT, CS, info);
1690 }
1691}
1692
Philip Reames1f017542015-02-20 23:16:52 +00001693static void addBasesAsLiveValues(StatepointLiveSetTy &liveset,
Philip Reamesf2041322015-02-20 19:26:04 +00001694 DenseMap<Value *, Value *> &PointerToBase) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001695 // Identify any base pointers which are used in this safepoint, but not
1696 // themselves relocated. We need to relocate them so that later inserted
1697 // safepoints can get the properly relocated base register.
1698 DenseSet<Value *> missing;
1699 for (Value *L : liveset) {
Philip Reamesf2041322015-02-20 19:26:04 +00001700 assert(PointerToBase.find(L) != PointerToBase.end());
1701 Value *base = PointerToBase[L];
Philip Reamesd16a9b12015-02-20 01:06:44 +00001702 assert(base);
1703 if (liveset.find(base) == liveset.end()) {
Philip Reamesf2041322015-02-20 19:26:04 +00001704 assert(PointerToBase.find(base) == PointerToBase.end());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001705 // uniqued by set insert
1706 missing.insert(base);
1707 }
1708 }
1709
1710 // Note that we want these at the end of the list, otherwise
1711 // register placement gets screwed up once we lower to STATEPOINT
1712 // instructions. This is an utter hack, but there doesn't seem to be a
1713 // better one.
1714 for (Value *base : missing) {
1715 assert(base);
1716 liveset.insert(base);
Philip Reamesf2041322015-02-20 19:26:04 +00001717 PointerToBase[base] = base;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001718 }
Philip Reamesf2041322015-02-20 19:26:04 +00001719 assert(liveset.size() == PointerToBase.size());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001720}
1721
1722static bool insertParsePoints(Function &F, DominatorTree &DT, Pass *P,
Philip Reamesd2b66462015-02-20 22:39:41 +00001723 SmallVectorImpl<CallSite> &toUpdate) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001724#ifndef NDEBUG
1725 // sanity check the input
1726 std::set<CallSite> uniqued;
1727 uniqued.insert(toUpdate.begin(), toUpdate.end());
1728 assert(uniqued.size() == toUpdate.size() && "no duplicates please!");
1729
1730 for (size_t i = 0; i < toUpdate.size(); i++) {
1731 CallSite &CS = toUpdate[i];
1732 assert(CS.getInstruction()->getParent()->getParent() == &F);
1733 assert(isStatepoint(CS) && "expected to already be a deopt statepoint");
1734 }
1735#endif
1736
1737 // A list of dummy calls added to the IR to keep various values obviously
1738 // live in the IR. We'll remove all of these when done.
Philip Reamesd2b66462015-02-20 22:39:41 +00001739 SmallVector<CallInst *, 64> holders;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001740
1741 // Insert a dummy call with all of the arguments to the vm_state we'll need
1742 // for the actual safepoint insertion. This ensures reference arguments in
1743 // the deopt argument list are considered live through the safepoint (and
1744 // thus makes sure they get relocated.)
1745 for (size_t i = 0; i < toUpdate.size(); i++) {
1746 CallSite &CS = toUpdate[i];
1747 Statepoint StatepointCS(CS);
1748
1749 SmallVector<Value *, 64> DeoptValues;
1750 for (Use &U : StatepointCS.vm_state_args()) {
1751 Value *Arg = cast<Value>(&U);
1752 if (isGCPointerType(Arg->getType()))
1753 DeoptValues.push_back(Arg);
1754 }
1755 insertUseHolderAfter(CS, DeoptValues, holders);
1756 }
1757
Philip Reamesd2b66462015-02-20 22:39:41 +00001758 SmallVector<struct PartiallyConstructedSafepointRecord, 64> records;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001759 records.reserve(toUpdate.size());
1760 for (size_t i = 0; i < toUpdate.size(); i++) {
1761 struct PartiallyConstructedSafepointRecord info;
1762 records.push_back(info);
1763 }
1764 assert(records.size() == toUpdate.size());
1765
1766 // A) Identify all gc pointers which are staticly live at the given call
1767 // site.
1768 findLiveReferences(F, DT, P, toUpdate, records);
1769
1770 // B) Find the base pointers for each live pointer
1771 /* scope for caching */ {
1772 // Cache the 'defining value' relation used in the computation and
1773 // insertion of base phis and selects. This ensures that we don't insert
1774 // large numbers of duplicate base_phis.
1775 DefiningValueMapTy DVCache;
1776
1777 for (size_t i = 0; i < records.size(); i++) {
1778 struct PartiallyConstructedSafepointRecord &info = records[i];
1779 CallSite &CS = toUpdate[i];
1780 findBasePointers(DT, DVCache, CS, info);
1781 }
1782 } // end of cache scope
1783
1784 // The base phi insertion logic (for any safepoint) may have inserted new
1785 // instructions which are now live at some safepoint. The simplest such
1786 // example is:
1787 // loop:
1788 // phi a <-- will be a new base_phi here
1789 // safepoint 1 <-- that needs to be live here
1790 // gep a + 1
1791 // safepoint 2
1792 // br loop
Philip Reames1f017542015-02-20 23:16:52 +00001793 DenseSet<llvm::Value *> allInsertedDefs;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001794 for (size_t i = 0; i < records.size(); i++) {
1795 struct PartiallyConstructedSafepointRecord &info = records[i];
Philip Reamesf2041322015-02-20 19:26:04 +00001796 allInsertedDefs.insert(info.NewInsertedDefs.begin(),
1797 info.NewInsertedDefs.end());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001798 }
1799
1800 // We insert some dummy calls after each safepoint to definitely hold live
1801 // the base pointers which were identified for that safepoint. We'll then
1802 // ask liveness for _every_ base inserted to see what is now live. Then we
1803 // remove the dummy calls.
1804 holders.reserve(holders.size() + records.size());
1805 for (size_t i = 0; i < records.size(); i++) {
1806 struct PartiallyConstructedSafepointRecord &info = records[i];
1807 CallSite &CS = toUpdate[i];
1808
1809 SmallVector<Value *, 128> Bases;
Philip Reamesf2041322015-02-20 19:26:04 +00001810 for (auto Pair : info.PointerToBase) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001811 Bases.push_back(Pair.second);
1812 }
1813 insertUseHolderAfter(CS, Bases, holders);
1814 }
1815
1816 // Add the bases explicitly to the live vector set. This may result in a few
1817 // extra relocations, but the base has to be available whenever a pointer
1818 // derived from it is used. Thus, we need it to be part of the statepoint's
1819 // gc arguments list. TODO: Introduce an explicit notion (in the following
1820 // code) of the GC argument list as seperate from the live Values at a
1821 // given statepoint.
1822 for (size_t i = 0; i < records.size(); i++) {
1823 struct PartiallyConstructedSafepointRecord &info = records[i];
Philip Reamesf2041322015-02-20 19:26:04 +00001824 addBasesAsLiveValues(info.liveset, info.PointerToBase);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001825 }
1826
1827 // If we inserted any new values, we need to adjust our notion of what is
1828 // live at a particular safepoint.
1829 if (!allInsertedDefs.empty()) {
1830 fixupLiveReferences(F, DT, P, allInsertedDefs, toUpdate, records);
1831 }
1832 if (PrintBasePointers) {
1833 for (size_t i = 0; i < records.size(); i++) {
1834 struct PartiallyConstructedSafepointRecord &info = records[i];
1835 errs() << "Base Pairs: (w/Relocation)\n";
Philip Reamesf2041322015-02-20 19:26:04 +00001836 for (auto Pair : info.PointerToBase) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001837 errs() << " derived %" << Pair.first->getName() << " base %"
1838 << Pair.second->getName() << "\n";
1839 }
1840 }
1841 }
1842 for (size_t i = 0; i < holders.size(); i++) {
1843 holders[i]->eraseFromParent();
1844 holders[i] = nullptr;
1845 }
1846 holders.clear();
1847
1848 // Now run through and replace the existing statepoints with new ones with
1849 // the live variables listed. We do not yet update uses of the values being
1850 // relocated. We have references to live variables that need to
1851 // survive to the last iteration of this loop. (By construction, the
1852 // previous statepoint can not be a live variable, thus we can and remove
1853 // the old statepoint calls as we go.)
1854 for (size_t i = 0; i < records.size(); i++) {
1855 struct PartiallyConstructedSafepointRecord &info = records[i];
1856 CallSite &CS = toUpdate[i];
1857 makeStatepointExplicit(DT, CS, P, info);
1858 }
1859 toUpdate.clear(); // prevent accident use of invalid CallSites
1860
1861 // In case if we inserted relocates in a different basic block than the
1862 // original safepoint (this can happen for invokes). We need to be sure that
1863 // original values were not used in any of the phi nodes at the
1864 // beginning of basic block containing them. Because we know that all such
1865 // blocks will have single predecessor we can safely assume that all phi
1866 // nodes have single entry (because of normalizeBBForInvokeSafepoint).
1867 // Just remove them all here.
1868 for (size_t i = 0; i < records.size(); i++) {
Philip Reames0a3240f2015-02-20 21:34:11 +00001869 Instruction *I = records[i].StatepointToken;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001870
1871 if (InvokeInst *invoke = dyn_cast<InvokeInst>(I)) {
1872 FoldSingleEntryPHINodes(invoke->getNormalDest());
1873 assert(!isa<PHINode>(invoke->getNormalDest()->begin()));
1874
1875 FoldSingleEntryPHINodes(invoke->getUnwindDest());
1876 assert(!isa<PHINode>(invoke->getUnwindDest()->begin()));
1877 }
1878 }
1879
1880 // Do all the fixups of the original live variables to their relocated selves
Philip Reamesd2b66462015-02-20 22:39:41 +00001881 SmallVector<Value *, 128> live;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001882 for (size_t i = 0; i < records.size(); i++) {
1883 struct PartiallyConstructedSafepointRecord &info = records[i];
1884 // We can't simply save the live set from the original insertion. One of
1885 // the live values might be the result of a call which needs a safepoint.
1886 // That Value* no longer exists and we need to use the new gc_result.
1887 // Thankfully, the liveset is embedded in the statepoint (and updated), so
1888 // we just grab that.
Philip Reames0a3240f2015-02-20 21:34:11 +00001889 Statepoint statepoint(info.StatepointToken);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001890 live.insert(live.end(), statepoint.gc_args_begin(),
1891 statepoint.gc_args_end());
1892 }
1893 unique_unsorted(live);
1894
Nick Lewyckyeb3231e2015-02-20 07:14:02 +00001895#ifndef NDEBUG
Philip Reamesd16a9b12015-02-20 01:06:44 +00001896 // sanity check
1897 for (auto ptr : live) {
1898 assert(isGCPointerType(ptr->getType()) && "must be a gc pointer type");
1899 }
Nick Lewyckyeb3231e2015-02-20 07:14:02 +00001900#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +00001901
1902 relocationViaAlloca(F, DT, live, records);
1903 return !records.empty();
1904}
1905
1906/// Returns true if this function should be rewritten by this pass. The main
1907/// point of this function is as an extension point for custom logic.
1908static bool shouldRewriteStatepointsIn(Function &F) {
1909 // TODO: This should check the GCStrategy
Philip Reames2ef029c2015-02-20 18:56:14 +00001910 if (F.hasGC()) {
1911 const std::string StatepointExampleName("statepoint-example");
1912 return StatepointExampleName == F.getGC();
1913 } else
1914 return false;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001915}
1916
1917bool RewriteStatepointsForGC::runOnFunction(Function &F) {
1918 // Nothing to do for declarations.
1919 if (F.isDeclaration() || F.empty())
1920 return false;
1921
1922 // Policy choice says not to rewrite - the most common reason is that we're
1923 // compiling code without a GCStrategy.
1924 if (!shouldRewriteStatepointsIn(F))
1925 return false;
1926
1927 // Gather all the statepoints which need rewritten.
Philip Reamesd2b66462015-02-20 22:39:41 +00001928 SmallVector<CallSite, 64> ParsePointNeeded;
1929 for (Instruction &I : inst_range(F)) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001930 // TODO: only the ones with the flag set!
Philip Reamesd2b66462015-02-20 22:39:41 +00001931 if (isStatepoint(I))
1932 ParsePointNeeded.push_back(CallSite(&I));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001933 }
1934
1935 // Return early if no work to do.
1936 if (ParsePointNeeded.empty())
1937 return false;
1938
1939 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1940 return insertParsePoints(F, DT, this, ParsePointNeeded);
1941}