1 //===- RewriteStatepointsForGC.cpp - Make GC relocations explicit ---------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // Rewrite call/invoke instructions so as to make potential relocations
10 // performed by the garbage collector explicit in the IR.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/Transforms/Scalar/RewriteStatepointsForGC.h"
15 
16 #include "llvm/ADT/ArrayRef.h"
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/DenseSet.h"
19 #include "llvm/ADT/MapVector.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/Sequence.h"
22 #include "llvm/ADT/SetVector.h"
23 #include "llvm/ADT/SmallSet.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/ADT/StringRef.h"
26 #include "llvm/ADT/iterator_range.h"
27 #include "llvm/Analysis/DomTreeUpdater.h"
28 #include "llvm/Analysis/TargetLibraryInfo.h"
29 #include "llvm/Analysis/TargetTransformInfo.h"
30 #include "llvm/IR/Argument.h"
31 #include "llvm/IR/AttributeMask.h"
32 #include "llvm/IR/Attributes.h"
33 #include "llvm/IR/BasicBlock.h"
34 #include "llvm/IR/CallingConv.h"
35 #include "llvm/IR/Constant.h"
36 #include "llvm/IR/Constants.h"
37 #include "llvm/IR/DataLayout.h"
38 #include "llvm/IR/DerivedTypes.h"
39 #include "llvm/IR/Dominators.h"
40 #include "llvm/IR/Function.h"
41 #include "llvm/IR/GCStrategy.h"
42 #include "llvm/IR/IRBuilder.h"
43 #include "llvm/IR/InstIterator.h"
44 #include "llvm/IR/InstrTypes.h"
45 #include "llvm/IR/Instruction.h"
46 #include "llvm/IR/Instructions.h"
47 #include "llvm/IR/IntrinsicInst.h"
48 #include "llvm/IR/Intrinsics.h"
49 #include "llvm/IR/LLVMContext.h"
50 #include "llvm/IR/MDBuilder.h"
51 #include "llvm/IR/Metadata.h"
52 #include "llvm/IR/Module.h"
53 #include "llvm/IR/Statepoint.h"
54 #include "llvm/IR/Type.h"
55 #include "llvm/IR/User.h"
56 #include "llvm/IR/Value.h"
57 #include "llvm/IR/ValueHandle.h"
58 #include "llvm/Support/Casting.h"
59 #include "llvm/Support/CommandLine.h"
60 #include "llvm/Support/Compiler.h"
61 #include "llvm/Support/Debug.h"
62 #include "llvm/Support/ErrorHandling.h"
63 #include "llvm/Support/raw_ostream.h"
64 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
65 #include "llvm/Transforms/Utils/Local.h"
66 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
67 #include <algorithm>
68 #include <cassert>
69 #include <cstddef>
70 #include <cstdint>
71 #include <iterator>
72 #include <optional>
73 #include <set>
74 #include <string>
75 #include <utility>
76 #include <vector>
77 
78 #define DEBUG_TYPE "rewrite-statepoints-for-gc"
79 
80 using namespace llvm;
81 
82 // Print the liveset found at the insert location
83 static cl::opt<bool> PrintLiveSet("spp-print-liveset", cl::Hidden,
84                                   cl::init(false));
85 static cl::opt<bool> PrintLiveSetSize("spp-print-liveset-size", cl::Hidden,
86                                       cl::init(false));
87 
88 // Print out the base pointers for debugging
89 static cl::opt<bool> PrintBasePointers("spp-print-base-pointers", cl::Hidden,
90                                        cl::init(false));
91 
92 // Cost threshold measuring when it is profitable to rematerialize value instead
93 // of relocating it
94 static cl::opt<unsigned>
95 RematerializationThreshold("spp-rematerialization-threshold", cl::Hidden,
96                            cl::init(6));
97 
98 #ifdef EXPENSIVE_CHECKS
99 static bool ClobberNonLive = true;
100 #else
101 static bool ClobberNonLive = false;
102 #endif
103 
104 static cl::opt<bool, true> ClobberNonLiveOverride("rs4gc-clobber-non-live",
105                                                   cl::location(ClobberNonLive),
106                                                   cl::Hidden);
107 
108 static cl::opt<bool>
109     AllowStatepointWithNoDeoptInfo("rs4gc-allow-statepoint-with-no-deopt-info",
110                                    cl::Hidden, cl::init(true));
111 
112 static cl::opt<bool> RematDerivedAtUses("rs4gc-remat-derived-at-uses",
113                                         cl::Hidden, cl::init(true));
114 
115 /// The IR fed into RewriteStatepointsForGC may have had attributes and
116 /// metadata implying dereferenceability that are no longer valid/correct after
117 /// RewriteStatepointsForGC has run. This is because semantically, after
118 /// RewriteStatepointsForGC runs, all calls to gc.statepoint "free" the entire
119 /// heap. stripNonValidData (conservatively) restores
120 /// correctness by erasing all attributes in the module that externally imply
121 /// dereferenceability. Similar reasoning also applies to the noalias
122 /// attributes and metadata. gc.statepoint can touch the entire heap including
123 /// noalias objects.
124 /// Apart from attributes and metadata, we also remove instructions that imply
125 /// constant physical memory: llvm.invariant.start.
126 static void stripNonValidData(Module &M);
127 
128 // Find the GC strategy for a function, or null if it doesn't have one.
129 static std::unique_ptr<GCStrategy> findGCStrategy(Function &F);
130 
131 static bool shouldRewriteStatepointsIn(Function &F);
132 
133 PreservedAnalyses RewriteStatepointsForGC::run(Module &M,
134                                                ModuleAnalysisManager &AM) {
135   bool Changed = false;
136   auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
137   for (Function &F : M) {
138     // Nothing to do for declarations.
139     if (F.isDeclaration() || F.empty())
140       continue;
141 
142     // Policy choice says not to rewrite - the most common reason is that we're
143     // compiling code without a GCStrategy.
144     if (!shouldRewriteStatepointsIn(F))
145       continue;
146 
147     auto &DT = FAM.getResult<DominatorTreeAnalysis>(F);
148     auto &TTI = FAM.getResult<TargetIRAnalysis>(F);
149     auto &TLI = FAM.getResult<TargetLibraryAnalysis>(F);
150     Changed |= runOnFunction(F, DT, TTI, TLI);
151   }
152   if (!Changed)
153     return PreservedAnalyses::all();
154 
155   // stripNonValidData asserts that shouldRewriteStatepointsIn
156   // returns true for at least one function in the module.  Since at least
157   // one function changed, we know that the precondition is satisfied.
158   stripNonValidData(M);
159 
160   PreservedAnalyses PA;
161   PA.preserve<TargetIRAnalysis>();
162   PA.preserve<TargetLibraryAnalysis>();
163   return PA;
164 }
165 
166 namespace {
167 
168 struct GCPtrLivenessData {
169   /// Values defined in this block.
170   MapVector<BasicBlock *, SetVector<Value *>> KillSet;
171 
172   /// Values used in this block (and thus live); does not included values
173   /// killed within this block.
174   MapVector<BasicBlock *, SetVector<Value *>> LiveSet;
175 
176   /// Values live into this basic block (i.e. used by any
177   /// instruction in this basic block or ones reachable from here)
178   MapVector<BasicBlock *, SetVector<Value *>> LiveIn;
179 
180   /// Values live out of this basic block (i.e. live into
181   /// any successor block)
182   MapVector<BasicBlock *, SetVector<Value *>> LiveOut;
183 };
184 
185 // The type of the internal cache used inside the findBasePointers family
186 // of functions.  From the callers perspective, this is an opaque type and
187 // should not be inspected.
188 //
189 // In the actual implementation this caches two relations:
190 // - The base relation itself (i.e. this pointer is based on that one)
191 // - The base defining value relation (i.e. before base_phi insertion)
192 // Generally, after the execution of a full findBasePointer call, only the
193 // base relation will remain.  Internally, we add a mixture of the two
194 // types, then update all the second type to the first type
195 using DefiningValueMapTy = MapVector<Value *, Value *>;
196 using IsKnownBaseMapTy = MapVector<Value *, bool>;
197 using PointerToBaseTy = MapVector<Value *, Value *>;
198 using StatepointLiveSetTy = SetVector<Value *>;
199 using RematerializedValueMapTy =
200     MapVector<AssertingVH<Instruction>, AssertingVH<Value>>;
201 
202 struct PartiallyConstructedSafepointRecord {
203   /// The set of values known to be live across this safepoint
204   StatepointLiveSetTy LiveSet;
205 
206   /// The *new* gc.statepoint instruction itself.  This produces the token
207   /// that normal path gc.relocates and the gc.result are tied to.
208   GCStatepointInst *StatepointToken;
209 
210   /// Instruction to which exceptional gc relocates are attached
211   /// Makes it easier to iterate through them during relocationViaAlloca.
212   Instruction *UnwindToken;
213 
214   /// Record live values we are rematerialized instead of relocating.
215   /// They are not included into 'LiveSet' field.
216   /// Maps rematerialized copy to it's original value.
217   RematerializedValueMapTy RematerializedValues;
218 };
219 
220 struct RematerizlizationCandidateRecord {
221   // Chain from derived pointer to base.
222   SmallVector<Instruction *, 3> ChainToBase;
223   // Original base.
224   Value *RootOfChain;
225   // Cost of chain.
226   InstructionCost Cost;
227 };
228 using RematCandTy = MapVector<Value *, RematerizlizationCandidateRecord>;
229 
230 } // end anonymous namespace
231 
232 static ArrayRef<Use> GetDeoptBundleOperands(const CallBase *Call) {
233   std::optional<OperandBundleUse> DeoptBundle =
234       Call->getOperandBundle(LLVMContext::OB_deopt);
235 
236   if (!DeoptBundle) {
237     assert(AllowStatepointWithNoDeoptInfo &&
238            "Found non-leaf call without deopt info!");
239     return std::nullopt;
240   }
241 
242   return DeoptBundle->Inputs;
243 }
244 
245 /// Compute the live-in set for every basic block in the function
246 static void computeLiveInValues(DominatorTree &DT, Function &F,
247                                 GCPtrLivenessData &Data, GCStrategy *GC);
248 
249 /// Given results from the dataflow liveness computation, find the set of live
250 /// Values at a particular instruction.
251 static void findLiveSetAtInst(Instruction *inst, GCPtrLivenessData &Data,
252                               StatepointLiveSetTy &out, GCStrategy *GC);
253 
254 static bool isGCPointerType(Type *T, GCStrategy *GC) {
255   assert(GC && "GC Strategy for isGCPointerType cannot be null");
256 
257   if (!isa<PointerType>(T))
258     return false;
259 
260   // conservative - same as StatepointLowering
261   return GC->isGCManagedPointer(T).value_or(true);
262 }
263 
264 // Return true if this type is one which a) is a gc pointer or contains a GC
265 // pointer and b) is of a type this code expects to encounter as a live value.
266 // (The insertion code will assert that a type which matches (a) and not (b)
267 // is not encountered.)
268 static bool isHandledGCPointerType(Type *T, GCStrategy *GC) {
269   // We fully support gc pointers
270   if (isGCPointerType(T, GC))
271     return true;
272   // We partially support vectors of gc pointers. The code will assert if it
273   // can't handle something.
274   if (auto VT = dyn_cast<VectorType>(T))
275     if (isGCPointerType(VT->getElementType(), GC))
276       return true;
277   return false;
278 }
279 
280 #ifndef NDEBUG
281 /// Returns true if this type contains a gc pointer whether we know how to
282 /// handle that type or not.
283 static bool containsGCPtrType(Type *Ty, GCStrategy *GC) {
284   if (isGCPointerType(Ty, GC))
285     return true;
286   if (VectorType *VT = dyn_cast<VectorType>(Ty))
287     return isGCPointerType(VT->getScalarType(), GC);
288   if (ArrayType *AT = dyn_cast<ArrayType>(Ty))
289     return containsGCPtrType(AT->getElementType(), GC);
290   if (StructType *ST = dyn_cast<StructType>(Ty))
291     return llvm::any_of(ST->elements(),
292                         [GC](Type *Ty) { return containsGCPtrType(Ty, GC); });
293   return false;
294 }
295 
296 // Returns true if this is a type which a) is a gc pointer or contains a GC
297 // pointer and b) is of a type which the code doesn't expect (i.e. first class
298 // aggregates).  Used to trip assertions.
299 static bool isUnhandledGCPointerType(Type *Ty, GCStrategy *GC) {
300   return containsGCPtrType(Ty, GC) && !isHandledGCPointerType(Ty, GC);
301 }
302 #endif
303 
304 // Return the name of the value suffixed with the provided value, or if the
305 // value didn't have a name, the default value specified.
306 static std::string suffixed_name_or(Value *V, StringRef Suffix,
307                                     StringRef DefaultName) {
308   return V->hasName() ? (V->getName() + Suffix).str() : DefaultName.str();
309 }
310 
311 // Conservatively identifies any definitions which might be live at the
312 // given instruction. The  analysis is performed immediately before the
313 // given instruction. Values defined by that instruction are not considered
314 // live.  Values used by that instruction are considered live.
315 static void analyzeParsePointLiveness(
316     DominatorTree &DT, GCPtrLivenessData &OriginalLivenessData, CallBase *Call,
317     PartiallyConstructedSafepointRecord &Result, GCStrategy *GC) {
318   StatepointLiveSetTy LiveSet;
319   findLiveSetAtInst(Call, OriginalLivenessData, LiveSet, GC);
320 
321   if (PrintLiveSet) {
322     dbgs() << "Live Variables:\n";
323     for (Value *V : LiveSet)
324       dbgs() << " " << V->getName() << " " << *V << "\n";
325   }
326   if (PrintLiveSetSize) {
327     dbgs() << "Safepoint For: " << Call->getCalledOperand()->getName() << "\n";
328     dbgs() << "Number live values: " << LiveSet.size() << "\n";
329   }
330   Result.LiveSet = LiveSet;
331 }
332 
333 /// Returns true if V is a known base.
334 static bool isKnownBase(Value *V, const IsKnownBaseMapTy &KnownBases);
335 
336 /// Caches the IsKnownBase flag for a value and asserts that it wasn't present
337 /// in the cache before.
338 static void setKnownBase(Value *V, bool IsKnownBase,
339                          IsKnownBaseMapTy &KnownBases);
340 
341 static Value *findBaseDefiningValue(Value *I, DefiningValueMapTy &Cache,
342                                     IsKnownBaseMapTy &KnownBases);
343 
344 /// Return a base defining value for the 'Index' element of the given vector
345 /// instruction 'I'.  If Index is null, returns a BDV for the entire vector
346 /// 'I'.  As an optimization, this method will try to determine when the
347 /// element is known to already be a base pointer.  If this can be established,
348 /// the second value in the returned pair will be true.  Note that either a
349 /// vector or a pointer typed value can be returned.  For the former, the
350 /// vector returned is a BDV (and possibly a base) of the entire vector 'I'.
351 /// If the later, the return pointer is a BDV (or possibly a base) for the
352 /// particular element in 'I'.
353 static Value *findBaseDefiningValueOfVector(Value *I, DefiningValueMapTy &Cache,
354                                             IsKnownBaseMapTy &KnownBases) {
355   // Each case parallels findBaseDefiningValue below, see that code for
356   // detailed motivation.
357 
358   auto Cached = Cache.find(I);
359   if (Cached != Cache.end())
360     return Cached->second;
361 
362   if (isa<Argument>(I)) {
363     // An incoming argument to the function is a base pointer
364     Cache[I] = I;
365     setKnownBase(I, /* IsKnownBase */true, KnownBases);
366     return I;
367   }
368 
369   if (isa<Constant>(I)) {
370     // Base of constant vector consists only of constant null pointers.
371     // For reasoning see similar case inside 'findBaseDefiningValue' function.
372     auto *CAZ = ConstantAggregateZero::get(I->getType());
373     Cache[I] = CAZ;
374     setKnownBase(CAZ, /* IsKnownBase */true, KnownBases);
375     return CAZ;
376   }
377 
378   if (isa<LoadInst>(I)) {
379     Cache[I] = I;
380     setKnownBase(I, /* IsKnownBase */true, KnownBases);
381     return I;
382   }
383 
384   if (isa<InsertElementInst>(I)) {
385     // We don't know whether this vector contains entirely base pointers or
386     // not.  To be conservatively correct, we treat it as a BDV and will
387     // duplicate code as needed to construct a parallel vector of bases.
388     Cache[I] = I;
389     setKnownBase(I, /* IsKnownBase */false, KnownBases);
390     return I;
391   }
392 
393   if (isa<ShuffleVectorInst>(I)) {
394     // We don't know whether this vector contains entirely base pointers or
395     // not.  To be conservatively correct, we treat it as a BDV and will
396     // duplicate code as needed to construct a parallel vector of bases.
397     // TODO: There a number of local optimizations which could be applied here
398     // for particular sufflevector patterns.
399     Cache[I] = I;
400     setKnownBase(I, /* IsKnownBase */false, KnownBases);
401     return I;
402   }
403 
404   // The behavior of getelementptr instructions is the same for vector and
405   // non-vector data types.
406   if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
407     auto *BDV =
408         findBaseDefiningValue(GEP->getPointerOperand(), Cache, KnownBases);
409     Cache[GEP] = BDV;
410     return BDV;
411   }
412 
413   // The behavior of freeze instructions is the same for vector and
414   // non-vector data types.
415   if (auto *Freeze = dyn_cast<FreezeInst>(I)) {
416     auto *BDV = findBaseDefiningValue(Freeze->getOperand(0), Cache, KnownBases);
417     Cache[Freeze] = BDV;
418     return BDV;
419   }
420 
421   // If the pointer comes through a bitcast of a vector of pointers to
422   // a vector of another type of pointer, then look through the bitcast
423   if (auto *BC = dyn_cast<BitCastInst>(I)) {
424     auto *BDV = findBaseDefiningValue(BC->getOperand(0), Cache, KnownBases);
425     Cache[BC] = BDV;
426     return BDV;
427   }
428 
429   // We assume that functions in the source language only return base
430   // pointers.  This should probably be generalized via attributes to support
431   // both source language and internal functions.
432   if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
433     Cache[I] = I;
434     setKnownBase(I, /* IsKnownBase */true, KnownBases);
435     return I;
436   }
437 
438   // A PHI or Select is a base defining value.  The outer findBasePointer
439   // algorithm is responsible for constructing a base value for this BDV.
440   assert((isa<SelectInst>(I) || isa<PHINode>(I)) &&
441          "unknown vector instruction - no base found for vector element");
442   Cache[I] = I;
443   setKnownBase(I, /* IsKnownBase */false, KnownBases);
444   return I;
445 }
446 
447 /// Helper function for findBasePointer - Will return a value which either a)
448 /// defines the base pointer for the input, b) blocks the simple search
449 /// (i.e. a PHI or Select of two derived pointers), or c) involves a change
450 /// from pointer to vector type or back.
451 static Value *findBaseDefiningValue(Value *I, DefiningValueMapTy &Cache,
452                                     IsKnownBaseMapTy &KnownBases) {
453   assert(I->getType()->isPtrOrPtrVectorTy() &&
454          "Illegal to ask for the base pointer of a non-pointer type");
455   auto Cached = Cache.find(I);
456   if (Cached != Cache.end())
457     return Cached->second;
458 
459   if (I->getType()->isVectorTy())
460     return findBaseDefiningValueOfVector(I, Cache, KnownBases);
461 
462   if (isa<Argument>(I)) {
463     // An incoming argument to the function is a base pointer
464     // We should have never reached here if this argument isn't an gc value
465     Cache[I] = I;
466     setKnownBase(I, /* IsKnownBase */true, KnownBases);
467     return I;
468   }
469 
470   if (isa<Constant>(I)) {
471     // We assume that objects with a constant base (e.g. a global) can't move
472     // and don't need to be reported to the collector because they are always
473     // live. Besides global references, all kinds of constants (e.g. undef,
474     // constant expressions, null pointers) can be introduced by the inliner or
475     // the optimizer, especially on dynamically dead paths.
476     // Here we treat all of them as having single null base. By doing this we
477     // trying to avoid problems reporting various conflicts in a form of
478     // "phi (const1, const2)" or "phi (const, regular gc ptr)".
479     // See constant.ll file for relevant test cases.
480 
481     auto *CPN = ConstantPointerNull::get(cast<PointerType>(I->getType()));
482     Cache[I] = CPN;
483     setKnownBase(CPN, /* IsKnownBase */true, KnownBases);
484     return CPN;
485   }
486 
487   // inttoptrs in an integral address space are currently ill-defined.  We
488   // treat them as defining base pointers here for consistency with the
489   // constant rule above and because we don't really have a better semantic
490   // to give them.  Note that the optimizer is always free to insert undefined
491   // behavior on dynamically dead paths as well.
492   if (isa<IntToPtrInst>(I)) {
493     Cache[I] = I;
494     setKnownBase(I, /* IsKnownBase */true, KnownBases);
495     return I;
496   }
497 
498   if (CastInst *CI = dyn_cast<CastInst>(I)) {
499     Value *Def = CI->stripPointerCasts();
500     // If stripping pointer casts changes the address space there is an
501     // addrspacecast in between.
502     assert(cast<PointerType>(Def->getType())->getAddressSpace() ==
503                cast<PointerType>(CI->getType())->getAddressSpace() &&
504            "unsupported addrspacecast");
505     // If we find a cast instruction here, it means we've found a cast which is
506     // not simply a pointer cast (i.e. an inttoptr).  We don't know how to
507     // handle int->ptr conversion.
508     assert(!isa<CastInst>(Def) && "shouldn't find another cast here");
509     auto *BDV = findBaseDefiningValue(Def, Cache, KnownBases);
510     Cache[CI] = BDV;
511     return BDV;
512   }
513 
514   if (isa<LoadInst>(I)) {
515     // The value loaded is an gc base itself
516     Cache[I] = I;
517     setKnownBase(I, /* IsKnownBase */true, KnownBases);
518     return I;
519   }
520 
521   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
522     // The base of this GEP is the base
523     auto *BDV =
524         findBaseDefiningValue(GEP->getPointerOperand(), Cache, KnownBases);
525     Cache[GEP] = BDV;
526     return BDV;
527   }
528 
529   if (auto *Freeze = dyn_cast<FreezeInst>(I)) {
530     auto *BDV = findBaseDefiningValue(Freeze->getOperand(0), Cache, KnownBases);
531     Cache[Freeze] = BDV;
532     return BDV;
533   }
534 
535   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
536     switch (II->getIntrinsicID()) {
537     default:
538       // fall through to general call handling
539       break;
540     case Intrinsic::experimental_gc_statepoint:
541       llvm_unreachable("statepoints don't produce pointers");
542     case Intrinsic::experimental_gc_relocate:
543       // Rerunning safepoint insertion after safepoints are already
544       // inserted is not supported.  It could probably be made to work,
545       // but why are you doing this?  There's no good reason.
546       llvm_unreachable("repeat safepoint insertion is not supported");
547     case Intrinsic::gcroot:
548       // Currently, this mechanism hasn't been extended to work with gcroot.
549       // There's no reason it couldn't be, but I haven't thought about the
550       // implications much.
551       llvm_unreachable(
552           "interaction with the gcroot mechanism is not supported");
553     case Intrinsic::experimental_gc_get_pointer_base:
554       auto *BDV = findBaseDefiningValue(II->getOperand(0), Cache, KnownBases);
555       Cache[II] = BDV;
556       return BDV;
557     }
558   }
559   // We assume that functions in the source language only return base
560   // pointers.  This should probably be generalized via attributes to support
561   // both source language and internal functions.
562   if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
563     Cache[I] = I;
564     setKnownBase(I, /* IsKnownBase */true, KnownBases);
565     return I;
566   }
567 
568   // TODO: I have absolutely no idea how to implement this part yet.  It's not
569   // necessarily hard, I just haven't really looked at it yet.
570   assert(!isa<LandingPadInst>(I) && "Landing Pad is unimplemented");
571 
572   if (isa<AtomicCmpXchgInst>(I)) {
573     // A CAS is effectively a atomic store and load combined under a
574     // predicate.  From the perspective of base pointers, we just treat it
575     // like a load.
576     Cache[I] = I;
577     setKnownBase(I, /* IsKnownBase */true, KnownBases);
578     return I;
579   }
580 
581   assert(!isa<AtomicRMWInst>(I) && "Xchg handled above, all others are "
582                                    "binary ops which don't apply to pointers");
583 
584   // The aggregate ops.  Aggregates can either be in the heap or on the
585   // stack, but in either case, this is simply a field load.  As a result,
586   // this is a defining definition of the base just like a load is.
587   if (isa<ExtractValueInst>(I)) {
588     Cache[I] = I;
589     setKnownBase(I, /* IsKnownBase */true, KnownBases);
590     return I;
591   }
592 
593   // We should never see an insert vector since that would require we be
594   // tracing back a struct value not a pointer value.
595   assert(!isa<InsertValueInst>(I) &&
596          "Base pointer for a struct is meaningless");
597 
598   // This value might have been generated by findBasePointer() called when
599   // substituting gc.get.pointer.base() intrinsic.
600   bool IsKnownBase =
601       isa<Instruction>(I) && cast<Instruction>(I)->getMetadata("is_base_value");
602   setKnownBase(I, /* IsKnownBase */IsKnownBase, KnownBases);
603   Cache[I] = I;
604 
605   // An extractelement produces a base result exactly when it's input does.
606   // We may need to insert a parallel instruction to extract the appropriate
607   // element out of the base vector corresponding to the input. Given this,
608   // it's analogous to the phi and select case even though it's not a merge.
609   if (isa<ExtractElementInst>(I))
610     // Note: There a lot of obvious peephole cases here.  This are deliberately
611     // handled after the main base pointer inference algorithm to make writing
612     // test cases to exercise that code easier.
613     return I;
614 
615   // The last two cases here don't return a base pointer.  Instead, they
616   // return a value which dynamically selects from among several base
617   // derived pointers (each with it's own base potentially).  It's the job of
618   // the caller to resolve these.
619   assert((isa<SelectInst>(I) || isa<PHINode>(I)) &&
620          "missing instruction case in findBaseDefiningValue");
621   return I;
622 }
623 
624 /// Returns the base defining value for this value.
625 static Value *findBaseDefiningValueCached(Value *I, DefiningValueMapTy &Cache,
626                                           IsKnownBaseMapTy &KnownBases) {
627   if (!Cache.contains(I)) {
628     auto *BDV = findBaseDefiningValue(I, Cache, KnownBases);
629     Cache[I] = BDV;
630     LLVM_DEBUG(dbgs() << "fBDV-cached: " << I->getName() << " -> "
631                       << Cache[I]->getName() << ", is known base = "
632                       << KnownBases[I] << "\n");
633   }
634   assert(Cache[I] != nullptr);
635   assert(KnownBases.contains(Cache[I]) &&
636          "Cached value must be present in known bases map");
637   return Cache[I];
638 }
639 
640 /// Return a base pointer for this value if known.  Otherwise, return it's
641 /// base defining value.
642 static Value *findBaseOrBDV(Value *I, DefiningValueMapTy &Cache,
643                             IsKnownBaseMapTy &KnownBases) {
644   Value *Def = findBaseDefiningValueCached(I, Cache, KnownBases);
645   auto Found = Cache.find(Def);
646   if (Found != Cache.end()) {
647     // Either a base-of relation, or a self reference.  Caller must check.
648     return Found->second;
649   }
650   // Only a BDV available
651   return Def;
652 }
653 
654 #ifndef NDEBUG
655 /// This value is a base pointer that is not generated by RS4GC, i.e. it already
656 /// exists in the code.
657 static bool isOriginalBaseResult(Value *V) {
658   // no recursion possible
659   return !isa<PHINode>(V) && !isa<SelectInst>(V) &&
660          !isa<ExtractElementInst>(V) && !isa<InsertElementInst>(V) &&
661          !isa<ShuffleVectorInst>(V);
662 }
663 #endif
664 
665 static bool isKnownBase(Value *V, const IsKnownBaseMapTy &KnownBases) {
666   auto It = KnownBases.find(V);
667   assert(It != KnownBases.end() && "Value not present in the map");
668   return It->second;
669 }
670 
671 static void setKnownBase(Value *V, bool IsKnownBase,
672                          IsKnownBaseMapTy &KnownBases) {
673 #ifndef NDEBUG
674   auto It = KnownBases.find(V);
675   if (It != KnownBases.end())
676     assert(It->second == IsKnownBase && "Changing already present value");
677 #endif
678   KnownBases[V] = IsKnownBase;
679 }
680 
681 // Returns true if First and Second values are both scalar or both vector.
682 static bool areBothVectorOrScalar(Value *First, Value *Second) {
683   return isa<VectorType>(First->getType()) ==
684          isa<VectorType>(Second->getType());
685 }
686 
687 namespace {
688 
689 /// Models the state of a single base defining value in the findBasePointer
690 /// algorithm for determining where a new instruction is needed to propagate
691 /// the base of this BDV.
692 class BDVState {
693 public:
694   enum StatusTy {
695      // Starting state of lattice
696      Unknown,
697      // Some specific base value -- does *not* mean that instruction
698      // propagates the base of the object
699      // ex: gep %arg, 16 -> %arg is the base value
700      Base,
701      // Need to insert a node to represent a merge.
702      Conflict
703   };
704 
705   BDVState() {
706     llvm_unreachable("missing state in map");
707   }
708 
709   explicit BDVState(Value *OriginalValue)
710     : OriginalValue(OriginalValue) {}
711   explicit BDVState(Value *OriginalValue, StatusTy Status, Value *BaseValue = nullptr)
712     : OriginalValue(OriginalValue), Status(Status), BaseValue(BaseValue) {
713     assert(Status != Base || BaseValue);
714   }
715 
716   StatusTy getStatus() const { return Status; }
717   Value *getOriginalValue() const { return OriginalValue; }
718   Value *getBaseValue() const { return BaseValue; }
719 
720   bool isBase() const { return getStatus() == Base; }
721   bool isUnknown() const { return getStatus() == Unknown; }
722   bool isConflict() const { return getStatus() == Conflict; }
723 
724   // Values of type BDVState form a lattice, and this function implements the
725   // meet
726   // operation.
727   void meet(const BDVState &Other) {
728     auto markConflict = [&]() {
729       Status = BDVState::Conflict;
730       BaseValue = nullptr;
731     };
732     // Conflict is a final state.
733     if (isConflict())
734       return;
735     // if we are not known - just take other state.
736     if (isUnknown()) {
737       Status = Other.getStatus();
738       BaseValue = Other.getBaseValue();
739       return;
740     }
741     // We are base.
742     assert(isBase() && "Unknown state");
743     // If other is unknown - just keep our state.
744     if (Other.isUnknown())
745       return;
746     // If other is conflict - it is a final state.
747     if (Other.isConflict())
748       return markConflict();
749     // Other is base as well.
750     assert(Other.isBase() && "Unknown state");
751     // If bases are different - Conflict.
752     if (getBaseValue() != Other.getBaseValue())
753       return markConflict();
754     // We are identical, do nothing.
755   }
756 
757   bool operator==(const BDVState &Other) const {
758     return OriginalValue == Other.OriginalValue && BaseValue == Other.BaseValue &&
759       Status == Other.Status;
760   }
761 
762   bool operator!=(const BDVState &other) const { return !(*this == other); }
763 
764   LLVM_DUMP_METHOD
765   void dump() const {
766     print(dbgs());
767     dbgs() << '\n';
768   }
769 
770   void print(raw_ostream &OS) const {
771     switch (getStatus()) {
772     case Unknown:
773       OS << "U";
774       break;
775     case Base:
776       OS << "B";
777       break;
778     case Conflict:
779       OS << "C";
780       break;
781     }
782     OS << " (base " << getBaseValue() << " - "
783        << (getBaseValue() ? getBaseValue()->getName() : "nullptr") << ")"
784        << " for  "  << OriginalValue->getName() << ":";
785   }
786 
787 private:
788   AssertingVH<Value> OriginalValue; // instruction this state corresponds to
789   StatusTy Status = Unknown;
790   AssertingVH<Value> BaseValue = nullptr; // Non-null only if Status == Base.
791 };
792 
793 } // end anonymous namespace
794 
795 #ifndef NDEBUG
796 static raw_ostream &operator<<(raw_ostream &OS, const BDVState &State) {
797   State.print(OS);
798   return OS;
799 }
800 #endif
801 
802 /// For a given value or instruction, figure out what base ptr its derived from.
803 /// For gc objects, this is simply itself.  On success, returns a value which is
804 /// the base pointer.  (This is reliable and can be used for relocation.)  On
805 /// failure, returns nullptr.
806 static Value *findBasePointer(Value *I, DefiningValueMapTy &Cache,
807                               IsKnownBaseMapTy &KnownBases) {
808   Value *Def = findBaseOrBDV(I, Cache, KnownBases);
809 
810   if (isKnownBase(Def, KnownBases) && areBothVectorOrScalar(Def, I))
811     return Def;
812 
813   // Here's the rough algorithm:
814   // - For every SSA value, construct a mapping to either an actual base
815   //   pointer or a PHI which obscures the base pointer.
816   // - Construct a mapping from PHI to unknown TOP state.  Use an
817   //   optimistic algorithm to propagate base pointer information.  Lattice
818   //   looks like:
819   //   UNKNOWN
820   //   b1 b2 b3 b4
821   //   CONFLICT
822   //   When algorithm terminates, all PHIs will either have a single concrete
823   //   base or be in a conflict state.
824   // - For every conflict, insert a dummy PHI node without arguments.  Add
825   //   these to the base[Instruction] = BasePtr mapping.  For every
826   //   non-conflict, add the actual base.
827   //  - For every conflict, add arguments for the base[a] of each input
828   //   arguments.
829   //
830   // Note: A simpler form of this would be to add the conflict form of all
831   // PHIs without running the optimistic algorithm.  This would be
832   // analogous to pessimistic data flow and would likely lead to an
833   // overall worse solution.
834 
835 #ifndef NDEBUG
836   auto isExpectedBDVType = [](Value *BDV) {
837     return isa<PHINode>(BDV) || isa<SelectInst>(BDV) ||
838            isa<ExtractElementInst>(BDV) || isa<InsertElementInst>(BDV) ||
839            isa<ShuffleVectorInst>(BDV);
840   };
841 #endif
842 
843   // Once populated, will contain a mapping from each potentially non-base BDV
844   // to a lattice value (described above) which corresponds to that BDV.
845   // We use the order of insertion (DFS over the def/use graph) to provide a
846   // stable deterministic ordering for visiting DenseMaps (which are unordered)
847   // below.  This is important for deterministic compilation.
848   MapVector<Value *, BDVState> States;
849 
850 #ifndef NDEBUG
851   auto VerifyStates = [&]() {
852     for (auto &Entry : States) {
853       assert(Entry.first == Entry.second.getOriginalValue());
854     }
855   };
856 #endif
857 
858   auto visitBDVOperands = [](Value *BDV, std::function<void (Value*)> F) {
859     if (PHINode *PN = dyn_cast<PHINode>(BDV)) {
860       for (Value *InVal : PN->incoming_values())
861         F(InVal);
862     } else if (SelectInst *SI = dyn_cast<SelectInst>(BDV)) {
863       F(SI->getTrueValue());
864       F(SI->getFalseValue());
865     } else if (auto *EE = dyn_cast<ExtractElementInst>(BDV)) {
866       F(EE->getVectorOperand());
867     } else if (auto *IE = dyn_cast<InsertElementInst>(BDV)) {
868       F(IE->getOperand(0));
869       F(IE->getOperand(1));
870     } else if (auto *SV = dyn_cast<ShuffleVectorInst>(BDV)) {
871       // For a canonical broadcast, ignore the undef argument
872       // (without this, we insert a parallel base shuffle for every broadcast)
873       F(SV->getOperand(0));
874       if (!SV->isZeroEltSplat())
875         F(SV->getOperand(1));
876     } else {
877       llvm_unreachable("unexpected BDV type");
878     }
879   };
880 
881 
882   // Recursively fill in all base defining values reachable from the initial
883   // one for which we don't already know a definite base value for
884   /* scope */ {
885     SmallVector<Value*, 16> Worklist;
886     Worklist.push_back(Def);
887     States.insert({Def, BDVState(Def)});
888     while (!Worklist.empty()) {
889       Value *Current = Worklist.pop_back_val();
890       assert(!isOriginalBaseResult(Current) && "why did it get added?");
891 
892       auto visitIncomingValue = [&](Value *InVal) {
893         Value *Base = findBaseOrBDV(InVal, Cache, KnownBases);
894         if (isKnownBase(Base, KnownBases) && areBothVectorOrScalar(Base, InVal))
895           // Known bases won't need new instructions introduced and can be
896           // ignored safely. However, this can only be done when InVal and Base
897           // are both scalar or both vector. Otherwise, we need to find a
898           // correct BDV for InVal, by creating an entry in the lattice
899           // (States).
900           return;
901         assert(isExpectedBDVType(Base) && "the only non-base values "
902                "we see should be base defining values");
903         if (States.insert(std::make_pair(Base, BDVState(Base))).second)
904           Worklist.push_back(Base);
905       };
906 
907       visitBDVOperands(Current, visitIncomingValue);
908     }
909   }
910 
911 #ifndef NDEBUG
912   VerifyStates();
913   LLVM_DEBUG(dbgs() << "States after initialization:\n");
914   for (const auto &Pair : States) {
915     LLVM_DEBUG(dbgs() << " " << Pair.second << " for " << *Pair.first << "\n");
916   }
917 #endif
918 
919   // Iterate forward through the value graph pruning any node from the state
920   // list where all of the inputs are base pointers.  The purpose of this is to
921   // reuse existing values when the derived pointer we were asked to materialize
922   // a base pointer for happens to be a base pointer itself.  (Or a sub-graph
923   // feeding it does.)
924   SmallVector<Value *> ToRemove;
925   do {
926     ToRemove.clear();
927     for (auto Pair : States) {
928       Value *BDV = Pair.first;
929       auto canPruneInput = [&](Value *V) {
930         // If the input of the BDV is the BDV itself we can prune it. This is
931         // only possible if the BDV is a PHI node.
932         if (V->stripPointerCasts() == BDV)
933           return true;
934         Value *VBDV = findBaseOrBDV(V, Cache, KnownBases);
935         if (V->stripPointerCasts() != VBDV)
936           return false;
937         // The assumption is that anything not in the state list is
938         // propagates a base pointer.
939         return States.count(VBDV) == 0;
940       };
941 
942       bool CanPrune = true;
943       visitBDVOperands(BDV, [&](Value *Op) {
944         CanPrune = CanPrune && canPruneInput(Op);
945       });
946       if (CanPrune)
947         ToRemove.push_back(BDV);
948     }
949     for (Value *V : ToRemove) {
950       States.erase(V);
951       // Cache the fact V is it's own base for later usage.
952       Cache[V] = V;
953     }
954   } while (!ToRemove.empty());
955 
956   // Did we manage to prove that Def itself must be a base pointer?
957   if (!States.count(Def))
958     return Def;
959 
960   // Return a phi state for a base defining value.  We'll generate a new
961   // base state for known bases and expect to find a cached state otherwise.
962   auto GetStateForBDV = [&](Value *BaseValue, Value *Input) {
963     auto I = States.find(BaseValue);
964     if (I != States.end())
965       return I->second;
966     assert(areBothVectorOrScalar(BaseValue, Input));
967     return BDVState(BaseValue, BDVState::Base, BaseValue);
968   };
969 
970   bool Progress = true;
971   while (Progress) {
972 #ifndef NDEBUG
973     const size_t OldSize = States.size();
974 #endif
975     Progress = false;
976     // We're only changing values in this loop, thus safe to keep iterators.
977     // Since this is computing a fixed point, the order of visit does not
978     // effect the result.  TODO: We could use a worklist here and make this run
979     // much faster.
980     for (auto Pair : States) {
981       Value *BDV = Pair.first;
982       // Only values that do not have known bases or those that have differing
983       // type (scalar versus vector) from a possible known base should be in the
984       // lattice.
985       assert((!isKnownBase(BDV, KnownBases) ||
986              !areBothVectorOrScalar(BDV, Pair.second.getBaseValue())) &&
987                  "why did it get added?");
988 
989       BDVState NewState(BDV);
990       visitBDVOperands(BDV, [&](Value *Op) {
991         Value *BDV = findBaseOrBDV(Op, Cache, KnownBases);
992         auto OpState = GetStateForBDV(BDV, Op);
993         NewState.meet(OpState);
994       });
995 
996       BDVState OldState = Pair.second;
997       if (OldState != NewState) {
998         Progress = true;
999         States[BDV] = NewState;
1000       }
1001     }
1002 
1003     assert(OldSize == States.size() &&
1004            "fixed point shouldn't be adding any new nodes to state");
1005   }
1006 
1007 #ifndef NDEBUG
1008   VerifyStates();
1009   LLVM_DEBUG(dbgs() << "States after meet iteration:\n");
1010   for (const auto &Pair : States) {
1011     LLVM_DEBUG(dbgs() << " " << Pair.second << " for " << *Pair.first << "\n");
1012   }
1013 #endif
1014 
1015   // Even though we have identified a concrete base (or a conflict) for all live
1016   // pointers at this point, there are cases where the base is of an
1017   // incompatible type compared to the original instruction. We conservatively
1018   // mark those as conflicts to ensure that corresponding BDVs will be generated
1019   // in the next steps.
1020 
1021   // this is a rather explicit check for all cases where we should mark the
1022   // state as a conflict to force the latter stages of the algorithm to emit
1023   // the BDVs.
1024   // TODO: in many cases the instructions emited for the conflicting states
1025   // will be identical to the I itself (if the I's operate on their BDVs
1026   // themselves). We should expoit this, but can't do it here since it would
1027   // break the invariant about the BDVs not being known to be a base.
1028   // TODO: the code also does not handle constants at all - the algorithm relies
1029   // on all constants having the same BDV and therefore constant-only insns
1030   // will never be in conflict, but this check is ignored here. If the
1031   // constant conflicts will be to BDVs themselves, they will be identical
1032   // instructions and will get optimized away (as in the above TODO)
1033   auto MarkConflict = [&](Instruction *I, Value *BaseValue) {
1034     // II and EE mixes vector & scalar so is always a conflict
1035     if (isa<InsertElementInst>(I) || isa<ExtractElementInst>(I))
1036       return true;
1037     // Shuffle vector is always a conflict as it creates new vector from
1038     // existing ones.
1039     if (isa<ShuffleVectorInst>(I))
1040       return true;
1041     // Any  instructions where the computed base type differs from the
1042     // instruction type. An example is where an extract instruction is used by a
1043     // select. Here the select's BDV is a vector (because of extract's BDV),
1044     // while the select itself is a scalar type. Note that the IE and EE
1045     // instruction check is not fully subsumed by the vector<->scalar check at
1046     // the end, this is due to the BDV algorithm being ignorant of BDV types at
1047     // this junction.
1048     if (!areBothVectorOrScalar(BaseValue, I))
1049       return true;
1050     return false;
1051   };
1052 
1053   for (auto Pair : States) {
1054     Instruction *I = cast<Instruction>(Pair.first);
1055     BDVState State = Pair.second;
1056     auto *BaseValue = State.getBaseValue();
1057     // Only values that do not have known bases or those that have differing
1058     // type (scalar versus vector) from a possible known base should be in the
1059     // lattice.
1060     assert(
1061         (!isKnownBase(I, KnownBases) || !areBothVectorOrScalar(I, BaseValue)) &&
1062         "why did it get added?");
1063     assert(!State.isUnknown() && "Optimistic algorithm didn't complete!");
1064 
1065     // since we only mark vec-scalar insns as conflicts in the pass, our work is
1066     // done if the instruction already conflicts
1067     if (State.isConflict())
1068       continue;
1069 
1070     if (MarkConflict(I, BaseValue))
1071       States[I] = BDVState(I, BDVState::Conflict);
1072   }
1073 
1074 #ifndef NDEBUG
1075   VerifyStates();
1076 #endif
1077 
1078   // Insert Phis for all conflicts
1079   // TODO: adjust naming patterns to avoid this order of iteration dependency
1080   for (auto Pair : States) {
1081     Instruction *I = cast<Instruction>(Pair.first);
1082     BDVState State = Pair.second;
1083     // Only values that do not have known bases or those that have differing
1084     // type (scalar versus vector) from a possible known base should be in the
1085     // lattice.
1086     assert((!isKnownBase(I, KnownBases) ||
1087             !areBothVectorOrScalar(I, State.getBaseValue())) &&
1088            "why did it get added?");
1089     assert(!State.isUnknown() && "Optimistic algorithm didn't complete!");
1090 
1091     // Since we're joining a vector and scalar base, they can never be the
1092     // same.  As a result, we should always see insert element having reached
1093     // the conflict state.
1094     assert(!isa<InsertElementInst>(I) || State.isConflict());
1095 
1096     if (!State.isConflict())
1097       continue;
1098 
1099     auto getMangledName = [](Instruction *I) -> std::string {
1100       if (isa<PHINode>(I)) {
1101         return suffixed_name_or(I, ".base", "base_phi");
1102       } else if (isa<SelectInst>(I)) {
1103         return suffixed_name_or(I, ".base", "base_select");
1104       } else if (isa<ExtractElementInst>(I)) {
1105         return suffixed_name_or(I, ".base", "base_ee");
1106       } else if (isa<InsertElementInst>(I)) {
1107         return suffixed_name_or(I, ".base", "base_ie");
1108       } else {
1109         return suffixed_name_or(I, ".base", "base_sv");
1110       }
1111     };
1112 
1113     Instruction *BaseInst = I->clone();
1114     BaseInst->insertBefore(I);
1115     BaseInst->setName(getMangledName(I));
1116     // Add metadata marking this as a base value
1117     BaseInst->setMetadata("is_base_value", MDNode::get(I->getContext(), {}));
1118     States[I] = BDVState(I, BDVState::Conflict, BaseInst);
1119     setKnownBase(BaseInst, /* IsKnownBase */true, KnownBases);
1120   }
1121 
1122 #ifndef NDEBUG
1123   VerifyStates();
1124 #endif
1125 
1126   // Returns a instruction which produces the base pointer for a given
1127   // instruction.  The instruction is assumed to be an input to one of the BDVs
1128   // seen in the inference algorithm above.  As such, we must either already
1129   // know it's base defining value is a base, or have inserted a new
1130   // instruction to propagate the base of it's BDV and have entered that newly
1131   // introduced instruction into the state table.  In either case, we are
1132   // assured to be able to determine an instruction which produces it's base
1133   // pointer.
1134   auto getBaseForInput = [&](Value *Input, Instruction *InsertPt) {
1135     Value *BDV = findBaseOrBDV(Input, Cache, KnownBases);
1136     Value *Base = nullptr;
1137     if (!States.count(BDV)) {
1138       assert(areBothVectorOrScalar(BDV, Input));
1139       Base = BDV;
1140     } else {
1141       // Either conflict or base.
1142       assert(States.count(BDV));
1143       Base = States[BDV].getBaseValue();
1144     }
1145     assert(Base && "Can't be null");
1146     // The cast is needed since base traversal may strip away bitcasts
1147     if (Base->getType() != Input->getType() && InsertPt)
1148       Base = new BitCastInst(Base, Input->getType(), "cast", InsertPt);
1149     return Base;
1150   };
1151 
1152   // Fixup all the inputs of the new PHIs.  Visit order needs to be
1153   // deterministic and predictable because we're naming newly created
1154   // instructions.
1155   for (auto Pair : States) {
1156     Instruction *BDV = cast<Instruction>(Pair.first);
1157     BDVState State = Pair.second;
1158 
1159     // Only values that do not have known bases or those that have differing
1160     // type (scalar versus vector) from a possible known base should be in the
1161     // lattice.
1162     assert((!isKnownBase(BDV, KnownBases) ||
1163             !areBothVectorOrScalar(BDV, State.getBaseValue())) &&
1164            "why did it get added?");
1165     assert(!State.isUnknown() && "Optimistic algorithm didn't complete!");
1166     if (!State.isConflict())
1167       continue;
1168 
1169     if (PHINode *BasePHI = dyn_cast<PHINode>(State.getBaseValue())) {
1170       PHINode *PN = cast<PHINode>(BDV);
1171       const unsigned NumPHIValues = PN->getNumIncomingValues();
1172 
1173       // The IR verifier requires phi nodes with multiple entries from the
1174       // same basic block to have the same incoming value for each of those
1175       // entries.  Since we're inserting bitcasts in the loop, make sure we
1176       // do so at least once per incoming block.
1177       DenseMap<BasicBlock *, Value*> BlockToValue;
1178       for (unsigned i = 0; i < NumPHIValues; i++) {
1179         Value *InVal = PN->getIncomingValue(i);
1180         BasicBlock *InBB = PN->getIncomingBlock(i);
1181         if (!BlockToValue.count(InBB))
1182           BlockToValue[InBB] = getBaseForInput(InVal, InBB->getTerminator());
1183         else {
1184 #ifndef NDEBUG
1185           Value *OldBase = BlockToValue[InBB];
1186           Value *Base = getBaseForInput(InVal, nullptr);
1187 
1188           // We can't use `stripPointerCasts` instead of this function because
1189           // `stripPointerCasts` doesn't handle vectors of pointers.
1190           auto StripBitCasts = [](Value *V) -> Value * {
1191             while (auto *BC = dyn_cast<BitCastInst>(V))
1192               V = BC->getOperand(0);
1193             return V;
1194           };
1195           // In essence this assert states: the only way two values
1196           // incoming from the same basic block may be different is by
1197           // being different bitcasts of the same value.  A cleanup
1198           // that remains TODO is changing findBaseOrBDV to return an
1199           // llvm::Value of the correct type (and still remain pure).
1200           // This will remove the need to add bitcasts.
1201           assert(StripBitCasts(Base) == StripBitCasts(OldBase) &&
1202                  "findBaseOrBDV should be pure!");
1203 #endif
1204         }
1205         Value *Base = BlockToValue[InBB];
1206         BasePHI->setIncomingValue(i, Base);
1207       }
1208     } else if (SelectInst *BaseSI =
1209                    dyn_cast<SelectInst>(State.getBaseValue())) {
1210       SelectInst *SI = cast<SelectInst>(BDV);
1211 
1212       // Find the instruction which produces the base for each input.
1213       // We may need to insert a bitcast.
1214       BaseSI->setTrueValue(getBaseForInput(SI->getTrueValue(), BaseSI));
1215       BaseSI->setFalseValue(getBaseForInput(SI->getFalseValue(), BaseSI));
1216     } else if (auto *BaseEE =
1217                    dyn_cast<ExtractElementInst>(State.getBaseValue())) {
1218       Value *InVal = cast<ExtractElementInst>(BDV)->getVectorOperand();
1219       // Find the instruction which produces the base for each input.  We may
1220       // need to insert a bitcast.
1221       BaseEE->setOperand(0, getBaseForInput(InVal, BaseEE));
1222     } else if (auto *BaseIE = dyn_cast<InsertElementInst>(State.getBaseValue())){
1223       auto *BdvIE = cast<InsertElementInst>(BDV);
1224       auto UpdateOperand = [&](int OperandIdx) {
1225         Value *InVal = BdvIE->getOperand(OperandIdx);
1226         Value *Base = getBaseForInput(InVal, BaseIE);
1227         BaseIE->setOperand(OperandIdx, Base);
1228       };
1229       UpdateOperand(0); // vector operand
1230       UpdateOperand(1); // scalar operand
1231     } else {
1232       auto *BaseSV = cast<ShuffleVectorInst>(State.getBaseValue());
1233       auto *BdvSV = cast<ShuffleVectorInst>(BDV);
1234       auto UpdateOperand = [&](int OperandIdx) {
1235         Value *InVal = BdvSV->getOperand(OperandIdx);
1236         Value *Base = getBaseForInput(InVal, BaseSV);
1237         BaseSV->setOperand(OperandIdx, Base);
1238       };
1239       UpdateOperand(0); // vector operand
1240       if (!BdvSV->isZeroEltSplat())
1241         UpdateOperand(1); // vector operand
1242       else {
1243         // Never read, so just use poison
1244         Value *InVal = BdvSV->getOperand(1);
1245         BaseSV->setOperand(1, PoisonValue::get(InVal->getType()));
1246       }
1247     }
1248   }
1249 
1250 #ifndef NDEBUG
1251   VerifyStates();
1252 #endif
1253 
1254   // get the data layout to compare the sizes of base/derived pointer values
1255   [[maybe_unused]] auto &DL =
1256       cast<llvm::Instruction>(Def)->getModule()->getDataLayout();
1257   // Cache all of our results so we can cheaply reuse them
1258   // NOTE: This is actually two caches: one of the base defining value
1259   // relation and one of the base pointer relation!  FIXME
1260   for (auto Pair : States) {
1261     auto *BDV = Pair.first;
1262     Value *Base = Pair.second.getBaseValue();
1263     assert(BDV && Base);
1264     // Whenever we have a derived ptr(s), their base
1265     // ptr(s) must be of the same size, not necessarily the same type
1266     assert(DL.getTypeAllocSize(BDV->getType()) ==
1267                DL.getTypeAllocSize(Base->getType()) &&
1268            "Derived and base values should have same size");
1269     // Only values that do not have known bases or those that have differing
1270     // type (scalar versus vector) from a possible known base should be in the
1271     // lattice.
1272     assert(
1273         (!isKnownBase(BDV, KnownBases) || !areBothVectorOrScalar(BDV, Base)) &&
1274         "why did it get added?");
1275 
1276     LLVM_DEBUG(
1277         dbgs() << "Updating base value cache"
1278                << " for: " << BDV->getName() << " from: "
1279                << (Cache.count(BDV) ? Cache[BDV]->getName().str() : "none")
1280                << " to: " << Base->getName() << "\n");
1281 
1282     Cache[BDV] = Base;
1283   }
1284   assert(Cache.count(Def));
1285   return Cache[Def];
1286 }
1287 
1288 // For a set of live pointers (base and/or derived), identify the base
1289 // pointer of the object which they are derived from.  This routine will
1290 // mutate the IR graph as needed to make the 'base' pointer live at the
1291 // definition site of 'derived'.  This ensures that any use of 'derived' can
1292 // also use 'base'.  This may involve the insertion of a number of
1293 // additional PHI nodes.
1294 //
1295 // preconditions: live is a set of pointer type Values
1296 //
1297 // side effects: may insert PHI nodes into the existing CFG, will preserve
1298 // CFG, will not remove or mutate any existing nodes
1299 //
1300 // post condition: PointerToBase contains one (derived, base) pair for every
1301 // pointer in live.  Note that derived can be equal to base if the original
1302 // pointer was a base pointer.
1303 static void findBasePointers(const StatepointLiveSetTy &live,
1304                              PointerToBaseTy &PointerToBase, DominatorTree *DT,
1305                              DefiningValueMapTy &DVCache,
1306                              IsKnownBaseMapTy &KnownBases) {
1307   for (Value *ptr : live) {
1308     Value *base = findBasePointer(ptr, DVCache, KnownBases);
1309     assert(base && "failed to find base pointer");
1310     PointerToBase[ptr] = base;
1311     assert((!isa<Instruction>(base) || !isa<Instruction>(ptr) ||
1312             DT->dominates(cast<Instruction>(base)->getParent(),
1313                           cast<Instruction>(ptr)->getParent())) &&
1314            "The base we found better dominate the derived pointer");
1315   }
1316 }
1317 
1318 /// Find the required based pointers (and adjust the live set) for the given
1319 /// parse point.
1320 static void findBasePointers(DominatorTree &DT, DefiningValueMapTy &DVCache,
1321                              CallBase *Call,
1322                              PartiallyConstructedSafepointRecord &result,
1323                              PointerToBaseTy &PointerToBase,
1324                              IsKnownBaseMapTy &KnownBases) {
1325   StatepointLiveSetTy PotentiallyDerivedPointers = result.LiveSet;
1326   // We assume that all pointers passed to deopt are base pointers; as an
1327   // optimization, we can use this to avoid seperately materializing the base
1328   // pointer graph.  This is only relevant since we're very conservative about
1329   // generating new conflict nodes during base pointer insertion.  If we were
1330   // smarter there, this would be irrelevant.
1331   if (auto Opt = Call->getOperandBundle(LLVMContext::OB_deopt))
1332     for (Value *V : Opt->Inputs) {
1333       if (!PotentiallyDerivedPointers.count(V))
1334         continue;
1335       PotentiallyDerivedPointers.remove(V);
1336       PointerToBase[V] = V;
1337     }
1338   findBasePointers(PotentiallyDerivedPointers, PointerToBase, &DT, DVCache,
1339                    KnownBases);
1340 }
1341 
1342 /// Given an updated version of the dataflow liveness results, update the
1343 /// liveset and base pointer maps for the call site CS.
1344 static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData,
1345                                   CallBase *Call,
1346                                   PartiallyConstructedSafepointRecord &result,
1347                                   PointerToBaseTy &PointerToBase,
1348                                   GCStrategy *GC);
1349 
1350 static void recomputeLiveInValues(
1351     Function &F, DominatorTree &DT, ArrayRef<CallBase *> toUpdate,
1352     MutableArrayRef<struct PartiallyConstructedSafepointRecord> records,
1353     PointerToBaseTy &PointerToBase, GCStrategy *GC) {
1354   // TODO-PERF: reuse the original liveness, then simply run the dataflow
1355   // again.  The old values are still live and will help it stabilize quickly.
1356   GCPtrLivenessData RevisedLivenessData;
1357   computeLiveInValues(DT, F, RevisedLivenessData, GC);
1358   for (size_t i = 0; i < records.size(); i++) {
1359     struct PartiallyConstructedSafepointRecord &info = records[i];
1360     recomputeLiveInValues(RevisedLivenessData, toUpdate[i], info, PointerToBase,
1361                           GC);
1362   }
1363 }
1364 
1365 // Utility function which clones all instructions from "ChainToBase"
1366 // and inserts them before "InsertBefore". Returns rematerialized value
1367 // which should be used after statepoint.
1368 static Instruction *rematerializeChain(ArrayRef<Instruction *> ChainToBase,
1369                                        Instruction *InsertBefore,
1370                                        Value *RootOfChain,
1371                                        Value *AlternateLiveBase) {
1372   Instruction *LastClonedValue = nullptr;
1373   Instruction *LastValue = nullptr;
1374   // Walk backwards to visit top-most instructions first.
1375   for (Instruction *Instr :
1376        make_range(ChainToBase.rbegin(), ChainToBase.rend())) {
1377     // Only GEP's and casts are supported as we need to be careful to not
1378     // introduce any new uses of pointers not in the liveset.
1379     // Note that it's fine to introduce new uses of pointers which were
1380     // otherwise not used after this statepoint.
1381     assert(isa<GetElementPtrInst>(Instr) || isa<CastInst>(Instr));
1382 
1383     Instruction *ClonedValue = Instr->clone();
1384     ClonedValue->insertBefore(InsertBefore);
1385     ClonedValue->setName(Instr->getName() + ".remat");
1386 
1387     // If it is not first instruction in the chain then it uses previously
1388     // cloned value. We should update it to use cloned value.
1389     if (LastClonedValue) {
1390       assert(LastValue);
1391       ClonedValue->replaceUsesOfWith(LastValue, LastClonedValue);
1392 #ifndef NDEBUG
1393       for (auto *OpValue : ClonedValue->operand_values()) {
1394         // Assert that cloned instruction does not use any instructions from
1395         // this chain other than LastClonedValue
1396         assert(!is_contained(ChainToBase, OpValue) &&
1397                "incorrect use in rematerialization chain");
1398         // Assert that the cloned instruction does not use the RootOfChain
1399         // or the AlternateLiveBase.
1400         assert(OpValue != RootOfChain && OpValue != AlternateLiveBase);
1401       }
1402 #endif
1403     } else {
1404       // For the first instruction, replace the use of unrelocated base i.e.
1405       // RootOfChain/OrigRootPhi, with the corresponding PHI present in the
1406       // live set. They have been proved to be the same PHI nodes.  Note
1407       // that the *only* use of the RootOfChain in the ChainToBase list is
1408       // the first Value in the list.
1409       if (RootOfChain != AlternateLiveBase)
1410         ClonedValue->replaceUsesOfWith(RootOfChain, AlternateLiveBase);
1411     }
1412 
1413     LastClonedValue = ClonedValue;
1414     LastValue = Instr;
1415   }
1416   assert(LastClonedValue);
1417   return LastClonedValue;
1418 }
1419 
1420 // When inserting gc.relocate and gc.result calls, we need to ensure there are
1421 // no uses of the original value / return value between the gc.statepoint and
1422 // the gc.relocate / gc.result call.  One case which can arise is a phi node
1423 // starting one of the successor blocks.  We also need to be able to insert the
1424 // gc.relocates only on the path which goes through the statepoint.  We might
1425 // need to split an edge to make this possible.
1426 static BasicBlock *
1427 normalizeForInvokeSafepoint(BasicBlock *BB, BasicBlock *InvokeParent,
1428                             DominatorTree &DT) {
1429   BasicBlock *Ret = BB;
1430   if (!BB->getUniquePredecessor())
1431     Ret = SplitBlockPredecessors(BB, InvokeParent, "", &DT);
1432 
1433   // Now that 'Ret' has unique predecessor we can safely remove all phi nodes
1434   // from it
1435   FoldSingleEntryPHINodes(Ret);
1436   assert(!isa<PHINode>(Ret->begin()) &&
1437          "All PHI nodes should have been removed!");
1438 
1439   // At this point, we can safely insert a gc.relocate or gc.result as the first
1440   // instruction in Ret if needed.
1441   return Ret;
1442 }
1443 
1444 // List of all function attributes which must be stripped when lowering from
1445 // abstract machine model to physical machine model.  Essentially, these are
1446 // all the effects a safepoint might have which we ignored in the abstract
1447 // machine model for purposes of optimization.  We have to strip these on
1448 // both function declarations and call sites.
1449 static constexpr Attribute::AttrKind FnAttrsToStrip[] =
1450   {Attribute::Memory, Attribute::NoSync, Attribute::NoFree};
1451 
1452 // Create new attribute set containing only attributes which can be transferred
1453 // from the original call to the safepoint.
1454 static AttributeList legalizeCallAttributes(CallBase *Call, bool IsMemIntrinsic,
1455                                             AttributeList StatepointAL) {
1456   AttributeList OrigAL = Call->getAttributes();
1457   if (OrigAL.isEmpty())
1458     return StatepointAL;
1459 
1460   // Remove the readonly, readnone, and statepoint function attributes.
1461   LLVMContext &Ctx = Call->getContext();
1462   AttrBuilder FnAttrs(Ctx, OrigAL.getFnAttrs());
1463   for (auto Attr : FnAttrsToStrip)
1464     FnAttrs.removeAttribute(Attr);
1465 
1466   for (Attribute A : OrigAL.getFnAttrs()) {
1467     if (isStatepointDirectiveAttr(A))
1468       FnAttrs.removeAttribute(A);
1469   }
1470 
1471   StatepointAL = StatepointAL.addFnAttributes(Ctx, FnAttrs);
1472 
1473   // The memory intrinsics do not have a 1:1 correspondence of the original
1474   // call arguments to the produced statepoint. Do not transfer the argument
1475   // attributes to avoid putting them on incorrect arguments.
1476   if (IsMemIntrinsic)
1477     return StatepointAL;
1478 
1479   // Attach the argument attributes from the original call at the corresponding
1480   // arguments in the statepoint. Note that any argument attributes that are
1481   // invalid after lowering are stripped in stripNonValidDataFromBody.
1482   for (unsigned I : llvm::seq(Call->arg_size()))
1483     StatepointAL = StatepointAL.addParamAttributes(
1484         Ctx, GCStatepointInst::CallArgsBeginPos + I,
1485         AttrBuilder(Ctx, OrigAL.getParamAttrs(I)));
1486 
1487   // Return attributes are later attached to the gc.result intrinsic.
1488   return StatepointAL;
1489 }
1490 
1491 /// Helper function to place all gc relocates necessary for the given
1492 /// statepoint.
1493 /// Inputs:
1494 ///   liveVariables - list of variables to be relocated.
1495 ///   basePtrs - base pointers.
1496 ///   statepointToken - statepoint instruction to which relocates should be
1497 ///   bound.
1498 ///   Builder - Llvm IR builder to be used to construct new calls.
1499 static void CreateGCRelocates(ArrayRef<Value *> LiveVariables,
1500                               ArrayRef<Value *> BasePtrs,
1501                               Instruction *StatepointToken,
1502                               IRBuilder<> &Builder, GCStrategy *GC) {
1503   if (LiveVariables.empty())
1504     return;
1505 
1506   auto FindIndex = [](ArrayRef<Value *> LiveVec, Value *Val) {
1507     auto ValIt = llvm::find(LiveVec, Val);
1508     assert(ValIt != LiveVec.end() && "Val not found in LiveVec!");
1509     size_t Index = std::distance(LiveVec.begin(), ValIt);
1510     assert(Index < LiveVec.size() && "Bug in std::find?");
1511     return Index;
1512   };
1513   Module *M = StatepointToken->getModule();
1514 
1515   // All gc_relocate are generated as i8 addrspace(1)* (or a vector type whose
1516   // element type is i8 addrspace(1)*). We originally generated unique
1517   // declarations for each pointer type, but this proved problematic because
1518   // the intrinsic mangling code is incomplete and fragile.  Since we're moving
1519   // towards a single unified pointer type anyways, we can just cast everything
1520   // to an i8* of the right address space.  A bitcast is added later to convert
1521   // gc_relocate to the actual value's type.
1522   auto getGCRelocateDecl = [&](Type *Ty) {
1523     assert(isHandledGCPointerType(Ty, GC));
1524     auto AS = Ty->getScalarType()->getPointerAddressSpace();
1525     Type *NewTy = PointerType::get(M->getContext(), AS);
1526     if (auto *VT = dyn_cast<VectorType>(Ty))
1527       NewTy = FixedVectorType::get(NewTy,
1528                                    cast<FixedVectorType>(VT)->getNumElements());
1529     return Intrinsic::getDeclaration(M, Intrinsic::experimental_gc_relocate,
1530                                      {NewTy});
1531   };
1532 
1533   // Lazily populated map from input types to the canonicalized form mentioned
1534   // in the comment above.  This should probably be cached somewhere more
1535   // broadly.
1536   DenseMap<Type *, Function *> TypeToDeclMap;
1537 
1538   for (unsigned i = 0; i < LiveVariables.size(); i++) {
1539     // Generate the gc.relocate call and save the result
1540     Value *BaseIdx = Builder.getInt32(FindIndex(LiveVariables, BasePtrs[i]));
1541     Value *LiveIdx = Builder.getInt32(i);
1542 
1543     Type *Ty = LiveVariables[i]->getType();
1544     if (!TypeToDeclMap.count(Ty))
1545       TypeToDeclMap[Ty] = getGCRelocateDecl(Ty);
1546     Function *GCRelocateDecl = TypeToDeclMap[Ty];
1547 
1548     // only specify a debug name if we can give a useful one
1549     CallInst *Reloc = Builder.CreateCall(
1550         GCRelocateDecl, {StatepointToken, BaseIdx, LiveIdx},
1551         suffixed_name_or(LiveVariables[i], ".relocated", ""));
1552     // Trick CodeGen into thinking there are lots of free registers at this
1553     // fake call.
1554     Reloc->setCallingConv(CallingConv::Cold);
1555   }
1556 }
1557 
1558 namespace {
1559 
1560 /// This struct is used to defer RAUWs and `eraseFromParent` s.  Using this
1561 /// avoids having to worry about keeping around dangling pointers to Values.
1562 class DeferredReplacement {
1563   AssertingVH<Instruction> Old;
1564   AssertingVH<Instruction> New;
1565   bool IsDeoptimize = false;
1566 
1567   DeferredReplacement() = default;
1568 
1569 public:
1570   static DeferredReplacement createRAUW(Instruction *Old, Instruction *New) {
1571     assert(Old != New && Old && New &&
1572            "Cannot RAUW equal values or to / from null!");
1573 
1574     DeferredReplacement D;
1575     D.Old = Old;
1576     D.New = New;
1577     return D;
1578   }
1579 
1580   static DeferredReplacement createDelete(Instruction *ToErase) {
1581     DeferredReplacement D;
1582     D.Old = ToErase;
1583     return D;
1584   }
1585 
1586   static DeferredReplacement createDeoptimizeReplacement(Instruction *Old) {
1587 #ifndef NDEBUG
1588     auto *F = cast<CallInst>(Old)->getCalledFunction();
1589     assert(F && F->getIntrinsicID() == Intrinsic::experimental_deoptimize &&
1590            "Only way to construct a deoptimize deferred replacement");
1591 #endif
1592     DeferredReplacement D;
1593     D.Old = Old;
1594     D.IsDeoptimize = true;
1595     return D;
1596   }
1597 
1598   /// Does the task represented by this instance.
1599   void doReplacement() {
1600     Instruction *OldI = Old;
1601     Instruction *NewI = New;
1602 
1603     assert(OldI != NewI && "Disallowed at construction?!");
1604     assert((!IsDeoptimize || !New) &&
1605            "Deoptimize intrinsics are not replaced!");
1606 
1607     Old = nullptr;
1608     New = nullptr;
1609 
1610     if (NewI)
1611       OldI->replaceAllUsesWith(NewI);
1612 
1613     if (IsDeoptimize) {
1614       // Note: we've inserted instructions, so the call to llvm.deoptimize may
1615       // not necessarily be followed by the matching return.
1616       auto *RI = cast<ReturnInst>(OldI->getParent()->getTerminator());
1617       new UnreachableInst(RI->getContext(), RI);
1618       RI->eraseFromParent();
1619     }
1620 
1621     OldI->eraseFromParent();
1622   }
1623 };
1624 
1625 } // end anonymous namespace
1626 
1627 static StringRef getDeoptLowering(CallBase *Call) {
1628   const char *DeoptLowering = "deopt-lowering";
1629   if (Call->hasFnAttr(DeoptLowering)) {
1630     // FIXME: Calls have a *really* confusing interface around attributes
1631     // with values.
1632     const AttributeList &CSAS = Call->getAttributes();
1633     if (CSAS.hasFnAttr(DeoptLowering))
1634       return CSAS.getFnAttr(DeoptLowering).getValueAsString();
1635     Function *F = Call->getCalledFunction();
1636     assert(F && F->hasFnAttribute(DeoptLowering));
1637     return F->getFnAttribute(DeoptLowering).getValueAsString();
1638   }
1639   return "live-through";
1640 }
1641 
1642 static void
1643 makeStatepointExplicitImpl(CallBase *Call, /* to replace */
1644                            const SmallVectorImpl<Value *> &BasePtrs,
1645                            const SmallVectorImpl<Value *> &LiveVariables,
1646                            PartiallyConstructedSafepointRecord &Result,
1647                            std::vector<DeferredReplacement> &Replacements,
1648                            const PointerToBaseTy &PointerToBase,
1649                            GCStrategy *GC) {
1650   assert(BasePtrs.size() == LiveVariables.size());
1651 
1652   // Then go ahead and use the builder do actually do the inserts.  We insert
1653   // immediately before the previous instruction under the assumption that all
1654   // arguments will be available here.  We can't insert afterwards since we may
1655   // be replacing a terminator.
1656   IRBuilder<> Builder(Call);
1657 
1658   ArrayRef<Value *> GCArgs(LiveVariables);
1659   uint64_t StatepointID = StatepointDirectives::DefaultStatepointID;
1660   uint32_t NumPatchBytes = 0;
1661   uint32_t Flags = uint32_t(StatepointFlags::None);
1662 
1663   SmallVector<Value *, 8> CallArgs(Call->args());
1664   std::optional<ArrayRef<Use>> DeoptArgs;
1665   if (auto Bundle = Call->getOperandBundle(LLVMContext::OB_deopt))
1666     DeoptArgs = Bundle->Inputs;
1667   std::optional<ArrayRef<Use>> TransitionArgs;
1668   if (auto Bundle = Call->getOperandBundle(LLVMContext::OB_gc_transition)) {
1669     TransitionArgs = Bundle->Inputs;
1670     // TODO: This flag no longer serves a purpose and can be removed later
1671     Flags |= uint32_t(StatepointFlags::GCTransition);
1672   }
1673 
1674   // Instead of lowering calls to @llvm.experimental.deoptimize as normal calls
1675   // with a return value, we lower then as never returning calls to
1676   // __llvm_deoptimize that are followed by unreachable to get better codegen.
1677   bool IsDeoptimize = false;
1678   bool IsMemIntrinsic = false;
1679 
1680   StatepointDirectives SD =
1681       parseStatepointDirectivesFromAttrs(Call->getAttributes());
1682   if (SD.NumPatchBytes)
1683     NumPatchBytes = *SD.NumPatchBytes;
1684   if (SD.StatepointID)
1685     StatepointID = *SD.StatepointID;
1686 
1687   // Pass through the requested lowering if any.  The default is live-through.
1688   StringRef DeoptLowering = getDeoptLowering(Call);
1689   if (DeoptLowering.equals("live-in"))
1690     Flags |= uint32_t(StatepointFlags::DeoptLiveIn);
1691   else {
1692     assert(DeoptLowering.equals("live-through") && "Unsupported value!");
1693   }
1694 
1695   FunctionCallee CallTarget(Call->getFunctionType(), Call->getCalledOperand());
1696   if (Function *F = dyn_cast<Function>(CallTarget.getCallee())) {
1697     auto IID = F->getIntrinsicID();
1698     if (IID == Intrinsic::experimental_deoptimize) {
1699       // Calls to llvm.experimental.deoptimize are lowered to calls to the
1700       // __llvm_deoptimize symbol.  We want to resolve this now, since the
1701       // verifier does not allow taking the address of an intrinsic function.
1702 
1703       SmallVector<Type *, 8> DomainTy;
1704       for (Value *Arg : CallArgs)
1705         DomainTy.push_back(Arg->getType());
1706       auto *FTy = FunctionType::get(Type::getVoidTy(F->getContext()), DomainTy,
1707                                     /* isVarArg = */ false);
1708 
1709       // Note: CallTarget can be a bitcast instruction of a symbol if there are
1710       // calls to @llvm.experimental.deoptimize with different argument types in
1711       // the same module.  This is fine -- we assume the frontend knew what it
1712       // was doing when generating this kind of IR.
1713       CallTarget = F->getParent()
1714                        ->getOrInsertFunction("__llvm_deoptimize", FTy);
1715 
1716       IsDeoptimize = true;
1717     } else if (IID == Intrinsic::memcpy_element_unordered_atomic ||
1718                IID == Intrinsic::memmove_element_unordered_atomic) {
1719       IsMemIntrinsic = true;
1720 
1721       // Unordered atomic memcpy and memmove intrinsics which are not explicitly
1722       // marked as "gc-leaf-function" should be lowered in a GC parseable way.
1723       // Specifically, these calls should be lowered to the
1724       // __llvm_{memcpy|memmove}_element_unordered_atomic_safepoint symbols.
1725       // Similarly to __llvm_deoptimize we want to resolve this now, since the
1726       // verifier does not allow taking the address of an intrinsic function.
1727       //
1728       // Moreover we need to shuffle the arguments for the call in order to
1729       // accommodate GC. The underlying source and destination objects might be
1730       // relocated during copy operation should the GC occur. To relocate the
1731       // derived source and destination pointers the implementation of the
1732       // intrinsic should know the corresponding base pointers.
1733       //
1734       // To make the base pointers available pass them explicitly as arguments:
1735       //   memcpy(dest_derived, source_derived, ...) =>
1736       //   memcpy(dest_base, dest_offset, source_base, source_offset, ...)
1737       auto &Context = Call->getContext();
1738       auto &DL = Call->getModule()->getDataLayout();
1739       auto GetBaseAndOffset = [&](Value *Derived) {
1740         Value *Base = nullptr;
1741         // Optimizations in unreachable code might substitute the real pointer
1742         // with undef, poison or null-derived constant. Return null base for
1743         // them to be consistent with the handling in the main algorithm in
1744         // findBaseDefiningValue.
1745         if (isa<Constant>(Derived))
1746           Base =
1747               ConstantPointerNull::get(cast<PointerType>(Derived->getType()));
1748         else {
1749           assert(PointerToBase.count(Derived));
1750           Base = PointerToBase.find(Derived)->second;
1751         }
1752         unsigned AddressSpace = Derived->getType()->getPointerAddressSpace();
1753         unsigned IntPtrSize = DL.getPointerSizeInBits(AddressSpace);
1754         Value *Base_int = Builder.CreatePtrToInt(
1755             Base, Type::getIntNTy(Context, IntPtrSize));
1756         Value *Derived_int = Builder.CreatePtrToInt(
1757             Derived, Type::getIntNTy(Context, IntPtrSize));
1758         return std::make_pair(Base, Builder.CreateSub(Derived_int, Base_int));
1759       };
1760 
1761       auto *Dest = CallArgs[0];
1762       Value *DestBase, *DestOffset;
1763       std::tie(DestBase, DestOffset) = GetBaseAndOffset(Dest);
1764 
1765       auto *Source = CallArgs[1];
1766       Value *SourceBase, *SourceOffset;
1767       std::tie(SourceBase, SourceOffset) = GetBaseAndOffset(Source);
1768 
1769       auto *LengthInBytes = CallArgs[2];
1770       auto *ElementSizeCI = cast<ConstantInt>(CallArgs[3]);
1771 
1772       CallArgs.clear();
1773       CallArgs.push_back(DestBase);
1774       CallArgs.push_back(DestOffset);
1775       CallArgs.push_back(SourceBase);
1776       CallArgs.push_back(SourceOffset);
1777       CallArgs.push_back(LengthInBytes);
1778 
1779       SmallVector<Type *, 8> DomainTy;
1780       for (Value *Arg : CallArgs)
1781         DomainTy.push_back(Arg->getType());
1782       auto *FTy = FunctionType::get(Type::getVoidTy(F->getContext()), DomainTy,
1783                                     /* isVarArg = */ false);
1784 
1785       auto GetFunctionName = [](Intrinsic::ID IID, ConstantInt *ElementSizeCI) {
1786         uint64_t ElementSize = ElementSizeCI->getZExtValue();
1787         if (IID == Intrinsic::memcpy_element_unordered_atomic) {
1788           switch (ElementSize) {
1789           case 1:
1790             return "__llvm_memcpy_element_unordered_atomic_safepoint_1";
1791           case 2:
1792             return "__llvm_memcpy_element_unordered_atomic_safepoint_2";
1793           case 4:
1794             return "__llvm_memcpy_element_unordered_atomic_safepoint_4";
1795           case 8:
1796             return "__llvm_memcpy_element_unordered_atomic_safepoint_8";
1797           case 16:
1798             return "__llvm_memcpy_element_unordered_atomic_safepoint_16";
1799           default:
1800             llvm_unreachable("unexpected element size!");
1801           }
1802         }
1803         assert(IID == Intrinsic::memmove_element_unordered_atomic);
1804         switch (ElementSize) {
1805         case 1:
1806           return "__llvm_memmove_element_unordered_atomic_safepoint_1";
1807         case 2:
1808           return "__llvm_memmove_element_unordered_atomic_safepoint_2";
1809         case 4:
1810           return "__llvm_memmove_element_unordered_atomic_safepoint_4";
1811         case 8:
1812           return "__llvm_memmove_element_unordered_atomic_safepoint_8";
1813         case 16:
1814           return "__llvm_memmove_element_unordered_atomic_safepoint_16";
1815         default:
1816           llvm_unreachable("unexpected element size!");
1817         }
1818       };
1819 
1820       CallTarget =
1821           F->getParent()
1822               ->getOrInsertFunction(GetFunctionName(IID, ElementSizeCI), FTy);
1823     }
1824   }
1825 
1826   // Create the statepoint given all the arguments
1827   GCStatepointInst *Token = nullptr;
1828   if (auto *CI = dyn_cast<CallInst>(Call)) {
1829     CallInst *SPCall = Builder.CreateGCStatepointCall(
1830         StatepointID, NumPatchBytes, CallTarget, Flags, CallArgs,
1831         TransitionArgs, DeoptArgs, GCArgs, "safepoint_token");
1832 
1833     SPCall->setTailCallKind(CI->getTailCallKind());
1834     SPCall->setCallingConv(CI->getCallingConv());
1835 
1836     // Set up function attrs directly on statepoint and return attrs later for
1837     // gc_result intrinsic.
1838     SPCall->setAttributes(
1839         legalizeCallAttributes(CI, IsMemIntrinsic, SPCall->getAttributes()));
1840 
1841     Token = cast<GCStatepointInst>(SPCall);
1842 
1843     // Put the following gc_result and gc_relocate calls immediately after the
1844     // the old call (which we're about to delete)
1845     assert(CI->getNextNode() && "Not a terminator, must have next!");
1846     Builder.SetInsertPoint(CI->getNextNode());
1847     Builder.SetCurrentDebugLocation(CI->getNextNode()->getDebugLoc());
1848   } else {
1849     auto *II = cast<InvokeInst>(Call);
1850 
1851     // Insert the new invoke into the old block.  We'll remove the old one in a
1852     // moment at which point this will become the new terminator for the
1853     // original block.
1854     InvokeInst *SPInvoke = Builder.CreateGCStatepointInvoke(
1855         StatepointID, NumPatchBytes, CallTarget, II->getNormalDest(),
1856         II->getUnwindDest(), Flags, CallArgs, TransitionArgs, DeoptArgs, GCArgs,
1857         "statepoint_token");
1858 
1859     SPInvoke->setCallingConv(II->getCallingConv());
1860 
1861     // Set up function attrs directly on statepoint and return attrs later for
1862     // gc_result intrinsic.
1863     SPInvoke->setAttributes(
1864         legalizeCallAttributes(II, IsMemIntrinsic, SPInvoke->getAttributes()));
1865 
1866     Token = cast<GCStatepointInst>(SPInvoke);
1867 
1868     // Generate gc relocates in exceptional path
1869     BasicBlock *UnwindBlock = II->getUnwindDest();
1870     assert(!isa<PHINode>(UnwindBlock->begin()) &&
1871            UnwindBlock->getUniquePredecessor() &&
1872            "can't safely insert in this block!");
1873 
1874     Builder.SetInsertPoint(UnwindBlock, UnwindBlock->getFirstInsertionPt());
1875     Builder.SetCurrentDebugLocation(II->getDebugLoc());
1876 
1877     // Attach exceptional gc relocates to the landingpad.
1878     Instruction *ExceptionalToken = UnwindBlock->getLandingPadInst();
1879     Result.UnwindToken = ExceptionalToken;
1880 
1881     CreateGCRelocates(LiveVariables, BasePtrs, ExceptionalToken, Builder, GC);
1882 
1883     // Generate gc relocates and returns for normal block
1884     BasicBlock *NormalDest = II->getNormalDest();
1885     assert(!isa<PHINode>(NormalDest->begin()) &&
1886            NormalDest->getUniquePredecessor() &&
1887            "can't safely insert in this block!");
1888 
1889     Builder.SetInsertPoint(NormalDest, NormalDest->getFirstInsertionPt());
1890 
1891     // gc relocates will be generated later as if it were regular call
1892     // statepoint
1893   }
1894   assert(Token && "Should be set in one of the above branches!");
1895 
1896   if (IsDeoptimize) {
1897     // If we're wrapping an @llvm.experimental.deoptimize in a statepoint, we
1898     // transform the tail-call like structure to a call to a void function
1899     // followed by unreachable to get better codegen.
1900     Replacements.push_back(
1901         DeferredReplacement::createDeoptimizeReplacement(Call));
1902   } else {
1903     Token->setName("statepoint_token");
1904     if (!Call->getType()->isVoidTy() && !Call->use_empty()) {
1905       StringRef Name = Call->hasName() ? Call->getName() : "";
1906       CallInst *GCResult = Builder.CreateGCResult(Token, Call->getType(), Name);
1907       GCResult->setAttributes(
1908           AttributeList::get(GCResult->getContext(), AttributeList::ReturnIndex,
1909                              Call->getAttributes().getRetAttrs()));
1910 
1911       // We cannot RAUW or delete CS.getInstruction() because it could be in the
1912       // live set of some other safepoint, in which case that safepoint's
1913       // PartiallyConstructedSafepointRecord will hold a raw pointer to this
1914       // llvm::Instruction.  Instead, we defer the replacement and deletion to
1915       // after the live sets have been made explicit in the IR, and we no longer
1916       // have raw pointers to worry about.
1917       Replacements.emplace_back(
1918           DeferredReplacement::createRAUW(Call, GCResult));
1919     } else {
1920       Replacements.emplace_back(DeferredReplacement::createDelete(Call));
1921     }
1922   }
1923 
1924   Result.StatepointToken = Token;
1925 
1926   // Second, create a gc.relocate for every live variable
1927   CreateGCRelocates(LiveVariables, BasePtrs, Token, Builder, GC);
1928 }
1929 
1930 // Replace an existing gc.statepoint with a new one and a set of gc.relocates
1931 // which make the relocations happening at this safepoint explicit.
1932 //
1933 // WARNING: Does not do any fixup to adjust users of the original live
1934 // values.  That's the callers responsibility.
1935 static void
1936 makeStatepointExplicit(DominatorTree &DT, CallBase *Call,
1937                        PartiallyConstructedSafepointRecord &Result,
1938                        std::vector<DeferredReplacement> &Replacements,
1939                        const PointerToBaseTy &PointerToBase, GCStrategy *GC) {
1940   const auto &LiveSet = Result.LiveSet;
1941 
1942   // Convert to vector for efficient cross referencing.
1943   SmallVector<Value *, 64> BaseVec, LiveVec;
1944   LiveVec.reserve(LiveSet.size());
1945   BaseVec.reserve(LiveSet.size());
1946   for (Value *L : LiveSet) {
1947     LiveVec.push_back(L);
1948     assert(PointerToBase.count(L));
1949     Value *Base = PointerToBase.find(L)->second;
1950     BaseVec.push_back(Base);
1951   }
1952   assert(LiveVec.size() == BaseVec.size());
1953 
1954   // Do the actual rewriting and delete the old statepoint
1955   makeStatepointExplicitImpl(Call, BaseVec, LiveVec, Result, Replacements,
1956                              PointerToBase, GC);
1957 }
1958 
1959 // Helper function for the relocationViaAlloca.
1960 //
1961 // It receives iterator to the statepoint gc relocates and emits a store to the
1962 // assigned location (via allocaMap) for the each one of them.  It adds the
1963 // visited values into the visitedLiveValues set, which we will later use them
1964 // for validation checking.
1965 static void
1966 insertRelocationStores(iterator_range<Value::user_iterator> GCRelocs,
1967                        DenseMap<Value *, AllocaInst *> &AllocaMap,
1968                        DenseSet<Value *> &VisitedLiveValues) {
1969   for (User *U : GCRelocs) {
1970     GCRelocateInst *Relocate = dyn_cast<GCRelocateInst>(U);
1971     if (!Relocate)
1972       continue;
1973 
1974     Value *OriginalValue = Relocate->getDerivedPtr();
1975     assert(AllocaMap.count(OriginalValue));
1976     Value *Alloca = AllocaMap[OriginalValue];
1977 
1978     // Emit store into the related alloca
1979     // All gc_relocates are i8 addrspace(1)* typed, and it must be bitcasted to
1980     // the correct type according to alloca.
1981     assert(Relocate->getNextNode() &&
1982            "Should always have one since it's not a terminator");
1983     IRBuilder<> Builder(Relocate->getNextNode());
1984     Value *CastedRelocatedValue =
1985       Builder.CreateBitCast(Relocate,
1986                             cast<AllocaInst>(Alloca)->getAllocatedType(),
1987                             suffixed_name_or(Relocate, ".casted", ""));
1988 
1989     new StoreInst(CastedRelocatedValue, Alloca,
1990                   cast<Instruction>(CastedRelocatedValue)->getNextNode());
1991 
1992 #ifndef NDEBUG
1993     VisitedLiveValues.insert(OriginalValue);
1994 #endif
1995   }
1996 }
1997 
1998 // Helper function for the "relocationViaAlloca". Similar to the
1999 // "insertRelocationStores" but works for rematerialized values.
2000 static void insertRematerializationStores(
2001     const RematerializedValueMapTy &RematerializedValues,
2002     DenseMap<Value *, AllocaInst *> &AllocaMap,
2003     DenseSet<Value *> &VisitedLiveValues) {
2004   for (auto RematerializedValuePair: RematerializedValues) {
2005     Instruction *RematerializedValue = RematerializedValuePair.first;
2006     Value *OriginalValue = RematerializedValuePair.second;
2007 
2008     assert(AllocaMap.count(OriginalValue) &&
2009            "Can not find alloca for rematerialized value");
2010     Value *Alloca = AllocaMap[OriginalValue];
2011 
2012     new StoreInst(RematerializedValue, Alloca,
2013                   RematerializedValue->getNextNode());
2014 
2015 #ifndef NDEBUG
2016     VisitedLiveValues.insert(OriginalValue);
2017 #endif
2018   }
2019 }
2020 
2021 /// Do all the relocation update via allocas and mem2reg
2022 static void relocationViaAlloca(
2023     Function &F, DominatorTree &DT, ArrayRef<Value *> Live,
2024     ArrayRef<PartiallyConstructedSafepointRecord> Records) {
2025 #ifndef NDEBUG
2026   // record initial number of (static) allocas; we'll check we have the same
2027   // number when we get done.
2028   int InitialAllocaNum = 0;
2029   for (Instruction &I : F.getEntryBlock())
2030     if (isa<AllocaInst>(I))
2031       InitialAllocaNum++;
2032 #endif
2033 
2034   // TODO-PERF: change data structures, reserve
2035   DenseMap<Value *, AllocaInst *> AllocaMap;
2036   SmallVector<AllocaInst *, 200> PromotableAllocas;
2037   // Used later to chack that we have enough allocas to store all values
2038   std::size_t NumRematerializedValues = 0;
2039   PromotableAllocas.reserve(Live.size());
2040 
2041   // Emit alloca for "LiveValue" and record it in "allocaMap" and
2042   // "PromotableAllocas"
2043   const DataLayout &DL = F.getParent()->getDataLayout();
2044   auto emitAllocaFor = [&](Value *LiveValue) {
2045     AllocaInst *Alloca = new AllocaInst(LiveValue->getType(),
2046                                         DL.getAllocaAddrSpace(), "",
2047                                         F.getEntryBlock().getFirstNonPHI());
2048     AllocaMap[LiveValue] = Alloca;
2049     PromotableAllocas.push_back(Alloca);
2050   };
2051 
2052   // Emit alloca for each live gc pointer
2053   for (Value *V : Live)
2054     emitAllocaFor(V);
2055 
2056   // Emit allocas for rematerialized values
2057   for (const auto &Info : Records)
2058     for (auto RematerializedValuePair : Info.RematerializedValues) {
2059       Value *OriginalValue = RematerializedValuePair.second;
2060       if (AllocaMap.count(OriginalValue) != 0)
2061         continue;
2062 
2063       emitAllocaFor(OriginalValue);
2064       ++NumRematerializedValues;
2065     }
2066 
2067   // The next two loops are part of the same conceptual operation.  We need to
2068   // insert a store to the alloca after the original def and at each
2069   // redefinition.  We need to insert a load before each use.  These are split
2070   // into distinct loops for performance reasons.
2071 
2072   // Update gc pointer after each statepoint: either store a relocated value or
2073   // null (if no relocated value was found for this gc pointer and it is not a
2074   // gc_result).  This must happen before we update the statepoint with load of
2075   // alloca otherwise we lose the link between statepoint and old def.
2076   for (const auto &Info : Records) {
2077     Value *Statepoint = Info.StatepointToken;
2078 
2079     // This will be used for consistency check
2080     DenseSet<Value *> VisitedLiveValues;
2081 
2082     // Insert stores for normal statepoint gc relocates
2083     insertRelocationStores(Statepoint->users(), AllocaMap, VisitedLiveValues);
2084 
2085     // In case if it was invoke statepoint
2086     // we will insert stores for exceptional path gc relocates.
2087     if (isa<InvokeInst>(Statepoint)) {
2088       insertRelocationStores(Info.UnwindToken->users(), AllocaMap,
2089                              VisitedLiveValues);
2090     }
2091 
2092     // Do similar thing with rematerialized values
2093     insertRematerializationStores(Info.RematerializedValues, AllocaMap,
2094                                   VisitedLiveValues);
2095 
2096     if (ClobberNonLive) {
2097       // As a debugging aid, pretend that an unrelocated pointer becomes null at
2098       // the gc.statepoint.  This will turn some subtle GC problems into
2099       // slightly easier to debug SEGVs.  Note that on large IR files with
2100       // lots of gc.statepoints this is extremely costly both memory and time
2101       // wise.
2102       SmallVector<AllocaInst *, 64> ToClobber;
2103       for (auto Pair : AllocaMap) {
2104         Value *Def = Pair.first;
2105         AllocaInst *Alloca = Pair.second;
2106 
2107         // This value was relocated
2108         if (VisitedLiveValues.count(Def)) {
2109           continue;
2110         }
2111         ToClobber.push_back(Alloca);
2112       }
2113 
2114       auto InsertClobbersAt = [&](Instruction *IP) {
2115         for (auto *AI : ToClobber) {
2116           auto AT = AI->getAllocatedType();
2117           Constant *CPN;
2118           if (AT->isVectorTy())
2119             CPN = ConstantAggregateZero::get(AT);
2120           else
2121             CPN = ConstantPointerNull::get(cast<PointerType>(AT));
2122           new StoreInst(CPN, AI, IP);
2123         }
2124       };
2125 
2126       // Insert the clobbering stores.  These may get intermixed with the
2127       // gc.results and gc.relocates, but that's fine.
2128       if (auto II = dyn_cast<InvokeInst>(Statepoint)) {
2129         InsertClobbersAt(&*II->getNormalDest()->getFirstInsertionPt());
2130         InsertClobbersAt(&*II->getUnwindDest()->getFirstInsertionPt());
2131       } else {
2132         InsertClobbersAt(cast<Instruction>(Statepoint)->getNextNode());
2133       }
2134     }
2135   }
2136 
2137   // Update use with load allocas and add store for gc_relocated.
2138   for (auto Pair : AllocaMap) {
2139     Value *Def = Pair.first;
2140     AllocaInst *Alloca = Pair.second;
2141 
2142     // We pre-record the uses of allocas so that we dont have to worry about
2143     // later update that changes the user information..
2144 
2145     SmallVector<Instruction *, 20> Uses;
2146     // PERF: trade a linear scan for repeated reallocation
2147     Uses.reserve(Def->getNumUses());
2148     for (User *U : Def->users()) {
2149       if (!isa<ConstantExpr>(U)) {
2150         // If the def has a ConstantExpr use, then the def is either a
2151         // ConstantExpr use itself or null.  In either case
2152         // (recursively in the first, directly in the second), the oop
2153         // it is ultimately dependent on is null and this particular
2154         // use does not need to be fixed up.
2155         Uses.push_back(cast<Instruction>(U));
2156       }
2157     }
2158 
2159     llvm::sort(Uses);
2160     auto Last = std::unique(Uses.begin(), Uses.end());
2161     Uses.erase(Last, Uses.end());
2162 
2163     for (Instruction *Use : Uses) {
2164       if (isa<PHINode>(Use)) {
2165         PHINode *Phi = cast<PHINode>(Use);
2166         for (unsigned i = 0; i < Phi->getNumIncomingValues(); i++) {
2167           if (Def == Phi->getIncomingValue(i)) {
2168             LoadInst *Load =
2169                 new LoadInst(Alloca->getAllocatedType(), Alloca, "",
2170                              Phi->getIncomingBlock(i)->getTerminator());
2171             Phi->setIncomingValue(i, Load);
2172           }
2173         }
2174       } else {
2175         LoadInst *Load =
2176             new LoadInst(Alloca->getAllocatedType(), Alloca, "", Use);
2177         Use->replaceUsesOfWith(Def, Load);
2178       }
2179     }
2180 
2181     // Emit store for the initial gc value.  Store must be inserted after load,
2182     // otherwise store will be in alloca's use list and an extra load will be
2183     // inserted before it.
2184     StoreInst *Store = new StoreInst(Def, Alloca, /*volatile*/ false,
2185                                      DL.getABITypeAlign(Def->getType()));
2186     if (Instruction *Inst = dyn_cast<Instruction>(Def)) {
2187       if (InvokeInst *Invoke = dyn_cast<InvokeInst>(Inst)) {
2188         // InvokeInst is a terminator so the store need to be inserted into its
2189         // normal destination block.
2190         BasicBlock *NormalDest = Invoke->getNormalDest();
2191         Store->insertBefore(NormalDest->getFirstNonPHI());
2192       } else {
2193         assert(!Inst->isTerminator() &&
2194                "The only terminator that can produce a value is "
2195                "InvokeInst which is handled above.");
2196         Store->insertAfter(Inst);
2197       }
2198     } else {
2199       assert(isa<Argument>(Def));
2200       Store->insertAfter(cast<Instruction>(Alloca));
2201     }
2202   }
2203 
2204   assert(PromotableAllocas.size() == Live.size() + NumRematerializedValues &&
2205          "we must have the same allocas with lives");
2206   (void) NumRematerializedValues;
2207   if (!PromotableAllocas.empty()) {
2208     // Apply mem2reg to promote alloca to SSA
2209     PromoteMemToReg(PromotableAllocas, DT);
2210   }
2211 
2212 #ifndef NDEBUG
2213   for (auto &I : F.getEntryBlock())
2214     if (isa<AllocaInst>(I))
2215       InitialAllocaNum--;
2216   assert(InitialAllocaNum == 0 && "We must not introduce any extra allocas");
2217 #endif
2218 }
2219 
2220 /// Implement a unique function which doesn't require we sort the input
2221 /// vector.  Doing so has the effect of changing the output of a couple of
2222 /// tests in ways which make them less useful in testing fused safepoints.
2223 template <typename T> static void unique_unsorted(SmallVectorImpl<T> &Vec) {
2224   SmallSet<T, 8> Seen;
2225   erase_if(Vec, [&](const T &V) { return !Seen.insert(V).second; });
2226 }
2227 
2228 /// Insert holders so that each Value is obviously live through the entire
2229 /// lifetime of the call.
2230 static void insertUseHolderAfter(CallBase *Call, const ArrayRef<Value *> Values,
2231                                  SmallVectorImpl<CallInst *> &Holders) {
2232   if (Values.empty())
2233     // No values to hold live, might as well not insert the empty holder
2234     return;
2235 
2236   Module *M = Call->getModule();
2237   // Use a dummy vararg function to actually hold the values live
2238   FunctionCallee Func = M->getOrInsertFunction(
2239       "__tmp_use", FunctionType::get(Type::getVoidTy(M->getContext()), true));
2240   if (isa<CallInst>(Call)) {
2241     // For call safepoints insert dummy calls right after safepoint
2242     Holders.push_back(
2243         CallInst::Create(Func, Values, "", &*++Call->getIterator()));
2244     return;
2245   }
2246   // For invoke safepooints insert dummy calls both in normal and
2247   // exceptional destination blocks
2248   auto *II = cast<InvokeInst>(Call);
2249   Holders.push_back(CallInst::Create(
2250       Func, Values, "", &*II->getNormalDest()->getFirstInsertionPt()));
2251   Holders.push_back(CallInst::Create(
2252       Func, Values, "", &*II->getUnwindDest()->getFirstInsertionPt()));
2253 }
2254 
2255 static void findLiveReferences(
2256     Function &F, DominatorTree &DT, ArrayRef<CallBase *> toUpdate,
2257     MutableArrayRef<struct PartiallyConstructedSafepointRecord> records,
2258     GCStrategy *GC) {
2259   GCPtrLivenessData OriginalLivenessData;
2260   computeLiveInValues(DT, F, OriginalLivenessData, GC);
2261   for (size_t i = 0; i < records.size(); i++) {
2262     struct PartiallyConstructedSafepointRecord &info = records[i];
2263     analyzeParsePointLiveness(DT, OriginalLivenessData, toUpdate[i], info, GC);
2264   }
2265 }
2266 
2267 // Helper function for the "rematerializeLiveValues". It walks use chain
2268 // starting from the "CurrentValue" until it reaches the root of the chain, i.e.
2269 // the base or a value it cannot process. Only "simple" values are processed
2270 // (currently it is GEP's and casts). The returned root is  examined by the
2271 // callers of findRematerializableChainToBasePointer.  Fills "ChainToBase" array
2272 // with all visited values.
2273 static Value* findRematerializableChainToBasePointer(
2274   SmallVectorImpl<Instruction*> &ChainToBase,
2275   Value *CurrentValue) {
2276   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurrentValue)) {
2277     ChainToBase.push_back(GEP);
2278     return findRematerializableChainToBasePointer(ChainToBase,
2279                                                   GEP->getPointerOperand());
2280   }
2281 
2282   if (CastInst *CI = dyn_cast<CastInst>(CurrentValue)) {
2283     if (!CI->isNoopCast(CI->getModule()->getDataLayout()))
2284       return CI;
2285 
2286     ChainToBase.push_back(CI);
2287     return findRematerializableChainToBasePointer(ChainToBase,
2288                                                   CI->getOperand(0));
2289   }
2290 
2291   // We have reached the root of the chain, which is either equal to the base or
2292   // is the first unsupported value along the use chain.
2293   return CurrentValue;
2294 }
2295 
2296 // Helper function for the "rematerializeLiveValues". Compute cost of the use
2297 // chain we are going to rematerialize.
2298 static InstructionCost
2299 chainToBasePointerCost(SmallVectorImpl<Instruction *> &Chain,
2300                        TargetTransformInfo &TTI) {
2301   InstructionCost Cost = 0;
2302 
2303   for (Instruction *Instr : Chain) {
2304     if (CastInst *CI = dyn_cast<CastInst>(Instr)) {
2305       assert(CI->isNoopCast(CI->getModule()->getDataLayout()) &&
2306              "non noop cast is found during rematerialization");
2307 
2308       Type *SrcTy = CI->getOperand(0)->getType();
2309       Cost += TTI.getCastInstrCost(CI->getOpcode(), CI->getType(), SrcTy,
2310                                    TTI::getCastContextHint(CI),
2311                                    TargetTransformInfo::TCK_SizeAndLatency, CI);
2312 
2313     } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Instr)) {
2314       // Cost of the address calculation
2315       Type *ValTy = GEP->getSourceElementType();
2316       Cost += TTI.getAddressComputationCost(ValTy);
2317 
2318       // And cost of the GEP itself
2319       // TODO: Use TTI->getGEPCost here (it exists, but appears to be not
2320       //       allowed for the external usage)
2321       if (!GEP->hasAllConstantIndices())
2322         Cost += 2;
2323 
2324     } else {
2325       llvm_unreachable("unsupported instruction type during rematerialization");
2326     }
2327   }
2328 
2329   return Cost;
2330 }
2331 
2332 static bool AreEquivalentPhiNodes(PHINode &OrigRootPhi, PHINode &AlternateRootPhi) {
2333   unsigned PhiNum = OrigRootPhi.getNumIncomingValues();
2334   if (PhiNum != AlternateRootPhi.getNumIncomingValues() ||
2335       OrigRootPhi.getParent() != AlternateRootPhi.getParent())
2336     return false;
2337   // Map of incoming values and their corresponding basic blocks of
2338   // OrigRootPhi.
2339   SmallDenseMap<Value *, BasicBlock *, 8> CurrentIncomingValues;
2340   for (unsigned i = 0; i < PhiNum; i++)
2341     CurrentIncomingValues[OrigRootPhi.getIncomingValue(i)] =
2342         OrigRootPhi.getIncomingBlock(i);
2343 
2344   // Both current and base PHIs should have same incoming values and
2345   // the same basic blocks corresponding to the incoming values.
2346   for (unsigned i = 0; i < PhiNum; i++) {
2347     auto CIVI =
2348         CurrentIncomingValues.find(AlternateRootPhi.getIncomingValue(i));
2349     if (CIVI == CurrentIncomingValues.end())
2350       return false;
2351     BasicBlock *CurrentIncomingBB = CIVI->second;
2352     if (CurrentIncomingBB != AlternateRootPhi.getIncomingBlock(i))
2353       return false;
2354   }
2355   return true;
2356 }
2357 
2358 // Find derived pointers that can be recomputed cheap enough and fill
2359 // RematerizationCandidates with such candidates.
2360 static void
2361 findRematerializationCandidates(PointerToBaseTy PointerToBase,
2362                                 RematCandTy &RematerizationCandidates,
2363                                 TargetTransformInfo &TTI) {
2364   const unsigned int ChainLengthThreshold = 10;
2365 
2366   for (auto P2B : PointerToBase) {
2367     auto *Derived = P2B.first;
2368     auto *Base = P2B.second;
2369     // Consider only derived pointers.
2370     if (Derived == Base)
2371       continue;
2372 
2373     // For each live pointer find its defining chain.
2374     SmallVector<Instruction *, 3> ChainToBase;
2375     Value *RootOfChain =
2376         findRematerializableChainToBasePointer(ChainToBase, Derived);
2377 
2378     // Nothing to do, or chain is too long
2379     if ( ChainToBase.size() == 0 ||
2380         ChainToBase.size() > ChainLengthThreshold)
2381       continue;
2382 
2383     // Handle the scenario where the RootOfChain is not equal to the
2384     // Base Value, but they are essentially the same phi values.
2385     if (RootOfChain != PointerToBase[Derived]) {
2386       PHINode *OrigRootPhi = dyn_cast<PHINode>(RootOfChain);
2387       PHINode *AlternateRootPhi = dyn_cast<PHINode>(PointerToBase[Derived]);
2388       if (!OrigRootPhi || !AlternateRootPhi)
2389         continue;
2390       // PHI nodes that have the same incoming values, and belonging to the same
2391       // basic blocks are essentially the same SSA value.  When the original phi
2392       // has incoming values with different base pointers, the original phi is
2393       // marked as conflict, and an additional `AlternateRootPhi` with the same
2394       // incoming values get generated by the findBasePointer function. We need
2395       // to identify the newly generated AlternateRootPhi (.base version of phi)
2396       // and RootOfChain (the original phi node itself) are the same, so that we
2397       // can rematerialize the gep and casts. This is a workaround for the
2398       // deficiency in the findBasePointer algorithm.
2399       if (!AreEquivalentPhiNodes(*OrigRootPhi, *AlternateRootPhi))
2400         continue;
2401     }
2402     // Compute cost of this chain.
2403     InstructionCost Cost = chainToBasePointerCost(ChainToBase, TTI);
2404     // TODO: We can also account for cases when we will be able to remove some
2405     //       of the rematerialized values by later optimization passes. I.e if
2406     //       we rematerialized several intersecting chains. Or if original values
2407     //       don't have any uses besides this statepoint.
2408 
2409     // Ok, there is a candidate.
2410     RematerizlizationCandidateRecord Record;
2411     Record.ChainToBase = ChainToBase;
2412     Record.RootOfChain = RootOfChain;
2413     Record.Cost = Cost;
2414     RematerizationCandidates.insert({ Derived, Record });
2415   }
2416 }
2417 
2418 // Try to rematerialize derived pointers immediately before their uses
2419 // (instead of rematerializing after every statepoint it is live through).
2420 // This can be beneficial when derived pointer is live across many
2421 // statepoints, but uses are rare.
2422 static void rematerializeLiveValuesAtUses(
2423     RematCandTy &RematerizationCandidates,
2424     MutableArrayRef<PartiallyConstructedSafepointRecord> Records,
2425     PointerToBaseTy &PointerToBase) {
2426   if (!RematDerivedAtUses)
2427     return;
2428 
2429   SmallVector<Instruction *, 32> LiveValuesToBeDeleted;
2430 
2431   LLVM_DEBUG(dbgs() << "Rematerialize derived pointers at uses, "
2432                     << "Num statepoints: " << Records.size() << '\n');
2433 
2434   for (auto &It : RematerizationCandidates) {
2435     Instruction *Cand = cast<Instruction>(It.first);
2436     auto &Record = It.second;
2437 
2438     if (Record.Cost >= RematerializationThreshold)
2439       continue;
2440 
2441     if (Cand->user_empty())
2442       continue;
2443 
2444     if (Cand->hasOneUse())
2445       if (auto *U = dyn_cast<Instruction>(Cand->getUniqueUndroppableUser()))
2446         if (U->getParent() == Cand->getParent())
2447           continue;
2448 
2449     // Rematerialization before PHI nodes is not implemented.
2450     if (llvm::any_of(Cand->users(),
2451                      [](const auto *U) { return isa<PHINode>(U); }))
2452       continue;
2453 
2454     LLVM_DEBUG(dbgs() << "Trying cand " << *Cand << " ... ");
2455 
2456     // Count of rematerialization instructions we introduce is equal to number
2457     // of candidate uses.
2458     // Count of rematerialization instructions we eliminate is equal to number
2459     // of statepoints it is live through.
2460     // Consider transformation profitable if latter is greater than former
2461     // (in other words, we create less than eliminate).
2462     unsigned NumLiveStatepoints = llvm::count_if(
2463         Records, [Cand](const auto &R) { return R.LiveSet.contains(Cand); });
2464     unsigned NumUses = Cand->getNumUses();
2465 
2466     LLVM_DEBUG(dbgs() << "Num uses: " << NumUses << " Num live statepoints: "
2467                       << NumLiveStatepoints << " ");
2468 
2469     if (NumLiveStatepoints < NumUses) {
2470       LLVM_DEBUG(dbgs() << "not profitable\n");
2471       continue;
2472     }
2473 
2474     // If rematerialization is 'free', then favor rematerialization at
2475     // uses as it generally shortens live ranges.
2476     // TODO: Short (size ==1) chains only?
2477     if (NumLiveStatepoints == NumUses && Record.Cost > 0) {
2478       LLVM_DEBUG(dbgs() << "not profitable\n");
2479       continue;
2480     }
2481 
2482     LLVM_DEBUG(dbgs() << "looks profitable\n");
2483 
2484     // ChainToBase may contain another remat candidate (as a sub chain) which
2485     // has been rewritten by now. Need to recollect chain to have up to date
2486     // value.
2487     // TODO: sort records in findRematerializationCandidates() in
2488     // decreasing chain size order?
2489     if (Record.ChainToBase.size() > 1) {
2490       Record.ChainToBase.clear();
2491       findRematerializableChainToBasePointer(Record.ChainToBase, Cand);
2492     }
2493 
2494     // Current rematerialization algorithm is very simple: we rematerialize
2495     // immediately before EVERY use, even if there are several uses in same
2496     // block or if use is local to Cand Def. The reason is that this allows
2497     // us to avoid recomputing liveness without complicated analysis:
2498     // - If we did not eliminate all uses of original Candidate, we do not
2499     //   know exaclty in what BBs it is still live.
2500     // - If we rematerialize once per BB, we need to find proper insertion
2501     //   place (first use in block, but after Def) and analyze if there is
2502     //   statepoint between uses in the block.
2503     while (!Cand->user_empty()) {
2504       Instruction *UserI = cast<Instruction>(*Cand->user_begin());
2505       Instruction *RematChain = rematerializeChain(
2506           Record.ChainToBase, UserI, Record.RootOfChain, PointerToBase[Cand]);
2507       UserI->replaceUsesOfWith(Cand, RematChain);
2508       PointerToBase[RematChain] = PointerToBase[Cand];
2509     }
2510     LiveValuesToBeDeleted.push_back(Cand);
2511   }
2512 
2513   LLVM_DEBUG(dbgs() << "Rematerialized " << LiveValuesToBeDeleted.size()
2514                     << " derived pointers\n");
2515   for (auto *Cand : LiveValuesToBeDeleted) {
2516     assert(Cand->use_empty() && "Unexpected user remain");
2517     RematerizationCandidates.erase(Cand);
2518     for (auto &R : Records) {
2519       assert(!R.LiveSet.contains(Cand) ||
2520              R.LiveSet.contains(PointerToBase[Cand]));
2521       R.LiveSet.remove(Cand);
2522     }
2523   }
2524 
2525   // Recollect not rematerialized chains - we might have rewritten
2526   // their sub-chains.
2527   if (!LiveValuesToBeDeleted.empty()) {
2528     for (auto &P : RematerizationCandidates) {
2529       auto &R = P.second;
2530       if (R.ChainToBase.size() > 1) {
2531         R.ChainToBase.clear();
2532         findRematerializableChainToBasePointer(R.ChainToBase, P.first);
2533       }
2534     }
2535   }
2536 }
2537 
2538 // From the statepoint live set pick values that are cheaper to recompute then
2539 // to relocate. Remove this values from the live set, rematerialize them after
2540 // statepoint and record them in "Info" structure. Note that similar to
2541 // relocated values we don't do any user adjustments here.
2542 static void rematerializeLiveValues(CallBase *Call,
2543                                     PartiallyConstructedSafepointRecord &Info,
2544                                     PointerToBaseTy &PointerToBase,
2545                                     RematCandTy &RematerizationCandidates,
2546                                     TargetTransformInfo &TTI) {
2547   // Record values we are going to delete from this statepoint live set.
2548   // We can not di this in following loop due to iterator invalidation.
2549   SmallVector<Value *, 32> LiveValuesToBeDeleted;
2550 
2551   for (Value *LiveValue : Info.LiveSet) {
2552     auto It = RematerizationCandidates.find(LiveValue);
2553     if (It == RematerizationCandidates.end())
2554       continue;
2555 
2556     RematerizlizationCandidateRecord &Record = It->second;
2557 
2558     InstructionCost Cost = Record.Cost;
2559     // For invokes we need to rematerialize each chain twice - for normal and
2560     // for unwind basic blocks. Model this by multiplying cost by two.
2561     if (isa<InvokeInst>(Call))
2562       Cost *= 2;
2563 
2564     // If it's too expensive - skip it.
2565     if (Cost >= RematerializationThreshold)
2566       continue;
2567 
2568     // Remove value from the live set
2569     LiveValuesToBeDeleted.push_back(LiveValue);
2570 
2571     // Clone instructions and record them inside "Info" structure.
2572 
2573     // Different cases for calls and invokes. For invokes we need to clone
2574     // instructions both on normal and unwind path.
2575     if (isa<CallInst>(Call)) {
2576       Instruction *InsertBefore = Call->getNextNode();
2577       assert(InsertBefore);
2578       Instruction *RematerializedValue =
2579           rematerializeChain(Record.ChainToBase, InsertBefore,
2580                              Record.RootOfChain, PointerToBase[LiveValue]);
2581       Info.RematerializedValues[RematerializedValue] = LiveValue;
2582     } else {
2583       auto *Invoke = cast<InvokeInst>(Call);
2584 
2585       Instruction *NormalInsertBefore =
2586           &*Invoke->getNormalDest()->getFirstInsertionPt();
2587       Instruction *UnwindInsertBefore =
2588           &*Invoke->getUnwindDest()->getFirstInsertionPt();
2589 
2590       Instruction *NormalRematerializedValue =
2591           rematerializeChain(Record.ChainToBase, NormalInsertBefore,
2592                              Record.RootOfChain, PointerToBase[LiveValue]);
2593       Instruction *UnwindRematerializedValue =
2594           rematerializeChain(Record.ChainToBase, UnwindInsertBefore,
2595                              Record.RootOfChain, PointerToBase[LiveValue]);
2596 
2597       Info.RematerializedValues[NormalRematerializedValue] = LiveValue;
2598       Info.RematerializedValues[UnwindRematerializedValue] = LiveValue;
2599     }
2600   }
2601 
2602   // Remove rematerialized values from the live set.
2603   for (auto *LiveValue: LiveValuesToBeDeleted) {
2604     Info.LiveSet.remove(LiveValue);
2605   }
2606 }
2607 
2608 static bool inlineGetBaseAndOffset(Function &F,
2609                                    SmallVectorImpl<CallInst *> &Intrinsics,
2610                                    DefiningValueMapTy &DVCache,
2611                                    IsKnownBaseMapTy &KnownBases) {
2612   auto &Context = F.getContext();
2613   auto &DL = F.getParent()->getDataLayout();
2614   bool Changed = false;
2615 
2616   for (auto *Callsite : Intrinsics)
2617     switch (Callsite->getIntrinsicID()) {
2618     case Intrinsic::experimental_gc_get_pointer_base: {
2619       Changed = true;
2620       Value *Base =
2621           findBasePointer(Callsite->getOperand(0), DVCache, KnownBases);
2622       assert(!DVCache.count(Callsite));
2623       auto *BaseBC = IRBuilder<>(Callsite).CreateBitCast(
2624           Base, Callsite->getType(), suffixed_name_or(Base, ".cast", ""));
2625       if (BaseBC != Base)
2626         DVCache[BaseBC] = Base;
2627       Callsite->replaceAllUsesWith(BaseBC);
2628       if (!BaseBC->hasName())
2629         BaseBC->takeName(Callsite);
2630       Callsite->eraseFromParent();
2631       break;
2632     }
2633     case Intrinsic::experimental_gc_get_pointer_offset: {
2634       Changed = true;
2635       Value *Derived = Callsite->getOperand(0);
2636       Value *Base = findBasePointer(Derived, DVCache, KnownBases);
2637       assert(!DVCache.count(Callsite));
2638       unsigned AddressSpace = Derived->getType()->getPointerAddressSpace();
2639       unsigned IntPtrSize = DL.getPointerSizeInBits(AddressSpace);
2640       IRBuilder<> Builder(Callsite);
2641       Value *BaseInt =
2642           Builder.CreatePtrToInt(Base, Type::getIntNTy(Context, IntPtrSize),
2643                                  suffixed_name_or(Base, ".int", ""));
2644       Value *DerivedInt =
2645           Builder.CreatePtrToInt(Derived, Type::getIntNTy(Context, IntPtrSize),
2646                                  suffixed_name_or(Derived, ".int", ""));
2647       Value *Offset = Builder.CreateSub(DerivedInt, BaseInt);
2648       Callsite->replaceAllUsesWith(Offset);
2649       Offset->takeName(Callsite);
2650       Callsite->eraseFromParent();
2651       break;
2652     }
2653     default:
2654       llvm_unreachable("Unknown intrinsic");
2655     }
2656 
2657   return Changed;
2658 }
2659 
2660 static bool insertParsePoints(Function &F, DominatorTree &DT,
2661                               TargetTransformInfo &TTI,
2662                               SmallVectorImpl<CallBase *> &ToUpdate,
2663                               DefiningValueMapTy &DVCache,
2664                               IsKnownBaseMapTy &KnownBases) {
2665   std::unique_ptr<GCStrategy> GC = findGCStrategy(F);
2666 
2667 #ifndef NDEBUG
2668   // Validate the input
2669   std::set<CallBase *> Uniqued;
2670   Uniqued.insert(ToUpdate.begin(), ToUpdate.end());
2671   assert(Uniqued.size() == ToUpdate.size() && "no duplicates please!");
2672 
2673   for (CallBase *Call : ToUpdate)
2674     assert(Call->getFunction() == &F);
2675 #endif
2676 
2677   // When inserting gc.relocates for invokes, we need to be able to insert at
2678   // the top of the successor blocks.  See the comment on
2679   // normalForInvokeSafepoint on exactly what is needed.  Note that this step
2680   // may restructure the CFG.
2681   for (CallBase *Call : ToUpdate) {
2682     auto *II = dyn_cast<InvokeInst>(Call);
2683     if (!II)
2684       continue;
2685     normalizeForInvokeSafepoint(II->getNormalDest(), II->getParent(), DT);
2686     normalizeForInvokeSafepoint(II->getUnwindDest(), II->getParent(), DT);
2687   }
2688 
2689   // A list of dummy calls added to the IR to keep various values obviously
2690   // live in the IR.  We'll remove all of these when done.
2691   SmallVector<CallInst *, 64> Holders;
2692 
2693   // Insert a dummy call with all of the deopt operands we'll need for the
2694   // actual safepoint insertion as arguments.  This ensures reference operands
2695   // in the deopt argument list are considered live through the safepoint (and
2696   // thus makes sure they get relocated.)
2697   for (CallBase *Call : ToUpdate) {
2698     SmallVector<Value *, 64> DeoptValues;
2699 
2700     for (Value *Arg : GetDeoptBundleOperands(Call)) {
2701       assert(!isUnhandledGCPointerType(Arg->getType(), GC.get()) &&
2702              "support for FCA unimplemented");
2703       if (isHandledGCPointerType(Arg->getType(), GC.get()))
2704         DeoptValues.push_back(Arg);
2705     }
2706 
2707     insertUseHolderAfter(Call, DeoptValues, Holders);
2708   }
2709 
2710   SmallVector<PartiallyConstructedSafepointRecord, 64> Records(ToUpdate.size());
2711 
2712   // A) Identify all gc pointers which are statically live at the given call
2713   // site.
2714   findLiveReferences(F, DT, ToUpdate, Records, GC.get());
2715 
2716   /// Global mapping from live pointers to a base-defining-value.
2717   PointerToBaseTy PointerToBase;
2718 
2719   // B) Find the base pointers for each live pointer
2720   for (size_t i = 0; i < Records.size(); i++) {
2721     PartiallyConstructedSafepointRecord &info = Records[i];
2722     findBasePointers(DT, DVCache, ToUpdate[i], info, PointerToBase, KnownBases);
2723   }
2724   if (PrintBasePointers) {
2725     errs() << "Base Pairs (w/o Relocation):\n";
2726     for (auto &Pair : PointerToBase) {
2727       errs() << " derived ";
2728       Pair.first->printAsOperand(errs(), false);
2729       errs() << " base ";
2730       Pair.second->printAsOperand(errs(), false);
2731       errs() << "\n";
2732       ;
2733     }
2734   }
2735 
2736   // The base phi insertion logic (for any safepoint) may have inserted new
2737   // instructions which are now live at some safepoint.  The simplest such
2738   // example is:
2739   // loop:
2740   //   phi a  <-- will be a new base_phi here
2741   //   safepoint 1 <-- that needs to be live here
2742   //   gep a + 1
2743   //   safepoint 2
2744   //   br loop
2745   // We insert some dummy calls after each safepoint to definitely hold live
2746   // the base pointers which were identified for that safepoint.  We'll then
2747   // ask liveness for _every_ base inserted to see what is now live.  Then we
2748   // remove the dummy calls.
2749   Holders.reserve(Holders.size() + Records.size());
2750   for (size_t i = 0; i < Records.size(); i++) {
2751     PartiallyConstructedSafepointRecord &Info = Records[i];
2752 
2753     SmallVector<Value *, 128> Bases;
2754     for (auto *Derived : Info.LiveSet) {
2755       assert(PointerToBase.count(Derived) && "Missed base for derived pointer");
2756       Bases.push_back(PointerToBase[Derived]);
2757     }
2758 
2759     insertUseHolderAfter(ToUpdate[i], Bases, Holders);
2760   }
2761 
2762   // By selecting base pointers, we've effectively inserted new uses. Thus, we
2763   // need to rerun liveness.  We may *also* have inserted new defs, but that's
2764   // not the key issue.
2765   recomputeLiveInValues(F, DT, ToUpdate, Records, PointerToBase, GC.get());
2766 
2767   if (PrintBasePointers) {
2768     errs() << "Base Pairs: (w/Relocation)\n";
2769     for (auto Pair : PointerToBase) {
2770       errs() << " derived ";
2771       Pair.first->printAsOperand(errs(), false);
2772       errs() << " base ";
2773       Pair.second->printAsOperand(errs(), false);
2774       errs() << "\n";
2775     }
2776   }
2777 
2778   // It is possible that non-constant live variables have a constant base.  For
2779   // example, a GEP with a variable offset from a global.  In this case we can
2780   // remove it from the liveset.  We already don't add constants to the liveset
2781   // because we assume they won't move at runtime and the GC doesn't need to be
2782   // informed about them.  The same reasoning applies if the base is constant.
2783   // Note that the relocation placement code relies on this filtering for
2784   // correctness as it expects the base to be in the liveset, which isn't true
2785   // if the base is constant.
2786   for (auto &Info : Records) {
2787     Info.LiveSet.remove_if([&](Value *LiveV) {
2788       assert(PointerToBase.count(LiveV) && "Missed base for derived pointer");
2789       return isa<Constant>(PointerToBase[LiveV]);
2790     });
2791   }
2792 
2793   for (CallInst *CI : Holders)
2794     CI->eraseFromParent();
2795 
2796   Holders.clear();
2797 
2798   // Compute the cost of possible re-materialization of derived pointers.
2799   RematCandTy RematerizationCandidates;
2800   findRematerializationCandidates(PointerToBase, RematerizationCandidates, TTI);
2801 
2802   // In order to reduce live set of statepoint we might choose to rematerialize
2803   // some values instead of relocating them. This is purely an optimization and
2804   // does not influence correctness.
2805   // First try rematerialization at uses, then after statepoints.
2806   rematerializeLiveValuesAtUses(RematerizationCandidates, Records,
2807                                 PointerToBase);
2808   for (size_t i = 0; i < Records.size(); i++)
2809     rematerializeLiveValues(ToUpdate[i], Records[i], PointerToBase,
2810                             RematerizationCandidates, TTI);
2811 
2812   // We need this to safely RAUW and delete call or invoke return values that
2813   // may themselves be live over a statepoint.  For details, please see usage in
2814   // makeStatepointExplicitImpl.
2815   std::vector<DeferredReplacement> Replacements;
2816 
2817   // Now run through and replace the existing statepoints with new ones with
2818   // the live variables listed.  We do not yet update uses of the values being
2819   // relocated. We have references to live variables that need to
2820   // survive to the last iteration of this loop.  (By construction, the
2821   // previous statepoint can not be a live variable, thus we can and remove
2822   // the old statepoint calls as we go.)
2823   for (size_t i = 0; i < Records.size(); i++)
2824     makeStatepointExplicit(DT, ToUpdate[i], Records[i], Replacements,
2825                            PointerToBase, GC.get());
2826 
2827   ToUpdate.clear(); // prevent accident use of invalid calls.
2828 
2829   for (auto &PR : Replacements)
2830     PR.doReplacement();
2831 
2832   Replacements.clear();
2833 
2834   for (auto &Info : Records) {
2835     // These live sets may contain state Value pointers, since we replaced calls
2836     // with operand bundles with calls wrapped in gc.statepoint, and some of
2837     // those calls may have been def'ing live gc pointers.  Clear these out to
2838     // avoid accidentally using them.
2839     //
2840     // TODO: We should create a separate data structure that does not contain
2841     // these live sets, and migrate to using that data structure from this point
2842     // onward.
2843     Info.LiveSet.clear();
2844   }
2845   PointerToBase.clear();
2846 
2847   // Do all the fixups of the original live variables to their relocated selves
2848   SmallVector<Value *, 128> Live;
2849   for (const PartiallyConstructedSafepointRecord &Info : Records) {
2850     // We can't simply save the live set from the original insertion.  One of
2851     // the live values might be the result of a call which needs a safepoint.
2852     // That Value* no longer exists and we need to use the new gc_result.
2853     // Thankfully, the live set is embedded in the statepoint (and updated), so
2854     // we just grab that.
2855     llvm::append_range(Live, Info.StatepointToken->gc_args());
2856 #ifndef NDEBUG
2857     // Do some basic validation checking on our liveness results before
2858     // performing relocation.  Relocation can and will turn mistakes in liveness
2859     // results into non-sensical code which is must harder to debug.
2860     // TODO: It would be nice to test consistency as well
2861     assert(DT.isReachableFromEntry(Info.StatepointToken->getParent()) &&
2862            "statepoint must be reachable or liveness is meaningless");
2863     for (Value *V : Info.StatepointToken->gc_args()) {
2864       if (!isa<Instruction>(V))
2865         // Non-instruction values trivial dominate all possible uses
2866         continue;
2867       auto *LiveInst = cast<Instruction>(V);
2868       assert(DT.isReachableFromEntry(LiveInst->getParent()) &&
2869              "unreachable values should never be live");
2870       assert(DT.dominates(LiveInst, Info.StatepointToken) &&
2871              "basic SSA liveness expectation violated by liveness analysis");
2872     }
2873 #endif
2874   }
2875   unique_unsorted(Live);
2876 
2877 #ifndef NDEBUG
2878   // Validation check
2879   for (auto *Ptr : Live)
2880     assert(isHandledGCPointerType(Ptr->getType(), GC.get()) &&
2881            "must be a gc pointer type");
2882 #endif
2883 
2884   relocationViaAlloca(F, DT, Live, Records);
2885   return !Records.empty();
2886 }
2887 
2888 // List of all parameter and return attributes which must be stripped when
2889 // lowering from the abstract machine model.  Note that we list attributes
2890 // here which aren't valid as return attributes, that is okay.
2891 static AttributeMask getParamAndReturnAttributesToRemove() {
2892   AttributeMask R;
2893   R.addAttribute(Attribute::Dereferenceable);
2894   R.addAttribute(Attribute::DereferenceableOrNull);
2895   R.addAttribute(Attribute::ReadNone);
2896   R.addAttribute(Attribute::ReadOnly);
2897   R.addAttribute(Attribute::WriteOnly);
2898   R.addAttribute(Attribute::NoAlias);
2899   R.addAttribute(Attribute::NoFree);
2900   return R;
2901 }
2902 
2903 static void stripNonValidAttributesFromPrototype(Function &F) {
2904   LLVMContext &Ctx = F.getContext();
2905 
2906   // Intrinsics are very delicate.  Lowering sometimes depends the presence
2907   // of certain attributes for correctness, but we may have also inferred
2908   // additional ones in the abstract machine model which need stripped.  This
2909   // assumes that the attributes defined in Intrinsic.td are conservatively
2910   // correct for both physical and abstract model.
2911   if (Intrinsic::ID id = F.getIntrinsicID()) {
2912     F.setAttributes(Intrinsic::getAttributes(Ctx, id));
2913     return;
2914   }
2915 
2916   AttributeMask R = getParamAndReturnAttributesToRemove();
2917   for (Argument &A : F.args())
2918     if (isa<PointerType>(A.getType()))
2919       F.removeParamAttrs(A.getArgNo(), R);
2920 
2921   if (isa<PointerType>(F.getReturnType()))
2922     F.removeRetAttrs(R);
2923 
2924   for (auto Attr : FnAttrsToStrip)
2925     F.removeFnAttr(Attr);
2926 }
2927 
2928 /// Certain metadata on instructions are invalid after running RS4GC.
2929 /// Optimizations that run after RS4GC can incorrectly use this metadata to
2930 /// optimize functions. We drop such metadata on the instruction.
2931 static void stripInvalidMetadataFromInstruction(Instruction &I) {
2932   if (!isa<LoadInst>(I) && !isa<StoreInst>(I))
2933     return;
2934   // These are the attributes that are still valid on loads and stores after
2935   // RS4GC.
2936   // The metadata implying dereferenceability and noalias are (conservatively)
2937   // dropped.  This is because semantically, after RewriteStatepointsForGC runs,
2938   // all calls to gc.statepoint "free" the entire heap. Also, gc.statepoint can
2939   // touch the entire heap including noalias objects. Note: The reasoning is
2940   // same as stripping the dereferenceability and noalias attributes that are
2941   // analogous to the metadata counterparts.
2942   // We also drop the invariant.load metadata on the load because that metadata
2943   // implies the address operand to the load points to memory that is never
2944   // changed once it became dereferenceable. This is no longer true after RS4GC.
2945   // Similar reasoning applies to invariant.group metadata, which applies to
2946   // loads within a group.
2947   unsigned ValidMetadataAfterRS4GC[] = {LLVMContext::MD_tbaa,
2948                          LLVMContext::MD_range,
2949                          LLVMContext::MD_alias_scope,
2950                          LLVMContext::MD_nontemporal,
2951                          LLVMContext::MD_nonnull,
2952                          LLVMContext::MD_align,
2953                          LLVMContext::MD_type};
2954 
2955   // Drops all metadata on the instruction other than ValidMetadataAfterRS4GC.
2956   I.dropUnknownNonDebugMetadata(ValidMetadataAfterRS4GC);
2957 }
2958 
2959 static void stripNonValidDataFromBody(Function &F) {
2960   if (F.empty())
2961     return;
2962 
2963   LLVMContext &Ctx = F.getContext();
2964   MDBuilder Builder(Ctx);
2965 
2966   // Set of invariantstart instructions that we need to remove.
2967   // Use this to avoid invalidating the instruction iterator.
2968   SmallVector<IntrinsicInst*, 12> InvariantStartInstructions;
2969 
2970   for (Instruction &I : instructions(F)) {
2971     // invariant.start on memory location implies that the referenced memory
2972     // location is constant and unchanging. This is no longer true after
2973     // RewriteStatepointsForGC runs because there can be calls to gc.statepoint
2974     // which frees the entire heap and the presence of invariant.start allows
2975     // the optimizer to sink the load of a memory location past a statepoint,
2976     // which is incorrect.
2977     if (auto *II = dyn_cast<IntrinsicInst>(&I))
2978       if (II->getIntrinsicID() == Intrinsic::invariant_start) {
2979         InvariantStartInstructions.push_back(II);
2980         continue;
2981       }
2982 
2983     if (MDNode *Tag = I.getMetadata(LLVMContext::MD_tbaa)) {
2984       MDNode *MutableTBAA = Builder.createMutableTBAAAccessTag(Tag);
2985       I.setMetadata(LLVMContext::MD_tbaa, MutableTBAA);
2986     }
2987 
2988     stripInvalidMetadataFromInstruction(I);
2989 
2990     AttributeMask R = getParamAndReturnAttributesToRemove();
2991     if (auto *Call = dyn_cast<CallBase>(&I)) {
2992       for (int i = 0, e = Call->arg_size(); i != e; i++)
2993         if (isa<PointerType>(Call->getArgOperand(i)->getType()))
2994           Call->removeParamAttrs(i, R);
2995       if (isa<PointerType>(Call->getType()))
2996         Call->removeRetAttrs(R);
2997     }
2998   }
2999 
3000   // Delete the invariant.start instructions and RAUW poison.
3001   for (auto *II : InvariantStartInstructions) {
3002     II->replaceAllUsesWith(PoisonValue::get(II->getType()));
3003     II->eraseFromParent();
3004   }
3005 }
3006 
3007 /// Looks up the GC strategy for a given function, returning null if the
3008 /// function doesn't have a GC tag. The strategy is stored in the cache.
3009 static std::unique_ptr<GCStrategy> findGCStrategy(Function &F) {
3010   if (!F.hasGC())
3011     return nullptr;
3012 
3013   return getGCStrategy(F.getGC());
3014 }
3015 
3016 /// Returns true if this function should be rewritten by this pass.  The main
3017 /// point of this function is as an extension point for custom logic.
3018 static bool shouldRewriteStatepointsIn(Function &F) {
3019   if (!F.hasGC())
3020     return false;
3021 
3022   std::unique_ptr<GCStrategy> Strategy = findGCStrategy(F);
3023 
3024   assert(Strategy && "GC strategy is required by function, but was not found");
3025 
3026   return Strategy->useRS4GC();
3027 }
3028 
3029 static void stripNonValidData(Module &M) {
3030 #ifndef NDEBUG
3031   assert(llvm::any_of(M, shouldRewriteStatepointsIn) && "precondition!");
3032 #endif
3033 
3034   for (Function &F : M)
3035     stripNonValidAttributesFromPrototype(F);
3036 
3037   for (Function &F : M)
3038     stripNonValidDataFromBody(F);
3039 }
3040 
3041 bool RewriteStatepointsForGC::runOnFunction(Function &F, DominatorTree &DT,
3042                                             TargetTransformInfo &TTI,
3043                                             const TargetLibraryInfo &TLI) {
3044   assert(!F.isDeclaration() && !F.empty() &&
3045          "need function body to rewrite statepoints in");
3046   assert(shouldRewriteStatepointsIn(F) && "mismatch in rewrite decision");
3047 
3048   auto NeedsRewrite = [&TLI](Instruction &I) {
3049     if (const auto *Call = dyn_cast<CallBase>(&I)) {
3050       if (isa<GCStatepointInst>(Call))
3051         return false;
3052       if (callsGCLeafFunction(Call, TLI))
3053         return false;
3054 
3055       // Normally it's up to the frontend to make sure that non-leaf calls also
3056       // have proper deopt state if it is required. We make an exception for
3057       // element atomic memcpy/memmove intrinsics here. Unlike other intrinsics
3058       // these are non-leaf by default. They might be generated by the optimizer
3059       // which doesn't know how to produce a proper deopt state. So if we see a
3060       // non-leaf memcpy/memmove without deopt state just treat it as a leaf
3061       // copy and don't produce a statepoint.
3062       if (!AllowStatepointWithNoDeoptInfo &&
3063           !Call->getOperandBundle(LLVMContext::OB_deopt)) {
3064         assert((isa<AtomicMemCpyInst>(Call) || isa<AtomicMemMoveInst>(Call)) &&
3065                "Don't expect any other calls here!");
3066         return false;
3067       }
3068       return true;
3069     }
3070     return false;
3071   };
3072 
3073   // Delete any unreachable statepoints so that we don't have unrewritten
3074   // statepoints surviving this pass.  This makes testing easier and the
3075   // resulting IR less confusing to human readers.
3076   DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
3077   bool MadeChange = removeUnreachableBlocks(F, &DTU);
3078   // Flush the Dominator Tree.
3079   DTU.getDomTree();
3080 
3081   // Gather all the statepoints which need rewritten.  Be careful to only
3082   // consider those in reachable code since we need to ask dominance queries
3083   // when rewriting.  We'll delete the unreachable ones in a moment.
3084   SmallVector<CallBase *, 64> ParsePointNeeded;
3085   SmallVector<CallInst *, 64> Intrinsics;
3086   for (Instruction &I : instructions(F)) {
3087     // TODO: only the ones with the flag set!
3088     if (NeedsRewrite(I)) {
3089       // NOTE removeUnreachableBlocks() is stronger than
3090       // DominatorTree::isReachableFromEntry(). In other words
3091       // removeUnreachableBlocks can remove some blocks for which
3092       // isReachableFromEntry() returns true.
3093       assert(DT.isReachableFromEntry(I.getParent()) &&
3094             "no unreachable blocks expected");
3095       ParsePointNeeded.push_back(cast<CallBase>(&I));
3096     }
3097     if (auto *CI = dyn_cast<CallInst>(&I))
3098       if (CI->getIntrinsicID() == Intrinsic::experimental_gc_get_pointer_base ||
3099           CI->getIntrinsicID() == Intrinsic::experimental_gc_get_pointer_offset)
3100         Intrinsics.emplace_back(CI);
3101   }
3102 
3103   // Return early if no work to do.
3104   if (ParsePointNeeded.empty() && Intrinsics.empty())
3105     return MadeChange;
3106 
3107   // As a prepass, go ahead and aggressively destroy single entry phi nodes.
3108   // These are created by LCSSA.  They have the effect of increasing the size
3109   // of liveness sets for no good reason.  It may be harder to do this post
3110   // insertion since relocations and base phis can confuse things.
3111   for (BasicBlock &BB : F)
3112     if (BB.getUniquePredecessor())
3113       MadeChange |= FoldSingleEntryPHINodes(&BB);
3114 
3115   // Before we start introducing relocations, we want to tweak the IR a bit to
3116   // avoid unfortunate code generation effects.  The main example is that we
3117   // want to try to make sure the comparison feeding a branch is after any
3118   // safepoints.  Otherwise, we end up with a comparison of pre-relocation
3119   // values feeding a branch after relocation.  This is semantically correct,
3120   // but results in extra register pressure since both the pre-relocation and
3121   // post-relocation copies must be available in registers.  For code without
3122   // relocations this is handled elsewhere, but teaching the scheduler to
3123   // reverse the transform we're about to do would be slightly complex.
3124   // Note: This may extend the live range of the inputs to the icmp and thus
3125   // increase the liveset of any statepoint we move over.  This is profitable
3126   // as long as all statepoints are in rare blocks.  If we had in-register
3127   // lowering for live values this would be a much safer transform.
3128   auto getConditionInst = [](Instruction *TI) -> Instruction * {
3129     if (auto *BI = dyn_cast<BranchInst>(TI))
3130       if (BI->isConditional())
3131         return dyn_cast<Instruction>(BI->getCondition());
3132     // TODO: Extend this to handle switches
3133     return nullptr;
3134   };
3135   for (BasicBlock &BB : F) {
3136     Instruction *TI = BB.getTerminator();
3137     if (auto *Cond = getConditionInst(TI))
3138       // TODO: Handle more than just ICmps here.  We should be able to move
3139       // most instructions without side effects or memory access.
3140       if (isa<ICmpInst>(Cond) && Cond->hasOneUse()) {
3141         MadeChange = true;
3142         Cond->moveBefore(TI);
3143       }
3144   }
3145 
3146   // Nasty workaround - The base computation code in the main algorithm doesn't
3147   // consider the fact that a GEP can be used to convert a scalar to a vector.
3148   // The right fix for this is to integrate GEPs into the base rewriting
3149   // algorithm properly, this is just a short term workaround to prevent
3150   // crashes by canonicalizing such GEPs into fully vector GEPs.
3151   for (Instruction &I : instructions(F)) {
3152     if (!isa<GetElementPtrInst>(I))
3153       continue;
3154 
3155     unsigned VF = 0;
3156     for (unsigned i = 0; i < I.getNumOperands(); i++)
3157       if (auto *OpndVTy = dyn_cast<VectorType>(I.getOperand(i)->getType())) {
3158         assert(VF == 0 ||
3159                VF == cast<FixedVectorType>(OpndVTy)->getNumElements());
3160         VF = cast<FixedVectorType>(OpndVTy)->getNumElements();
3161       }
3162 
3163     // It's the vector to scalar traversal through the pointer operand which
3164     // confuses base pointer rewriting, so limit ourselves to that case.
3165     if (!I.getOperand(0)->getType()->isVectorTy() && VF != 0) {
3166       IRBuilder<> B(&I);
3167       auto *Splat = B.CreateVectorSplat(VF, I.getOperand(0));
3168       I.setOperand(0, Splat);
3169       MadeChange = true;
3170     }
3171   }
3172 
3173   // Cache the 'defining value' relation used in the computation and
3174   // insertion of base phis and selects.  This ensures that we don't insert
3175   // large numbers of duplicate base_phis. Use one cache for both
3176   // inlineGetBaseAndOffset() and insertParsePoints().
3177   DefiningValueMapTy DVCache;
3178 
3179   // Mapping between a base values and a flag indicating whether it's a known
3180   // base or not.
3181   IsKnownBaseMapTy KnownBases;
3182 
3183   if (!Intrinsics.empty())
3184     // Inline @gc.get.pointer.base() and @gc.get.pointer.offset() before finding
3185     // live references.
3186     MadeChange |= inlineGetBaseAndOffset(F, Intrinsics, DVCache, KnownBases);
3187 
3188   if (!ParsePointNeeded.empty())
3189     MadeChange |=
3190         insertParsePoints(F, DT, TTI, ParsePointNeeded, DVCache, KnownBases);
3191 
3192   return MadeChange;
3193 }
3194 
3195 // liveness computation via standard dataflow
3196 // -------------------------------------------------------------------
3197 
3198 // TODO: Consider using bitvectors for liveness, the set of potentially
3199 // interesting values should be small and easy to pre-compute.
3200 
3201 /// Compute the live-in set for the location rbegin starting from
3202 /// the live-out set of the basic block
3203 static void computeLiveInValues(BasicBlock::reverse_iterator Begin,
3204                                 BasicBlock::reverse_iterator End,
3205                                 SetVector<Value *> &LiveTmp, GCStrategy *GC) {
3206   for (auto &I : make_range(Begin, End)) {
3207     // KILL/Def - Remove this definition from LiveIn
3208     LiveTmp.remove(&I);
3209 
3210     // Don't consider *uses* in PHI nodes, we handle their contribution to
3211     // predecessor blocks when we seed the LiveOut sets
3212     if (isa<PHINode>(I))
3213       continue;
3214 
3215     // USE - Add to the LiveIn set for this instruction
3216     for (Value *V : I.operands()) {
3217       assert(!isUnhandledGCPointerType(V->getType(), GC) &&
3218              "support for FCA unimplemented");
3219       if (isHandledGCPointerType(V->getType(), GC) && !isa<Constant>(V)) {
3220         // The choice to exclude all things constant here is slightly subtle.
3221         // There are two independent reasons:
3222         // - We assume that things which are constant (from LLVM's definition)
3223         // do not move at runtime.  For example, the address of a global
3224         // variable is fixed, even though it's contents may not be.
3225         // - Second, we can't disallow arbitrary inttoptr constants even
3226         // if the language frontend does.  Optimization passes are free to
3227         // locally exploit facts without respect to global reachability.  This
3228         // can create sections of code which are dynamically unreachable and
3229         // contain just about anything.  (see constants.ll in tests)
3230         LiveTmp.insert(V);
3231       }
3232     }
3233   }
3234 }
3235 
3236 static void computeLiveOutSeed(BasicBlock *BB, SetVector<Value *> &LiveTmp,
3237                                GCStrategy *GC) {
3238   for (BasicBlock *Succ : successors(BB)) {
3239     for (auto &I : *Succ) {
3240       PHINode *PN = dyn_cast<PHINode>(&I);
3241       if (!PN)
3242         break;
3243 
3244       Value *V = PN->getIncomingValueForBlock(BB);
3245       assert(!isUnhandledGCPointerType(V->getType(), GC) &&
3246              "support for FCA unimplemented");
3247       if (isHandledGCPointerType(V->getType(), GC) && !isa<Constant>(V))
3248         LiveTmp.insert(V);
3249     }
3250   }
3251 }
3252 
3253 static SetVector<Value *> computeKillSet(BasicBlock *BB, GCStrategy *GC) {
3254   SetVector<Value *> KillSet;
3255   for (Instruction &I : *BB)
3256     if (isHandledGCPointerType(I.getType(), GC))
3257       KillSet.insert(&I);
3258   return KillSet;
3259 }
3260 
3261 #ifndef NDEBUG
3262 /// Check that the items in 'Live' dominate 'TI'.  This is used as a basic
3263 /// validation check for the liveness computation.
3264 static void checkBasicSSA(DominatorTree &DT, SetVector<Value *> &Live,
3265                           Instruction *TI, bool TermOkay = false) {
3266   for (Value *V : Live) {
3267     if (auto *I = dyn_cast<Instruction>(V)) {
3268       // The terminator can be a member of the LiveOut set.  LLVM's definition
3269       // of instruction dominance states that V does not dominate itself.  As
3270       // such, we need to special case this to allow it.
3271       if (TermOkay && TI == I)
3272         continue;
3273       assert(DT.dominates(I, TI) &&
3274              "basic SSA liveness expectation violated by liveness analysis");
3275     }
3276   }
3277 }
3278 
3279 /// Check that all the liveness sets used during the computation of liveness
3280 /// obey basic SSA properties.  This is useful for finding cases where we miss
3281 /// a def.
3282 static void checkBasicSSA(DominatorTree &DT, GCPtrLivenessData &Data,
3283                           BasicBlock &BB) {
3284   checkBasicSSA(DT, Data.LiveSet[&BB], BB.getTerminator());
3285   checkBasicSSA(DT, Data.LiveOut[&BB], BB.getTerminator(), true);
3286   checkBasicSSA(DT, Data.LiveIn[&BB], BB.getTerminator());
3287 }
3288 #endif
3289 
3290 static void computeLiveInValues(DominatorTree &DT, Function &F,
3291                                 GCPtrLivenessData &Data, GCStrategy *GC) {
3292   SmallSetVector<BasicBlock *, 32> Worklist;
3293 
3294   // Seed the liveness for each individual block
3295   for (BasicBlock &BB : F) {
3296     Data.KillSet[&BB] = computeKillSet(&BB, GC);
3297     Data.LiveSet[&BB].clear();
3298     computeLiveInValues(BB.rbegin(), BB.rend(), Data.LiveSet[&BB], GC);
3299 
3300 #ifndef NDEBUG
3301     for (Value *Kill : Data.KillSet[&BB])
3302       assert(!Data.LiveSet[&BB].count(Kill) && "live set contains kill");
3303 #endif
3304 
3305     Data.LiveOut[&BB] = SetVector<Value *>();
3306     computeLiveOutSeed(&BB, Data.LiveOut[&BB], GC);
3307     Data.LiveIn[&BB] = Data.LiveSet[&BB];
3308     Data.LiveIn[&BB].set_union(Data.LiveOut[&BB]);
3309     Data.LiveIn[&BB].set_subtract(Data.KillSet[&BB]);
3310     if (!Data.LiveIn[&BB].empty())
3311       Worklist.insert(pred_begin(&BB), pred_end(&BB));
3312   }
3313 
3314   // Propagate that liveness until stable
3315   while (!Worklist.empty()) {
3316     BasicBlock *BB = Worklist.pop_back_val();
3317 
3318     // Compute our new liveout set, then exit early if it hasn't changed despite
3319     // the contribution of our successor.
3320     SetVector<Value *> LiveOut = Data.LiveOut[BB];
3321     const auto OldLiveOutSize = LiveOut.size();
3322     for (BasicBlock *Succ : successors(BB)) {
3323       assert(Data.LiveIn.count(Succ));
3324       LiveOut.set_union(Data.LiveIn[Succ]);
3325     }
3326     // assert OutLiveOut is a subset of LiveOut
3327     if (OldLiveOutSize == LiveOut.size()) {
3328       // If the sets are the same size, then we didn't actually add anything
3329       // when unioning our successors LiveIn.  Thus, the LiveIn of this block
3330       // hasn't changed.
3331       continue;
3332     }
3333     Data.LiveOut[BB] = LiveOut;
3334 
3335     // Apply the effects of this basic block
3336     SetVector<Value *> LiveTmp = LiveOut;
3337     LiveTmp.set_union(Data.LiveSet[BB]);
3338     LiveTmp.set_subtract(Data.KillSet[BB]);
3339 
3340     assert(Data.LiveIn.count(BB));
3341     const SetVector<Value *> &OldLiveIn = Data.LiveIn[BB];
3342     // assert: OldLiveIn is a subset of LiveTmp
3343     if (OldLiveIn.size() != LiveTmp.size()) {
3344       Data.LiveIn[BB] = LiveTmp;
3345       Worklist.insert(pred_begin(BB), pred_end(BB));
3346     }
3347   } // while (!Worklist.empty())
3348 
3349 #ifndef NDEBUG
3350   // Verify our output against SSA properties.  This helps catch any
3351   // missing kills during the above iteration.
3352   for (BasicBlock &BB : F)
3353     checkBasicSSA(DT, Data, BB);
3354 #endif
3355 }
3356 
3357 static void findLiveSetAtInst(Instruction *Inst, GCPtrLivenessData &Data,
3358                               StatepointLiveSetTy &Out, GCStrategy *GC) {
3359   BasicBlock *BB = Inst->getParent();
3360 
3361   // Note: The copy is intentional and required
3362   assert(Data.LiveOut.count(BB));
3363   SetVector<Value *> LiveOut = Data.LiveOut[BB];
3364 
3365   // We want to handle the statepoint itself oddly.  It's
3366   // call result is not live (normal), nor are it's arguments
3367   // (unless they're used again later).  This adjustment is
3368   // specifically what we need to relocate
3369   computeLiveInValues(BB->rbegin(), ++Inst->getIterator().getReverse(), LiveOut,
3370                       GC);
3371   LiveOut.remove(Inst);
3372   Out.insert(LiveOut.begin(), LiveOut.end());
3373 }
3374 
3375 static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData,
3376                                   CallBase *Call,
3377                                   PartiallyConstructedSafepointRecord &Info,
3378                                   PointerToBaseTy &PointerToBase,
3379                                   GCStrategy *GC) {
3380   StatepointLiveSetTy Updated;
3381   findLiveSetAtInst(Call, RevisedLivenessData, Updated, GC);
3382 
3383   // We may have base pointers which are now live that weren't before.  We need
3384   // to update the PointerToBase structure to reflect this.
3385   for (auto *V : Updated)
3386     PointerToBase.insert({ V, V });
3387 
3388   Info.LiveSet = Updated;
3389 }
3390