1 //===- RewriteStatepointsForGC.cpp - Make GC relocations explicit ---------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Rewrite an existing set of gc.statepoints such that they make potential
11 // relocations performed by the garbage collector explicit in the IR.
13 //===----------------------------------------------------------------------===//
15 #include "llvm/Pass.h"
16 #include "llvm/Analysis/CFG.h"
17 #include "llvm/Analysis/InstructionSimplify.h"
18 #include "llvm/Analysis/TargetTransformInfo.h"
19 #include "llvm/ADT/SetOperations.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/ADT/DenseSet.h"
22 #include "llvm/ADT/SetVector.h"
23 #include "llvm/ADT/StringRef.h"
24 #include "llvm/ADT/MapVector.h"
25 #include "llvm/IR/BasicBlock.h"
26 #include "llvm/IR/CallSite.h"
27 #include "llvm/IR/Dominators.h"
28 #include "llvm/IR/Function.h"
29 #include "llvm/IR/IRBuilder.h"
30 #include "llvm/IR/InstIterator.h"
31 #include "llvm/IR/Instructions.h"
32 #include "llvm/IR/Intrinsics.h"
33 #include "llvm/IR/IntrinsicInst.h"
34 #include "llvm/IR/Module.h"
35 #include "llvm/IR/MDBuilder.h"
36 #include "llvm/IR/Statepoint.h"
37 #include "llvm/IR/Value.h"
38 #include "llvm/IR/Verifier.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/CommandLine.h"
41 #include "llvm/Transforms/Scalar.h"
42 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
43 #include "llvm/Transforms/Utils/Cloning.h"
44 #include "llvm/Transforms/Utils/Local.h"
45 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
47 #define DEBUG_TYPE "rewrite-statepoints-for-gc"
51 // Print the liveset found at the insert location
52 static cl::opt<bool> PrintLiveSet("spp-print-liveset", cl::Hidden,
54 static cl::opt<bool> PrintLiveSetSize("spp-print-liveset-size", cl::Hidden,
56 // Print out the base pointers for debugging
57 static cl::opt<bool> PrintBasePointers("spp-print-base-pointers", cl::Hidden,
60 // Cost threshold measuring when it is profitable to rematerialize value instead
62 static cl::opt<unsigned>
63 RematerializationThreshold("spp-rematerialization-threshold", cl::Hidden,
67 static bool ClobberNonLive = true;
69 static bool ClobberNonLive = false;
71 static cl::opt<bool, true> ClobberNonLiveOverride("rs4gc-clobber-non-live",
72 cl::location(ClobberNonLive),
76 struct RewriteStatepointsForGC : public ModulePass {
77 static char ID; // Pass identification, replacement for typeid
79 RewriteStatepointsForGC() : ModulePass(ID) {
80 initializeRewriteStatepointsForGCPass(*PassRegistry::getPassRegistry());
82 bool runOnFunction(Function &F);
83 bool runOnModule(Module &M) override {
86 Changed |= runOnFunction(F);
89 // stripDereferenceabilityInfo asserts that shouldRewriteStatepointsIn
90 // returns true for at least one function in the module. Since at least
91 // one function changed, we know that the precondition is satisfied.
92 stripDereferenceabilityInfo(M);
98 void getAnalysisUsage(AnalysisUsage &AU) const override {
99 // We add and rewrite a bunch of instructions, but don't really do much
100 // else. We could in theory preserve a lot more analyses here.
101 AU.addRequired<DominatorTreeWrapperPass>();
102 AU.addRequired<TargetTransformInfoWrapperPass>();
105 /// The IR fed into RewriteStatepointsForGC may have had attributes implying
106 /// dereferenceability that are no longer valid/correct after
107 /// RewriteStatepointsForGC has run. This is because semantically, after
108 /// RewriteStatepointsForGC runs, all calls to gc.statepoint "free" the entire
109 /// heap. stripDereferenceabilityInfo (conservatively) restores correctness
110 /// by erasing all attributes in the module that externally imply
111 /// dereferenceability.
113 void stripDereferenceabilityInfo(Module &M);
115 // Helpers for stripDereferenceabilityInfo
116 void stripDereferenceabilityInfoFromBody(Function &F);
117 void stripDereferenceabilityInfoFromPrototype(Function &F);
121 char RewriteStatepointsForGC::ID = 0;
123 ModulePass *llvm::createRewriteStatepointsForGCPass() {
124 return new RewriteStatepointsForGC();
127 INITIALIZE_PASS_BEGIN(RewriteStatepointsForGC, "rewrite-statepoints-for-gc",
128 "Make relocations explicit at statepoints", false, false)
129 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
130 INITIALIZE_PASS_END(RewriteStatepointsForGC, "rewrite-statepoints-for-gc",
131 "Make relocations explicit at statepoints", false, false)
134 struct GCPtrLivenessData {
135 /// Values defined in this block.
136 DenseMap<BasicBlock *, DenseSet<Value *>> KillSet;
137 /// Values used in this block (and thus live); does not included values
138 /// killed within this block.
139 DenseMap<BasicBlock *, DenseSet<Value *>> LiveSet;
141 /// Values live into this basic block (i.e. used by any
142 /// instruction in this basic block or ones reachable from here)
143 DenseMap<BasicBlock *, DenseSet<Value *>> LiveIn;
145 /// Values live out of this basic block (i.e. live into
146 /// any successor block)
147 DenseMap<BasicBlock *, DenseSet<Value *>> LiveOut;
150 // The type of the internal cache used inside the findBasePointers family
151 // of functions. From the callers perspective, this is an opaque type and
152 // should not be inspected.
154 // In the actual implementation this caches two relations:
155 // - The base relation itself (i.e. this pointer is based on that one)
156 // - The base defining value relation (i.e. before base_phi insertion)
157 // Generally, after the execution of a full findBasePointer call, only the
158 // base relation will remain. Internally, we add a mixture of the two
159 // types, then update all the second type to the first type
160 typedef DenseMap<Value *, Value *> DefiningValueMapTy;
161 typedef DenseSet<llvm::Value *> StatepointLiveSetTy;
162 typedef DenseMap<Instruction *, Value *> RematerializedValueMapTy;
164 struct PartiallyConstructedSafepointRecord {
165 /// The set of values known to be live across this safepoint
166 StatepointLiveSetTy liveset;
168 /// Mapping from live pointers to a base-defining-value
169 DenseMap<llvm::Value *, llvm::Value *> PointerToBase;
171 /// The *new* gc.statepoint instruction itself. This produces the token
172 /// that normal path gc.relocates and the gc.result are tied to.
173 Instruction *StatepointToken;
175 /// Instruction to which exceptional gc relocates are attached
176 /// Makes it easier to iterate through them during relocationViaAlloca.
177 Instruction *UnwindToken;
179 /// Record live values we are rematerialized instead of relocating.
180 /// They are not included into 'liveset' field.
181 /// Maps rematerialized copy to it's original value.
182 RematerializedValueMapTy RematerializedValues;
186 /// Compute the live-in set for every basic block in the function
187 static void computeLiveInValues(DominatorTree &DT, Function &F,
188 GCPtrLivenessData &Data);
190 /// Given results from the dataflow liveness computation, find the set of live
191 /// Values at a particular instruction.
192 static void findLiveSetAtInst(Instruction *inst, GCPtrLivenessData &Data,
193 StatepointLiveSetTy &out);
195 // TODO: Once we can get to the GCStrategy, this becomes
196 // Optional<bool> isGCManagedPointer(const Value *V) const override {
198 static bool isGCPointerType(Type *T) {
199 if (auto *PT = dyn_cast<PointerType>(T))
200 // For the sake of this example GC, we arbitrarily pick addrspace(1) as our
201 // GC managed heap. We know that a pointer into this heap needs to be
202 // updated and that no other pointer does.
203 return (1 == PT->getAddressSpace());
207 // Return true if this type is one which a) is a gc pointer or contains a GC
208 // pointer and b) is of a type this code expects to encounter as a live value.
209 // (The insertion code will assert that a type which matches (a) and not (b)
210 // is not encountered.)
211 static bool isHandledGCPointerType(Type *T) {
212 // We fully support gc pointers
213 if (isGCPointerType(T))
215 // We partially support vectors of gc pointers. The code will assert if it
216 // can't handle something.
217 if (auto VT = dyn_cast<VectorType>(T))
218 if (isGCPointerType(VT->getElementType()))
224 /// Returns true if this type contains a gc pointer whether we know how to
225 /// handle that type or not.
226 static bool containsGCPtrType(Type *Ty) {
227 if (isGCPointerType(Ty))
229 if (VectorType *VT = dyn_cast<VectorType>(Ty))
230 return isGCPointerType(VT->getScalarType());
231 if (ArrayType *AT = dyn_cast<ArrayType>(Ty))
232 return containsGCPtrType(AT->getElementType());
233 if (StructType *ST = dyn_cast<StructType>(Ty))
235 ST->subtypes().begin(), ST->subtypes().end(),
236 [](Type *SubType) { return containsGCPtrType(SubType); });
240 // Returns true if this is a type which a) is a gc pointer or contains a GC
241 // pointer and b) is of a type which the code doesn't expect (i.e. first class
242 // aggregates). Used to trip assertions.
243 static bool isUnhandledGCPointerType(Type *Ty) {
244 return containsGCPtrType(Ty) && !isHandledGCPointerType(Ty);
248 static bool order_by_name(llvm::Value *a, llvm::Value *b) {
249 if (a->hasName() && b->hasName()) {
250 return -1 == a->getName().compare(b->getName());
251 } else if (a->hasName() && !b->hasName()) {
253 } else if (!a->hasName() && b->hasName()) {
256 // Better than nothing, but not stable
261 // Conservatively identifies any definitions which might be live at the
262 // given instruction. The analysis is performed immediately before the
263 // given instruction. Values defined by that instruction are not considered
264 // live. Values used by that instruction are considered live.
265 static void analyzeParsePointLiveness(
266 DominatorTree &DT, GCPtrLivenessData &OriginalLivenessData,
267 const CallSite &CS, PartiallyConstructedSafepointRecord &result) {
268 Instruction *inst = CS.getInstruction();
270 StatepointLiveSetTy liveset;
271 findLiveSetAtInst(inst, OriginalLivenessData, liveset);
274 // Note: This output is used by several of the test cases
275 // The order of elements in a set is not stable, put them in a vec and sort
277 SmallVector<Value *, 64> Temp;
278 Temp.insert(Temp.end(), liveset.begin(), liveset.end());
279 std::sort(Temp.begin(), Temp.end(), order_by_name);
280 errs() << "Live Variables:\n";
281 for (Value *V : Temp)
282 dbgs() << " " << V->getName() << " " << *V << "\n";
284 if (PrintLiveSetSize) {
285 errs() << "Safepoint For: " << CS.getCalledValue()->getName() << "\n";
286 errs() << "Number live values: " << liveset.size() << "\n";
288 result.liveset = liveset;
291 static bool isKnownBaseResult(Value *V);
293 /// A single base defining value - An immediate base defining value for an
294 /// instruction 'Def' is an input to 'Def' whose base is also a base of 'Def'.
295 /// For instructions which have multiple pointer [vector] inputs or that
296 /// transition between vector and scalar types, there is no immediate base
297 /// defining value. The 'base defining value' for 'Def' is the transitive
298 /// closure of this relation stopping at the first instruction which has no
299 /// immediate base defining value. The b.d.v. might itself be a base pointer,
300 /// but it can also be an arbitrary derived pointer.
301 struct BaseDefiningValueResult {
302 /// Contains the value which is the base defining value.
304 /// True if the base defining value is also known to be an actual base
306 const bool IsKnownBase;
307 BaseDefiningValueResult(Value *BDV, bool IsKnownBase)
308 : BDV(BDV), IsKnownBase(IsKnownBase) {
310 // Check consistency between new and old means of checking whether a BDV is
312 bool MustBeBase = isKnownBaseResult(BDV);
313 assert(!MustBeBase || MustBeBase == IsKnownBase);
319 static BaseDefiningValueResult findBaseDefiningValue(Value *I);
321 /// Return a base defining value for the 'Index' element of the given vector
322 /// instruction 'I'. If Index is null, returns a BDV for the entire vector
323 /// 'I'. As an optimization, this method will try to determine when the
324 /// element is known to already be a base pointer. If this can be established,
325 /// the second value in the returned pair will be true. Note that either a
326 /// vector or a pointer typed value can be returned. For the former, the
327 /// vector returned is a BDV (and possibly a base) of the entire vector 'I'.
328 /// If the later, the return pointer is a BDV (or possibly a base) for the
329 /// particular element in 'I'.
330 static BaseDefiningValueResult
331 findBaseDefiningValueOfVector(Value *I, Value *Index = nullptr) {
332 assert(I->getType()->isVectorTy() &&
333 cast<VectorType>(I->getType())->getElementType()->isPointerTy() &&
334 "Illegal to ask for the base pointer of a non-pointer type");
336 // Each case parallels findBaseDefiningValue below, see that code for
337 // detailed motivation.
339 if (isa<Argument>(I))
340 // An incoming argument to the function is a base pointer
341 return BaseDefiningValueResult(I, true);
343 // We shouldn't see the address of a global as a vector value?
344 assert(!isa<GlobalVariable>(I) &&
345 "unexpected global variable found in base of vector");
347 // inlining could possibly introduce phi node that contains
348 // undef if callee has multiple returns
349 if (isa<UndefValue>(I))
350 // utterly meaningless, but useful for dealing with partially optimized
352 return BaseDefiningValueResult(I, true);
354 // Due to inheritance, this must be _after_ the global variable and undef
356 if (Constant *Con = dyn_cast<Constant>(I)) {
357 assert(!isa<GlobalVariable>(I) && !isa<UndefValue>(I) &&
358 "order of checks wrong!");
359 assert(Con->isNullValue() && "null is the only case which makes sense");
360 return BaseDefiningValueResult(Con, true);
363 if (isa<LoadInst>(I))
364 return BaseDefiningValueResult(I, true);
366 // For an insert element, we might be able to look through it if we know
367 // something about the indexes.
368 if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(I)) {
370 Value *InsertIndex = IEI->getOperand(2);
371 // This index is inserting the value, look for its BDV
372 if (InsertIndex == Index)
373 return findBaseDefiningValue(IEI->getOperand(1));
374 // Both constant, and can't be equal per above. This insert is definitely
375 // not relevant, look back at the rest of the vector and keep trying.
376 if (isa<ConstantInt>(Index) && isa<ConstantInt>(InsertIndex))
377 return findBaseDefiningValueOfVector(IEI->getOperand(0), Index);
380 // If both inputs to the insertelement are known bases, then so is the
381 // insertelement itself. NOTE: This should be handled within the generic
382 // base pointer inference code and after http://reviews.llvm.org/D12583,
383 // will be. However, when strengthening asserts I needed to add this to
384 // keep an existing test passing which was 'working'. FIXME
385 if (findBaseDefiningValue(IEI->getOperand(0)).IsKnownBase &&
386 findBaseDefiningValue(IEI->getOperand(1)).IsKnownBase)
387 return BaseDefiningValueResult(IEI, true);
389 // We don't know whether this vector contains entirely base pointers or
390 // not. To be conservatively correct, we treat it as a BDV and will
391 // duplicate code as needed to construct a parallel vector of bases.
392 return BaseDefiningValueResult(IEI, false);
395 if (isa<ShuffleVectorInst>(I))
396 // We don't know whether this vector contains entirely base pointers or
397 // not. To be conservatively correct, we treat it as a BDV and will
398 // duplicate code as needed to construct a parallel vector of bases.
399 // TODO: There a number of local optimizations which could be applied here
400 // for particular sufflevector patterns.
401 return BaseDefiningValueResult(I, false);
403 // A PHI or Select is a base defining value. The outer findBasePointer
404 // algorithm is responsible for constructing a base value for this BDV.
405 assert((isa<SelectInst>(I) || isa<PHINode>(I)) &&
406 "unknown vector instruction - no base found for vector element");
407 return BaseDefiningValueResult(I, false);
410 /// Helper function for findBasePointer - Will return a value which either a)
411 /// defines the base pointer for the input, b) blocks the simple search
412 /// (i.e. a PHI or Select of two derived pointers), or c) involves a change
413 /// from pointer to vector type or back.
414 static BaseDefiningValueResult findBaseDefiningValue(Value *I) {
415 if (I->getType()->isVectorTy())
416 return findBaseDefiningValueOfVector(I);
418 assert(I->getType()->isPointerTy() &&
419 "Illegal to ask for the base pointer of a non-pointer type");
421 if (isa<Argument>(I))
422 // An incoming argument to the function is a base pointer
423 // We should have never reached here if this argument isn't an gc value
424 return BaseDefiningValueResult(I, true);
426 if (isa<GlobalVariable>(I))
428 return BaseDefiningValueResult(I, true);
430 // inlining could possibly introduce phi node that contains
431 // undef if callee has multiple returns
432 if (isa<UndefValue>(I))
433 // utterly meaningless, but useful for dealing with
434 // partially optimized code.
435 return BaseDefiningValueResult(I, true);
437 // Due to inheritance, this must be _after_ the global variable and undef
439 if (isa<Constant>(I)) {
440 assert(!isa<GlobalVariable>(I) && !isa<UndefValue>(I) &&
441 "order of checks wrong!");
442 // Note: Finding a constant base for something marked for relocation
443 // doesn't really make sense. The most likely case is either a) some
444 // screwed up the address space usage or b) your validating against
445 // compiled C++ code w/o the proper separation. The only real exception
446 // is a null pointer. You could have generic code written to index of
447 // off a potentially null value and have proven it null. We also use
448 // null pointers in dead paths of relocation phis (which we might later
449 // want to find a base pointer for).
450 assert(isa<ConstantPointerNull>(I) &&
451 "null is the only case which makes sense");
452 return BaseDefiningValueResult(I, true);
455 if (CastInst *CI = dyn_cast<CastInst>(I)) {
456 Value *Def = CI->stripPointerCasts();
457 // If we find a cast instruction here, it means we've found a cast which is
458 // not simply a pointer cast (i.e. an inttoptr). We don't know how to
459 // handle int->ptr conversion.
460 assert(!isa<CastInst>(Def) && "shouldn't find another cast here");
461 return findBaseDefiningValue(Def);
464 if (isa<LoadInst>(I))
465 // The value loaded is an gc base itself
466 return BaseDefiningValueResult(I, true);
469 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I))
470 // The base of this GEP is the base
471 return findBaseDefiningValue(GEP->getPointerOperand());
473 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
474 switch (II->getIntrinsicID()) {
475 case Intrinsic::experimental_gc_result_ptr:
477 // fall through to general call handling
479 case Intrinsic::experimental_gc_statepoint:
480 case Intrinsic::experimental_gc_result_float:
481 case Intrinsic::experimental_gc_result_int:
482 llvm_unreachable("these don't produce pointers");
483 case Intrinsic::experimental_gc_relocate: {
484 // Rerunning safepoint insertion after safepoints are already
485 // inserted is not supported. It could probably be made to work,
486 // but why are you doing this? There's no good reason.
487 llvm_unreachable("repeat safepoint insertion is not supported");
489 case Intrinsic::gcroot:
490 // Currently, this mechanism hasn't been extended to work with gcroot.
491 // There's no reason it couldn't be, but I haven't thought about the
492 // implications much.
494 "interaction with the gcroot mechanism is not supported");
497 // We assume that functions in the source language only return base
498 // pointers. This should probably be generalized via attributes to support
499 // both source language and internal functions.
500 if (isa<CallInst>(I) || isa<InvokeInst>(I))
501 return BaseDefiningValueResult(I, true);
503 // I have absolutely no idea how to implement this part yet. It's not
504 // necessarily hard, I just haven't really looked at it yet.
505 assert(!isa<LandingPadInst>(I) && "Landing Pad is unimplemented");
507 if (isa<AtomicCmpXchgInst>(I))
508 // A CAS is effectively a atomic store and load combined under a
509 // predicate. From the perspective of base pointers, we just treat it
511 return BaseDefiningValueResult(I, true);
513 assert(!isa<AtomicRMWInst>(I) && "Xchg handled above, all others are "
514 "binary ops which don't apply to pointers");
516 // The aggregate ops. Aggregates can either be in the heap or on the
517 // stack, but in either case, this is simply a field load. As a result,
518 // this is a defining definition of the base just like a load is.
519 if (isa<ExtractValueInst>(I))
520 return BaseDefiningValueResult(I, true);
522 // We should never see an insert vector since that would require we be
523 // tracing back a struct value not a pointer value.
524 assert(!isa<InsertValueInst>(I) &&
525 "Base pointer for a struct is meaningless");
527 // An extractelement produces a base result exactly when it's input does.
528 // We may need to insert a parallel instruction to extract the appropriate
529 // element out of the base vector corresponding to the input. Given this,
530 // it's analogous to the phi and select case even though it's not a merge.
531 if (auto *EEI = dyn_cast<ExtractElementInst>(I)) {
532 Value *VectorOperand = EEI->getVectorOperand();
533 Value *Index = EEI->getIndexOperand();
534 auto VecResult = findBaseDefiningValueOfVector(VectorOperand, Index);
535 Value *VectorBase = VecResult.BDV;
536 if (VectorBase->getType()->isPointerTy())
537 // We found a BDV for this specific element with the vector. This is an
538 // optimization, but in practice it covers most of the useful cases
539 // created via scalarization. Note: The peephole optimization here is
540 // currently needed for correctness since the general algorithm doesn't
541 // yet handle insertelements. That will change shortly.
542 return BaseDefiningValueResult(VectorBase, VecResult.IsKnownBase);
544 assert(VectorBase->getType()->isVectorTy());
545 // Otherwise, we have an instruction which potentially produces a
546 // derived pointer and we need findBasePointers to clone code for us
547 // such that we can create an instruction which produces the
548 // accompanying base pointer.
549 return BaseDefiningValueResult(I, VecResult.IsKnownBase);
553 // The last two cases here don't return a base pointer. Instead, they
554 // return a value which dynamically selects from among several base
555 // derived pointers (each with it's own base potentially). It's the job of
556 // the caller to resolve these.
557 assert((isa<SelectInst>(I) || isa<PHINode>(I)) &&
558 "missing instruction case in findBaseDefiningValing");
559 return BaseDefiningValueResult(I, false);
562 /// Returns the base defining value for this value.
563 static Value *findBaseDefiningValueCached(Value *I, DefiningValueMapTy &Cache) {
564 Value *&Cached = Cache[I];
566 Cached = findBaseDefiningValue(I).BDV;
567 DEBUG(dbgs() << "fBDV-cached: " << I->getName() << " -> "
568 << Cached->getName() << "\n");
570 assert(Cache[I] != nullptr);
574 /// Return a base pointer for this value if known. Otherwise, return it's
575 /// base defining value.
576 static Value *findBaseOrBDV(Value *I, DefiningValueMapTy &Cache) {
577 Value *Def = findBaseDefiningValueCached(I, Cache);
578 auto Found = Cache.find(Def);
579 if (Found != Cache.end()) {
580 // Either a base-of relation, or a self reference. Caller must check.
581 return Found->second;
583 // Only a BDV available
587 /// Given the result of a call to findBaseDefiningValue, or findBaseOrBDV,
588 /// is it known to be a base pointer? Or do we need to continue searching.
589 static bool isKnownBaseResult(Value *V) {
590 if (!isa<PHINode>(V) && !isa<SelectInst>(V) && !isa<ExtractElementInst>(V)) {
591 // no recursion possible
594 if (isa<Instruction>(V) &&
595 cast<Instruction>(V)->getMetadata("is_base_value")) {
596 // This is a previously inserted base phi or select. We know
597 // that this is a base value.
601 // We need to keep searching
606 /// Models the state of a single base defining value in the findBasePointer
607 /// algorithm for determining where a new instruction is needed to propagate
608 /// the base of this BDV.
611 enum Status { Unknown, Base, Conflict };
613 BDVState(Status s, Value *b = nullptr) : status(s), base(b) {
614 assert(status != Base || b);
616 explicit BDVState(Value *b) : status(Base), base(b) {}
617 BDVState() : status(Unknown), base(nullptr) {}
619 Status getStatus() const { return status; }
620 Value *getBase() const { return base; }
622 bool isBase() const { return getStatus() == Base; }
623 bool isUnknown() const { return getStatus() == Unknown; }
624 bool isConflict() const { return getStatus() == Conflict; }
626 bool operator==(const BDVState &other) const {
627 return base == other.base && status == other.status;
630 bool operator!=(const BDVState &other) const { return !(*this == other); }
633 void dump() const { print(dbgs()); dbgs() << '\n'; }
635 void print(raw_ostream &OS) const {
647 OS << " (" << base << " - "
648 << (base ? base->getName() : "nullptr") << "): ";
653 Value *base; // non null only if status == base
658 static raw_ostream &operator<<(raw_ostream &OS, const BDVState &State) {
665 // Values of type BDVState form a lattice, and this is a helper
666 // class that implementes the meet operation. The meat of the meet
667 // operation is implemented in MeetBDVStates::pureMeet
668 class MeetBDVStates {
670 /// Initializes the currentResult to the TOP state so that if can be met with
671 /// any other state to produce that state.
674 // Destructively meet the current result with the given BDVState
675 void meetWith(BDVState otherState) {
676 currentResult = meet(otherState, currentResult);
679 BDVState getResult() const { return currentResult; }
682 BDVState currentResult;
684 /// Perform a meet operation on two elements of the BDVState lattice.
685 static BDVState meet(BDVState LHS, BDVState RHS) {
686 assert((pureMeet(LHS, RHS) == pureMeet(RHS, LHS)) &&
687 "math is wrong: meet does not commute!");
688 BDVState Result = pureMeet(LHS, RHS);
689 DEBUG(dbgs() << "meet of " << LHS << " with " << RHS
690 << " produced " << Result << "\n");
694 static BDVState pureMeet(const BDVState &stateA, const BDVState &stateB) {
695 switch (stateA.getStatus()) {
696 case BDVState::Unknown:
700 assert(stateA.getBase() && "can't be null");
701 if (stateB.isUnknown())
704 if (stateB.isBase()) {
705 if (stateA.getBase() == stateB.getBase()) {
706 assert(stateA == stateB && "equality broken!");
709 return BDVState(BDVState::Conflict);
711 assert(stateB.isConflict() && "only three states!");
712 return BDVState(BDVState::Conflict);
714 case BDVState::Conflict:
717 llvm_unreachable("only three states!");
723 /// For a given value or instruction, figure out what base ptr it's derived
724 /// from. For gc objects, this is simply itself. On success, returns a value
725 /// which is the base pointer. (This is reliable and can be used for
726 /// relocation.) On failure, returns nullptr.
727 static Value *findBasePointer(Value *I, DefiningValueMapTy &cache) {
728 Value *def = findBaseOrBDV(I, cache);
730 if (isKnownBaseResult(def)) {
734 // Here's the rough algorithm:
735 // - For every SSA value, construct a mapping to either an actual base
736 // pointer or a PHI which obscures the base pointer.
737 // - Construct a mapping from PHI to unknown TOP state. Use an
738 // optimistic algorithm to propagate base pointer information. Lattice
743 // When algorithm terminates, all PHIs will either have a single concrete
744 // base or be in a conflict state.
745 // - For every conflict, insert a dummy PHI node without arguments. Add
746 // these to the base[Instruction] = BasePtr mapping. For every
747 // non-conflict, add the actual base.
748 // - For every conflict, add arguments for the base[a] of each input
751 // Note: A simpler form of this would be to add the conflict form of all
752 // PHIs without running the optimistic algorithm. This would be
753 // analogous to pessimistic data flow and would likely lead to an
754 // overall worse solution.
757 auto isExpectedBDVType = [](Value *BDV) {
758 return isa<PHINode>(BDV) || isa<SelectInst>(BDV) || isa<ExtractElementInst>(BDV);
762 // Once populated, will contain a mapping from each potentially non-base BDV
763 // to a lattice value (described above) which corresponds to that BDV.
764 // We use the order of insertion (DFS over the def/use graph) to provide a
765 // stable deterministic ordering for visiting DenseMaps (which are unordered)
766 // below. This is important for deterministic compilation.
767 MapVector<Value *, BDVState> states;
769 // Recursively fill in all base defining values reachable from the initial
770 // one for which we don't already know a definite base value for
772 SmallVector<Value*, 16> Worklist;
773 Worklist.push_back(def);
774 states.insert(std::make_pair(def, BDVState()));
775 while (!Worklist.empty()) {
776 Value *Current = Worklist.pop_back_val();
777 assert(!isKnownBaseResult(Current) && "why did it get added?");
779 auto visitIncomingValue = [&](Value *InVal) {
780 Value *Base = findBaseOrBDV(InVal, cache);
781 if (isKnownBaseResult(Base))
782 // Known bases won't need new instructions introduced and can be
785 assert(isExpectedBDVType(Base) && "the only non-base values "
786 "we see should be base defining values");
787 if (states.insert(std::make_pair(Base, BDVState())).second)
788 Worklist.push_back(Base);
790 if (PHINode *Phi = dyn_cast<PHINode>(Current)) {
791 for (Value *InVal : Phi->incoming_values())
792 visitIncomingValue(InVal);
793 } else if (SelectInst *Sel = dyn_cast<SelectInst>(Current)) {
794 visitIncomingValue(Sel->getTrueValue());
795 visitIncomingValue(Sel->getFalseValue());
796 } else if (auto *EE = dyn_cast<ExtractElementInst>(Current)) {
797 visitIncomingValue(EE->getVectorOperand());
799 // There are two classes of instructions we know we don't handle.
800 assert(isa<ShuffleVectorInst>(Current) ||
801 isa<InsertElementInst>(Current));
802 llvm_unreachable("unimplemented instruction case");
808 DEBUG(dbgs() << "States after initialization:\n");
809 for (auto Pair : states) {
810 DEBUG(dbgs() << " " << Pair.second << " for " << *Pair.first << "\n");
814 // Return a phi state for a base defining value. We'll generate a new
815 // base state for known bases and expect to find a cached state otherwise.
816 auto getStateForBDV = [&](Value *baseValue) {
817 if (isKnownBaseResult(baseValue))
818 return BDVState(baseValue);
819 auto I = states.find(baseValue);
820 assert(I != states.end() && "lookup failed!");
824 bool progress = true;
827 size_t oldSize = states.size();
830 // We're only changing values in this loop, thus safe to keep iterators.
831 // Since this is computing a fixed point, the order of visit does not
832 // effect the result. TODO: We could use a worklist here and make this run
834 for (auto Pair : states) {
835 Value *v = Pair.first;
836 assert(!isKnownBaseResult(v) && "why did it get added?");
838 // Given an input value for the current instruction, return a BDVState
839 // instance which represents the BDV of that value.
840 auto getStateForInput = [&](Value *V) mutable {
841 Value *BDV = findBaseOrBDV(V, cache);
842 return getStateForBDV(BDV);
845 MeetBDVStates calculateMeet;
846 if (SelectInst *select = dyn_cast<SelectInst>(v)) {
847 calculateMeet.meetWith(getStateForInput(select->getTrueValue()));
848 calculateMeet.meetWith(getStateForInput(select->getFalseValue()));
849 } else if (PHINode *Phi = dyn_cast<PHINode>(v)) {
850 for (Value *Val : Phi->incoming_values())
851 calculateMeet.meetWith(getStateForInput(Val));
853 // The 'meet' for an extractelement is slightly trivial, but it's still
854 // useful in that it drives us to conflict if our input is.
855 auto *EE = cast<ExtractElementInst>(v);
856 calculateMeet.meetWith(getStateForInput(EE->getVectorOperand()));
859 BDVState oldState = states[v];
860 BDVState newState = calculateMeet.getResult();
861 if (oldState != newState) {
863 states[v] = newState;
867 assert(oldSize <= states.size());
868 assert(oldSize == states.size() || progress);
872 DEBUG(dbgs() << "States after meet iteration:\n");
873 for (auto Pair : states) {
874 DEBUG(dbgs() << " " << Pair.second << " for " << *Pair.first << "\n");
878 // Insert Phis for all conflicts
879 // TODO: adjust naming patterns to avoid this order of iteration dependency
880 for (auto Pair : states) {
881 Instruction *I = cast<Instruction>(Pair.first);
882 BDVState State = Pair.second;
883 assert(!isKnownBaseResult(I) && "why did it get added?");
884 assert(!State.isUnknown() && "Optimistic algorithm didn't complete!");
886 // extractelement instructions are a bit special in that we may need to
887 // insert an extract even when we know an exact base for the instruction.
888 // The problem is that we need to convert from a vector base to a scalar
889 // base for the particular indice we're interested in.
890 if (State.isBase() && isa<ExtractElementInst>(I) &&
891 isa<VectorType>(State.getBase()->getType())) {
892 auto *EE = cast<ExtractElementInst>(I);
893 // TODO: In many cases, the new instruction is just EE itself. We should
894 // exploit this, but can't do it here since it would break the invariant
895 // about the BDV not being known to be a base.
896 auto *BaseInst = ExtractElementInst::Create(State.getBase(),
897 EE->getIndexOperand(),
899 BaseInst->setMetadata("is_base_value", MDNode::get(I->getContext(), {}));
900 states[I] = BDVState(BDVState::Base, BaseInst);
903 if (!State.isConflict())
906 /// Create and insert a new instruction which will represent the base of
907 /// the given instruction 'I'.
908 auto MakeBaseInstPlaceholder = [](Instruction *I) -> Instruction* {
909 if (isa<PHINode>(I)) {
910 BasicBlock *BB = I->getParent();
911 int NumPreds = std::distance(pred_begin(BB), pred_end(BB));
912 assert(NumPreds > 0 && "how did we reach here");
913 std::string Name = I->hasName() ?
914 (I->getName() + ".base").str() : "base_phi";
915 return PHINode::Create(I->getType(), NumPreds, Name, I);
916 } else if (SelectInst *Sel = dyn_cast<SelectInst>(I)) {
917 // The undef will be replaced later
918 UndefValue *Undef = UndefValue::get(Sel->getType());
919 std::string Name = I->hasName() ?
920 (I->getName() + ".base").str() : "base_select";
921 return SelectInst::Create(Sel->getCondition(), Undef,
924 auto *EE = cast<ExtractElementInst>(I);
925 UndefValue *Undef = UndefValue::get(EE->getVectorOperand()->getType());
926 std::string Name = I->hasName() ?
927 (I->getName() + ".base").str() : "base_ee";
928 return ExtractElementInst::Create(Undef, EE->getIndexOperand(), Name,
932 Instruction *BaseInst = MakeBaseInstPlaceholder(I);
933 // Add metadata marking this as a base value
934 BaseInst->setMetadata("is_base_value", MDNode::get(I->getContext(), {}));
935 states[I] = BDVState(BDVState::Conflict, BaseInst);
938 // Returns a instruction which produces the base pointer for a given
939 // instruction. The instruction is assumed to be an input to one of the BDVs
940 // seen in the inference algorithm above. As such, we must either already
941 // know it's base defining value is a base, or have inserted a new
942 // instruction to propagate the base of it's BDV and have entered that newly
943 // introduced instruction into the state table. In either case, we are
944 // assured to be able to determine an instruction which produces it's base
946 auto getBaseForInput = [&](Value *Input, Instruction *InsertPt) {
947 Value *BDV = findBaseOrBDV(Input, cache);
948 Value *Base = nullptr;
949 if (isKnownBaseResult(BDV)) {
952 // Either conflict or base.
953 assert(states.count(BDV));
954 Base = states[BDV].getBase();
956 assert(Base && "can't be null");
957 // The cast is needed since base traversal may strip away bitcasts
958 if (Base->getType() != Input->getType() &&
960 Base = new BitCastInst(Base, Input->getType(), "cast",
966 // Fixup all the inputs of the new PHIs. Visit order needs to be
967 // deterministic and predictable because we're naming newly created
969 for (auto Pair : states) {
970 Instruction *v = cast<Instruction>(Pair.first);
971 BDVState state = Pair.second;
973 assert(!isKnownBaseResult(v) && "why did it get added?");
974 assert(!state.isUnknown() && "Optimistic algorithm didn't complete!");
975 if (!state.isConflict())
978 if (PHINode *basephi = dyn_cast<PHINode>(state.getBase())) {
979 PHINode *phi = cast<PHINode>(v);
980 unsigned NumPHIValues = phi->getNumIncomingValues();
981 for (unsigned i = 0; i < NumPHIValues; i++) {
982 Value *InVal = phi->getIncomingValue(i);
983 BasicBlock *InBB = phi->getIncomingBlock(i);
985 // If we've already seen InBB, add the same incoming value
986 // we added for it earlier. The IR verifier requires phi
987 // nodes with multiple entries from the same basic block
988 // to have the same incoming value for each of those
989 // entries. If we don't do this check here and basephi
990 // has a different type than base, we'll end up adding two
991 // bitcasts (and hence two distinct values) as incoming
992 // values for the same basic block.
994 int blockIndex = basephi->getBasicBlockIndex(InBB);
995 if (blockIndex != -1) {
996 Value *oldBase = basephi->getIncomingValue(blockIndex);
997 basephi->addIncoming(oldBase, InBB);
1000 Value *Base = getBaseForInput(InVal, nullptr);
1001 // In essence this assert states: the only way two
1002 // values incoming from the same basic block may be
1003 // different is by being different bitcasts of the same
1004 // value. A cleanup that remains TODO is changing
1005 // findBaseOrBDV to return an llvm::Value of the correct
1006 // type (and still remain pure). This will remove the
1007 // need to add bitcasts.
1008 assert(Base->stripPointerCasts() == oldBase->stripPointerCasts() &&
1009 "sanity -- findBaseOrBDV should be pure!");
1014 // Find the instruction which produces the base for each input. We may
1015 // need to insert a bitcast in the incoming block.
1016 // TODO: Need to split critical edges if insertion is needed
1017 Value *Base = getBaseForInput(InVal, InBB->getTerminator());
1018 basephi->addIncoming(Base, InBB);
1020 assert(basephi->getNumIncomingValues() == NumPHIValues);
1021 } else if (SelectInst *BaseSel = dyn_cast<SelectInst>(state.getBase())) {
1022 SelectInst *Sel = cast<SelectInst>(v);
1023 // Operand 1 & 2 are true, false path respectively. TODO: refactor to
1024 // something more safe and less hacky.
1025 for (int i = 1; i <= 2; i++) {
1026 Value *InVal = Sel->getOperand(i);
1027 // Find the instruction which produces the base for each input. We may
1028 // need to insert a bitcast.
1029 Value *Base = getBaseForInput(InVal, BaseSel);
1030 BaseSel->setOperand(i, Base);
1033 auto *BaseEE = cast<ExtractElementInst>(state.getBase());
1034 Value *InVal = cast<ExtractElementInst>(v)->getVectorOperand();
1035 // Find the instruction which produces the base for each input. We may
1036 // need to insert a bitcast.
1037 Value *Base = getBaseForInput(InVal, BaseEE);
1038 BaseEE->setOperand(0, Base);
1042 // Now that we're done with the algorithm, see if we can optimize the
1043 // results slightly by reducing the number of new instructions needed.
1044 // Arguably, this should be integrated into the algorithm above, but
1045 // doing as a post process step is easier to reason about for the moment.
1046 DenseMap<Value *, Value *> ReverseMap;
1047 SmallPtrSet<Instruction *, 16> NewInsts;
1048 SmallSetVector<AssertingVH<Instruction>, 16> Worklist;
1049 // Note: We need to visit the states in a deterministic order. We uses the
1050 // Keys we sorted above for this purpose. Note that we are papering over a
1051 // bigger problem with the algorithm above - it's visit order is not
1052 // deterministic. A larger change is needed to fix this.
1053 for (auto Pair : states) {
1054 auto *BDV = Pair.first;
1055 auto State = Pair.second;
1056 Value *Base = State.getBase();
1057 assert(BDV && Base);
1058 assert(!isKnownBaseResult(BDV) && "why did it get added?");
1059 assert(isKnownBaseResult(Base) &&
1060 "must be something we 'know' is a base pointer");
1061 if (!State.isConflict())
1064 ReverseMap[Base] = BDV;
1065 if (auto *BaseI = dyn_cast<Instruction>(Base)) {
1066 NewInsts.insert(BaseI);
1067 Worklist.insert(BaseI);
1070 auto ReplaceBaseInstWith = [&](Value *BDV, Instruction *BaseI,
1071 Value *Replacement) {
1072 // Add users which are new instructions (excluding self references)
1073 for (User *U : BaseI->users())
1074 if (auto *UI = dyn_cast<Instruction>(U))
1075 if (NewInsts.count(UI) && UI != BaseI)
1076 Worklist.insert(UI);
1077 // Then do the actual replacement
1078 NewInsts.erase(BaseI);
1079 ReverseMap.erase(BaseI);
1080 BaseI->replaceAllUsesWith(Replacement);
1081 BaseI->eraseFromParent();
1082 assert(states.count(BDV));
1083 assert(states[BDV].isConflict() && states[BDV].getBase() == BaseI);
1084 states[BDV] = BDVState(BDVState::Conflict, Replacement);
1086 const DataLayout &DL = cast<Instruction>(def)->getModule()->getDataLayout();
1087 while (!Worklist.empty()) {
1088 Instruction *BaseI = Worklist.pop_back_val();
1089 assert(NewInsts.count(BaseI));
1090 Value *Bdv = ReverseMap[BaseI];
1091 if (auto *BdvI = dyn_cast<Instruction>(Bdv))
1092 if (BaseI->isIdenticalTo(BdvI)) {
1093 DEBUG(dbgs() << "Identical Base: " << *BaseI << "\n");
1094 ReplaceBaseInstWith(Bdv, BaseI, Bdv);
1097 if (Value *V = SimplifyInstruction(BaseI, DL)) {
1098 DEBUG(dbgs() << "Base " << *BaseI << " simplified to " << *V << "\n");
1099 ReplaceBaseInstWith(Bdv, BaseI, V);
1104 // Cache all of our results so we can cheaply reuse them
1105 // NOTE: This is actually two caches: one of the base defining value
1106 // relation and one of the base pointer relation! FIXME
1107 for (auto Pair : states) {
1108 auto *BDV = Pair.first;
1109 Value *base = Pair.second.getBase();
1110 assert(BDV && base);
1112 std::string fromstr =
1113 cache.count(BDV) ? (cache[BDV]->hasName() ? cache[BDV]->getName() : "")
1115 DEBUG(dbgs() << "Updating base value cache"
1116 << " for: " << (BDV->hasName() ? BDV->getName() : "")
1117 << " from: " << fromstr
1118 << " to: " << (base->hasName() ? base->getName() : "") << "\n");
1120 if (cache.count(BDV)) {
1121 // Once we transition from the BDV relation being store in the cache to
1122 // the base relation being stored, it must be stable
1123 assert((!isKnownBaseResult(cache[BDV]) || cache[BDV] == base) &&
1124 "base relation should be stable");
1128 assert(cache.find(def) != cache.end());
1132 // For a set of live pointers (base and/or derived), identify the base
1133 // pointer of the object which they are derived from. This routine will
1134 // mutate the IR graph as needed to make the 'base' pointer live at the
1135 // definition site of 'derived'. This ensures that any use of 'derived' can
1136 // also use 'base'. This may involve the insertion of a number of
1137 // additional PHI nodes.
1139 // preconditions: live is a set of pointer type Values
1141 // side effects: may insert PHI nodes into the existing CFG, will preserve
1142 // CFG, will not remove or mutate any existing nodes
1144 // post condition: PointerToBase contains one (derived, base) pair for every
1145 // pointer in live. Note that derived can be equal to base if the original
1146 // pointer was a base pointer.
1148 findBasePointers(const StatepointLiveSetTy &live,
1149 DenseMap<llvm::Value *, llvm::Value *> &PointerToBase,
1150 DominatorTree *DT, DefiningValueMapTy &DVCache) {
1151 // For the naming of values inserted to be deterministic - which makes for
1152 // much cleaner and more stable tests - we need to assign an order to the
1153 // live values. DenseSets do not provide a deterministic order across runs.
1154 SmallVector<Value *, 64> Temp;
1155 Temp.insert(Temp.end(), live.begin(), live.end());
1156 std::sort(Temp.begin(), Temp.end(), order_by_name);
1157 for (Value *ptr : Temp) {
1158 Value *base = findBasePointer(ptr, DVCache);
1159 assert(base && "failed to find base pointer");
1160 PointerToBase[ptr] = base;
1161 assert((!isa<Instruction>(base) || !isa<Instruction>(ptr) ||
1162 DT->dominates(cast<Instruction>(base)->getParent(),
1163 cast<Instruction>(ptr)->getParent())) &&
1164 "The base we found better dominate the derived pointer");
1166 // If you see this trip and like to live really dangerously, the code should
1167 // be correct, just with idioms the verifier can't handle. You can try
1168 // disabling the verifier at your own substantial risk.
1169 assert(!isa<ConstantPointerNull>(base) &&
1170 "the relocation code needs adjustment to handle the relocation of "
1171 "a null pointer constant without causing false positives in the "
1172 "safepoint ir verifier.");
1176 /// Find the required based pointers (and adjust the live set) for the given
1178 static void findBasePointers(DominatorTree &DT, DefiningValueMapTy &DVCache,
1180 PartiallyConstructedSafepointRecord &result) {
1181 DenseMap<llvm::Value *, llvm::Value *> PointerToBase;
1182 findBasePointers(result.liveset, PointerToBase, &DT, DVCache);
1184 if (PrintBasePointers) {
1185 // Note: Need to print these in a stable order since this is checked in
1187 errs() << "Base Pairs (w/o Relocation):\n";
1188 SmallVector<Value *, 64> Temp;
1189 Temp.reserve(PointerToBase.size());
1190 for (auto Pair : PointerToBase) {
1191 Temp.push_back(Pair.first);
1193 std::sort(Temp.begin(), Temp.end(), order_by_name);
1194 for (Value *Ptr : Temp) {
1195 Value *Base = PointerToBase[Ptr];
1196 errs() << " derived %" << Ptr->getName() << " base %" << Base->getName()
1201 result.PointerToBase = PointerToBase;
1204 /// Given an updated version of the dataflow liveness results, update the
1205 /// liveset and base pointer maps for the call site CS.
1206 static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData,
1208 PartiallyConstructedSafepointRecord &result);
1210 static void recomputeLiveInValues(
1211 Function &F, DominatorTree &DT, Pass *P, ArrayRef<CallSite> toUpdate,
1212 MutableArrayRef<struct PartiallyConstructedSafepointRecord> records) {
1213 // TODO-PERF: reuse the original liveness, then simply run the dataflow
1214 // again. The old values are still live and will help it stabilize quickly.
1215 GCPtrLivenessData RevisedLivenessData;
1216 computeLiveInValues(DT, F, RevisedLivenessData);
1217 for (size_t i = 0; i < records.size(); i++) {
1218 struct PartiallyConstructedSafepointRecord &info = records[i];
1219 const CallSite &CS = toUpdate[i];
1220 recomputeLiveInValues(RevisedLivenessData, CS, info);
1224 // When inserting gc.relocate calls, we need to ensure there are no uses
1225 // of the original value between the gc.statepoint and the gc.relocate call.
1226 // One case which can arise is a phi node starting one of the successor blocks.
1227 // We also need to be able to insert the gc.relocates only on the path which
1228 // goes through the statepoint. We might need to split an edge to make this
1231 normalizeForInvokeSafepoint(BasicBlock *BB, BasicBlock *InvokeParent,
1232 DominatorTree &DT) {
1233 BasicBlock *Ret = BB;
1234 if (!BB->getUniquePredecessor()) {
1235 Ret = SplitBlockPredecessors(BB, InvokeParent, "", &DT);
1238 // Now that 'ret' has unique predecessor we can safely remove all phi nodes
1240 FoldSingleEntryPHINodes(Ret);
1241 assert(!isa<PHINode>(Ret->begin()));
1243 // At this point, we can safely insert a gc.relocate as the first instruction
1244 // in Ret if needed.
1248 static int find_index(ArrayRef<Value *> livevec, Value *val) {
1249 auto itr = std::find(livevec.begin(), livevec.end(), val);
1250 assert(livevec.end() != itr);
1251 size_t index = std::distance(livevec.begin(), itr);
1252 assert(index < livevec.size());
1256 // Create new attribute set containing only attributes which can be transferred
1257 // from original call to the safepoint.
1258 static AttributeSet legalizeCallAttributes(AttributeSet AS) {
1261 for (unsigned Slot = 0; Slot < AS.getNumSlots(); Slot++) {
1262 unsigned index = AS.getSlotIndex(Slot);
1264 if (index == AttributeSet::ReturnIndex ||
1265 index == AttributeSet::FunctionIndex) {
1267 for (auto it = AS.begin(Slot), it_end = AS.end(Slot); it != it_end;
1269 Attribute attr = *it;
1271 // Do not allow certain attributes - just skip them
1272 // Safepoint can not be read only or read none.
1273 if (attr.hasAttribute(Attribute::ReadNone) ||
1274 attr.hasAttribute(Attribute::ReadOnly))
1277 ret = ret.addAttributes(
1278 AS.getContext(), index,
1279 AttributeSet::get(AS.getContext(), index, AttrBuilder(attr)));
1283 // Just skip parameter attributes for now
1289 /// Helper function to place all gc relocates necessary for the given
1292 /// liveVariables - list of variables to be relocated.
1293 /// liveStart - index of the first live variable.
1294 /// basePtrs - base pointers.
1295 /// statepointToken - statepoint instruction to which relocates should be
1297 /// Builder - Llvm IR builder to be used to construct new calls.
1298 static void CreateGCRelocates(ArrayRef<llvm::Value *> LiveVariables,
1299 const int LiveStart,
1300 ArrayRef<llvm::Value *> BasePtrs,
1301 Instruction *StatepointToken,
1302 IRBuilder<> Builder) {
1303 if (LiveVariables.empty())
1306 // All gc_relocate are set to i8 addrspace(1)* type. We originally generated
1307 // unique declarations for each pointer type, but this proved problematic
1308 // because the intrinsic mangling code is incomplete and fragile. Since
1309 // we're moving towards a single unified pointer type anyways, we can just
1310 // cast everything to an i8* of the right address space. A bitcast is added
1311 // later to convert gc_relocate to the actual value's type.
1312 Module *M = StatepointToken->getModule();
1313 auto AS = cast<PointerType>(LiveVariables[0]->getType())->getAddressSpace();
1314 Type *Types[] = {Type::getInt8PtrTy(M->getContext(), AS)};
1315 Value *GCRelocateDecl =
1316 Intrinsic::getDeclaration(M, Intrinsic::experimental_gc_relocate, Types);
1318 for (unsigned i = 0; i < LiveVariables.size(); i++) {
1319 // Generate the gc.relocate call and save the result
1321 Builder.getInt32(LiveStart + find_index(LiveVariables, BasePtrs[i]));
1323 Builder.getInt32(LiveStart + find_index(LiveVariables, LiveVariables[i]));
1325 // only specify a debug name if we can give a useful one
1326 CallInst *Reloc = Builder.CreateCall(
1327 GCRelocateDecl, {StatepointToken, BaseIdx, LiveIdx},
1328 LiveVariables[i]->hasName() ? LiveVariables[i]->getName() + ".relocated"
1330 // Trick CodeGen into thinking there are lots of free registers at this
1332 Reloc->setCallingConv(CallingConv::Cold);
1337 makeStatepointExplicitImpl(const CallSite &CS, /* to replace */
1338 const SmallVectorImpl<llvm::Value *> &basePtrs,
1339 const SmallVectorImpl<llvm::Value *> &liveVariables,
1341 PartiallyConstructedSafepointRecord &result) {
1342 assert(basePtrs.size() == liveVariables.size());
1343 assert(isStatepoint(CS) &&
1344 "This method expects to be rewriting a statepoint");
1346 BasicBlock *BB = CS.getInstruction()->getParent();
1348 Function *F = BB->getParent();
1349 assert(F && "must be set");
1350 Module *M = F->getParent();
1352 assert(M && "must be set");
1354 // We're not changing the function signature of the statepoint since the gc
1355 // arguments go into the var args section.
1356 Function *gc_statepoint_decl = CS.getCalledFunction();
1358 // Then go ahead and use the builder do actually do the inserts. We insert
1359 // immediately before the previous instruction under the assumption that all
1360 // arguments will be available here. We can't insert afterwards since we may
1361 // be replacing a terminator.
1362 Instruction *insertBefore = CS.getInstruction();
1363 IRBuilder<> Builder(insertBefore);
1364 // Copy all of the arguments from the original statepoint - this includes the
1365 // target, call args, and deopt args
1366 SmallVector<llvm::Value *, 64> args;
1367 args.insert(args.end(), CS.arg_begin(), CS.arg_end());
1368 // TODO: Clear the 'needs rewrite' flag
1370 // add all the pointers to be relocated (gc arguments)
1371 // Capture the start of the live variable list for use in the gc_relocates
1372 const int live_start = args.size();
1373 args.insert(args.end(), liveVariables.begin(), liveVariables.end());
1375 // Create the statepoint given all the arguments
1376 Instruction *token = nullptr;
1377 AttributeSet return_attributes;
1379 CallInst *toReplace = cast<CallInst>(CS.getInstruction());
1381 Builder.CreateCall(gc_statepoint_decl, args, "safepoint_token");
1382 call->setTailCall(toReplace->isTailCall());
1383 call->setCallingConv(toReplace->getCallingConv());
1385 // Currently we will fail on parameter attributes and on certain
1386 // function attributes.
1387 AttributeSet new_attrs = legalizeCallAttributes(toReplace->getAttributes());
1388 // In case if we can handle this set of attributes - set up function attrs
1389 // directly on statepoint and return attrs later for gc_result intrinsic.
1390 call->setAttributes(new_attrs.getFnAttributes());
1391 return_attributes = new_attrs.getRetAttributes();
1395 // Put the following gc_result and gc_relocate calls immediately after the
1396 // the old call (which we're about to delete)
1397 BasicBlock::iterator next(toReplace);
1398 assert(BB->end() != next && "not a terminator, must have next");
1400 Instruction *IP = &*(next);
1401 Builder.SetInsertPoint(IP);
1402 Builder.SetCurrentDebugLocation(IP->getDebugLoc());
1405 InvokeInst *toReplace = cast<InvokeInst>(CS.getInstruction());
1407 // Insert the new invoke into the old block. We'll remove the old one in a
1408 // moment at which point this will become the new terminator for the
1410 InvokeInst *invoke = InvokeInst::Create(
1411 gc_statepoint_decl, toReplace->getNormalDest(),
1412 toReplace->getUnwindDest(), args, "statepoint_token", toReplace->getParent());
1413 invoke->setCallingConv(toReplace->getCallingConv());
1415 // Currently we will fail on parameter attributes and on certain
1416 // function attributes.
1417 AttributeSet new_attrs = legalizeCallAttributes(toReplace->getAttributes());
1418 // In case if we can handle this set of attributes - set up function attrs
1419 // directly on statepoint and return attrs later for gc_result intrinsic.
1420 invoke->setAttributes(new_attrs.getFnAttributes());
1421 return_attributes = new_attrs.getRetAttributes();
1425 // Generate gc relocates in exceptional path
1426 BasicBlock *unwindBlock = toReplace->getUnwindDest();
1427 assert(!isa<PHINode>(unwindBlock->begin()) &&
1428 unwindBlock->getUniquePredecessor() &&
1429 "can't safely insert in this block!");
1431 Instruction *IP = &*(unwindBlock->getFirstInsertionPt());
1432 Builder.SetInsertPoint(IP);
1433 Builder.SetCurrentDebugLocation(toReplace->getDebugLoc());
1435 // Extract second element from landingpad return value. We will attach
1436 // exceptional gc relocates to it.
1437 const unsigned idx = 1;
1438 Instruction *exceptional_token =
1439 cast<Instruction>(Builder.CreateExtractValue(
1440 unwindBlock->getLandingPadInst(), idx, "relocate_token"));
1441 result.UnwindToken = exceptional_token;
1443 CreateGCRelocates(liveVariables, live_start, basePtrs,
1444 exceptional_token, Builder);
1446 // Generate gc relocates and returns for normal block
1447 BasicBlock *normalDest = toReplace->getNormalDest();
1448 assert(!isa<PHINode>(normalDest->begin()) &&
1449 normalDest->getUniquePredecessor() &&
1450 "can't safely insert in this block!");
1452 IP = &*(normalDest->getFirstInsertionPt());
1453 Builder.SetInsertPoint(IP);
1455 // gc relocates will be generated later as if it were regular call
1460 // Take the name of the original value call if it had one.
1461 token->takeName(CS.getInstruction());
1463 // The GCResult is already inserted, we just need to find it
1465 Instruction *toReplace = CS.getInstruction();
1466 assert((toReplace->hasNUses(0) || toReplace->hasNUses(1)) &&
1467 "only valid use before rewrite is gc.result");
1468 assert(!toReplace->hasOneUse() ||
1469 isGCResult(cast<Instruction>(*toReplace->user_begin())));
1472 // Update the gc.result of the original statepoint (if any) to use the newly
1473 // inserted statepoint. This is safe to do here since the token can't be
1474 // considered a live reference.
1475 CS.getInstruction()->replaceAllUsesWith(token);
1477 result.StatepointToken = token;
1479 // Second, create a gc.relocate for every live variable
1480 CreateGCRelocates(liveVariables, live_start, basePtrs, token, Builder);
1484 struct name_ordering {
1487 bool operator()(name_ordering const &a, name_ordering const &b) {
1488 return -1 == a.derived->getName().compare(b.derived->getName());
1492 static void stablize_order(SmallVectorImpl<Value *> &basevec,
1493 SmallVectorImpl<Value *> &livevec) {
1494 assert(basevec.size() == livevec.size());
1496 SmallVector<name_ordering, 64> temp;
1497 for (size_t i = 0; i < basevec.size(); i++) {
1499 v.base = basevec[i];
1500 v.derived = livevec[i];
1503 std::sort(temp.begin(), temp.end(), name_ordering());
1504 for (size_t i = 0; i < basevec.size(); i++) {
1505 basevec[i] = temp[i].base;
1506 livevec[i] = temp[i].derived;
1510 // Replace an existing gc.statepoint with a new one and a set of gc.relocates
1511 // which make the relocations happening at this safepoint explicit.
1513 // WARNING: Does not do any fixup to adjust users of the original live
1514 // values. That's the callers responsibility.
1516 makeStatepointExplicit(DominatorTree &DT, const CallSite &CS, Pass *P,
1517 PartiallyConstructedSafepointRecord &result) {
1518 auto liveset = result.liveset;
1519 auto PointerToBase = result.PointerToBase;
1521 // Convert to vector for efficient cross referencing.
1522 SmallVector<Value *, 64> basevec, livevec;
1523 livevec.reserve(liveset.size());
1524 basevec.reserve(liveset.size());
1525 for (Value *L : liveset) {
1526 livevec.push_back(L);
1527 assert(PointerToBase.count(L));
1528 Value *base = PointerToBase[L];
1529 basevec.push_back(base);
1531 assert(livevec.size() == basevec.size());
1533 // To make the output IR slightly more stable (for use in diffs), ensure a
1534 // fixed order of the values in the safepoint (by sorting the value name).
1535 // The order is otherwise meaningless.
1536 stablize_order(basevec, livevec);
1538 // Do the actual rewriting and delete the old statepoint
1539 makeStatepointExplicitImpl(CS, basevec, livevec, P, result);
1540 CS.getInstruction()->eraseFromParent();
1543 // Helper function for the relocationViaAlloca.
1544 // It receives iterator to the statepoint gc relocates and emits store to the
1546 // location (via allocaMap) for the each one of them.
1547 // Add visited values into the visitedLiveValues set we will later use them
1548 // for sanity check.
1550 insertRelocationStores(iterator_range<Value::user_iterator> GCRelocs,
1551 DenseMap<Value *, Value *> &AllocaMap,
1552 DenseSet<Value *> &VisitedLiveValues) {
1554 for (User *U : GCRelocs) {
1555 if (!isa<IntrinsicInst>(U))
1558 IntrinsicInst *RelocatedValue = cast<IntrinsicInst>(U);
1560 // We only care about relocates
1561 if (RelocatedValue->getIntrinsicID() !=
1562 Intrinsic::experimental_gc_relocate) {
1566 GCRelocateOperands RelocateOperands(RelocatedValue);
1567 Value *OriginalValue =
1568 const_cast<Value *>(RelocateOperands.getDerivedPtr());
1569 assert(AllocaMap.count(OriginalValue));
1570 Value *Alloca = AllocaMap[OriginalValue];
1572 // Emit store into the related alloca
1573 // All gc_relocate are i8 addrspace(1)* typed, and it must be bitcasted to
1574 // the correct type according to alloca.
1575 assert(RelocatedValue->getNextNode() && "Should always have one since it's not a terminator");
1576 IRBuilder<> Builder(RelocatedValue->getNextNode());
1577 Value *CastedRelocatedValue =
1578 Builder.CreateBitCast(RelocatedValue, cast<AllocaInst>(Alloca)->getAllocatedType(),
1579 RelocatedValue->hasName() ? RelocatedValue->getName() + ".casted" : "");
1581 StoreInst *Store = new StoreInst(CastedRelocatedValue, Alloca);
1582 Store->insertAfter(cast<Instruction>(CastedRelocatedValue));
1585 VisitedLiveValues.insert(OriginalValue);
1590 // Helper function for the "relocationViaAlloca". Similar to the
1591 // "insertRelocationStores" but works for rematerialized values.
1593 insertRematerializationStores(
1594 RematerializedValueMapTy RematerializedValues,
1595 DenseMap<Value *, Value *> &AllocaMap,
1596 DenseSet<Value *> &VisitedLiveValues) {
1598 for (auto RematerializedValuePair: RematerializedValues) {
1599 Instruction *RematerializedValue = RematerializedValuePair.first;
1600 Value *OriginalValue = RematerializedValuePair.second;
1602 assert(AllocaMap.count(OriginalValue) &&
1603 "Can not find alloca for rematerialized value");
1604 Value *Alloca = AllocaMap[OriginalValue];
1606 StoreInst *Store = new StoreInst(RematerializedValue, Alloca);
1607 Store->insertAfter(RematerializedValue);
1610 VisitedLiveValues.insert(OriginalValue);
1615 /// do all the relocation update via allocas and mem2reg
1616 static void relocationViaAlloca(
1617 Function &F, DominatorTree &DT, ArrayRef<Value *> Live,
1618 ArrayRef<struct PartiallyConstructedSafepointRecord> Records) {
1620 // record initial number of (static) allocas; we'll check we have the same
1621 // number when we get done.
1622 int InitialAllocaNum = 0;
1623 for (auto I = F.getEntryBlock().begin(), E = F.getEntryBlock().end(); I != E;
1625 if (isa<AllocaInst>(*I))
1629 // TODO-PERF: change data structures, reserve
1630 DenseMap<Value *, Value *> AllocaMap;
1631 SmallVector<AllocaInst *, 200> PromotableAllocas;
1632 // Used later to chack that we have enough allocas to store all values
1633 std::size_t NumRematerializedValues = 0;
1634 PromotableAllocas.reserve(Live.size());
1636 // Emit alloca for "LiveValue" and record it in "allocaMap" and
1637 // "PromotableAllocas"
1638 auto emitAllocaFor = [&](Value *LiveValue) {
1639 AllocaInst *Alloca = new AllocaInst(LiveValue->getType(), "",
1640 F.getEntryBlock().getFirstNonPHI());
1641 AllocaMap[LiveValue] = Alloca;
1642 PromotableAllocas.push_back(Alloca);
1645 // emit alloca for each live gc pointer
1646 for (unsigned i = 0; i < Live.size(); i++) {
1647 emitAllocaFor(Live[i]);
1650 // emit allocas for rematerialized values
1651 for (size_t i = 0; i < Records.size(); i++) {
1652 const struct PartiallyConstructedSafepointRecord &Info = Records[i];
1654 for (auto RematerializedValuePair : Info.RematerializedValues) {
1655 Value *OriginalValue = RematerializedValuePair.second;
1656 if (AllocaMap.count(OriginalValue) != 0)
1659 emitAllocaFor(OriginalValue);
1660 ++NumRematerializedValues;
1664 // The next two loops are part of the same conceptual operation. We need to
1665 // insert a store to the alloca after the original def and at each
1666 // redefinition. We need to insert a load before each use. These are split
1667 // into distinct loops for performance reasons.
1669 // update gc pointer after each statepoint
1670 // either store a relocated value or null (if no relocated value found for
1671 // this gc pointer and it is not a gc_result)
1672 // this must happen before we update the statepoint with load of alloca
1673 // otherwise we lose the link between statepoint and old def
1674 for (size_t i = 0; i < Records.size(); i++) {
1675 const struct PartiallyConstructedSafepointRecord &Info = Records[i];
1676 Value *Statepoint = Info.StatepointToken;
1678 // This will be used for consistency check
1679 DenseSet<Value *> VisitedLiveValues;
1681 // Insert stores for normal statepoint gc relocates
1682 insertRelocationStores(Statepoint->users(), AllocaMap, VisitedLiveValues);
1684 // In case if it was invoke statepoint
1685 // we will insert stores for exceptional path gc relocates.
1686 if (isa<InvokeInst>(Statepoint)) {
1687 insertRelocationStores(Info.UnwindToken->users(), AllocaMap,
1691 // Do similar thing with rematerialized values
1692 insertRematerializationStores(Info.RematerializedValues, AllocaMap,
1695 if (ClobberNonLive) {
1696 // As a debugging aid, pretend that an unrelocated pointer becomes null at
1697 // the gc.statepoint. This will turn some subtle GC problems into
1698 // slightly easier to debug SEGVs. Note that on large IR files with
1699 // lots of gc.statepoints this is extremely costly both memory and time
1701 SmallVector<AllocaInst *, 64> ToClobber;
1702 for (auto Pair : AllocaMap) {
1703 Value *Def = Pair.first;
1704 AllocaInst *Alloca = cast<AllocaInst>(Pair.second);
1706 // This value was relocated
1707 if (VisitedLiveValues.count(Def)) {
1710 ToClobber.push_back(Alloca);
1713 auto InsertClobbersAt = [&](Instruction *IP) {
1714 for (auto *AI : ToClobber) {
1715 auto AIType = cast<PointerType>(AI->getType());
1716 auto PT = cast<PointerType>(AIType->getElementType());
1717 Constant *CPN = ConstantPointerNull::get(PT);
1718 StoreInst *Store = new StoreInst(CPN, AI);
1719 Store->insertBefore(IP);
1723 // Insert the clobbering stores. These may get intermixed with the
1724 // gc.results and gc.relocates, but that's fine.
1725 if (auto II = dyn_cast<InvokeInst>(Statepoint)) {
1726 InsertClobbersAt(II->getNormalDest()->getFirstInsertionPt());
1727 InsertClobbersAt(II->getUnwindDest()->getFirstInsertionPt());
1729 BasicBlock::iterator Next(cast<CallInst>(Statepoint));
1731 InsertClobbersAt(Next);
1735 // update use with load allocas and add store for gc_relocated
1736 for (auto Pair : AllocaMap) {
1737 Value *Def = Pair.first;
1738 Value *Alloca = Pair.second;
1740 // we pre-record the uses of allocas so that we dont have to worry about
1742 // that change the user information.
1743 SmallVector<Instruction *, 20> Uses;
1744 // PERF: trade a linear scan for repeated reallocation
1745 Uses.reserve(std::distance(Def->user_begin(), Def->user_end()));
1746 for (User *U : Def->users()) {
1747 if (!isa<ConstantExpr>(U)) {
1748 // If the def has a ConstantExpr use, then the def is either a
1749 // ConstantExpr use itself or null. In either case
1750 // (recursively in the first, directly in the second), the oop
1751 // it is ultimately dependent on is null and this particular
1752 // use does not need to be fixed up.
1753 Uses.push_back(cast<Instruction>(U));
1757 std::sort(Uses.begin(), Uses.end());
1758 auto Last = std::unique(Uses.begin(), Uses.end());
1759 Uses.erase(Last, Uses.end());
1761 for (Instruction *Use : Uses) {
1762 if (isa<PHINode>(Use)) {
1763 PHINode *Phi = cast<PHINode>(Use);
1764 for (unsigned i = 0; i < Phi->getNumIncomingValues(); i++) {
1765 if (Def == Phi->getIncomingValue(i)) {
1766 LoadInst *Load = new LoadInst(
1767 Alloca, "", Phi->getIncomingBlock(i)->getTerminator());
1768 Phi->setIncomingValue(i, Load);
1772 LoadInst *Load = new LoadInst(Alloca, "", Use);
1773 Use->replaceUsesOfWith(Def, Load);
1777 // emit store for the initial gc value
1778 // store must be inserted after load, otherwise store will be in alloca's
1779 // use list and an extra load will be inserted before it
1780 StoreInst *Store = new StoreInst(Def, Alloca);
1781 if (Instruction *Inst = dyn_cast<Instruction>(Def)) {
1782 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(Inst)) {
1783 // InvokeInst is a TerminatorInst so the store need to be inserted
1784 // into its normal destination block.
1785 BasicBlock *NormalDest = Invoke->getNormalDest();
1786 Store->insertBefore(NormalDest->getFirstNonPHI());
1788 assert(!Inst->isTerminator() &&
1789 "The only TerminatorInst that can produce a value is "
1790 "InvokeInst which is handled above.");
1791 Store->insertAfter(Inst);
1794 assert(isa<Argument>(Def));
1795 Store->insertAfter(cast<Instruction>(Alloca));
1799 assert(PromotableAllocas.size() == Live.size() + NumRematerializedValues &&
1800 "we must have the same allocas with lives");
1801 if (!PromotableAllocas.empty()) {
1802 // apply mem2reg to promote alloca to SSA
1803 PromoteMemToReg(PromotableAllocas, DT);
1807 for (auto I = F.getEntryBlock().begin(), E = F.getEntryBlock().end(); I != E;
1809 if (isa<AllocaInst>(*I))
1811 assert(InitialAllocaNum == 0 && "We must not introduce any extra allocas");
1815 /// Implement a unique function which doesn't require we sort the input
1816 /// vector. Doing so has the effect of changing the output of a couple of
1817 /// tests in ways which make them less useful in testing fused safepoints.
1818 template <typename T> static void unique_unsorted(SmallVectorImpl<T> &Vec) {
1819 SmallSet<T, 8> Seen;
1820 Vec.erase(std::remove_if(Vec.begin(), Vec.end(), [&](const T &V) {
1821 return !Seen.insert(V).second;
1825 /// Insert holders so that each Value is obviously live through the entire
1826 /// lifetime of the call.
1827 static void insertUseHolderAfter(CallSite &CS, const ArrayRef<Value *> Values,
1828 SmallVectorImpl<CallInst *> &Holders) {
1830 // No values to hold live, might as well not insert the empty holder
1833 Module *M = CS.getInstruction()->getParent()->getParent()->getParent();
1834 // Use a dummy vararg function to actually hold the values live
1835 Function *Func = cast<Function>(M->getOrInsertFunction(
1836 "__tmp_use", FunctionType::get(Type::getVoidTy(M->getContext()), true)));
1838 // For call safepoints insert dummy calls right after safepoint
1839 BasicBlock::iterator Next(CS.getInstruction());
1841 Holders.push_back(CallInst::Create(Func, Values, "", Next));
1844 // For invoke safepooints insert dummy calls both in normal and
1845 // exceptional destination blocks
1846 auto *II = cast<InvokeInst>(CS.getInstruction());
1847 Holders.push_back(CallInst::Create(
1848 Func, Values, "", II->getNormalDest()->getFirstInsertionPt()));
1849 Holders.push_back(CallInst::Create(
1850 Func, Values, "", II->getUnwindDest()->getFirstInsertionPt()));
1853 static void findLiveReferences(
1854 Function &F, DominatorTree &DT, Pass *P, ArrayRef<CallSite> toUpdate,
1855 MutableArrayRef<struct PartiallyConstructedSafepointRecord> records) {
1856 GCPtrLivenessData OriginalLivenessData;
1857 computeLiveInValues(DT, F, OriginalLivenessData);
1858 for (size_t i = 0; i < records.size(); i++) {
1859 struct PartiallyConstructedSafepointRecord &info = records[i];
1860 const CallSite &CS = toUpdate[i];
1861 analyzeParsePointLiveness(DT, OriginalLivenessData, CS, info);
1865 /// Remove any vector of pointers from the liveset by scalarizing them over the
1866 /// statepoint instruction. Adds the scalarized pieces to the liveset. It
1867 /// would be preferable to include the vector in the statepoint itself, but
1868 /// the lowering code currently does not handle that. Extending it would be
1869 /// slightly non-trivial since it requires a format change. Given how rare
1870 /// such cases are (for the moment?) scalarizing is an acceptable compromise.
1871 static void splitVectorValues(Instruction *StatepointInst,
1872 StatepointLiveSetTy &LiveSet,
1873 DenseMap<Value *, Value *>& PointerToBase,
1874 DominatorTree &DT) {
1875 SmallVector<Value *, 16> ToSplit;
1876 for (Value *V : LiveSet)
1877 if (isa<VectorType>(V->getType()))
1878 ToSplit.push_back(V);
1880 if (ToSplit.empty())
1883 DenseMap<Value *, SmallVector<Value *, 16>> ElementMapping;
1885 Function &F = *(StatepointInst->getParent()->getParent());
1887 DenseMap<Value *, AllocaInst *> AllocaMap;
1888 // First is normal return, second is exceptional return (invoke only)
1889 DenseMap<Value *, std::pair<Value *, Value *>> Replacements;
1890 for (Value *V : ToSplit) {
1891 AllocaInst *Alloca =
1892 new AllocaInst(V->getType(), "", F.getEntryBlock().getFirstNonPHI());
1893 AllocaMap[V] = Alloca;
1895 VectorType *VT = cast<VectorType>(V->getType());
1896 IRBuilder<> Builder(StatepointInst);
1897 SmallVector<Value *, 16> Elements;
1898 for (unsigned i = 0; i < VT->getNumElements(); i++)
1899 Elements.push_back(Builder.CreateExtractElement(V, Builder.getInt32(i)));
1900 ElementMapping[V] = Elements;
1902 auto InsertVectorReform = [&](Instruction *IP) {
1903 Builder.SetInsertPoint(IP);
1904 Builder.SetCurrentDebugLocation(IP->getDebugLoc());
1905 Value *ResultVec = UndefValue::get(VT);
1906 for (unsigned i = 0; i < VT->getNumElements(); i++)
1907 ResultVec = Builder.CreateInsertElement(ResultVec, Elements[i],
1908 Builder.getInt32(i));
1912 if (isa<CallInst>(StatepointInst)) {
1913 BasicBlock::iterator Next(StatepointInst);
1915 Instruction *IP = &*(Next);
1916 Replacements[V].first = InsertVectorReform(IP);
1917 Replacements[V].second = nullptr;
1919 InvokeInst *Invoke = cast<InvokeInst>(StatepointInst);
1920 // We've already normalized - check that we don't have shared destination
1922 BasicBlock *NormalDest = Invoke->getNormalDest();
1923 assert(!isa<PHINode>(NormalDest->begin()));
1924 BasicBlock *UnwindDest = Invoke->getUnwindDest();
1925 assert(!isa<PHINode>(UnwindDest->begin()));
1926 // Insert insert element sequences in both successors
1927 Instruction *IP = &*(NormalDest->getFirstInsertionPt());
1928 Replacements[V].first = InsertVectorReform(IP);
1929 IP = &*(UnwindDest->getFirstInsertionPt());
1930 Replacements[V].second = InsertVectorReform(IP);
1934 for (Value *V : ToSplit) {
1935 AllocaInst *Alloca = AllocaMap[V];
1937 // Capture all users before we start mutating use lists
1938 SmallVector<Instruction *, 16> Users;
1939 for (User *U : V->users())
1940 Users.push_back(cast<Instruction>(U));
1942 for (Instruction *I : Users) {
1943 if (auto Phi = dyn_cast<PHINode>(I)) {
1944 for (unsigned i = 0; i < Phi->getNumIncomingValues(); i++)
1945 if (V == Phi->getIncomingValue(i)) {
1946 LoadInst *Load = new LoadInst(
1947 Alloca, "", Phi->getIncomingBlock(i)->getTerminator());
1948 Phi->setIncomingValue(i, Load);
1951 LoadInst *Load = new LoadInst(Alloca, "", I);
1952 I->replaceUsesOfWith(V, Load);
1956 // Store the original value and the replacement value into the alloca
1957 StoreInst *Store = new StoreInst(V, Alloca);
1958 if (auto I = dyn_cast<Instruction>(V))
1959 Store->insertAfter(I);
1961 Store->insertAfter(Alloca);
1963 // Normal return for invoke, or call return
1964 Instruction *Replacement = cast<Instruction>(Replacements[V].first);
1965 (new StoreInst(Replacement, Alloca))->insertAfter(Replacement);
1966 // Unwind return for invoke only
1967 Replacement = cast_or_null<Instruction>(Replacements[V].second);
1969 (new StoreInst(Replacement, Alloca))->insertAfter(Replacement);
1972 // apply mem2reg to promote alloca to SSA
1973 SmallVector<AllocaInst *, 16> Allocas;
1974 for (Value *V : ToSplit)
1975 Allocas.push_back(AllocaMap[V]);
1976 PromoteMemToReg(Allocas, DT);
1978 // Update our tracking of live pointers and base mappings to account for the
1979 // changes we just made.
1980 for (Value *V : ToSplit) {
1981 auto &Elements = ElementMapping[V];
1984 LiveSet.insert(Elements.begin(), Elements.end());
1985 // We need to update the base mapping as well.
1986 assert(PointerToBase.count(V));
1987 Value *OldBase = PointerToBase[V];
1988 auto &BaseElements = ElementMapping[OldBase];
1989 PointerToBase.erase(V);
1990 assert(Elements.size() == BaseElements.size());
1991 for (unsigned i = 0; i < Elements.size(); i++) {
1992 Value *Elem = Elements[i];
1993 PointerToBase[Elem] = BaseElements[i];
1998 // Helper function for the "rematerializeLiveValues". It walks use chain
1999 // starting from the "CurrentValue" until it meets "BaseValue". Only "simple"
2000 // values are visited (currently it is GEP's and casts). Returns true if it
2001 // successfully reached "BaseValue" and false otherwise.
2002 // Fills "ChainToBase" array with all visited values. "BaseValue" is not
2004 static bool findRematerializableChainToBasePointer(
2005 SmallVectorImpl<Instruction*> &ChainToBase,
2006 Value *CurrentValue, Value *BaseValue) {
2008 // We have found a base value
2009 if (CurrentValue == BaseValue) {
2013 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurrentValue)) {
2014 ChainToBase.push_back(GEP);
2015 return findRematerializableChainToBasePointer(ChainToBase,
2016 GEP->getPointerOperand(),
2020 if (CastInst *CI = dyn_cast<CastInst>(CurrentValue)) {
2021 Value *Def = CI->stripPointerCasts();
2023 // This two checks are basically similar. First one is here for the
2024 // consistency with findBasePointers logic.
2025 assert(!isa<CastInst>(Def) && "not a pointer cast found");
2026 if (!CI->isNoopCast(CI->getModule()->getDataLayout()))
2029 ChainToBase.push_back(CI);
2030 return findRematerializableChainToBasePointer(ChainToBase, Def, BaseValue);
2033 // Not supported instruction in the chain
2037 // Helper function for the "rematerializeLiveValues". Compute cost of the use
2038 // chain we are going to rematerialize.
2040 chainToBasePointerCost(SmallVectorImpl<Instruction*> &Chain,
2041 TargetTransformInfo &TTI) {
2044 for (Instruction *Instr : Chain) {
2045 if (CastInst *CI = dyn_cast<CastInst>(Instr)) {
2046 assert(CI->isNoopCast(CI->getModule()->getDataLayout()) &&
2047 "non noop cast is found during rematerialization");
2049 Type *SrcTy = CI->getOperand(0)->getType();
2050 Cost += TTI.getCastInstrCost(CI->getOpcode(), CI->getType(), SrcTy);
2052 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Instr)) {
2053 // Cost of the address calculation
2054 Type *ValTy = GEP->getPointerOperandType()->getPointerElementType();
2055 Cost += TTI.getAddressComputationCost(ValTy);
2057 // And cost of the GEP itself
2058 // TODO: Use TTI->getGEPCost here (it exists, but appears to be not
2059 // allowed for the external usage)
2060 if (!GEP->hasAllConstantIndices())
2064 llvm_unreachable("unsupported instruciton type during rematerialization");
2071 // From the statepoint liveset pick values that are cheaper to recompute then to
2072 // relocate. Remove this values from the liveset, rematerialize them after
2073 // statepoint and record them in "Info" structure. Note that similar to
2074 // relocated values we don't do any user adjustments here.
2075 static void rematerializeLiveValues(CallSite CS,
2076 PartiallyConstructedSafepointRecord &Info,
2077 TargetTransformInfo &TTI) {
2078 const unsigned int ChainLengthThreshold = 10;
2080 // Record values we are going to delete from this statepoint live set.
2081 // We can not di this in following loop due to iterator invalidation.
2082 SmallVector<Value *, 32> LiveValuesToBeDeleted;
2084 for (Value *LiveValue: Info.liveset) {
2085 // For each live pointer find it's defining chain
2086 SmallVector<Instruction *, 3> ChainToBase;
2087 assert(Info.PointerToBase.count(LiveValue));
2089 findRematerializableChainToBasePointer(ChainToBase,
2091 Info.PointerToBase[LiveValue]);
2092 // Nothing to do, or chain is too long
2094 ChainToBase.size() == 0 ||
2095 ChainToBase.size() > ChainLengthThreshold)
2098 // Compute cost of this chain
2099 unsigned Cost = chainToBasePointerCost(ChainToBase, TTI);
2100 // TODO: We can also account for cases when we will be able to remove some
2101 // of the rematerialized values by later optimization passes. I.e if
2102 // we rematerialized several intersecting chains. Or if original values
2103 // don't have any uses besides this statepoint.
2105 // For invokes we need to rematerialize each chain twice - for normal and
2106 // for unwind basic blocks. Model this by multiplying cost by two.
2107 if (CS.isInvoke()) {
2110 // If it's too expensive - skip it
2111 if (Cost >= RematerializationThreshold)
2114 // Remove value from the live set
2115 LiveValuesToBeDeleted.push_back(LiveValue);
2117 // Clone instructions and record them inside "Info" structure
2119 // Walk backwards to visit top-most instructions first
2120 std::reverse(ChainToBase.begin(), ChainToBase.end());
2122 // Utility function which clones all instructions from "ChainToBase"
2123 // and inserts them before "InsertBefore". Returns rematerialized value
2124 // which should be used after statepoint.
2125 auto rematerializeChain = [&ChainToBase](Instruction *InsertBefore) {
2126 Instruction *LastClonedValue = nullptr;
2127 Instruction *LastValue = nullptr;
2128 for (Instruction *Instr: ChainToBase) {
2129 // Only GEP's and casts are suported as we need to be careful to not
2130 // introduce any new uses of pointers not in the liveset.
2131 // Note that it's fine to introduce new uses of pointers which were
2132 // otherwise not used after this statepoint.
2133 assert(isa<GetElementPtrInst>(Instr) || isa<CastInst>(Instr));
2135 Instruction *ClonedValue = Instr->clone();
2136 ClonedValue->insertBefore(InsertBefore);
2137 ClonedValue->setName(Instr->getName() + ".remat");
2139 // If it is not first instruction in the chain then it uses previously
2140 // cloned value. We should update it to use cloned value.
2141 if (LastClonedValue) {
2143 ClonedValue->replaceUsesOfWith(LastValue, LastClonedValue);
2145 // Assert that cloned instruction does not use any instructions from
2146 // this chain other than LastClonedValue
2147 for (auto OpValue : ClonedValue->operand_values()) {
2148 assert(std::find(ChainToBase.begin(), ChainToBase.end(), OpValue) ==
2149 ChainToBase.end() &&
2150 "incorrect use in rematerialization chain");
2155 LastClonedValue = ClonedValue;
2158 assert(LastClonedValue);
2159 return LastClonedValue;
2162 // Different cases for calls and invokes. For invokes we need to clone
2163 // instructions both on normal and unwind path.
2165 Instruction *InsertBefore = CS.getInstruction()->getNextNode();
2166 assert(InsertBefore);
2167 Instruction *RematerializedValue = rematerializeChain(InsertBefore);
2168 Info.RematerializedValues[RematerializedValue] = LiveValue;
2170 InvokeInst *Invoke = cast<InvokeInst>(CS.getInstruction());
2172 Instruction *NormalInsertBefore =
2173 Invoke->getNormalDest()->getFirstInsertionPt();
2174 Instruction *UnwindInsertBefore =
2175 Invoke->getUnwindDest()->getFirstInsertionPt();
2177 Instruction *NormalRematerializedValue =
2178 rematerializeChain(NormalInsertBefore);
2179 Instruction *UnwindRematerializedValue =
2180 rematerializeChain(UnwindInsertBefore);
2182 Info.RematerializedValues[NormalRematerializedValue] = LiveValue;
2183 Info.RematerializedValues[UnwindRematerializedValue] = LiveValue;
2187 // Remove rematerializaed values from the live set
2188 for (auto LiveValue: LiveValuesToBeDeleted) {
2189 Info.liveset.erase(LiveValue);
2193 static bool insertParsePoints(Function &F, DominatorTree &DT, Pass *P,
2194 SmallVectorImpl<CallSite> &toUpdate) {
2196 // sanity check the input
2197 std::set<CallSite> uniqued;
2198 uniqued.insert(toUpdate.begin(), toUpdate.end());
2199 assert(uniqued.size() == toUpdate.size() && "no duplicates please!");
2201 for (size_t i = 0; i < toUpdate.size(); i++) {
2202 CallSite &CS = toUpdate[i];
2203 assert(CS.getInstruction()->getParent()->getParent() == &F);
2204 assert(isStatepoint(CS) && "expected to already be a deopt statepoint");
2208 // When inserting gc.relocates for invokes, we need to be able to insert at
2209 // the top of the successor blocks. See the comment on
2210 // normalForInvokeSafepoint on exactly what is needed. Note that this step
2211 // may restructure the CFG.
2212 for (CallSite CS : toUpdate) {
2215 InvokeInst *invoke = cast<InvokeInst>(CS.getInstruction());
2216 normalizeForInvokeSafepoint(invoke->getNormalDest(), invoke->getParent(),
2218 normalizeForInvokeSafepoint(invoke->getUnwindDest(), invoke->getParent(),
2222 // A list of dummy calls added to the IR to keep various values obviously
2223 // live in the IR. We'll remove all of these when done.
2224 SmallVector<CallInst *, 64> holders;
2226 // Insert a dummy call with all of the arguments to the vm_state we'll need
2227 // for the actual safepoint insertion. This ensures reference arguments in
2228 // the deopt argument list are considered live through the safepoint (and
2229 // thus makes sure they get relocated.)
2230 for (size_t i = 0; i < toUpdate.size(); i++) {
2231 CallSite &CS = toUpdate[i];
2232 Statepoint StatepointCS(CS);
2234 SmallVector<Value *, 64> DeoptValues;
2235 for (Use &U : StatepointCS.vm_state_args()) {
2236 Value *Arg = cast<Value>(&U);
2237 assert(!isUnhandledGCPointerType(Arg->getType()) &&
2238 "support for FCA unimplemented");
2239 if (isHandledGCPointerType(Arg->getType()))
2240 DeoptValues.push_back(Arg);
2242 insertUseHolderAfter(CS, DeoptValues, holders);
2245 SmallVector<struct PartiallyConstructedSafepointRecord, 64> records;
2246 records.reserve(toUpdate.size());
2247 for (size_t i = 0; i < toUpdate.size(); i++) {
2248 struct PartiallyConstructedSafepointRecord info;
2249 records.push_back(info);
2251 assert(records.size() == toUpdate.size());
2253 // A) Identify all gc pointers which are statically live at the given call
2255 findLiveReferences(F, DT, P, toUpdate, records);
2257 // B) Find the base pointers for each live pointer
2258 /* scope for caching */ {
2259 // Cache the 'defining value' relation used in the computation and
2260 // insertion of base phis and selects. This ensures that we don't insert
2261 // large numbers of duplicate base_phis.
2262 DefiningValueMapTy DVCache;
2264 for (size_t i = 0; i < records.size(); i++) {
2265 struct PartiallyConstructedSafepointRecord &info = records[i];
2266 CallSite &CS = toUpdate[i];
2267 findBasePointers(DT, DVCache, CS, info);
2269 } // end of cache scope
2271 // The base phi insertion logic (for any safepoint) may have inserted new
2272 // instructions which are now live at some safepoint. The simplest such
2275 // phi a <-- will be a new base_phi here
2276 // safepoint 1 <-- that needs to be live here
2280 // We insert some dummy calls after each safepoint to definitely hold live
2281 // the base pointers which were identified for that safepoint. We'll then
2282 // ask liveness for _every_ base inserted to see what is now live. Then we
2283 // remove the dummy calls.
2284 holders.reserve(holders.size() + records.size());
2285 for (size_t i = 0; i < records.size(); i++) {
2286 struct PartiallyConstructedSafepointRecord &info = records[i];
2287 CallSite &CS = toUpdate[i];
2289 SmallVector<Value *, 128> Bases;
2290 for (auto Pair : info.PointerToBase) {
2291 Bases.push_back(Pair.second);
2293 insertUseHolderAfter(CS, Bases, holders);
2296 // By selecting base pointers, we've effectively inserted new uses. Thus, we
2297 // need to rerun liveness. We may *also* have inserted new defs, but that's
2298 // not the key issue.
2299 recomputeLiveInValues(F, DT, P, toUpdate, records);
2301 if (PrintBasePointers) {
2302 for (size_t i = 0; i < records.size(); i++) {
2303 struct PartiallyConstructedSafepointRecord &info = records[i];
2304 errs() << "Base Pairs: (w/Relocation)\n";
2305 for (auto Pair : info.PointerToBase) {
2306 errs() << " derived %" << Pair.first->getName() << " base %"
2307 << Pair.second->getName() << "\n";
2311 for (size_t i = 0; i < holders.size(); i++) {
2312 holders[i]->eraseFromParent();
2313 holders[i] = nullptr;
2317 // Do a limited scalarization of any live at safepoint vector values which
2318 // contain pointers. This enables this pass to run after vectorization at
2319 // the cost of some possible performance loss. TODO: it would be nice to
2320 // natively support vectors all the way through the backend so we don't need
2321 // to scalarize here.
2322 for (size_t i = 0; i < records.size(); i++) {
2323 struct PartiallyConstructedSafepointRecord &info = records[i];
2324 Instruction *statepoint = toUpdate[i].getInstruction();
2325 splitVectorValues(cast<Instruction>(statepoint), info.liveset,
2326 info.PointerToBase, DT);
2329 // In order to reduce live set of statepoint we might choose to rematerialize
2330 // some values instead of relocating them. This is purely an optimization and
2331 // does not influence correctness.
2332 TargetTransformInfo &TTI =
2333 P->getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
2335 for (size_t i = 0; i < records.size(); i++) {
2336 struct PartiallyConstructedSafepointRecord &info = records[i];
2337 CallSite &CS = toUpdate[i];
2339 rematerializeLiveValues(CS, info, TTI);
2342 // Now run through and replace the existing statepoints with new ones with
2343 // the live variables listed. We do not yet update uses of the values being
2344 // relocated. We have references to live variables that need to
2345 // survive to the last iteration of this loop. (By construction, the
2346 // previous statepoint can not be a live variable, thus we can and remove
2347 // the old statepoint calls as we go.)
2348 for (size_t i = 0; i < records.size(); i++) {
2349 struct PartiallyConstructedSafepointRecord &info = records[i];
2350 CallSite &CS = toUpdate[i];
2351 makeStatepointExplicit(DT, CS, P, info);
2353 toUpdate.clear(); // prevent accident use of invalid CallSites
2355 // Do all the fixups of the original live variables to their relocated selves
2356 SmallVector<Value *, 128> live;
2357 for (size_t i = 0; i < records.size(); i++) {
2358 struct PartiallyConstructedSafepointRecord &info = records[i];
2359 // We can't simply save the live set from the original insertion. One of
2360 // the live values might be the result of a call which needs a safepoint.
2361 // That Value* no longer exists and we need to use the new gc_result.
2362 // Thankfully, the liveset is embedded in the statepoint (and updated), so
2363 // we just grab that.
2364 Statepoint statepoint(info.StatepointToken);
2365 live.insert(live.end(), statepoint.gc_args_begin(),
2366 statepoint.gc_args_end());
2368 // Do some basic sanity checks on our liveness results before performing
2369 // relocation. Relocation can and will turn mistakes in liveness results
2370 // into non-sensical code which is must harder to debug.
2371 // TODO: It would be nice to test consistency as well
2372 assert(DT.isReachableFromEntry(info.StatepointToken->getParent()) &&
2373 "statepoint must be reachable or liveness is meaningless");
2374 for (Value *V : statepoint.gc_args()) {
2375 if (!isa<Instruction>(V))
2376 // Non-instruction values trivial dominate all possible uses
2378 auto LiveInst = cast<Instruction>(V);
2379 assert(DT.isReachableFromEntry(LiveInst->getParent()) &&
2380 "unreachable values should never be live");
2381 assert(DT.dominates(LiveInst, info.StatepointToken) &&
2382 "basic SSA liveness expectation violated by liveness analysis");
2386 unique_unsorted(live);
2390 for (auto ptr : live) {
2391 assert(isGCPointerType(ptr->getType()) && "must be a gc pointer type");
2395 relocationViaAlloca(F, DT, live, records);
2396 return !records.empty();
2399 // Handles both return values and arguments for Functions and CallSites.
2400 template <typename AttrHolder>
2401 static void RemoveDerefAttrAtIndex(LLVMContext &Ctx, AttrHolder &AH,
2404 if (AH.getDereferenceableBytes(Index))
2405 R.addAttribute(Attribute::get(Ctx, Attribute::Dereferenceable,
2406 AH.getDereferenceableBytes(Index)));
2407 if (AH.getDereferenceableOrNullBytes(Index))
2408 R.addAttribute(Attribute::get(Ctx, Attribute::DereferenceableOrNull,
2409 AH.getDereferenceableOrNullBytes(Index)));
2412 AH.setAttributes(AH.getAttributes().removeAttributes(
2413 Ctx, Index, AttributeSet::get(Ctx, Index, R)));
2417 RewriteStatepointsForGC::stripDereferenceabilityInfoFromPrototype(Function &F) {
2418 LLVMContext &Ctx = F.getContext();
2420 for (Argument &A : F.args())
2421 if (isa<PointerType>(A.getType()))
2422 RemoveDerefAttrAtIndex(Ctx, F, A.getArgNo() + 1);
2424 if (isa<PointerType>(F.getReturnType()))
2425 RemoveDerefAttrAtIndex(Ctx, F, AttributeSet::ReturnIndex);
2428 void RewriteStatepointsForGC::stripDereferenceabilityInfoFromBody(Function &F) {
2432 LLVMContext &Ctx = F.getContext();
2433 MDBuilder Builder(Ctx);
2435 for (Instruction &I : instructions(F)) {
2436 if (const MDNode *MD = I.getMetadata(LLVMContext::MD_tbaa)) {
2437 assert(MD->getNumOperands() < 5 && "unrecognized metadata shape!");
2438 bool IsImmutableTBAA =
2439 MD->getNumOperands() == 4 &&
2440 mdconst::extract<ConstantInt>(MD->getOperand(3))->getValue() == 1;
2442 if (!IsImmutableTBAA)
2443 continue; // no work to do, MD_tbaa is already marked mutable
2445 MDNode *Base = cast<MDNode>(MD->getOperand(0));
2446 MDNode *Access = cast<MDNode>(MD->getOperand(1));
2448 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue();
2450 MDNode *MutableTBAA =
2451 Builder.createTBAAStructTagNode(Base, Access, Offset);
2452 I.setMetadata(LLVMContext::MD_tbaa, MutableTBAA);
2455 if (CallSite CS = CallSite(&I)) {
2456 for (int i = 0, e = CS.arg_size(); i != e; i++)
2457 if (isa<PointerType>(CS.getArgument(i)->getType()))
2458 RemoveDerefAttrAtIndex(Ctx, CS, i + 1);
2459 if (isa<PointerType>(CS.getType()))
2460 RemoveDerefAttrAtIndex(Ctx, CS, AttributeSet::ReturnIndex);
2465 /// Returns true if this function should be rewritten by this pass. The main
2466 /// point of this function is as an extension point for custom logic.
2467 static bool shouldRewriteStatepointsIn(Function &F) {
2468 // TODO: This should check the GCStrategy
2470 const char *FunctionGCName = F.getGC();
2471 const StringRef StatepointExampleName("statepoint-example");
2472 const StringRef CoreCLRName("coreclr");
2473 return (StatepointExampleName == FunctionGCName) ||
2474 (CoreCLRName == FunctionGCName);
2479 void RewriteStatepointsForGC::stripDereferenceabilityInfo(Module &M) {
2481 assert(std::any_of(M.begin(), M.end(), shouldRewriteStatepointsIn) &&
2485 for (Function &F : M)
2486 stripDereferenceabilityInfoFromPrototype(F);
2488 for (Function &F : M)
2489 stripDereferenceabilityInfoFromBody(F);
2492 bool RewriteStatepointsForGC::runOnFunction(Function &F) {
2493 // Nothing to do for declarations.
2494 if (F.isDeclaration() || F.empty())
2497 // Policy choice says not to rewrite - the most common reason is that we're
2498 // compiling code without a GCStrategy.
2499 if (!shouldRewriteStatepointsIn(F))
2502 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
2504 // Gather all the statepoints which need rewritten. Be careful to only
2505 // consider those in reachable code since we need to ask dominance queries
2506 // when rewriting. We'll delete the unreachable ones in a moment.
2507 SmallVector<CallSite, 64> ParsePointNeeded;
2508 bool HasUnreachableStatepoint = false;
2509 for (Instruction &I : instructions(F)) {
2510 // TODO: only the ones with the flag set!
2511 if (isStatepoint(I)) {
2512 if (DT.isReachableFromEntry(I.getParent()))
2513 ParsePointNeeded.push_back(CallSite(&I));
2515 HasUnreachableStatepoint = true;
2519 bool MadeChange = false;
2521 // Delete any unreachable statepoints so that we don't have unrewritten
2522 // statepoints surviving this pass. This makes testing easier and the
2523 // resulting IR less confusing to human readers. Rather than be fancy, we
2524 // just reuse a utility function which removes the unreachable blocks.
2525 if (HasUnreachableStatepoint)
2526 MadeChange |= removeUnreachableBlocks(F);
2528 // Return early if no work to do.
2529 if (ParsePointNeeded.empty())
2532 // As a prepass, go ahead and aggressively destroy single entry phi nodes.
2533 // These are created by LCSSA. They have the effect of increasing the size
2534 // of liveness sets for no good reason. It may be harder to do this post
2535 // insertion since relocations and base phis can confuse things.
2536 for (BasicBlock &BB : F)
2537 if (BB.getUniquePredecessor()) {
2539 FoldSingleEntryPHINodes(&BB);
2542 // Before we start introducing relocations, we want to tweak the IR a bit to
2543 // avoid unfortunate code generation effects. The main example is that we
2544 // want to try to make sure the comparison feeding a branch is after any
2545 // safepoints. Otherwise, we end up with a comparison of pre-relocation
2546 // values feeding a branch after relocation. This is semantically correct,
2547 // but results in extra register pressure since both the pre-relocation and
2548 // post-relocation copies must be available in registers. For code without
2549 // relocations this is handled elsewhere, but teaching the scheduler to
2550 // reverse the transform we're about to do would be slightly complex.
2551 // Note: This may extend the live range of the inputs to the icmp and thus
2552 // increase the liveset of any statepoint we move over. This is profitable
2553 // as long as all statepoints are in rare blocks. If we had in-register
2554 // lowering for live values this would be a much safer transform.
2555 auto getConditionInst = [](TerminatorInst *TI) -> Instruction* {
2556 if (auto *BI = dyn_cast<BranchInst>(TI))
2557 if (BI->isConditional())
2558 return dyn_cast<Instruction>(BI->getCondition());
2559 // TODO: Extend this to handle switches
2562 for (BasicBlock &BB : F) {
2563 TerminatorInst *TI = BB.getTerminator();
2564 if (auto *Cond = getConditionInst(TI))
2565 // TODO: Handle more than just ICmps here. We should be able to move
2566 // most instructions without side effects or memory access.
2567 if (isa<ICmpInst>(Cond) && Cond->hasOneUse()) {
2569 Cond->moveBefore(TI);
2573 MadeChange |= insertParsePoints(F, DT, this, ParsePointNeeded);
2577 // liveness computation via standard dataflow
2578 // -------------------------------------------------------------------
2580 // TODO: Consider using bitvectors for liveness, the set of potentially
2581 // interesting values should be small and easy to pre-compute.
2583 /// Compute the live-in set for the location rbegin starting from
2584 /// the live-out set of the basic block
2585 static void computeLiveInValues(BasicBlock::reverse_iterator rbegin,
2586 BasicBlock::reverse_iterator rend,
2587 DenseSet<Value *> &LiveTmp) {
2589 for (BasicBlock::reverse_iterator ritr = rbegin; ritr != rend; ritr++) {
2590 Instruction *I = &*ritr;
2592 // KILL/Def - Remove this definition from LiveIn
2595 // Don't consider *uses* in PHI nodes, we handle their contribution to
2596 // predecessor blocks when we seed the LiveOut sets
2597 if (isa<PHINode>(I))
2600 // USE - Add to the LiveIn set for this instruction
2601 for (Value *V : I->operands()) {
2602 assert(!isUnhandledGCPointerType(V->getType()) &&
2603 "support for FCA unimplemented");
2604 if (isHandledGCPointerType(V->getType()) && !isa<Constant>(V)) {
2605 // The choice to exclude all things constant here is slightly subtle.
2606 // There are two independent reasons:
2607 // - We assume that things which are constant (from LLVM's definition)
2608 // do not move at runtime. For example, the address of a global
2609 // variable is fixed, even though it's contents may not be.
2610 // - Second, we can't disallow arbitrary inttoptr constants even
2611 // if the language frontend does. Optimization passes are free to
2612 // locally exploit facts without respect to global reachability. This
2613 // can create sections of code which are dynamically unreachable and
2614 // contain just about anything. (see constants.ll in tests)
2621 static void computeLiveOutSeed(BasicBlock *BB, DenseSet<Value *> &LiveTmp) {
2623 for (BasicBlock *Succ : successors(BB)) {
2624 const BasicBlock::iterator E(Succ->getFirstNonPHI());
2625 for (BasicBlock::iterator I = Succ->begin(); I != E; I++) {
2626 PHINode *Phi = cast<PHINode>(&*I);
2627 Value *V = Phi->getIncomingValueForBlock(BB);
2628 assert(!isUnhandledGCPointerType(V->getType()) &&
2629 "support for FCA unimplemented");
2630 if (isHandledGCPointerType(V->getType()) && !isa<Constant>(V)) {
2637 static DenseSet<Value *> computeKillSet(BasicBlock *BB) {
2638 DenseSet<Value *> KillSet;
2639 for (Instruction &I : *BB)
2640 if (isHandledGCPointerType(I.getType()))
2646 /// Check that the items in 'Live' dominate 'TI'. This is used as a basic
2647 /// sanity check for the liveness computation.
2648 static void checkBasicSSA(DominatorTree &DT, DenseSet<Value *> &Live,
2649 TerminatorInst *TI, bool TermOkay = false) {
2650 for (Value *V : Live) {
2651 if (auto *I = dyn_cast<Instruction>(V)) {
2652 // The terminator can be a member of the LiveOut set. LLVM's definition
2653 // of instruction dominance states that V does not dominate itself. As
2654 // such, we need to special case this to allow it.
2655 if (TermOkay && TI == I)
2657 assert(DT.dominates(I, TI) &&
2658 "basic SSA liveness expectation violated by liveness analysis");
2663 /// Check that all the liveness sets used during the computation of liveness
2664 /// obey basic SSA properties. This is useful for finding cases where we miss
2666 static void checkBasicSSA(DominatorTree &DT, GCPtrLivenessData &Data,
2668 checkBasicSSA(DT, Data.LiveSet[&BB], BB.getTerminator());
2669 checkBasicSSA(DT, Data.LiveOut[&BB], BB.getTerminator(), true);
2670 checkBasicSSA(DT, Data.LiveIn[&BB], BB.getTerminator());
2674 static void computeLiveInValues(DominatorTree &DT, Function &F,
2675 GCPtrLivenessData &Data) {
2677 SmallSetVector<BasicBlock *, 200> Worklist;
2678 auto AddPredsToWorklist = [&](BasicBlock *BB) {
2679 // We use a SetVector so that we don't have duplicates in the worklist.
2680 Worklist.insert(pred_begin(BB), pred_end(BB));
2682 auto NextItem = [&]() {
2683 BasicBlock *BB = Worklist.back();
2684 Worklist.pop_back();
2688 // Seed the liveness for each individual block
2689 for (BasicBlock &BB : F) {
2690 Data.KillSet[&BB] = computeKillSet(&BB);
2691 Data.LiveSet[&BB].clear();
2692 computeLiveInValues(BB.rbegin(), BB.rend(), Data.LiveSet[&BB]);
2695 for (Value *Kill : Data.KillSet[&BB])
2696 assert(!Data.LiveSet[&BB].count(Kill) && "live set contains kill");
2699 Data.LiveOut[&BB] = DenseSet<Value *>();
2700 computeLiveOutSeed(&BB, Data.LiveOut[&BB]);
2701 Data.LiveIn[&BB] = Data.LiveSet[&BB];
2702 set_union(Data.LiveIn[&BB], Data.LiveOut[&BB]);
2703 set_subtract(Data.LiveIn[&BB], Data.KillSet[&BB]);
2704 if (!Data.LiveIn[&BB].empty())
2705 AddPredsToWorklist(&BB);
2708 // Propagate that liveness until stable
2709 while (!Worklist.empty()) {
2710 BasicBlock *BB = NextItem();
2712 // Compute our new liveout set, then exit early if it hasn't changed
2713 // despite the contribution of our successor.
2714 DenseSet<Value *> LiveOut = Data.LiveOut[BB];
2715 const auto OldLiveOutSize = LiveOut.size();
2716 for (BasicBlock *Succ : successors(BB)) {
2717 assert(Data.LiveIn.count(Succ));
2718 set_union(LiveOut, Data.LiveIn[Succ]);
2720 // assert OutLiveOut is a subset of LiveOut
2721 if (OldLiveOutSize == LiveOut.size()) {
2722 // If the sets are the same size, then we didn't actually add anything
2723 // when unioning our successors LiveIn Thus, the LiveIn of this block
2727 Data.LiveOut[BB] = LiveOut;
2729 // Apply the effects of this basic block
2730 DenseSet<Value *> LiveTmp = LiveOut;
2731 set_union(LiveTmp, Data.LiveSet[BB]);
2732 set_subtract(LiveTmp, Data.KillSet[BB]);
2734 assert(Data.LiveIn.count(BB));
2735 const DenseSet<Value *> &OldLiveIn = Data.LiveIn[BB];
2736 // assert: OldLiveIn is a subset of LiveTmp
2737 if (OldLiveIn.size() != LiveTmp.size()) {
2738 Data.LiveIn[BB] = LiveTmp;
2739 AddPredsToWorklist(BB);
2741 } // while( !worklist.empty() )
2744 // Sanity check our output against SSA properties. This helps catch any
2745 // missing kills during the above iteration.
2746 for (BasicBlock &BB : F) {
2747 checkBasicSSA(DT, Data, BB);
2752 static void findLiveSetAtInst(Instruction *Inst, GCPtrLivenessData &Data,
2753 StatepointLiveSetTy &Out) {
2755 BasicBlock *BB = Inst->getParent();
2757 // Note: The copy is intentional and required
2758 assert(Data.LiveOut.count(BB));
2759 DenseSet<Value *> LiveOut = Data.LiveOut[BB];
2761 // We want to handle the statepoint itself oddly. It's
2762 // call result is not live (normal), nor are it's arguments
2763 // (unless they're used again later). This adjustment is
2764 // specifically what we need to relocate
2765 BasicBlock::reverse_iterator rend(Inst);
2766 computeLiveInValues(BB->rbegin(), rend, LiveOut);
2767 LiveOut.erase(Inst);
2768 Out.insert(LiveOut.begin(), LiveOut.end());
2771 static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData,
2773 PartiallyConstructedSafepointRecord &Info) {
2774 Instruction *Inst = CS.getInstruction();
2775 StatepointLiveSetTy Updated;
2776 findLiveSetAtInst(Inst, RevisedLivenessData, Updated);
2779 DenseSet<Value *> Bases;
2780 for (auto KVPair : Info.PointerToBase) {
2781 Bases.insert(KVPair.second);
2784 // We may have base pointers which are now live that weren't before. We need
2785 // to update the PointerToBase structure to reflect this.
2786 for (auto V : Updated)
2787 if (!Info.PointerToBase.count(V)) {
2788 assert(Bases.count(V) && "can't find base for unexpected live value");
2789 Info.PointerToBase[V] = V;
2794 for (auto V : Updated) {
2795 assert(Info.PointerToBase.count(V) &&
2796 "must be able to find base for live value");
2800 // Remove any stale base mappings - this can happen since our liveness is
2801 // more precise then the one inherent in the base pointer analysis
2802 DenseSet<Value *> ToErase;
2803 for (auto KVPair : Info.PointerToBase)
2804 if (!Updated.count(KVPair.first))
2805 ToErase.insert(KVPair.first);
2806 for (auto V : ToErase)
2807 Info.PointerToBase.erase(V);
2810 for (auto KVPair : Info.PointerToBase)
2811 assert(Updated.count(KVPair.first) && "record for non-live value");
2814 Info.liveset = Updated;