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/TargetTransformInfo.h"
18 #include "llvm/ADT/SetOperations.h"
19 #include "llvm/ADT/Statistic.h"
20 #include "llvm/ADT/DenseSet.h"
21 #include "llvm/ADT/SetVector.h"
22 #include "llvm/ADT/StringRef.h"
23 #include "llvm/IR/BasicBlock.h"
24 #include "llvm/IR/CallSite.h"
25 #include "llvm/IR/Dominators.h"
26 #include "llvm/IR/Function.h"
27 #include "llvm/IR/IRBuilder.h"
28 #include "llvm/IR/InstIterator.h"
29 #include "llvm/IR/Instructions.h"
30 #include "llvm/IR/Intrinsics.h"
31 #include "llvm/IR/IntrinsicInst.h"
32 #include "llvm/IR/Module.h"
33 #include "llvm/IR/MDBuilder.h"
34 #include "llvm/IR/Statepoint.h"
35 #include "llvm/IR/Value.h"
36 #include "llvm/IR/Verifier.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/CommandLine.h"
39 #include "llvm/Transforms/Scalar.h"
40 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
41 #include "llvm/Transforms/Utils/Cloning.h"
42 #include "llvm/Transforms/Utils/Local.h"
43 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
45 #define DEBUG_TYPE "rewrite-statepoints-for-gc"
49 // Print tracing output
50 static cl::opt<bool> TraceLSP("trace-rewrite-statepoints", cl::Hidden,
53 // Print the liveset found at the insert location
54 static cl::opt<bool> PrintLiveSet("spp-print-liveset", cl::Hidden,
56 static cl::opt<bool> PrintLiveSetSize("spp-print-liveset-size", cl::Hidden,
58 // Print out the base pointers for debugging
59 static cl::opt<bool> PrintBasePointers("spp-print-base-pointers", cl::Hidden,
62 // Cost threshold measuring when it is profitable to rematerialize value instead
64 static cl::opt<unsigned>
65 RematerializationThreshold("spp-rematerialization-threshold", cl::Hidden,
69 static bool ClobberNonLive = true;
71 static bool ClobberNonLive = false;
73 static cl::opt<bool, true> ClobberNonLiveOverride("rs4gc-clobber-non-live",
74 cl::location(ClobberNonLive),
78 struct RewriteStatepointsForGC : public ModulePass {
79 static char ID; // Pass identification, replacement for typeid
81 RewriteStatepointsForGC() : ModulePass(ID) {
82 initializeRewriteStatepointsForGCPass(*PassRegistry::getPassRegistry());
84 bool runOnFunction(Function &F);
85 bool runOnModule(Module &M) override {
88 Changed |= runOnFunction(F);
91 // stripDereferenceabilityInfo asserts that shouldRewriteStatepointsIn
92 // returns true for at least one function in the module. Since at least
93 // one function changed, we know that the precondition is satisfied.
94 stripDereferenceabilityInfo(M);
100 void getAnalysisUsage(AnalysisUsage &AU) const override {
101 // We add and rewrite a bunch of instructions, but don't really do much
102 // else. We could in theory preserve a lot more analyses here.
103 AU.addRequired<DominatorTreeWrapperPass>();
104 AU.addRequired<TargetTransformInfoWrapperPass>();
107 /// The IR fed into RewriteStatepointsForGC may have had attributes implying
108 /// dereferenceability that are no longer valid/correct after
109 /// RewriteStatepointsForGC has run. This is because semantically, after
110 /// RewriteStatepointsForGC runs, all calls to gc.statepoint "free" the entire
111 /// heap. stripDereferenceabilityInfo (conservatively) restores correctness
112 /// by erasing all attributes in the module that externally imply
113 /// dereferenceability.
115 void stripDereferenceabilityInfo(Module &M);
117 // Helpers for stripDereferenceabilityInfo
118 void stripDereferenceabilityInfoFromBody(Function &F);
119 void stripDereferenceabilityInfoFromPrototype(Function &F);
123 char RewriteStatepointsForGC::ID = 0;
125 ModulePass *llvm::createRewriteStatepointsForGCPass() {
126 return new RewriteStatepointsForGC();
129 INITIALIZE_PASS_BEGIN(RewriteStatepointsForGC, "rewrite-statepoints-for-gc",
130 "Make relocations explicit at statepoints", false, false)
131 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
132 INITIALIZE_PASS_END(RewriteStatepointsForGC, "rewrite-statepoints-for-gc",
133 "Make relocations explicit at statepoints", false, false)
136 struct GCPtrLivenessData {
137 /// Values defined in this block.
138 DenseMap<BasicBlock *, DenseSet<Value *>> KillSet;
139 /// Values used in this block (and thus live); does not included values
140 /// killed within this block.
141 DenseMap<BasicBlock *, DenseSet<Value *>> LiveSet;
143 /// Values live into this basic block (i.e. used by any
144 /// instruction in this basic block or ones reachable from here)
145 DenseMap<BasicBlock *, DenseSet<Value *>> LiveIn;
147 /// Values live out of this basic block (i.e. live into
148 /// any successor block)
149 DenseMap<BasicBlock *, DenseSet<Value *>> LiveOut;
152 // The type of the internal cache used inside the findBasePointers family
153 // of functions. From the callers perspective, this is an opaque type and
154 // should not be inspected.
156 // In the actual implementation this caches two relations:
157 // - The base relation itself (i.e. this pointer is based on that one)
158 // - The base defining value relation (i.e. before base_phi insertion)
159 // Generally, after the execution of a full findBasePointer call, only the
160 // base relation will remain. Internally, we add a mixture of the two
161 // types, then update all the second type to the first type
162 typedef DenseMap<Value *, Value *> DefiningValueMapTy;
163 typedef DenseSet<llvm::Value *> StatepointLiveSetTy;
164 typedef DenseMap<Instruction *, Value *> RematerializedValueMapTy;
166 struct PartiallyConstructedSafepointRecord {
167 /// The set of values known to be live accross this safepoint
168 StatepointLiveSetTy liveset;
170 /// Mapping from live pointers to a base-defining-value
171 DenseMap<llvm::Value *, llvm::Value *> PointerToBase;
173 /// The *new* gc.statepoint instruction itself. This produces the token
174 /// that normal path gc.relocates and the gc.result are tied to.
175 Instruction *StatepointToken;
177 /// Instruction to which exceptional gc relocates are attached
178 /// Makes it easier to iterate through them during relocationViaAlloca.
179 Instruction *UnwindToken;
181 /// Record live values we are rematerialized instead of relocating.
182 /// They are not included into 'liveset' field.
183 /// Maps rematerialized copy to it's original value.
184 RematerializedValueMapTy RematerializedValues;
188 /// Compute the live-in set for every basic block in the function
189 static void computeLiveInValues(DominatorTree &DT, Function &F,
190 GCPtrLivenessData &Data);
192 /// Given results from the dataflow liveness computation, find the set of live
193 /// Values at a particular instruction.
194 static void findLiveSetAtInst(Instruction *inst, GCPtrLivenessData &Data,
195 StatepointLiveSetTy &out);
197 // TODO: Once we can get to the GCStrategy, this becomes
198 // Optional<bool> isGCManagedPointer(const Value *V) const override {
200 static bool isGCPointerType(const Type *T) {
201 if (const PointerType *PT = dyn_cast<PointerType>(T))
202 // For the sake of this example GC, we arbitrarily pick addrspace(1) as our
203 // GC managed heap. We know that a pointer into this heap needs to be
204 // updated and that no other pointer does.
205 return (1 == PT->getAddressSpace());
209 // Return true if this type is one which a) is a gc pointer or contains a GC
210 // pointer and b) is of a type this code expects to encounter as a live value.
211 // (The insertion code will assert that a type which matches (a) and not (b)
212 // is not encountered.)
213 static bool isHandledGCPointerType(Type *T) {
214 // We fully support gc pointers
215 if (isGCPointerType(T))
217 // We partially support vectors of gc pointers. The code will assert if it
218 // can't handle something.
219 if (auto VT = dyn_cast<VectorType>(T))
220 if (isGCPointerType(VT->getElementType()))
226 /// Returns true if this type contains a gc pointer whether we know how to
227 /// handle that type or not.
228 static bool containsGCPtrType(Type *Ty) {
229 if (isGCPointerType(Ty))
231 if (VectorType *VT = dyn_cast<VectorType>(Ty))
232 return isGCPointerType(VT->getScalarType());
233 if (ArrayType *AT = dyn_cast<ArrayType>(Ty))
234 return containsGCPtrType(AT->getElementType());
235 if (StructType *ST = dyn_cast<StructType>(Ty))
237 ST->subtypes().begin(), ST->subtypes().end(),
238 [](Type *SubType) { return containsGCPtrType(SubType); });
242 // Returns true if this is a type which a) is a gc pointer or contains a GC
243 // pointer and b) is of a type which the code doesn't expect (i.e. first class
244 // aggregates). Used to trip assertions.
245 static bool isUnhandledGCPointerType(Type *Ty) {
246 return containsGCPtrType(Ty) && !isHandledGCPointerType(Ty);
250 static bool order_by_name(llvm::Value *a, llvm::Value *b) {
251 if (a->hasName() && b->hasName()) {
252 return -1 == a->getName().compare(b->getName());
253 } else if (a->hasName() && !b->hasName()) {
255 } else if (!a->hasName() && b->hasName()) {
258 // Better than nothing, but not stable
263 // Conservatively identifies any definitions which might be live at the
264 // given instruction. The analysis is performed immediately before the
265 // given instruction. Values defined by that instruction are not considered
266 // live. Values used by that instruction are considered live.
267 static void analyzeParsePointLiveness(
268 DominatorTree &DT, GCPtrLivenessData &OriginalLivenessData,
269 const CallSite &CS, PartiallyConstructedSafepointRecord &result) {
270 Instruction *inst = CS.getInstruction();
272 StatepointLiveSetTy liveset;
273 findLiveSetAtInst(inst, OriginalLivenessData, liveset);
276 // Note: This output is used by several of the test cases
277 // The order of elemtns in a set is not stable, put them in a vec and sort
279 SmallVector<Value *, 64> temp;
280 temp.insert(temp.end(), liveset.begin(), liveset.end());
281 std::sort(temp.begin(), temp.end(), order_by_name);
282 errs() << "Live Variables:\n";
283 for (Value *V : temp) {
284 errs() << " " << V->getName(); // no newline
288 if (PrintLiveSetSize) {
289 errs() << "Safepoint For: " << CS.getCalledValue()->getName() << "\n";
290 errs() << "Number live values: " << liveset.size() << "\n";
292 result.liveset = liveset;
295 static Value *findBaseDefiningValue(Value *I);
297 /// If we can trivially determine that the index specified in the given vector
298 /// is a base pointer, return it. In cases where the entire vector is known to
299 /// consist of base pointers, the entire vector will be returned. This
300 /// indicates that the relevant extractelement is a valid base pointer and
301 /// should be used directly.
302 static Value *findBaseOfVector(Value *I, Value *Index) {
303 assert(I->getType()->isVectorTy() &&
304 cast<VectorType>(I->getType())->getElementType()->isPointerTy() &&
305 "Illegal to ask for the base pointer of a non-pointer type");
307 // Each case parallels findBaseDefiningValue below, see that code for
308 // detailed motivation.
310 if (isa<Argument>(I))
311 // An incoming argument to the function is a base pointer
314 // We shouldn't see the address of a global as a vector value?
315 assert(!isa<GlobalVariable>(I) &&
316 "unexpected global variable found in base of vector");
318 // inlining could possibly introduce phi node that contains
319 // undef if callee has multiple returns
320 if (isa<UndefValue>(I))
321 // utterly meaningless, but useful for dealing with partially optimized
325 // Due to inheritance, this must be _after_ the global variable and undef
327 if (Constant *Con = dyn_cast<Constant>(I)) {
328 assert(!isa<GlobalVariable>(I) && !isa<UndefValue>(I) &&
329 "order of checks wrong!");
330 assert(Con->isNullValue() && "null is the only case which makes sense");
334 if (isa<LoadInst>(I))
337 // For an insert element, we might be able to look through it if we know
338 // something about the indexes, but if the indices are arbitrary values, we
339 // can't without much more extensive scalarization.
340 if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(I)) {
341 Value *InsertIndex = IEI->getOperand(2);
342 // This index is inserting the value, look for it's base
343 if (InsertIndex == Index)
344 return findBaseDefiningValue(IEI->getOperand(1));
345 // Both constant, and can't be equal per above. This insert is definitely
346 // not relevant, look back at the rest of the vector and keep trying.
347 if (isa<ConstantInt>(Index) && isa<ConstantInt>(InsertIndex))
348 return findBaseOfVector(IEI->getOperand(0), Index);
351 // Note: This code is currently rather incomplete. We are essentially only
352 // handling cases where the vector element is trivially a base pointer. We
353 // need to update the entire base pointer construction algorithm to know how
354 // to track vector elements and potentially scalarize, but the case which
355 // would motivate the work hasn't shown up in real workloads yet.
356 llvm_unreachable("no base found for vector element");
359 /// Helper function for findBasePointer - Will return a value which either a)
360 /// defines the base pointer for the input or b) blocks the simple search
361 /// (i.e. a PHI or Select of two derived pointers)
362 static Value *findBaseDefiningValue(Value *I) {
363 assert(I->getType()->isPointerTy() &&
364 "Illegal to ask for the base pointer of a non-pointer type");
366 // This case is a bit of a hack - it only handles extracts from vectors which
367 // trivially contain only base pointers or cases where we can directly match
368 // the index of the original extract element to an insertion into the vector.
369 // See note inside the function for how to improve this.
370 if (auto *EEI = dyn_cast<ExtractElementInst>(I)) {
371 Value *VectorOperand = EEI->getVectorOperand();
372 Value *Index = EEI->getIndexOperand();
373 Value *VectorBase = findBaseOfVector(VectorOperand, Index);
374 // If the result returned is a vector, we know the entire vector must
375 // contain base pointers. In that case, the extractelement is a valid base
377 if (VectorBase->getType()->isVectorTy())
379 // Otherwise, we needed to look through the vector to find the base for
380 // this particular element.
381 assert(VectorBase->getType()->isPointerTy());
385 if (isa<Argument>(I))
386 // An incoming argument to the function is a base pointer
387 // We should have never reached here if this argument isn't an gc value
390 if (isa<GlobalVariable>(I))
394 // inlining could possibly introduce phi node that contains
395 // undef if callee has multiple returns
396 if (isa<UndefValue>(I))
397 // utterly meaningless, but useful for dealing with
398 // partially optimized code.
401 // Due to inheritance, this must be _after_ the global variable and undef
403 if (Constant *Con = dyn_cast<Constant>(I)) {
404 assert(!isa<GlobalVariable>(I) && !isa<UndefValue>(I) &&
405 "order of checks wrong!");
406 // Note: Finding a constant base for something marked for relocation
407 // doesn't really make sense. The most likely case is either a) some
408 // screwed up the address space usage or b) your validating against
409 // compiled C++ code w/o the proper separation. The only real exception
410 // is a null pointer. You could have generic code written to index of
411 // off a potentially null value and have proven it null. We also use
412 // null pointers in dead paths of relocation phis (which we might later
413 // want to find a base pointer for).
414 assert(isa<ConstantPointerNull>(Con) &&
415 "null is the only case which makes sense");
419 if (CastInst *CI = dyn_cast<CastInst>(I)) {
420 Value *Def = CI->stripPointerCasts();
421 // If we find a cast instruction here, it means we've found a cast which is
422 // not simply a pointer cast (i.e. an inttoptr). We don't know how to
423 // handle int->ptr conversion.
424 assert(!isa<CastInst>(Def) && "shouldn't find another cast here");
425 return findBaseDefiningValue(Def);
428 if (isa<LoadInst>(I))
429 return I; // The value loaded is an gc base itself
431 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I))
432 // The base of this GEP is the base
433 return findBaseDefiningValue(GEP->getPointerOperand());
435 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
436 switch (II->getIntrinsicID()) {
437 case Intrinsic::experimental_gc_result_ptr:
439 // fall through to general call handling
441 case Intrinsic::experimental_gc_statepoint:
442 case Intrinsic::experimental_gc_result_float:
443 case Intrinsic::experimental_gc_result_int:
444 llvm_unreachable("these don't produce pointers");
445 case Intrinsic::experimental_gc_relocate: {
446 // Rerunning safepoint insertion after safepoints are already
447 // inserted is not supported. It could probably be made to work,
448 // but why are you doing this? There's no good reason.
449 llvm_unreachable("repeat safepoint insertion is not supported");
451 case Intrinsic::gcroot:
452 // Currently, this mechanism hasn't been extended to work with gcroot.
453 // There's no reason it couldn't be, but I haven't thought about the
454 // implications much.
456 "interaction with the gcroot mechanism is not supported");
459 // We assume that functions in the source language only return base
460 // pointers. This should probably be generalized via attributes to support
461 // both source language and internal functions.
462 if (isa<CallInst>(I) || isa<InvokeInst>(I))
465 // I have absolutely no idea how to implement this part yet. It's not
466 // neccessarily hard, I just haven't really looked at it yet.
467 assert(!isa<LandingPadInst>(I) && "Landing Pad is unimplemented");
469 if (isa<AtomicCmpXchgInst>(I))
470 // A CAS is effectively a atomic store and load combined under a
471 // predicate. From the perspective of base pointers, we just treat it
475 assert(!isa<AtomicRMWInst>(I) && "Xchg handled above, all others are "
476 "binary ops which don't apply to pointers");
478 // The aggregate ops. Aggregates can either be in the heap or on the
479 // stack, but in either case, this is simply a field load. As a result,
480 // this is a defining definition of the base just like a load is.
481 if (isa<ExtractValueInst>(I))
484 // We should never see an insert vector since that would require we be
485 // tracing back a struct value not a pointer value.
486 assert(!isa<InsertValueInst>(I) &&
487 "Base pointer for a struct is meaningless");
489 // The last two cases here don't return a base pointer. Instead, they
490 // return a value which dynamically selects from amoung several base
491 // derived pointers (each with it's own base potentially). It's the job of
492 // the caller to resolve these.
493 assert((isa<SelectInst>(I) || isa<PHINode>(I)) &&
494 "missing instruction case in findBaseDefiningValing");
498 /// Returns the base defining value for this value.
499 static Value *findBaseDefiningValueCached(Value *I, DefiningValueMapTy &Cache) {
500 Value *&Cached = Cache[I];
502 Cached = findBaseDefiningValue(I);
504 assert(Cache[I] != nullptr);
507 dbgs() << "fBDV-cached: " << I->getName() << " -> " << Cached->getName()
513 /// Return a base pointer for this value if known. Otherwise, return it's
514 /// base defining value.
515 static Value *findBaseOrBDV(Value *I, DefiningValueMapTy &Cache) {
516 Value *Def = findBaseDefiningValueCached(I, Cache);
517 auto Found = Cache.find(Def);
518 if (Found != Cache.end()) {
519 // Either a base-of relation, or a self reference. Caller must check.
520 return Found->second;
522 // Only a BDV available
526 /// Given the result of a call to findBaseDefiningValue, or findBaseOrBDV,
527 /// is it known to be a base pointer? Or do we need to continue searching.
528 static bool isKnownBaseResult(Value *V) {
529 if (!isa<PHINode>(V) && !isa<SelectInst>(V)) {
530 // no recursion possible
533 if (isa<Instruction>(V) &&
534 cast<Instruction>(V)->getMetadata("is_base_value")) {
535 // This is a previously inserted base phi or select. We know
536 // that this is a base value.
540 // We need to keep searching
544 // TODO: find a better name for this
548 enum Status { Unknown, Base, Conflict };
550 PhiState(Status s, Value *b = nullptr) : status(s), base(b) {
551 assert(status != Base || b);
553 PhiState(Value *b) : status(Base), base(b) {}
554 PhiState() : status(Unknown), base(nullptr) {}
556 Status getStatus() const { return status; }
557 Value *getBase() const { return base; }
559 bool isBase() const { return getStatus() == Base; }
560 bool isUnknown() const { return getStatus() == Unknown; }
561 bool isConflict() const { return getStatus() == Conflict; }
563 bool operator==(const PhiState &other) const {
564 return base == other.base && status == other.status;
567 bool operator!=(const PhiState &other) const { return !(*this == other); }
570 errs() << status << " (" << base << " - "
571 << (base ? base->getName() : "nullptr") << "): ";
576 Value *base; // non null only if status == base
579 typedef DenseMap<Value *, PhiState> ConflictStateMapTy;
580 // Values of type PhiState form a lattice, and this is a helper
581 // class that implementes the meet operation. The meat of the meet
582 // operation is implemented in MeetPhiStates::pureMeet
583 class MeetPhiStates {
585 // phiStates is a mapping from PHINodes and SelectInst's to PhiStates.
586 explicit MeetPhiStates(const ConflictStateMapTy &phiStates)
587 : phiStates(phiStates) {}
589 // Destructively meet the current result with the base V. V can
590 // either be a merge instruction (SelectInst / PHINode), in which
591 // case its status is looked up in the phiStates map; or a regular
592 // SSA value, in which case it is assumed to be a base.
593 void meetWith(Value *V) {
594 PhiState otherState = getStateForBDV(V);
595 assert((MeetPhiStates::pureMeet(otherState, currentResult) ==
596 MeetPhiStates::pureMeet(currentResult, otherState)) &&
597 "math is wrong: meet does not commute!");
598 currentResult = MeetPhiStates::pureMeet(otherState, currentResult);
601 PhiState getResult() const { return currentResult; }
604 const ConflictStateMapTy &phiStates;
605 PhiState currentResult;
607 /// Return a phi state for a base defining value. We'll generate a new
608 /// base state for known bases and expect to find a cached state otherwise
609 PhiState getStateForBDV(Value *baseValue) {
610 if (isKnownBaseResult(baseValue)) {
611 return PhiState(baseValue);
613 return lookupFromMap(baseValue);
617 PhiState lookupFromMap(Value *V) {
618 auto I = phiStates.find(V);
619 assert(I != phiStates.end() && "lookup failed!");
623 static PhiState pureMeet(const PhiState &stateA, const PhiState &stateB) {
624 switch (stateA.getStatus()) {
625 case PhiState::Unknown:
629 assert(stateA.getBase() && "can't be null");
630 if (stateB.isUnknown())
633 if (stateB.isBase()) {
634 if (stateA.getBase() == stateB.getBase()) {
635 assert(stateA == stateB && "equality broken!");
638 return PhiState(PhiState::Conflict);
640 assert(stateB.isConflict() && "only three states!");
641 return PhiState(PhiState::Conflict);
643 case PhiState::Conflict:
646 llvm_unreachable("only three states!");
650 /// For a given value or instruction, figure out what base ptr it's derived
651 /// from. For gc objects, this is simply itself. On success, returns a value
652 /// which is the base pointer. (This is reliable and can be used for
653 /// relocation.) On failure, returns nullptr.
654 static Value *findBasePointer(Value *I, DefiningValueMapTy &cache) {
655 Value *def = findBaseOrBDV(I, cache);
657 if (isKnownBaseResult(def)) {
661 // Here's the rough algorithm:
662 // - For every SSA value, construct a mapping to either an actual base
663 // pointer or a PHI which obscures the base pointer.
664 // - Construct a mapping from PHI to unknown TOP state. Use an
665 // optimistic algorithm to propagate base pointer information. Lattice
670 // When algorithm terminates, all PHIs will either have a single concrete
671 // base or be in a conflict state.
672 // - For every conflict, insert a dummy PHI node without arguments. Add
673 // these to the base[Instruction] = BasePtr mapping. For every
674 // non-conflict, add the actual base.
675 // - For every conflict, add arguments for the base[a] of each input
678 // Note: A simpler form of this would be to add the conflict form of all
679 // PHIs without running the optimistic algorithm. This would be
680 // analougous to pessimistic data flow and would likely lead to an
681 // overall worse solution.
683 ConflictStateMapTy states;
684 states[def] = PhiState();
685 // Recursively fill in all phis & selects reachable from the initial one
686 // for which we don't already know a definite base value for
687 // TODO: This should be rewritten with a worklist
691 // Since we're adding elements to 'states' as we run, we can't keep
692 // iterators into the set.
693 SmallVector<Value *, 16> Keys;
694 Keys.reserve(states.size());
695 for (auto Pair : states) {
696 Value *V = Pair.first;
699 for (Value *v : Keys) {
700 assert(!isKnownBaseResult(v) && "why did it get added?");
701 if (PHINode *phi = dyn_cast<PHINode>(v)) {
702 assert(phi->getNumIncomingValues() > 0 &&
703 "zero input phis are illegal");
704 for (Value *InVal : phi->incoming_values()) {
705 Value *local = findBaseOrBDV(InVal, cache);
706 if (!isKnownBaseResult(local) && states.find(local) == states.end()) {
707 states[local] = PhiState();
711 } else if (SelectInst *sel = dyn_cast<SelectInst>(v)) {
712 Value *local = findBaseOrBDV(sel->getTrueValue(), cache);
713 if (!isKnownBaseResult(local) && states.find(local) == states.end()) {
714 states[local] = PhiState();
717 local = findBaseOrBDV(sel->getFalseValue(), cache);
718 if (!isKnownBaseResult(local) && states.find(local) == states.end()) {
719 states[local] = PhiState();
727 errs() << "States after initialization:\n";
728 for (auto Pair : states) {
729 Instruction *v = cast<Instruction>(Pair.first);
730 PhiState state = Pair.second;
736 // TODO: come back and revisit the state transitions around inputs which
737 // have reached conflict state. The current version seems too conservative.
739 bool progress = true;
742 size_t oldSize = states.size();
745 // We're only changing keys in this loop, thus safe to keep iterators
746 for (auto Pair : states) {
747 MeetPhiStates calculateMeet(states);
748 Value *v = Pair.first;
749 assert(!isKnownBaseResult(v) && "why did it get added?");
750 if (SelectInst *select = dyn_cast<SelectInst>(v)) {
751 calculateMeet.meetWith(findBaseOrBDV(select->getTrueValue(), cache));
752 calculateMeet.meetWith(findBaseOrBDV(select->getFalseValue(), cache));
754 for (Value *Val : cast<PHINode>(v)->incoming_values())
755 calculateMeet.meetWith(findBaseOrBDV(Val, cache));
757 PhiState oldState = states[v];
758 PhiState newState = calculateMeet.getResult();
759 if (oldState != newState) {
761 states[v] = newState;
765 assert(oldSize <= states.size());
766 assert(oldSize == states.size() || progress);
770 errs() << "States after meet iteration:\n";
771 for (auto Pair : states) {
772 Instruction *v = cast<Instruction>(Pair.first);
773 PhiState state = Pair.second;
779 // Insert Phis for all conflicts
780 // We want to keep naming deterministic in the loop that follows, so
781 // sort the keys before iteration. This is useful in allowing us to
782 // write stable tests. Note that there is no invalidation issue here.
783 SmallVector<Value *, 16> Keys;
784 Keys.reserve(states.size());
785 for (auto Pair : states) {
786 Value *V = Pair.first;
789 std::sort(Keys.begin(), Keys.end(), order_by_name);
790 // TODO: adjust naming patterns to avoid this order of iteration dependency
791 for (Value *V : Keys) {
792 Instruction *v = cast<Instruction>(V);
793 PhiState state = states[V];
794 assert(!isKnownBaseResult(v) && "why did it get added?");
795 assert(!state.isUnknown() && "Optimistic algorithm didn't complete!");
796 if (!state.isConflict())
799 if (isa<PHINode>(v)) {
801 std::distance(pred_begin(v->getParent()), pred_end(v->getParent()));
802 assert(num_preds > 0 && "how did we reach here");
803 PHINode *phi = PHINode::Create(v->getType(), num_preds, "base_phi", v);
804 // Add metadata marking this as a base value
805 auto *const_1 = ConstantInt::get(
807 v->getParent()->getParent()->getParent()->getContext()),
809 auto MDConst = ConstantAsMetadata::get(const_1);
810 MDNode *md = MDNode::get(
811 v->getParent()->getParent()->getParent()->getContext(), MDConst);
812 phi->setMetadata("is_base_value", md);
813 states[v] = PhiState(PhiState::Conflict, phi);
815 SelectInst *sel = cast<SelectInst>(v);
816 // The undef will be replaced later
817 UndefValue *undef = UndefValue::get(sel->getType());
818 SelectInst *basesel = SelectInst::Create(sel->getCondition(), undef,
819 undef, "base_select", sel);
820 // Add metadata marking this as a base value
821 auto *const_1 = ConstantInt::get(
823 v->getParent()->getParent()->getParent()->getContext()),
825 auto MDConst = ConstantAsMetadata::get(const_1);
826 MDNode *md = MDNode::get(
827 v->getParent()->getParent()->getParent()->getContext(), MDConst);
828 basesel->setMetadata("is_base_value", md);
829 states[v] = PhiState(PhiState::Conflict, basesel);
833 // Fixup all the inputs of the new PHIs
834 for (auto Pair : states) {
835 Instruction *v = cast<Instruction>(Pair.first);
836 PhiState state = Pair.second;
838 assert(!isKnownBaseResult(v) && "why did it get added?");
839 assert(!state.isUnknown() && "Optimistic algorithm didn't complete!");
840 if (!state.isConflict())
843 if (PHINode *basephi = dyn_cast<PHINode>(state.getBase())) {
844 PHINode *phi = cast<PHINode>(v);
845 unsigned NumPHIValues = phi->getNumIncomingValues();
846 for (unsigned i = 0; i < NumPHIValues; i++) {
847 Value *InVal = phi->getIncomingValue(i);
848 BasicBlock *InBB = phi->getIncomingBlock(i);
850 // If we've already seen InBB, add the same incoming value
851 // we added for it earlier. The IR verifier requires phi
852 // nodes with multiple entries from the same basic block
853 // to have the same incoming value for each of those
854 // entries. If we don't do this check here and basephi
855 // has a different type than base, we'll end up adding two
856 // bitcasts (and hence two distinct values) as incoming
857 // values for the same basic block.
859 int blockIndex = basephi->getBasicBlockIndex(InBB);
860 if (blockIndex != -1) {
861 Value *oldBase = basephi->getIncomingValue(blockIndex);
862 basephi->addIncoming(oldBase, InBB);
864 Value *base = findBaseOrBDV(InVal, cache);
865 if (!isKnownBaseResult(base)) {
866 // Either conflict or base.
867 assert(states.count(base));
868 base = states[base].getBase();
869 assert(base != nullptr && "unknown PhiState!");
872 // In essense this assert states: the only way two
873 // values incoming from the same basic block may be
874 // different is by being different bitcasts of the same
875 // value. A cleanup that remains TODO is changing
876 // findBaseOrBDV to return an llvm::Value of the correct
877 // type (and still remain pure). This will remove the
878 // need to add bitcasts.
879 assert(base->stripPointerCasts() == oldBase->stripPointerCasts() &&
880 "sanity -- findBaseOrBDV should be pure!");
885 // Find either the defining value for the PHI or the normal base for
887 Value *base = findBaseOrBDV(InVal, cache);
888 if (!isKnownBaseResult(base)) {
889 // Either conflict or base.
890 assert(states.count(base));
891 base = states[base].getBase();
892 assert(base != nullptr && "unknown PhiState!");
894 assert(base && "can't be null");
895 // Must use original input BB since base may not be Instruction
896 // The cast is needed since base traversal may strip away bitcasts
897 if (base->getType() != basephi->getType()) {
898 base = new BitCastInst(base, basephi->getType(), "cast",
899 InBB->getTerminator());
901 basephi->addIncoming(base, InBB);
903 assert(basephi->getNumIncomingValues() == NumPHIValues);
905 SelectInst *basesel = cast<SelectInst>(state.getBase());
906 SelectInst *sel = cast<SelectInst>(v);
907 // Operand 1 & 2 are true, false path respectively. TODO: refactor to
908 // something more safe and less hacky.
909 for (int i = 1; i <= 2; i++) {
910 Value *InVal = sel->getOperand(i);
911 // Find either the defining value for the PHI or the normal base for
913 Value *base = findBaseOrBDV(InVal, cache);
914 if (!isKnownBaseResult(base)) {
915 // Either conflict or base.
916 assert(states.count(base));
917 base = states[base].getBase();
918 assert(base != nullptr && "unknown PhiState!");
920 assert(base && "can't be null");
921 // Must use original input BB since base may not be Instruction
922 // The cast is needed since base traversal may strip away bitcasts
923 if (base->getType() != basesel->getType()) {
924 base = new BitCastInst(base, basesel->getType(), "cast", basesel);
926 basesel->setOperand(i, base);
931 // Cache all of our results so we can cheaply reuse them
932 // NOTE: This is actually two caches: one of the base defining value
933 // relation and one of the base pointer relation! FIXME
934 for (auto item : states) {
935 Value *v = item.first;
936 Value *base = item.second.getBase();
938 assert(!isKnownBaseResult(v) && "why did it get added?");
941 std::string fromstr =
942 cache.count(v) ? (cache[v]->hasName() ? cache[v]->getName() : "")
944 errs() << "Updating base value cache"
945 << " for: " << (v->hasName() ? v->getName() : "")
946 << " from: " << fromstr
947 << " to: " << (base->hasName() ? base->getName() : "") << "\n";
950 assert(isKnownBaseResult(base) &&
951 "must be something we 'know' is a base pointer");
952 if (cache.count(v)) {
953 // Once we transition from the BDV relation being store in the cache to
954 // the base relation being stored, it must be stable
955 assert((!isKnownBaseResult(cache[v]) || cache[v] == base) &&
956 "base relation should be stable");
960 assert(cache.find(def) != cache.end());
964 // For a set of live pointers (base and/or derived), identify the base
965 // pointer of the object which they are derived from. This routine will
966 // mutate the IR graph as needed to make the 'base' pointer live at the
967 // definition site of 'derived'. This ensures that any use of 'derived' can
968 // also use 'base'. This may involve the insertion of a number of
969 // additional PHI nodes.
971 // preconditions: live is a set of pointer type Values
973 // side effects: may insert PHI nodes into the existing CFG, will preserve
974 // CFG, will not remove or mutate any existing nodes
976 // post condition: PointerToBase contains one (derived, base) pair for every
977 // pointer in live. Note that derived can be equal to base if the original
978 // pointer was a base pointer.
980 findBasePointers(const StatepointLiveSetTy &live,
981 DenseMap<llvm::Value *, llvm::Value *> &PointerToBase,
982 DominatorTree *DT, DefiningValueMapTy &DVCache) {
983 // For the naming of values inserted to be deterministic - which makes for
984 // much cleaner and more stable tests - we need to assign an order to the
985 // live values. DenseSets do not provide a deterministic order across runs.
986 SmallVector<Value *, 64> Temp;
987 Temp.insert(Temp.end(), live.begin(), live.end());
988 std::sort(Temp.begin(), Temp.end(), order_by_name);
989 for (Value *ptr : Temp) {
990 Value *base = findBasePointer(ptr, DVCache);
991 assert(base && "failed to find base pointer");
992 PointerToBase[ptr] = base;
993 assert((!isa<Instruction>(base) || !isa<Instruction>(ptr) ||
994 DT->dominates(cast<Instruction>(base)->getParent(),
995 cast<Instruction>(ptr)->getParent())) &&
996 "The base we found better dominate the derived pointer");
998 // If you see this trip and like to live really dangerously, the code should
999 // be correct, just with idioms the verifier can't handle. You can try
1000 // disabling the verifier at your own substaintial risk.
1001 assert(!isa<ConstantPointerNull>(base) &&
1002 "the relocation code needs adjustment to handle the relocation of "
1003 "a null pointer constant without causing false positives in the "
1004 "safepoint ir verifier.");
1008 /// Find the required based pointers (and adjust the live set) for the given
1010 static void findBasePointers(DominatorTree &DT, DefiningValueMapTy &DVCache,
1012 PartiallyConstructedSafepointRecord &result) {
1013 DenseMap<llvm::Value *, llvm::Value *> PointerToBase;
1014 findBasePointers(result.liveset, PointerToBase, &DT, DVCache);
1016 if (PrintBasePointers) {
1017 // Note: Need to print these in a stable order since this is checked in
1019 errs() << "Base Pairs (w/o Relocation):\n";
1020 SmallVector<Value *, 64> Temp;
1021 Temp.reserve(PointerToBase.size());
1022 for (auto Pair : PointerToBase) {
1023 Temp.push_back(Pair.first);
1025 std::sort(Temp.begin(), Temp.end(), order_by_name);
1026 for (Value *Ptr : Temp) {
1027 Value *Base = PointerToBase[Ptr];
1028 errs() << " derived %" << Ptr->getName() << " base %" << Base->getName()
1033 result.PointerToBase = PointerToBase;
1036 /// Given an updated version of the dataflow liveness results, update the
1037 /// liveset and base pointer maps for the call site CS.
1038 static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData,
1040 PartiallyConstructedSafepointRecord &result);
1042 static void recomputeLiveInValues(
1043 Function &F, DominatorTree &DT, Pass *P, ArrayRef<CallSite> toUpdate,
1044 MutableArrayRef<struct PartiallyConstructedSafepointRecord> records) {
1045 // TODO-PERF: reuse the original liveness, then simply run the dataflow
1046 // again. The old values are still live and will help it stablize quickly.
1047 GCPtrLivenessData RevisedLivenessData;
1048 computeLiveInValues(DT, F, RevisedLivenessData);
1049 for (size_t i = 0; i < records.size(); i++) {
1050 struct PartiallyConstructedSafepointRecord &info = records[i];
1051 const CallSite &CS = toUpdate[i];
1052 recomputeLiveInValues(RevisedLivenessData, CS, info);
1056 // When inserting gc.relocate calls, we need to ensure there are no uses
1057 // of the original value between the gc.statepoint and the gc.relocate call.
1058 // One case which can arise is a phi node starting one of the successor blocks.
1059 // We also need to be able to insert the gc.relocates only on the path which
1060 // goes through the statepoint. We might need to split an edge to make this
1063 normalizeForInvokeSafepoint(BasicBlock *BB, BasicBlock *InvokeParent,
1064 DominatorTree &DT) {
1065 BasicBlock *Ret = BB;
1066 if (!BB->getUniquePredecessor()) {
1067 Ret = SplitBlockPredecessors(BB, InvokeParent, "", nullptr, &DT);
1070 // Now that 'ret' has unique predecessor we can safely remove all phi nodes
1072 FoldSingleEntryPHINodes(Ret);
1073 assert(!isa<PHINode>(Ret->begin()));
1075 // At this point, we can safely insert a gc.relocate as the first instruction
1076 // in Ret if needed.
1080 static int find_index(ArrayRef<Value *> livevec, Value *val) {
1081 auto itr = std::find(livevec.begin(), livevec.end(), val);
1082 assert(livevec.end() != itr);
1083 size_t index = std::distance(livevec.begin(), itr);
1084 assert(index < livevec.size());
1088 // Create new attribute set containing only attributes which can be transfered
1089 // from original call to the safepoint.
1090 static AttributeSet legalizeCallAttributes(AttributeSet AS) {
1093 for (unsigned Slot = 0; Slot < AS.getNumSlots(); Slot++) {
1094 unsigned index = AS.getSlotIndex(Slot);
1096 if (index == AttributeSet::ReturnIndex ||
1097 index == AttributeSet::FunctionIndex) {
1099 for (auto it = AS.begin(Slot), it_end = AS.end(Slot); it != it_end;
1101 Attribute attr = *it;
1103 // Do not allow certain attributes - just skip them
1104 // Safepoint can not be read only or read none.
1105 if (attr.hasAttribute(Attribute::ReadNone) ||
1106 attr.hasAttribute(Attribute::ReadOnly))
1109 ret = ret.addAttributes(
1110 AS.getContext(), index,
1111 AttributeSet::get(AS.getContext(), index, AttrBuilder(attr)));
1115 // Just skip parameter attributes for now
1121 /// Helper function to place all gc relocates necessary for the given
1124 /// liveVariables - list of variables to be relocated.
1125 /// liveStart - index of the first live variable.
1126 /// basePtrs - base pointers.
1127 /// statepointToken - statepoint instruction to which relocates should be
1129 /// Builder - Llvm IR builder to be used to construct new calls.
1130 static void CreateGCRelocates(ArrayRef<llvm::Value *> LiveVariables,
1131 const int LiveStart,
1132 ArrayRef<llvm::Value *> BasePtrs,
1133 Instruction *StatepointToken,
1134 IRBuilder<> Builder) {
1135 SmallVector<Instruction *, 64> NewDefs;
1136 NewDefs.reserve(LiveVariables.size());
1138 Module *M = StatepointToken->getParent()->getParent()->getParent();
1140 for (unsigned i = 0; i < LiveVariables.size(); i++) {
1141 // We generate a (potentially) unique declaration for every pointer type
1142 // combination. This results is some blow up the function declarations in
1143 // the IR, but removes the need for argument bitcasts which shrinks the IR
1144 // greatly and makes it much more readable.
1145 SmallVector<Type *, 1> Types; // one per 'any' type
1146 // All gc_relocate are set to i8 addrspace(1)* type. This could help avoid
1147 // cases where the actual value's type mangling is not supported by llvm. A
1148 // bitcast is added later to convert gc_relocate to the actual value's type.
1149 Types.push_back(Type::getInt8PtrTy(M->getContext(), 1));
1150 Value *GCRelocateDecl = Intrinsic::getDeclaration(
1151 M, Intrinsic::experimental_gc_relocate, Types);
1153 // Generate the gc.relocate call and save the result
1155 ConstantInt::get(Type::getInt32Ty(M->getContext()),
1156 LiveStart + find_index(LiveVariables, BasePtrs[i]));
1157 Value *LiveIdx = ConstantInt::get(
1158 Type::getInt32Ty(M->getContext()),
1159 LiveStart + find_index(LiveVariables, LiveVariables[i]));
1161 // only specify a debug name if we can give a useful one
1162 Value *Reloc = Builder.CreateCall(
1163 GCRelocateDecl, {StatepointToken, BaseIdx, LiveIdx},
1164 LiveVariables[i]->hasName() ? LiveVariables[i]->getName() + ".relocated"
1166 // Trick CodeGen into thinking there are lots of free registers at this
1168 cast<CallInst>(Reloc)->setCallingConv(CallingConv::Cold);
1170 NewDefs.push_back(cast<Instruction>(Reloc));
1172 assert(NewDefs.size() == LiveVariables.size() &&
1173 "missing or extra redefinition at safepoint");
1177 makeStatepointExplicitImpl(const CallSite &CS, /* to replace */
1178 const SmallVectorImpl<llvm::Value *> &basePtrs,
1179 const SmallVectorImpl<llvm::Value *> &liveVariables,
1181 PartiallyConstructedSafepointRecord &result) {
1182 assert(basePtrs.size() == liveVariables.size());
1183 assert(isStatepoint(CS) &&
1184 "This method expects to be rewriting a statepoint");
1186 BasicBlock *BB = CS.getInstruction()->getParent();
1188 Function *F = BB->getParent();
1189 assert(F && "must be set");
1190 Module *M = F->getParent();
1192 assert(M && "must be set");
1194 // We're not changing the function signature of the statepoint since the gc
1195 // arguments go into the var args section.
1196 Function *gc_statepoint_decl = CS.getCalledFunction();
1198 // Then go ahead and use the builder do actually do the inserts. We insert
1199 // immediately before the previous instruction under the assumption that all
1200 // arguments will be available here. We can't insert afterwards since we may
1201 // be replacing a terminator.
1202 Instruction *insertBefore = CS.getInstruction();
1203 IRBuilder<> Builder(insertBefore);
1204 // Copy all of the arguments from the original statepoint - this includes the
1205 // target, call args, and deopt args
1206 SmallVector<llvm::Value *, 64> args;
1207 args.insert(args.end(), CS.arg_begin(), CS.arg_end());
1208 // TODO: Clear the 'needs rewrite' flag
1210 // add all the pointers to be relocated (gc arguments)
1211 // Capture the start of the live variable list for use in the gc_relocates
1212 const int live_start = args.size();
1213 args.insert(args.end(), liveVariables.begin(), liveVariables.end());
1215 // Create the statepoint given all the arguments
1216 Instruction *token = nullptr;
1217 AttributeSet return_attributes;
1219 CallInst *toReplace = cast<CallInst>(CS.getInstruction());
1221 Builder.CreateCall(gc_statepoint_decl, args, "safepoint_token");
1222 call->setTailCall(toReplace->isTailCall());
1223 call->setCallingConv(toReplace->getCallingConv());
1225 // Currently we will fail on parameter attributes and on certain
1226 // function attributes.
1227 AttributeSet new_attrs = legalizeCallAttributes(toReplace->getAttributes());
1228 // In case if we can handle this set of sttributes - set up function attrs
1229 // directly on statepoint and return attrs later for gc_result intrinsic.
1230 call->setAttributes(new_attrs.getFnAttributes());
1231 return_attributes = new_attrs.getRetAttributes();
1235 // Put the following gc_result and gc_relocate calls immediately after the
1236 // the old call (which we're about to delete)
1237 BasicBlock::iterator next(toReplace);
1238 assert(BB->end() != next && "not a terminator, must have next");
1240 Instruction *IP = &*(next);
1241 Builder.SetInsertPoint(IP);
1242 Builder.SetCurrentDebugLocation(IP->getDebugLoc());
1245 InvokeInst *toReplace = cast<InvokeInst>(CS.getInstruction());
1247 // Insert the new invoke into the old block. We'll remove the old one in a
1248 // moment at which point this will become the new terminator for the
1250 InvokeInst *invoke = InvokeInst::Create(
1251 gc_statepoint_decl, toReplace->getNormalDest(),
1252 toReplace->getUnwindDest(), args, "", toReplace->getParent());
1253 invoke->setCallingConv(toReplace->getCallingConv());
1255 // Currently we will fail on parameter attributes and on certain
1256 // function attributes.
1257 AttributeSet new_attrs = legalizeCallAttributes(toReplace->getAttributes());
1258 // In case if we can handle this set of sttributes - set up function attrs
1259 // directly on statepoint and return attrs later for gc_result intrinsic.
1260 invoke->setAttributes(new_attrs.getFnAttributes());
1261 return_attributes = new_attrs.getRetAttributes();
1265 // Generate gc relocates in exceptional path
1266 BasicBlock *unwindBlock = toReplace->getUnwindDest();
1267 assert(!isa<PHINode>(unwindBlock->begin()) &&
1268 unwindBlock->getUniquePredecessor() &&
1269 "can't safely insert in this block!");
1271 Instruction *IP = &*(unwindBlock->getFirstInsertionPt());
1272 Builder.SetInsertPoint(IP);
1273 Builder.SetCurrentDebugLocation(toReplace->getDebugLoc());
1275 // Extract second element from landingpad return value. We will attach
1276 // exceptional gc relocates to it.
1277 const unsigned idx = 1;
1278 Instruction *exceptional_token =
1279 cast<Instruction>(Builder.CreateExtractValue(
1280 unwindBlock->getLandingPadInst(), idx, "relocate_token"));
1281 result.UnwindToken = exceptional_token;
1283 // Just throw away return value. We will use the one we got for normal
1285 (void)CreateGCRelocates(liveVariables, live_start, basePtrs,
1286 exceptional_token, Builder);
1288 // Generate gc relocates and returns for normal block
1289 BasicBlock *normalDest = toReplace->getNormalDest();
1290 assert(!isa<PHINode>(normalDest->begin()) &&
1291 normalDest->getUniquePredecessor() &&
1292 "can't safely insert in this block!");
1294 IP = &*(normalDest->getFirstInsertionPt());
1295 Builder.SetInsertPoint(IP);
1297 // gc relocates will be generated later as if it were regular call
1302 // Take the name of the original value call if it had one.
1303 token->takeName(CS.getInstruction());
1305 // The GCResult is already inserted, we just need to find it
1307 Instruction *toReplace = CS.getInstruction();
1308 assert((toReplace->hasNUses(0) || toReplace->hasNUses(1)) &&
1309 "only valid use before rewrite is gc.result");
1310 assert(!toReplace->hasOneUse() ||
1311 isGCResult(cast<Instruction>(*toReplace->user_begin())));
1314 // Update the gc.result of the original statepoint (if any) to use the newly
1315 // inserted statepoint. This is safe to do here since the token can't be
1316 // considered a live reference.
1317 CS.getInstruction()->replaceAllUsesWith(token);
1319 result.StatepointToken = token;
1321 // Second, create a gc.relocate for every live variable
1322 CreateGCRelocates(liveVariables, live_start, basePtrs, token, Builder);
1326 struct name_ordering {
1329 bool operator()(name_ordering const &a, name_ordering const &b) {
1330 return -1 == a.derived->getName().compare(b.derived->getName());
1334 static void stablize_order(SmallVectorImpl<Value *> &basevec,
1335 SmallVectorImpl<Value *> &livevec) {
1336 assert(basevec.size() == livevec.size());
1338 SmallVector<name_ordering, 64> temp;
1339 for (size_t i = 0; i < basevec.size(); i++) {
1341 v.base = basevec[i];
1342 v.derived = livevec[i];
1345 std::sort(temp.begin(), temp.end(), name_ordering());
1346 for (size_t i = 0; i < basevec.size(); i++) {
1347 basevec[i] = temp[i].base;
1348 livevec[i] = temp[i].derived;
1352 // Replace an existing gc.statepoint with a new one and a set of gc.relocates
1353 // which make the relocations happening at this safepoint explicit.
1355 // WARNING: Does not do any fixup to adjust users of the original live
1356 // values. That's the callers responsibility.
1358 makeStatepointExplicit(DominatorTree &DT, const CallSite &CS, Pass *P,
1359 PartiallyConstructedSafepointRecord &result) {
1360 auto liveset = result.liveset;
1361 auto PointerToBase = result.PointerToBase;
1363 // Convert to vector for efficient cross referencing.
1364 SmallVector<Value *, 64> basevec, livevec;
1365 livevec.reserve(liveset.size());
1366 basevec.reserve(liveset.size());
1367 for (Value *L : liveset) {
1368 livevec.push_back(L);
1370 assert(PointerToBase.find(L) != PointerToBase.end());
1371 Value *base = PointerToBase[L];
1372 basevec.push_back(base);
1374 assert(livevec.size() == basevec.size());
1376 // To make the output IR slightly more stable (for use in diffs), ensure a
1377 // fixed order of the values in the safepoint (by sorting the value name).
1378 // The order is otherwise meaningless.
1379 stablize_order(basevec, livevec);
1381 // Do the actual rewriting and delete the old statepoint
1382 makeStatepointExplicitImpl(CS, basevec, livevec, P, result);
1383 CS.getInstruction()->eraseFromParent();
1386 // Helper function for the relocationViaAlloca.
1387 // It receives iterator to the statepoint gc relocates and emits store to the
1389 // location (via allocaMap) for the each one of them.
1390 // Add visited values into the visitedLiveValues set we will later use them
1391 // for sanity check.
1393 insertRelocationStores(iterator_range<Value::user_iterator> GCRelocs,
1394 DenseMap<Value *, Value *> &AllocaMap,
1395 DenseSet<Value *> &VisitedLiveValues) {
1397 for (User *U : GCRelocs) {
1398 if (!isa<IntrinsicInst>(U))
1401 IntrinsicInst *RelocatedValue = cast<IntrinsicInst>(U);
1403 // We only care about relocates
1404 if (RelocatedValue->getIntrinsicID() !=
1405 Intrinsic::experimental_gc_relocate) {
1409 GCRelocateOperands RelocateOperands(RelocatedValue);
1410 Value *OriginalValue =
1411 const_cast<Value *>(RelocateOperands.getDerivedPtr());
1412 assert(AllocaMap.count(OriginalValue));
1413 Value *Alloca = AllocaMap[OriginalValue];
1415 // Emit store into the related alloca
1416 // All gc_relocate are i8 addrspace(1)* typed, and it must be bitcasted to
1417 // the correct type according to alloca.
1418 assert(RelocatedValue->getNextNode() && "Should always have one since it's not a terminator");
1419 IRBuilder<> Builder(RelocatedValue->getNextNode());
1420 Value *CastedRelocatedValue =
1421 Builder.CreateBitCast(RelocatedValue, cast<AllocaInst>(Alloca)->getAllocatedType(),
1422 RelocatedValue->hasName() ? RelocatedValue->getName() + ".casted" : "");
1424 StoreInst *Store = new StoreInst(CastedRelocatedValue, Alloca);
1425 Store->insertAfter(cast<Instruction>(CastedRelocatedValue));
1428 VisitedLiveValues.insert(OriginalValue);
1433 // Helper function for the "relocationViaAlloca". Similar to the
1434 // "insertRelocationStores" but works for rematerialized values.
1436 insertRematerializationStores(
1437 RematerializedValueMapTy RematerializedValues,
1438 DenseMap<Value *, Value *> &AllocaMap,
1439 DenseSet<Value *> &VisitedLiveValues) {
1441 for (auto RematerializedValuePair: RematerializedValues) {
1442 Instruction *RematerializedValue = RematerializedValuePair.first;
1443 Value *OriginalValue = RematerializedValuePair.second;
1445 assert(AllocaMap.count(OriginalValue) &&
1446 "Can not find alloca for rematerialized value");
1447 Value *Alloca = AllocaMap[OriginalValue];
1449 StoreInst *Store = new StoreInst(RematerializedValue, Alloca);
1450 Store->insertAfter(RematerializedValue);
1453 VisitedLiveValues.insert(OriginalValue);
1458 /// do all the relocation update via allocas and mem2reg
1459 static void relocationViaAlloca(
1460 Function &F, DominatorTree &DT, ArrayRef<Value *> Live,
1461 ArrayRef<struct PartiallyConstructedSafepointRecord> Records) {
1463 // record initial number of (static) allocas; we'll check we have the same
1464 // number when we get done.
1465 int InitialAllocaNum = 0;
1466 for (auto I = F.getEntryBlock().begin(), E = F.getEntryBlock().end(); I != E;
1468 if (isa<AllocaInst>(*I))
1472 // TODO-PERF: change data structures, reserve
1473 DenseMap<Value *, Value *> AllocaMap;
1474 SmallVector<AllocaInst *, 200> PromotableAllocas;
1475 // Used later to chack that we have enough allocas to store all values
1476 std::size_t NumRematerializedValues = 0;
1477 PromotableAllocas.reserve(Live.size());
1479 // Emit alloca for "LiveValue" and record it in "allocaMap" and
1480 // "PromotableAllocas"
1481 auto emitAllocaFor = [&](Value *LiveValue) {
1482 AllocaInst *Alloca = new AllocaInst(LiveValue->getType(), "",
1483 F.getEntryBlock().getFirstNonPHI());
1484 AllocaMap[LiveValue] = Alloca;
1485 PromotableAllocas.push_back(Alloca);
1488 // emit alloca for each live gc pointer
1489 for (unsigned i = 0; i < Live.size(); i++) {
1490 emitAllocaFor(Live[i]);
1493 // emit allocas for rematerialized values
1494 for (size_t i = 0; i < Records.size(); i++) {
1495 const struct PartiallyConstructedSafepointRecord &Info = Records[i];
1497 for (auto RematerializedValuePair : Info.RematerializedValues) {
1498 Value *OriginalValue = RematerializedValuePair.second;
1499 if (AllocaMap.count(OriginalValue) != 0)
1502 emitAllocaFor(OriginalValue);
1503 ++NumRematerializedValues;
1507 // The next two loops are part of the same conceptual operation. We need to
1508 // insert a store to the alloca after the original def and at each
1509 // redefinition. We need to insert a load before each use. These are split
1510 // into distinct loops for performance reasons.
1512 // update gc pointer after each statepoint
1513 // either store a relocated value or null (if no relocated value found for
1514 // this gc pointer and it is not a gc_result)
1515 // this must happen before we update the statepoint with load of alloca
1516 // otherwise we lose the link between statepoint and old def
1517 for (size_t i = 0; i < Records.size(); i++) {
1518 const struct PartiallyConstructedSafepointRecord &Info = Records[i];
1519 Value *Statepoint = Info.StatepointToken;
1521 // This will be used for consistency check
1522 DenseSet<Value *> VisitedLiveValues;
1524 // Insert stores for normal statepoint gc relocates
1525 insertRelocationStores(Statepoint->users(), AllocaMap, VisitedLiveValues);
1527 // In case if it was invoke statepoint
1528 // we will insert stores for exceptional path gc relocates.
1529 if (isa<InvokeInst>(Statepoint)) {
1530 insertRelocationStores(Info.UnwindToken->users(), AllocaMap,
1534 // Do similar thing with rematerialized values
1535 insertRematerializationStores(Info.RematerializedValues, AllocaMap,
1538 if (ClobberNonLive) {
1539 // As a debuging aid, pretend that an unrelocated pointer becomes null at
1540 // the gc.statepoint. This will turn some subtle GC problems into
1541 // slightly easier to debug SEGVs. Note that on large IR files with
1542 // lots of gc.statepoints this is extremely costly both memory and time
1544 SmallVector<AllocaInst *, 64> ToClobber;
1545 for (auto Pair : AllocaMap) {
1546 Value *Def = Pair.first;
1547 AllocaInst *Alloca = cast<AllocaInst>(Pair.second);
1549 // This value was relocated
1550 if (VisitedLiveValues.count(Def)) {
1553 ToClobber.push_back(Alloca);
1556 auto InsertClobbersAt = [&](Instruction *IP) {
1557 for (auto *AI : ToClobber) {
1558 auto AIType = cast<PointerType>(AI->getType());
1559 auto PT = cast<PointerType>(AIType->getElementType());
1560 Constant *CPN = ConstantPointerNull::get(PT);
1561 StoreInst *Store = new StoreInst(CPN, AI);
1562 Store->insertBefore(IP);
1566 // Insert the clobbering stores. These may get intermixed with the
1567 // gc.results and gc.relocates, but that's fine.
1568 if (auto II = dyn_cast<InvokeInst>(Statepoint)) {
1569 InsertClobbersAt(II->getNormalDest()->getFirstInsertionPt());
1570 InsertClobbersAt(II->getUnwindDest()->getFirstInsertionPt());
1572 BasicBlock::iterator Next(cast<CallInst>(Statepoint));
1574 InsertClobbersAt(Next);
1578 // update use with load allocas and add store for gc_relocated
1579 for (auto Pair : AllocaMap) {
1580 Value *Def = Pair.first;
1581 Value *Alloca = Pair.second;
1583 // we pre-record the uses of allocas so that we dont have to worry about
1585 // that change the user information.
1586 SmallVector<Instruction *, 20> Uses;
1587 // PERF: trade a linear scan for repeated reallocation
1588 Uses.reserve(std::distance(Def->user_begin(), Def->user_end()));
1589 for (User *U : Def->users()) {
1590 if (!isa<ConstantExpr>(U)) {
1591 // If the def has a ConstantExpr use, then the def is either a
1592 // ConstantExpr use itself or null. In either case
1593 // (recursively in the first, directly in the second), the oop
1594 // it is ultimately dependent on is null and this particular
1595 // use does not need to be fixed up.
1596 Uses.push_back(cast<Instruction>(U));
1600 std::sort(Uses.begin(), Uses.end());
1601 auto Last = std::unique(Uses.begin(), Uses.end());
1602 Uses.erase(Last, Uses.end());
1604 for (Instruction *Use : Uses) {
1605 if (isa<PHINode>(Use)) {
1606 PHINode *Phi = cast<PHINode>(Use);
1607 for (unsigned i = 0; i < Phi->getNumIncomingValues(); i++) {
1608 if (Def == Phi->getIncomingValue(i)) {
1609 LoadInst *Load = new LoadInst(
1610 Alloca, "", Phi->getIncomingBlock(i)->getTerminator());
1611 Phi->setIncomingValue(i, Load);
1615 LoadInst *Load = new LoadInst(Alloca, "", Use);
1616 Use->replaceUsesOfWith(Def, Load);
1620 // emit store for the initial gc value
1621 // store must be inserted after load, otherwise store will be in alloca's
1622 // use list and an extra load will be inserted before it
1623 StoreInst *Store = new StoreInst(Def, Alloca);
1624 if (Instruction *Inst = dyn_cast<Instruction>(Def)) {
1625 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(Inst)) {
1626 // InvokeInst is a TerminatorInst so the store need to be inserted
1627 // into its normal destination block.
1628 BasicBlock *NormalDest = Invoke->getNormalDest();
1629 Store->insertBefore(NormalDest->getFirstNonPHI());
1631 assert(!Inst->isTerminator() &&
1632 "The only TerminatorInst that can produce a value is "
1633 "InvokeInst which is handled above.");
1634 Store->insertAfter(Inst);
1637 assert(isa<Argument>(Def));
1638 Store->insertAfter(cast<Instruction>(Alloca));
1642 assert(PromotableAllocas.size() == Live.size() + NumRematerializedValues &&
1643 "we must have the same allocas with lives");
1644 if (!PromotableAllocas.empty()) {
1645 // apply mem2reg to promote alloca to SSA
1646 PromoteMemToReg(PromotableAllocas, DT);
1650 for (auto I = F.getEntryBlock().begin(), E = F.getEntryBlock().end(); I != E;
1652 if (isa<AllocaInst>(*I))
1654 assert(InitialAllocaNum == 0 && "We must not introduce any extra allocas");
1658 /// Implement a unique function which doesn't require we sort the input
1659 /// vector. Doing so has the effect of changing the output of a couple of
1660 /// tests in ways which make them less useful in testing fused safepoints.
1661 template <typename T> static void unique_unsorted(SmallVectorImpl<T> &Vec) {
1663 SmallVector<T, 128> TempVec;
1664 TempVec.reserve(Vec.size());
1665 for (auto Element : Vec)
1666 TempVec.push_back(Element);
1668 for (auto V : TempVec) {
1669 if (Seen.insert(V).second) {
1675 /// Insert holders so that each Value is obviously live through the entire
1676 /// lifetime of the call.
1677 static void insertUseHolderAfter(CallSite &CS, const ArrayRef<Value *> Values,
1678 SmallVectorImpl<CallInst *> &Holders) {
1680 // No values to hold live, might as well not insert the empty holder
1683 Module *M = CS.getInstruction()->getParent()->getParent()->getParent();
1684 // Use a dummy vararg function to actually hold the values live
1685 Function *Func = cast<Function>(M->getOrInsertFunction(
1686 "__tmp_use", FunctionType::get(Type::getVoidTy(M->getContext()), true)));
1688 // For call safepoints insert dummy calls right after safepoint
1689 BasicBlock::iterator Next(CS.getInstruction());
1691 Holders.push_back(CallInst::Create(Func, Values, "", Next));
1694 // For invoke safepooints insert dummy calls both in normal and
1695 // exceptional destination blocks
1696 auto *II = cast<InvokeInst>(CS.getInstruction());
1697 Holders.push_back(CallInst::Create(
1698 Func, Values, "", II->getNormalDest()->getFirstInsertionPt()));
1699 Holders.push_back(CallInst::Create(
1700 Func, Values, "", II->getUnwindDest()->getFirstInsertionPt()));
1703 static void findLiveReferences(
1704 Function &F, DominatorTree &DT, Pass *P, ArrayRef<CallSite> toUpdate,
1705 MutableArrayRef<struct PartiallyConstructedSafepointRecord> records) {
1706 GCPtrLivenessData OriginalLivenessData;
1707 computeLiveInValues(DT, F, OriginalLivenessData);
1708 for (size_t i = 0; i < records.size(); i++) {
1709 struct PartiallyConstructedSafepointRecord &info = records[i];
1710 const CallSite &CS = toUpdate[i];
1711 analyzeParsePointLiveness(DT, OriginalLivenessData, CS, info);
1715 /// Remove any vector of pointers from the liveset by scalarizing them over the
1716 /// statepoint instruction. Adds the scalarized pieces to the liveset. It
1717 /// would be preferrable to include the vector in the statepoint itself, but
1718 /// the lowering code currently does not handle that. Extending it would be
1719 /// slightly non-trivial since it requires a format change. Given how rare
1720 /// such cases are (for the moment?) scalarizing is an acceptable comprimise.
1721 static void splitVectorValues(Instruction *StatepointInst,
1722 StatepointLiveSetTy &LiveSet, DominatorTree &DT) {
1723 SmallVector<Value *, 16> ToSplit;
1724 for (Value *V : LiveSet)
1725 if (isa<VectorType>(V->getType()))
1726 ToSplit.push_back(V);
1728 if (ToSplit.empty())
1731 Function &F = *(StatepointInst->getParent()->getParent());
1733 DenseMap<Value *, AllocaInst *> AllocaMap;
1734 // First is normal return, second is exceptional return (invoke only)
1735 DenseMap<Value *, std::pair<Value *, Value *>> Replacements;
1736 for (Value *V : ToSplit) {
1739 AllocaInst *Alloca =
1740 new AllocaInst(V->getType(), "", F.getEntryBlock().getFirstNonPHI());
1741 AllocaMap[V] = Alloca;
1743 VectorType *VT = cast<VectorType>(V->getType());
1744 IRBuilder<> Builder(StatepointInst);
1745 SmallVector<Value *, 16> Elements;
1746 for (unsigned i = 0; i < VT->getNumElements(); i++)
1747 Elements.push_back(Builder.CreateExtractElement(V, Builder.getInt32(i)));
1748 LiveSet.insert(Elements.begin(), Elements.end());
1750 auto InsertVectorReform = [&](Instruction *IP) {
1751 Builder.SetInsertPoint(IP);
1752 Builder.SetCurrentDebugLocation(IP->getDebugLoc());
1753 Value *ResultVec = UndefValue::get(VT);
1754 for (unsigned i = 0; i < VT->getNumElements(); i++)
1755 ResultVec = Builder.CreateInsertElement(ResultVec, Elements[i],
1756 Builder.getInt32(i));
1760 if (isa<CallInst>(StatepointInst)) {
1761 BasicBlock::iterator Next(StatepointInst);
1763 Instruction *IP = &*(Next);
1764 Replacements[V].first = InsertVectorReform(IP);
1765 Replacements[V].second = nullptr;
1767 InvokeInst *Invoke = cast<InvokeInst>(StatepointInst);
1768 // We've already normalized - check that we don't have shared destination
1770 BasicBlock *NormalDest = Invoke->getNormalDest();
1771 assert(!isa<PHINode>(NormalDest->begin()));
1772 BasicBlock *UnwindDest = Invoke->getUnwindDest();
1773 assert(!isa<PHINode>(UnwindDest->begin()));
1774 // Insert insert element sequences in both successors
1775 Instruction *IP = &*(NormalDest->getFirstInsertionPt());
1776 Replacements[V].first = InsertVectorReform(IP);
1777 IP = &*(UnwindDest->getFirstInsertionPt());
1778 Replacements[V].second = InsertVectorReform(IP);
1781 for (Value *V : ToSplit) {
1782 AllocaInst *Alloca = AllocaMap[V];
1784 // Capture all users before we start mutating use lists
1785 SmallVector<Instruction *, 16> Users;
1786 for (User *U : V->users())
1787 Users.push_back(cast<Instruction>(U));
1789 for (Instruction *I : Users) {
1790 if (auto Phi = dyn_cast<PHINode>(I)) {
1791 for (unsigned i = 0; i < Phi->getNumIncomingValues(); i++)
1792 if (V == Phi->getIncomingValue(i)) {
1793 LoadInst *Load = new LoadInst(
1794 Alloca, "", Phi->getIncomingBlock(i)->getTerminator());
1795 Phi->setIncomingValue(i, Load);
1798 LoadInst *Load = new LoadInst(Alloca, "", I);
1799 I->replaceUsesOfWith(V, Load);
1803 // Store the original value and the replacement value into the alloca
1804 StoreInst *Store = new StoreInst(V, Alloca);
1805 if (auto I = dyn_cast<Instruction>(V))
1806 Store->insertAfter(I);
1808 Store->insertAfter(Alloca);
1810 // Normal return for invoke, or call return
1811 Instruction *Replacement = cast<Instruction>(Replacements[V].first);
1812 (new StoreInst(Replacement, Alloca))->insertAfter(Replacement);
1813 // Unwind return for invoke only
1814 Replacement = cast_or_null<Instruction>(Replacements[V].second);
1816 (new StoreInst(Replacement, Alloca))->insertAfter(Replacement);
1819 // apply mem2reg to promote alloca to SSA
1820 SmallVector<AllocaInst *, 16> Allocas;
1821 for (Value *V : ToSplit)
1822 Allocas.push_back(AllocaMap[V]);
1823 PromoteMemToReg(Allocas, DT);
1826 // Helper function for the "rematerializeLiveValues". It walks use chain
1827 // starting from the "CurrentValue" until it meets "BaseValue". Only "simple"
1828 // values are visited (currently it is GEP's and casts). Returns true if it
1829 // sucessfully reached "BaseValue" and false otherwise.
1830 // Fills "ChainToBase" array with all visited values. "BaseValue" is not
1832 static bool findRematerializableChainToBasePointer(
1833 SmallVectorImpl<Instruction*> &ChainToBase,
1834 Value *CurrentValue, Value *BaseValue) {
1836 // We have found a base value
1837 if (CurrentValue == BaseValue) {
1841 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurrentValue)) {
1842 ChainToBase.push_back(GEP);
1843 return findRematerializableChainToBasePointer(ChainToBase,
1844 GEP->getPointerOperand(),
1848 if (CastInst *CI = dyn_cast<CastInst>(CurrentValue)) {
1849 Value *Def = CI->stripPointerCasts();
1851 // This two checks are basically similar. First one is here for the
1852 // consistency with findBasePointers logic.
1853 assert(!isa<CastInst>(Def) && "not a pointer cast found");
1854 if (!CI->isNoopCast(CI->getModule()->getDataLayout()))
1857 ChainToBase.push_back(CI);
1858 return findRematerializableChainToBasePointer(ChainToBase, Def, BaseValue);
1861 // Not supported instruction in the chain
1865 // Helper function for the "rematerializeLiveValues". Compute cost of the use
1866 // chain we are going to rematerialize.
1868 chainToBasePointerCost(SmallVectorImpl<Instruction*> &Chain,
1869 TargetTransformInfo &TTI) {
1872 for (Instruction *Instr : Chain) {
1873 if (CastInst *CI = dyn_cast<CastInst>(Instr)) {
1874 assert(CI->isNoopCast(CI->getModule()->getDataLayout()) &&
1875 "non noop cast is found during rematerialization");
1877 Type *SrcTy = CI->getOperand(0)->getType();
1878 Cost += TTI.getCastInstrCost(CI->getOpcode(), CI->getType(), SrcTy);
1880 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Instr)) {
1881 // Cost of the address calculation
1882 Type *ValTy = GEP->getPointerOperandType()->getPointerElementType();
1883 Cost += TTI.getAddressComputationCost(ValTy);
1885 // And cost of the GEP itself
1886 // TODO: Use TTI->getGEPCost here (it exists, but appears to be not
1887 // allowed for the external usage)
1888 if (!GEP->hasAllConstantIndices())
1892 llvm_unreachable("unsupported instruciton type during rematerialization");
1899 // From the statepoint liveset pick values that are cheaper to recompute then to
1900 // relocate. Remove this values from the liveset, rematerialize them after
1901 // statepoint and record them in "Info" structure. Note that similar to
1902 // relocated values we don't do any user adjustments here.
1903 static void rematerializeLiveValues(CallSite CS,
1904 PartiallyConstructedSafepointRecord &Info,
1905 TargetTransformInfo &TTI) {
1906 const unsigned int ChainLengthThreshold = 10;
1908 // Record values we are going to delete from this statepoint live set.
1909 // We can not di this in following loop due to iterator invalidation.
1910 SmallVector<Value *, 32> LiveValuesToBeDeleted;
1912 for (Value *LiveValue: Info.liveset) {
1913 // For each live pointer find it's defining chain
1914 SmallVector<Instruction *, 3> ChainToBase;
1915 assert(Info.PointerToBase.find(LiveValue) != Info.PointerToBase.end());
1917 findRematerializableChainToBasePointer(ChainToBase,
1919 Info.PointerToBase[LiveValue]);
1920 // Nothing to do, or chain is too long
1922 ChainToBase.size() == 0 ||
1923 ChainToBase.size() > ChainLengthThreshold)
1926 // Compute cost of this chain
1927 unsigned Cost = chainToBasePointerCost(ChainToBase, TTI);
1928 // TODO: We can also account for cases when we will be able to remove some
1929 // of the rematerialized values by later optimization passes. I.e if
1930 // we rematerialized several intersecting chains. Or if original values
1931 // don't have any uses besides this statepoint.
1933 // For invokes we need to rematerialize each chain twice - for normal and
1934 // for unwind basic blocks. Model this by multiplying cost by two.
1935 if (CS.isInvoke()) {
1938 // If it's too expensive - skip it
1939 if (Cost >= RematerializationThreshold)
1942 // Remove value from the live set
1943 LiveValuesToBeDeleted.push_back(LiveValue);
1945 // Clone instructions and record them inside "Info" structure
1947 // Walk backwards to visit top-most instructions first
1948 std::reverse(ChainToBase.begin(), ChainToBase.end());
1950 // Utility function which clones all instructions from "ChainToBase"
1951 // and inserts them before "InsertBefore". Returns rematerialized value
1952 // which should be used after statepoint.
1953 auto rematerializeChain = [&ChainToBase](Instruction *InsertBefore) {
1954 Instruction *LastClonedValue = nullptr;
1955 Instruction *LastValue = nullptr;
1956 for (Instruction *Instr: ChainToBase) {
1957 // Only GEP's and casts are suported as we need to be careful to not
1958 // introduce any new uses of pointers not in the liveset.
1959 // Note that it's fine to introduce new uses of pointers which were
1960 // otherwise not used after this statepoint.
1961 assert(isa<GetElementPtrInst>(Instr) || isa<CastInst>(Instr));
1963 Instruction *ClonedValue = Instr->clone();
1964 ClonedValue->insertBefore(InsertBefore);
1965 ClonedValue->setName(Instr->getName() + ".remat");
1967 // If it is not first instruction in the chain then it uses previously
1968 // cloned value. We should update it to use cloned value.
1969 if (LastClonedValue) {
1971 ClonedValue->replaceUsesOfWith(LastValue, LastClonedValue);
1973 // Assert that cloned instruction does not use any instructions from
1974 // this chain other than LastClonedValue
1975 for (auto OpValue : ClonedValue->operand_values()) {
1976 assert(std::find(ChainToBase.begin(), ChainToBase.end(), OpValue) ==
1977 ChainToBase.end() &&
1978 "incorrect use in rematerialization chain");
1983 LastClonedValue = ClonedValue;
1986 assert(LastClonedValue);
1987 return LastClonedValue;
1990 // Different cases for calls and invokes. For invokes we need to clone
1991 // instructions both on normal and unwind path.
1993 Instruction *InsertBefore = CS.getInstruction()->getNextNode();
1994 assert(InsertBefore);
1995 Instruction *RematerializedValue = rematerializeChain(InsertBefore);
1996 Info.RematerializedValues[RematerializedValue] = LiveValue;
1998 InvokeInst *Invoke = cast<InvokeInst>(CS.getInstruction());
2000 Instruction *NormalInsertBefore =
2001 Invoke->getNormalDest()->getFirstInsertionPt();
2002 Instruction *UnwindInsertBefore =
2003 Invoke->getUnwindDest()->getFirstInsertionPt();
2005 Instruction *NormalRematerializedValue =
2006 rematerializeChain(NormalInsertBefore);
2007 Instruction *UnwindRematerializedValue =
2008 rematerializeChain(UnwindInsertBefore);
2010 Info.RematerializedValues[NormalRematerializedValue] = LiveValue;
2011 Info.RematerializedValues[UnwindRematerializedValue] = LiveValue;
2015 // Remove rematerializaed values from the live set
2016 for (auto LiveValue: LiveValuesToBeDeleted) {
2017 Info.liveset.erase(LiveValue);
2021 static bool insertParsePoints(Function &F, DominatorTree &DT, Pass *P,
2022 SmallVectorImpl<CallSite> &toUpdate) {
2024 // sanity check the input
2025 std::set<CallSite> uniqued;
2026 uniqued.insert(toUpdate.begin(), toUpdate.end());
2027 assert(uniqued.size() == toUpdate.size() && "no duplicates please!");
2029 for (size_t i = 0; i < toUpdate.size(); i++) {
2030 CallSite &CS = toUpdate[i];
2031 assert(CS.getInstruction()->getParent()->getParent() == &F);
2032 assert(isStatepoint(CS) && "expected to already be a deopt statepoint");
2036 // When inserting gc.relocates for invokes, we need to be able to insert at
2037 // the top of the successor blocks. See the comment on
2038 // normalForInvokeSafepoint on exactly what is needed. Note that this step
2039 // may restructure the CFG.
2040 for (CallSite CS : toUpdate) {
2043 InvokeInst *invoke = cast<InvokeInst>(CS.getInstruction());
2044 normalizeForInvokeSafepoint(invoke->getNormalDest(), invoke->getParent(),
2046 normalizeForInvokeSafepoint(invoke->getUnwindDest(), invoke->getParent(),
2050 // A list of dummy calls added to the IR to keep various values obviously
2051 // live in the IR. We'll remove all of these when done.
2052 SmallVector<CallInst *, 64> holders;
2054 // Insert a dummy call with all of the arguments to the vm_state we'll need
2055 // for the actual safepoint insertion. This ensures reference arguments in
2056 // the deopt argument list are considered live through the safepoint (and
2057 // thus makes sure they get relocated.)
2058 for (size_t i = 0; i < toUpdate.size(); i++) {
2059 CallSite &CS = toUpdate[i];
2060 Statepoint StatepointCS(CS);
2062 SmallVector<Value *, 64> DeoptValues;
2063 for (Use &U : StatepointCS.vm_state_args()) {
2064 Value *Arg = cast<Value>(&U);
2065 assert(!isUnhandledGCPointerType(Arg->getType()) &&
2066 "support for FCA unimplemented");
2067 if (isHandledGCPointerType(Arg->getType()))
2068 DeoptValues.push_back(Arg);
2070 insertUseHolderAfter(CS, DeoptValues, holders);
2073 SmallVector<struct PartiallyConstructedSafepointRecord, 64> records;
2074 records.reserve(toUpdate.size());
2075 for (size_t i = 0; i < toUpdate.size(); i++) {
2076 struct PartiallyConstructedSafepointRecord info;
2077 records.push_back(info);
2079 assert(records.size() == toUpdate.size());
2081 // A) Identify all gc pointers which are staticly live at the given call
2083 findLiveReferences(F, DT, P, toUpdate, records);
2085 // Do a limited scalarization of any live at safepoint vector values which
2086 // contain pointers. This enables this pass to run after vectorization at
2087 // the cost of some possible performance loss. TODO: it would be nice to
2088 // natively support vectors all the way through the backend so we don't need
2089 // to scalarize here.
2090 for (size_t i = 0; i < records.size(); i++) {
2091 struct PartiallyConstructedSafepointRecord &info = records[i];
2092 Instruction *statepoint = toUpdate[i].getInstruction();
2093 splitVectorValues(cast<Instruction>(statepoint), info.liveset, DT);
2096 // B) Find the base pointers for each live pointer
2097 /* scope for caching */ {
2098 // Cache the 'defining value' relation used in the computation and
2099 // insertion of base phis and selects. This ensures that we don't insert
2100 // large numbers of duplicate base_phis.
2101 DefiningValueMapTy DVCache;
2103 for (size_t i = 0; i < records.size(); i++) {
2104 struct PartiallyConstructedSafepointRecord &info = records[i];
2105 CallSite &CS = toUpdate[i];
2106 findBasePointers(DT, DVCache, CS, info);
2108 } // end of cache scope
2110 // The base phi insertion logic (for any safepoint) may have inserted new
2111 // instructions which are now live at some safepoint. The simplest such
2114 // phi a <-- will be a new base_phi here
2115 // safepoint 1 <-- that needs to be live here
2119 // We insert some dummy calls after each safepoint to definitely hold live
2120 // the base pointers which were identified for that safepoint. We'll then
2121 // ask liveness for _every_ base inserted to see what is now live. Then we
2122 // remove the dummy calls.
2123 holders.reserve(holders.size() + records.size());
2124 for (size_t i = 0; i < records.size(); i++) {
2125 struct PartiallyConstructedSafepointRecord &info = records[i];
2126 CallSite &CS = toUpdate[i];
2128 SmallVector<Value *, 128> Bases;
2129 for (auto Pair : info.PointerToBase) {
2130 Bases.push_back(Pair.second);
2132 insertUseHolderAfter(CS, Bases, holders);
2135 // By selecting base pointers, we've effectively inserted new uses. Thus, we
2136 // need to rerun liveness. We may *also* have inserted new defs, but that's
2137 // not the key issue.
2138 recomputeLiveInValues(F, DT, P, toUpdate, records);
2140 if (PrintBasePointers) {
2141 for (size_t i = 0; i < records.size(); i++) {
2142 struct PartiallyConstructedSafepointRecord &info = records[i];
2143 errs() << "Base Pairs: (w/Relocation)\n";
2144 for (auto Pair : info.PointerToBase) {
2145 errs() << " derived %" << Pair.first->getName() << " base %"
2146 << Pair.second->getName() << "\n";
2150 for (size_t i = 0; i < holders.size(); i++) {
2151 holders[i]->eraseFromParent();
2152 holders[i] = nullptr;
2156 // In order to reduce live set of statepoint we might choose to rematerialize
2157 // some values instead of relocating them. This is purelly an optimization and
2158 // does not influence correctness.
2159 TargetTransformInfo &TTI =
2160 P->getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
2162 for (size_t i = 0; i < records.size(); i++) {
2163 struct PartiallyConstructedSafepointRecord &info = records[i];
2164 CallSite &CS = toUpdate[i];
2166 rematerializeLiveValues(CS, info, TTI);
2169 // Now run through and replace the existing statepoints with new ones with
2170 // the live variables listed. We do not yet update uses of the values being
2171 // relocated. We have references to live variables that need to
2172 // survive to the last iteration of this loop. (By construction, the
2173 // previous statepoint can not be a live variable, thus we can and remove
2174 // the old statepoint calls as we go.)
2175 for (size_t i = 0; i < records.size(); i++) {
2176 struct PartiallyConstructedSafepointRecord &info = records[i];
2177 CallSite &CS = toUpdate[i];
2178 makeStatepointExplicit(DT, CS, P, info);
2180 toUpdate.clear(); // prevent accident use of invalid CallSites
2182 // Do all the fixups of the original live variables to their relocated selves
2183 SmallVector<Value *, 128> live;
2184 for (size_t i = 0; i < records.size(); i++) {
2185 struct PartiallyConstructedSafepointRecord &info = records[i];
2186 // We can't simply save the live set from the original insertion. One of
2187 // the live values might be the result of a call which needs a safepoint.
2188 // That Value* no longer exists and we need to use the new gc_result.
2189 // Thankfully, the liveset is embedded in the statepoint (and updated), so
2190 // we just grab that.
2191 Statepoint statepoint(info.StatepointToken);
2192 live.insert(live.end(), statepoint.gc_args_begin(),
2193 statepoint.gc_args_end());
2195 // Do some basic sanity checks on our liveness results before performing
2196 // relocation. Relocation can and will turn mistakes in liveness results
2197 // into non-sensical code which is must harder to debug.
2198 // TODO: It would be nice to test consistency as well
2199 assert(DT.isReachableFromEntry(info.StatepointToken->getParent()) &&
2200 "statepoint must be reachable or liveness is meaningless");
2201 for (Value *V : statepoint.gc_args()) {
2202 if (!isa<Instruction>(V))
2203 // Non-instruction values trivial dominate all possible uses
2205 auto LiveInst = cast<Instruction>(V);
2206 assert(DT.isReachableFromEntry(LiveInst->getParent()) &&
2207 "unreachable values should never be live");
2208 assert(DT.dominates(LiveInst, info.StatepointToken) &&
2209 "basic SSA liveness expectation violated by liveness analysis");
2213 unique_unsorted(live);
2217 for (auto ptr : live) {
2218 assert(isGCPointerType(ptr->getType()) && "must be a gc pointer type");
2222 relocationViaAlloca(F, DT, live, records);
2223 return !records.empty();
2226 // Handles both return values and arguments for Functions and CallSites.
2227 template <typename AttrHolder>
2228 static void RemoveDerefAttrAtIndex(LLVMContext &Ctx, AttrHolder &AH,
2231 if (AH.getDereferenceableBytes(Index))
2232 R.addAttribute(Attribute::get(Ctx, Attribute::Dereferenceable,
2233 AH.getDereferenceableBytes(Index)));
2234 if (AH.getDereferenceableOrNullBytes(Index))
2235 R.addAttribute(Attribute::get(Ctx, Attribute::DereferenceableOrNull,
2236 AH.getDereferenceableOrNullBytes(Index)));
2239 AH.setAttributes(AH.getAttributes().removeAttributes(
2240 Ctx, Index, AttributeSet::get(Ctx, Index, R)));
2244 RewriteStatepointsForGC::stripDereferenceabilityInfoFromPrototype(Function &F) {
2245 LLVMContext &Ctx = F.getContext();
2247 for (Argument &A : F.args())
2248 if (isa<PointerType>(A.getType()))
2249 RemoveDerefAttrAtIndex(Ctx, F, A.getArgNo() + 1);
2251 if (isa<PointerType>(F.getReturnType()))
2252 RemoveDerefAttrAtIndex(Ctx, F, AttributeSet::ReturnIndex);
2255 void RewriteStatepointsForGC::stripDereferenceabilityInfoFromBody(Function &F) {
2259 LLVMContext &Ctx = F.getContext();
2260 MDBuilder Builder(Ctx);
2262 for (Instruction &I : inst_range(F)) {
2263 if (const MDNode *MD = I.getMetadata(LLVMContext::MD_tbaa)) {
2264 assert(MD->getNumOperands() < 5 && "unrecognized metadata shape!");
2265 bool IsImmutableTBAA =
2266 MD->getNumOperands() == 4 &&
2267 mdconst::extract<ConstantInt>(MD->getOperand(3))->getValue() == 1;
2269 if (!IsImmutableTBAA)
2270 continue; // no work to do, MD_tbaa is already marked mutable
2272 MDNode *Base = cast<MDNode>(MD->getOperand(0));
2273 MDNode *Access = cast<MDNode>(MD->getOperand(1));
2275 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue();
2277 MDNode *MutableTBAA =
2278 Builder.createTBAAStructTagNode(Base, Access, Offset);
2279 I.setMetadata(LLVMContext::MD_tbaa, MutableTBAA);
2282 if (CallSite CS = CallSite(&I)) {
2283 for (int i = 0, e = CS.arg_size(); i != e; i++)
2284 if (isa<PointerType>(CS.getArgument(i)->getType()))
2285 RemoveDerefAttrAtIndex(Ctx, CS, i + 1);
2286 if (isa<PointerType>(CS.getType()))
2287 RemoveDerefAttrAtIndex(Ctx, CS, AttributeSet::ReturnIndex);
2292 /// Returns true if this function should be rewritten by this pass. The main
2293 /// point of this function is as an extension point for custom logic.
2294 static bool shouldRewriteStatepointsIn(Function &F) {
2295 // TODO: This should check the GCStrategy
2297 const char *FunctionGCName = F.getGC();
2298 const StringRef StatepointExampleName("statepoint-example");
2299 const StringRef CoreCLRName("coreclr");
2300 return (StatepointExampleName == FunctionGCName) ||
2301 (CoreCLRName == FunctionGCName);
2306 void RewriteStatepointsForGC::stripDereferenceabilityInfo(Module &M) {
2308 assert(std::any_of(M.begin(), M.end(), shouldRewriteStatepointsIn) &&
2312 for (Function &F : M)
2313 stripDereferenceabilityInfoFromPrototype(F);
2315 for (Function &F : M)
2316 stripDereferenceabilityInfoFromBody(F);
2319 bool RewriteStatepointsForGC::runOnFunction(Function &F) {
2320 // Nothing to do for declarations.
2321 if (F.isDeclaration() || F.empty())
2324 // Policy choice says not to rewrite - the most common reason is that we're
2325 // compiling code without a GCStrategy.
2326 if (!shouldRewriteStatepointsIn(F))
2329 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
2331 // Gather all the statepoints which need rewritten. Be careful to only
2332 // consider those in reachable code since we need to ask dominance queries
2333 // when rewriting. We'll delete the unreachable ones in a moment.
2334 SmallVector<CallSite, 64> ParsePointNeeded;
2335 bool HasUnreachableStatepoint = false;
2336 for (Instruction &I : inst_range(F)) {
2337 // TODO: only the ones with the flag set!
2338 if (isStatepoint(I)) {
2339 if (DT.isReachableFromEntry(I.getParent()))
2340 ParsePointNeeded.push_back(CallSite(&I));
2342 HasUnreachableStatepoint = true;
2346 bool MadeChange = false;
2348 // Delete any unreachable statepoints so that we don't have unrewritten
2349 // statepoints surviving this pass. This makes testing easier and the
2350 // resulting IR less confusing to human readers. Rather than be fancy, we
2351 // just reuse a utility function which removes the unreachable blocks.
2352 if (HasUnreachableStatepoint)
2353 MadeChange |= removeUnreachableBlocks(F);
2355 // Return early if no work to do.
2356 if (ParsePointNeeded.empty())
2359 // As a prepass, go ahead and aggressively destroy single entry phi nodes.
2360 // These are created by LCSSA. They have the effect of increasing the size
2361 // of liveness sets for no good reason. It may be harder to do this post
2362 // insertion since relocations and base phis can confuse things.
2363 for (BasicBlock &BB : F)
2364 if (BB.getUniquePredecessor()) {
2366 FoldSingleEntryPHINodes(&BB);
2369 MadeChange |= insertParsePoints(F, DT, this, ParsePointNeeded);
2373 // liveness computation via standard dataflow
2374 // -------------------------------------------------------------------
2376 // TODO: Consider using bitvectors for liveness, the set of potentially
2377 // interesting values should be small and easy to pre-compute.
2379 /// Compute the live-in set for the location rbegin starting from
2380 /// the live-out set of the basic block
2381 static void computeLiveInValues(BasicBlock::reverse_iterator rbegin,
2382 BasicBlock::reverse_iterator rend,
2383 DenseSet<Value *> &LiveTmp) {
2385 for (BasicBlock::reverse_iterator ritr = rbegin; ritr != rend; ritr++) {
2386 Instruction *I = &*ritr;
2388 // KILL/Def - Remove this definition from LiveIn
2391 // Don't consider *uses* in PHI nodes, we handle their contribution to
2392 // predecessor blocks when we seed the LiveOut sets
2393 if (isa<PHINode>(I))
2396 // USE - Add to the LiveIn set for this instruction
2397 for (Value *V : I->operands()) {
2398 assert(!isUnhandledGCPointerType(V->getType()) &&
2399 "support for FCA unimplemented");
2400 if (isHandledGCPointerType(V->getType()) && !isa<Constant>(V)) {
2401 // The choice to exclude all things constant here is slightly subtle.
2402 // There are two idependent reasons:
2403 // - We assume that things which are constant (from LLVM's definition)
2404 // do not move at runtime. For example, the address of a global
2405 // variable is fixed, even though it's contents may not be.
2406 // - Second, we can't disallow arbitrary inttoptr constants even
2407 // if the language frontend does. Optimization passes are free to
2408 // locally exploit facts without respect to global reachability. This
2409 // can create sections of code which are dynamically unreachable and
2410 // contain just about anything. (see constants.ll in tests)
2417 static void computeLiveOutSeed(BasicBlock *BB, DenseSet<Value *> &LiveTmp) {
2419 for (BasicBlock *Succ : successors(BB)) {
2420 const BasicBlock::iterator E(Succ->getFirstNonPHI());
2421 for (BasicBlock::iterator I = Succ->begin(); I != E; I++) {
2422 PHINode *Phi = cast<PHINode>(&*I);
2423 Value *V = Phi->getIncomingValueForBlock(BB);
2424 assert(!isUnhandledGCPointerType(V->getType()) &&
2425 "support for FCA unimplemented");
2426 if (isHandledGCPointerType(V->getType()) && !isa<Constant>(V)) {
2433 static DenseSet<Value *> computeKillSet(BasicBlock *BB) {
2434 DenseSet<Value *> KillSet;
2435 for (Instruction &I : *BB)
2436 if (isHandledGCPointerType(I.getType()))
2442 /// Check that the items in 'Live' dominate 'TI'. This is used as a basic
2443 /// sanity check for the liveness computation.
2444 static void checkBasicSSA(DominatorTree &DT, DenseSet<Value *> &Live,
2445 TerminatorInst *TI, bool TermOkay = false) {
2446 for (Value *V : Live) {
2447 if (auto *I = dyn_cast<Instruction>(V)) {
2448 // The terminator can be a member of the LiveOut set. LLVM's definition
2449 // of instruction dominance states that V does not dominate itself. As
2450 // such, we need to special case this to allow it.
2451 if (TermOkay && TI == I)
2453 assert(DT.dominates(I, TI) &&
2454 "basic SSA liveness expectation violated by liveness analysis");
2459 /// Check that all the liveness sets used during the computation of liveness
2460 /// obey basic SSA properties. This is useful for finding cases where we miss
2462 static void checkBasicSSA(DominatorTree &DT, GCPtrLivenessData &Data,
2464 checkBasicSSA(DT, Data.LiveSet[&BB], BB.getTerminator());
2465 checkBasicSSA(DT, Data.LiveOut[&BB], BB.getTerminator(), true);
2466 checkBasicSSA(DT, Data.LiveIn[&BB], BB.getTerminator());
2470 static void computeLiveInValues(DominatorTree &DT, Function &F,
2471 GCPtrLivenessData &Data) {
2473 SmallSetVector<BasicBlock *, 200> Worklist;
2474 auto AddPredsToWorklist = [&](BasicBlock *BB) {
2475 // We use a SetVector so that we don't have duplicates in the worklist.
2476 Worklist.insert(pred_begin(BB), pred_end(BB));
2478 auto NextItem = [&]() {
2479 BasicBlock *BB = Worklist.back();
2480 Worklist.pop_back();
2484 // Seed the liveness for each individual block
2485 for (BasicBlock &BB : F) {
2486 Data.KillSet[&BB] = computeKillSet(&BB);
2487 Data.LiveSet[&BB].clear();
2488 computeLiveInValues(BB.rbegin(), BB.rend(), Data.LiveSet[&BB]);
2491 for (Value *Kill : Data.KillSet[&BB])
2492 assert(!Data.LiveSet[&BB].count(Kill) && "live set contains kill");
2495 Data.LiveOut[&BB] = DenseSet<Value *>();
2496 computeLiveOutSeed(&BB, Data.LiveOut[&BB]);
2497 Data.LiveIn[&BB] = Data.LiveSet[&BB];
2498 set_union(Data.LiveIn[&BB], Data.LiveOut[&BB]);
2499 set_subtract(Data.LiveIn[&BB], Data.KillSet[&BB]);
2500 if (!Data.LiveIn[&BB].empty())
2501 AddPredsToWorklist(&BB);
2504 // Propagate that liveness until stable
2505 while (!Worklist.empty()) {
2506 BasicBlock *BB = NextItem();
2508 // Compute our new liveout set, then exit early if it hasn't changed
2509 // despite the contribution of our successor.
2510 DenseSet<Value *> LiveOut = Data.LiveOut[BB];
2511 const auto OldLiveOutSize = LiveOut.size();
2512 for (BasicBlock *Succ : successors(BB)) {
2513 assert(Data.LiveIn.count(Succ));
2514 set_union(LiveOut, Data.LiveIn[Succ]);
2516 // assert OutLiveOut is a subset of LiveOut
2517 if (OldLiveOutSize == LiveOut.size()) {
2518 // If the sets are the same size, then we didn't actually add anything
2519 // when unioning our successors LiveIn Thus, the LiveIn of this block
2523 Data.LiveOut[BB] = LiveOut;
2525 // Apply the effects of this basic block
2526 DenseSet<Value *> LiveTmp = LiveOut;
2527 set_union(LiveTmp, Data.LiveSet[BB]);
2528 set_subtract(LiveTmp, Data.KillSet[BB]);
2530 assert(Data.LiveIn.count(BB));
2531 const DenseSet<Value *> &OldLiveIn = Data.LiveIn[BB];
2532 // assert: OldLiveIn is a subset of LiveTmp
2533 if (OldLiveIn.size() != LiveTmp.size()) {
2534 Data.LiveIn[BB] = LiveTmp;
2535 AddPredsToWorklist(BB);
2537 } // while( !worklist.empty() )
2540 // Sanity check our ouput against SSA properties. This helps catch any
2541 // missing kills during the above iteration.
2542 for (BasicBlock &BB : F) {
2543 checkBasicSSA(DT, Data, BB);
2548 static void findLiveSetAtInst(Instruction *Inst, GCPtrLivenessData &Data,
2549 StatepointLiveSetTy &Out) {
2551 BasicBlock *BB = Inst->getParent();
2553 // Note: The copy is intentional and required
2554 assert(Data.LiveOut.count(BB));
2555 DenseSet<Value *> LiveOut = Data.LiveOut[BB];
2557 // We want to handle the statepoint itself oddly. It's
2558 // call result is not live (normal), nor are it's arguments
2559 // (unless they're used again later). This adjustment is
2560 // specifically what we need to relocate
2561 BasicBlock::reverse_iterator rend(Inst);
2562 computeLiveInValues(BB->rbegin(), rend, LiveOut);
2563 LiveOut.erase(Inst);
2564 Out.insert(LiveOut.begin(), LiveOut.end());
2567 static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData,
2569 PartiallyConstructedSafepointRecord &Info) {
2570 Instruction *Inst = CS.getInstruction();
2571 StatepointLiveSetTy Updated;
2572 findLiveSetAtInst(Inst, RevisedLivenessData, Updated);
2575 DenseSet<Value *> Bases;
2576 for (auto KVPair : Info.PointerToBase) {
2577 Bases.insert(KVPair.second);
2580 // We may have base pointers which are now live that weren't before. We need
2581 // to update the PointerToBase structure to reflect this.
2582 for (auto V : Updated)
2583 if (!Info.PointerToBase.count(V)) {
2584 assert(Bases.count(V) && "can't find base for unexpected live value");
2585 Info.PointerToBase[V] = V;
2590 for (auto V : Updated) {
2591 assert(Info.PointerToBase.count(V) &&
2592 "must be able to find base for live value");
2596 // Remove any stale base mappings - this can happen since our liveness is
2597 // more precise then the one inherent in the base pointer analysis
2598 DenseSet<Value *> ToErase;
2599 for (auto KVPair : Info.PointerToBase)
2600 if (!Updated.count(KVPair.first))
2601 ToErase.insert(KVPair.first);
2602 for (auto V : ToErase)
2603 Info.PointerToBase.erase(V);
2606 for (auto KVPair : Info.PointerToBase)
2607 assert(Updated.count(KVPair.first) && "record for non-live value");
2610 Info.liveset = Updated;