xref: /llvm-project/llvm/lib/Transforms/Scalar/RewriteStatepointsForGC.cpp (revision e6e62efa880e7afe8a054f24857d1b64b8567767)
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 = States[BDV];
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   // Handle all instructions that have a vector BDV, but the instruction itself
1016   // is of scalar type.
1017   for (auto Pair : States) {
1018     Instruction *I = cast<Instruction>(Pair.first);
1019     BDVState State = Pair.second;
1020     auto *BaseValue = State.getBaseValue();
1021     // Only values that do not have known bases or those that have differing
1022     // type (scalar versus vector) from a possible known base should be in the
1023     // lattice.
1024     assert(
1025         (!isKnownBase(I, KnownBases) || !areBothVectorOrScalar(I, BaseValue)) &&
1026         "why did it get added?");
1027     assert(!State.isUnknown() && "Optimistic algorithm didn't complete!");
1028 
1029     if (!State.isBase() || !isa<VectorType>(BaseValue->getType()))
1030       continue;
1031     // extractelement instructions are a bit special in that we may need to
1032     // insert an extract even when we know an exact base for the instruction.
1033     // The problem is that we need to convert from a vector base to a scalar
1034     // base for the particular indice we're interested in.
1035     if (isa<ExtractElementInst>(I)) {
1036       auto *EE = cast<ExtractElementInst>(I);
1037       // TODO: In many cases, the new instruction is just EE itself.  We should
1038       // exploit this, but can't do it here since it would break the invariant
1039       // about the BDV not being known to be a base.
1040       auto *BaseInst = ExtractElementInst::Create(
1041           State.getBaseValue(), EE->getIndexOperand(), "base_ee", EE);
1042       BaseInst->setMetadata("is_base_value", MDNode::get(I->getContext(), {}));
1043       States[I] = BDVState(I, BDVState::Base, BaseInst);
1044       setKnownBase(BaseInst, /* IsKnownBase */true, KnownBases);
1045     } else if (!isa<VectorType>(I->getType())) {
1046       // We need to handle cases that have a vector base but the instruction is
1047       // a scalar type (these could be phis or selects or any instruction that
1048       // are of scalar type, but the base can be a vector type).  We
1049       // conservatively set this as conflict.  Setting the base value for these
1050       // conflicts is handled in the next loop which traverses States.
1051       States[I] = BDVState(I, BDVState::Conflict);
1052     }
1053   }
1054 
1055 #ifndef NDEBUG
1056   VerifyStates();
1057 #endif
1058 
1059   // Insert Phis for all conflicts
1060   // TODO: adjust naming patterns to avoid this order of iteration dependency
1061   for (auto Pair : States) {
1062     Instruction *I = cast<Instruction>(Pair.first);
1063     BDVState State = Pair.second;
1064     // Only values that do not have known bases or those that have differing
1065     // type (scalar versus vector) from a possible known base should be in the
1066     // lattice.
1067     assert((!isKnownBase(I, KnownBases) ||
1068             !areBothVectorOrScalar(I, State.getBaseValue())) &&
1069            "why did it get added?");
1070     assert(!State.isUnknown() && "Optimistic algorithm didn't complete!");
1071 
1072     // Since we're joining a vector and scalar base, they can never be the
1073     // same.  As a result, we should always see insert element having reached
1074     // the conflict state.
1075     assert(!isa<InsertElementInst>(I) || State.isConflict());
1076 
1077     if (!State.isConflict())
1078       continue;
1079 
1080     auto getMangledName = [](Instruction *I) -> std::string {
1081       if (isa<PHINode>(I)) {
1082         return suffixed_name_or(I, ".base", "base_phi");
1083       } else if (isa<SelectInst>(I)) {
1084         return suffixed_name_or(I, ".base", "base_select");
1085       } else if (isa<ExtractElementInst>(I)) {
1086         return suffixed_name_or(I, ".base", "base_ee");
1087       } else if (isa<InsertElementInst>(I)) {
1088         return suffixed_name_or(I, ".base", "base_ie");
1089       } else {
1090         return suffixed_name_or(I, ".base", "base_sv");
1091       }
1092     };
1093 
1094     Instruction *BaseInst = I->clone();
1095     BaseInst->insertBefore(I);
1096     BaseInst->setName(getMangledName(I));
1097     // Add metadata marking this as a base value
1098     BaseInst->setMetadata("is_base_value", MDNode::get(I->getContext(), {}));
1099     States[I] = BDVState(I, BDVState::Conflict, BaseInst);
1100     setKnownBase(BaseInst, /* IsKnownBase */true, KnownBases);
1101   }
1102 
1103 #ifndef NDEBUG
1104   VerifyStates();
1105 #endif
1106 
1107   // Returns a instruction which produces the base pointer for a given
1108   // instruction.  The instruction is assumed to be an input to one of the BDVs
1109   // seen in the inference algorithm above.  As such, we must either already
1110   // know it's base defining value is a base, or have inserted a new
1111   // instruction to propagate the base of it's BDV and have entered that newly
1112   // introduced instruction into the state table.  In either case, we are
1113   // assured to be able to determine an instruction which produces it's base
1114   // pointer.
1115   auto getBaseForInput = [&](Value *Input, Instruction *InsertPt) {
1116     Value *BDV = findBaseOrBDV(Input, Cache, KnownBases);
1117     Value *Base = nullptr;
1118     if (!States.count(BDV)) {
1119       assert(areBothVectorOrScalar(BDV, Input));
1120       Base = BDV;
1121     } else {
1122       // Either conflict or base.
1123       assert(States.count(BDV));
1124       Base = States[BDV].getBaseValue();
1125     }
1126     assert(Base && "Can't be null");
1127     // The cast is needed since base traversal may strip away bitcasts
1128     if (Base->getType() != Input->getType() && InsertPt)
1129       Base = new BitCastInst(Base, Input->getType(), "cast", InsertPt);
1130     return Base;
1131   };
1132 
1133   // Fixup all the inputs of the new PHIs.  Visit order needs to be
1134   // deterministic and predictable because we're naming newly created
1135   // instructions.
1136   for (auto Pair : States) {
1137     Instruction *BDV = cast<Instruction>(Pair.first);
1138     BDVState State = Pair.second;
1139 
1140     // Only values that do not have known bases or those that have differing
1141     // type (scalar versus vector) from a possible known base should be in the
1142     // lattice.
1143     assert((!isKnownBase(BDV, KnownBases) ||
1144             !areBothVectorOrScalar(BDV, State.getBaseValue())) &&
1145            "why did it get added?");
1146     assert(!State.isUnknown() && "Optimistic algorithm didn't complete!");
1147     if (!State.isConflict())
1148       continue;
1149 
1150     if (PHINode *BasePHI = dyn_cast<PHINode>(State.getBaseValue())) {
1151       PHINode *PN = cast<PHINode>(BDV);
1152       const unsigned NumPHIValues = PN->getNumIncomingValues();
1153 
1154       // The IR verifier requires phi nodes with multiple entries from the
1155       // same basic block to have the same incoming value for each of those
1156       // entries.  Since we're inserting bitcasts in the loop, make sure we
1157       // do so at least once per incoming block.
1158       DenseMap<BasicBlock *, Value*> BlockToValue;
1159       for (unsigned i = 0; i < NumPHIValues; i++) {
1160         Value *InVal = PN->getIncomingValue(i);
1161         BasicBlock *InBB = PN->getIncomingBlock(i);
1162         if (!BlockToValue.count(InBB))
1163           BlockToValue[InBB] = getBaseForInput(InVal, InBB->getTerminator());
1164         else {
1165 #ifndef NDEBUG
1166           Value *OldBase = BlockToValue[InBB];
1167           Value *Base = getBaseForInput(InVal, nullptr);
1168 
1169           // We can't use `stripPointerCasts` instead of this function because
1170           // `stripPointerCasts` doesn't handle vectors of pointers.
1171           auto StripBitCasts = [](Value *V) -> Value * {
1172             while (auto *BC = dyn_cast<BitCastInst>(V))
1173               V = BC->getOperand(0);
1174             return V;
1175           };
1176           // In essence this assert states: the only way two values
1177           // incoming from the same basic block may be different is by
1178           // being different bitcasts of the same value.  A cleanup
1179           // that remains TODO is changing findBaseOrBDV to return an
1180           // llvm::Value of the correct type (and still remain pure).
1181           // This will remove the need to add bitcasts.
1182           assert(StripBitCasts(Base) == StripBitCasts(OldBase) &&
1183                  "findBaseOrBDV should be pure!");
1184 #endif
1185         }
1186         Value *Base = BlockToValue[InBB];
1187         BasePHI->setIncomingValue(i, Base);
1188       }
1189     } else if (SelectInst *BaseSI =
1190                    dyn_cast<SelectInst>(State.getBaseValue())) {
1191       SelectInst *SI = cast<SelectInst>(BDV);
1192 
1193       // Find the instruction which produces the base for each input.
1194       // We may need to insert a bitcast.
1195       BaseSI->setTrueValue(getBaseForInput(SI->getTrueValue(), BaseSI));
1196       BaseSI->setFalseValue(getBaseForInput(SI->getFalseValue(), BaseSI));
1197     } else if (auto *BaseEE =
1198                    dyn_cast<ExtractElementInst>(State.getBaseValue())) {
1199       Value *InVal = cast<ExtractElementInst>(BDV)->getVectorOperand();
1200       // Find the instruction which produces the base for each input.  We may
1201       // need to insert a bitcast.
1202       BaseEE->setOperand(0, getBaseForInput(InVal, BaseEE));
1203     } else if (auto *BaseIE = dyn_cast<InsertElementInst>(State.getBaseValue())){
1204       auto *BdvIE = cast<InsertElementInst>(BDV);
1205       auto UpdateOperand = [&](int OperandIdx) {
1206         Value *InVal = BdvIE->getOperand(OperandIdx);
1207         Value *Base = getBaseForInput(InVal, BaseIE);
1208         BaseIE->setOperand(OperandIdx, Base);
1209       };
1210       UpdateOperand(0); // vector operand
1211       UpdateOperand(1); // scalar operand
1212     } else {
1213       auto *BaseSV = cast<ShuffleVectorInst>(State.getBaseValue());
1214       auto *BdvSV = cast<ShuffleVectorInst>(BDV);
1215       auto UpdateOperand = [&](int OperandIdx) {
1216         Value *InVal = BdvSV->getOperand(OperandIdx);
1217         Value *Base = getBaseForInput(InVal, BaseSV);
1218         BaseSV->setOperand(OperandIdx, Base);
1219       };
1220       UpdateOperand(0); // vector operand
1221       if (!BdvSV->isZeroEltSplat())
1222         UpdateOperand(1); // vector operand
1223       else {
1224         // Never read, so just use poison
1225         Value *InVal = BdvSV->getOperand(1);
1226         BaseSV->setOperand(1, PoisonValue::get(InVal->getType()));
1227       }
1228     }
1229   }
1230 
1231 #ifndef NDEBUG
1232   VerifyStates();
1233 #endif
1234 
1235   // Cache all of our results so we can cheaply reuse them
1236   // NOTE: This is actually two caches: one of the base defining value
1237   // relation and one of the base pointer relation!  FIXME
1238   for (auto Pair : States) {
1239     auto *BDV = Pair.first;
1240     Value *Base = Pair.second.getBaseValue();
1241     assert(BDV && Base);
1242     // Only values that do not have known bases or those that have differing
1243     // type (scalar versus vector) from a possible known base should be in the
1244     // lattice.
1245     assert(
1246         (!isKnownBase(BDV, KnownBases) || !areBothVectorOrScalar(BDV, Base)) &&
1247         "why did it get added?");
1248 
1249     LLVM_DEBUG(
1250         dbgs() << "Updating base value cache"
1251                << " for: " << BDV->getName() << " from: "
1252                << (Cache.count(BDV) ? Cache[BDV]->getName().str() : "none")
1253                << " to: " << Base->getName() << "\n");
1254 
1255     Cache[BDV] = Base;
1256   }
1257   assert(Cache.count(Def));
1258   return Cache[Def];
1259 }
1260 
1261 // For a set of live pointers (base and/or derived), identify the base
1262 // pointer of the object which they are derived from.  This routine will
1263 // mutate the IR graph as needed to make the 'base' pointer live at the
1264 // definition site of 'derived'.  This ensures that any use of 'derived' can
1265 // also use 'base'.  This may involve the insertion of a number of
1266 // additional PHI nodes.
1267 //
1268 // preconditions: live is a set of pointer type Values
1269 //
1270 // side effects: may insert PHI nodes into the existing CFG, will preserve
1271 // CFG, will not remove or mutate any existing nodes
1272 //
1273 // post condition: PointerToBase contains one (derived, base) pair for every
1274 // pointer in live.  Note that derived can be equal to base if the original
1275 // pointer was a base pointer.
1276 static void findBasePointers(const StatepointLiveSetTy &live,
1277                              PointerToBaseTy &PointerToBase, DominatorTree *DT,
1278                              DefiningValueMapTy &DVCache,
1279                              IsKnownBaseMapTy &KnownBases) {
1280   for (Value *ptr : live) {
1281     Value *base = findBasePointer(ptr, DVCache, KnownBases);
1282     assert(base && "failed to find base pointer");
1283     PointerToBase[ptr] = base;
1284     assert((!isa<Instruction>(base) || !isa<Instruction>(ptr) ||
1285             DT->dominates(cast<Instruction>(base)->getParent(),
1286                           cast<Instruction>(ptr)->getParent())) &&
1287            "The base we found better dominate the derived pointer");
1288   }
1289 }
1290 
1291 /// Find the required based pointers (and adjust the live set) for the given
1292 /// parse point.
1293 static void findBasePointers(DominatorTree &DT, DefiningValueMapTy &DVCache,
1294                              CallBase *Call,
1295                              PartiallyConstructedSafepointRecord &result,
1296                              PointerToBaseTy &PointerToBase,
1297                              IsKnownBaseMapTy &KnownBases) {
1298   StatepointLiveSetTy PotentiallyDerivedPointers = result.LiveSet;
1299   // We assume that all pointers passed to deopt are base pointers; as an
1300   // optimization, we can use this to avoid seperately materializing the base
1301   // pointer graph.  This is only relevant since we're very conservative about
1302   // generating new conflict nodes during base pointer insertion.  If we were
1303   // smarter there, this would be irrelevant.
1304   if (auto Opt = Call->getOperandBundle(LLVMContext::OB_deopt))
1305     for (Value *V : Opt->Inputs) {
1306       if (!PotentiallyDerivedPointers.count(V))
1307         continue;
1308       PotentiallyDerivedPointers.remove(V);
1309       PointerToBase[V] = V;
1310     }
1311   findBasePointers(PotentiallyDerivedPointers, PointerToBase, &DT, DVCache,
1312                    KnownBases);
1313 }
1314 
1315 /// Given an updated version of the dataflow liveness results, update the
1316 /// liveset and base pointer maps for the call site CS.
1317 static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData,
1318                                   CallBase *Call,
1319                                   PartiallyConstructedSafepointRecord &result,
1320                                   PointerToBaseTy &PointerToBase,
1321                                   GCStrategy *GC);
1322 
1323 static void recomputeLiveInValues(
1324     Function &F, DominatorTree &DT, ArrayRef<CallBase *> toUpdate,
1325     MutableArrayRef<struct PartiallyConstructedSafepointRecord> records,
1326     PointerToBaseTy &PointerToBase, GCStrategy *GC) {
1327   // TODO-PERF: reuse the original liveness, then simply run the dataflow
1328   // again.  The old values are still live and will help it stabilize quickly.
1329   GCPtrLivenessData RevisedLivenessData;
1330   computeLiveInValues(DT, F, RevisedLivenessData, GC);
1331   for (size_t i = 0; i < records.size(); i++) {
1332     struct PartiallyConstructedSafepointRecord &info = records[i];
1333     recomputeLiveInValues(RevisedLivenessData, toUpdate[i], info, PointerToBase,
1334                           GC);
1335   }
1336 }
1337 
1338 // Utility function which clones all instructions from "ChainToBase"
1339 // and inserts them before "InsertBefore". Returns rematerialized value
1340 // which should be used after statepoint.
1341 static Instruction *rematerializeChain(ArrayRef<Instruction *> ChainToBase,
1342                                        Instruction *InsertBefore,
1343                                        Value *RootOfChain,
1344                                        Value *AlternateLiveBase) {
1345   Instruction *LastClonedValue = nullptr;
1346   Instruction *LastValue = nullptr;
1347   // Walk backwards to visit top-most instructions first.
1348   for (Instruction *Instr :
1349        make_range(ChainToBase.rbegin(), ChainToBase.rend())) {
1350     // Only GEP's and casts are supported as we need to be careful to not
1351     // introduce any new uses of pointers not in the liveset.
1352     // Note that it's fine to introduce new uses of pointers which were
1353     // otherwise not used after this statepoint.
1354     assert(isa<GetElementPtrInst>(Instr) || isa<CastInst>(Instr));
1355 
1356     Instruction *ClonedValue = Instr->clone();
1357     ClonedValue->insertBefore(InsertBefore);
1358     ClonedValue->setName(Instr->getName() + ".remat");
1359 
1360     // If it is not first instruction in the chain then it uses previously
1361     // cloned value. We should update it to use cloned value.
1362     if (LastClonedValue) {
1363       assert(LastValue);
1364       ClonedValue->replaceUsesOfWith(LastValue, LastClonedValue);
1365 #ifndef NDEBUG
1366       for (auto *OpValue : ClonedValue->operand_values()) {
1367         // Assert that cloned instruction does not use any instructions from
1368         // this chain other than LastClonedValue
1369         assert(!is_contained(ChainToBase, OpValue) &&
1370                "incorrect use in rematerialization chain");
1371         // Assert that the cloned instruction does not use the RootOfChain
1372         // or the AlternateLiveBase.
1373         assert(OpValue != RootOfChain && OpValue != AlternateLiveBase);
1374       }
1375 #endif
1376     } else {
1377       // For the first instruction, replace the use of unrelocated base i.e.
1378       // RootOfChain/OrigRootPhi, with the corresponding PHI present in the
1379       // live set. They have been proved to be the same PHI nodes.  Note
1380       // that the *only* use of the RootOfChain in the ChainToBase list is
1381       // the first Value in the list.
1382       if (RootOfChain != AlternateLiveBase)
1383         ClonedValue->replaceUsesOfWith(RootOfChain, AlternateLiveBase);
1384     }
1385 
1386     LastClonedValue = ClonedValue;
1387     LastValue = Instr;
1388   }
1389   assert(LastClonedValue);
1390   return LastClonedValue;
1391 }
1392 
1393 // When inserting gc.relocate and gc.result calls, we need to ensure there are
1394 // no uses of the original value / return value between the gc.statepoint and
1395 // the gc.relocate / gc.result call.  One case which can arise is a phi node
1396 // starting one of the successor blocks.  We also need to be able to insert the
1397 // gc.relocates only on the path which goes through the statepoint.  We might
1398 // need to split an edge to make this possible.
1399 static BasicBlock *
1400 normalizeForInvokeSafepoint(BasicBlock *BB, BasicBlock *InvokeParent,
1401                             DominatorTree &DT) {
1402   BasicBlock *Ret = BB;
1403   if (!BB->getUniquePredecessor())
1404     Ret = SplitBlockPredecessors(BB, InvokeParent, "", &DT);
1405 
1406   // Now that 'Ret' has unique predecessor we can safely remove all phi nodes
1407   // from it
1408   FoldSingleEntryPHINodes(Ret);
1409   assert(!isa<PHINode>(Ret->begin()) &&
1410          "All PHI nodes should have been removed!");
1411 
1412   // At this point, we can safely insert a gc.relocate or gc.result as the first
1413   // instruction in Ret if needed.
1414   return Ret;
1415 }
1416 
1417 // List of all function attributes which must be stripped when lowering from
1418 // abstract machine model to physical machine model.  Essentially, these are
1419 // all the effects a safepoint might have which we ignored in the abstract
1420 // machine model for purposes of optimization.  We have to strip these on
1421 // both function declarations and call sites.
1422 static constexpr Attribute::AttrKind FnAttrsToStrip[] =
1423   {Attribute::Memory, Attribute::NoSync, Attribute::NoFree};
1424 
1425 // Create new attribute set containing only attributes which can be transferred
1426 // from the original call to the safepoint.
1427 static AttributeList legalizeCallAttributes(CallBase *Call, bool IsMemIntrinsic,
1428                                             AttributeList StatepointAL) {
1429   AttributeList OrigAL = Call->getAttributes();
1430   if (OrigAL.isEmpty())
1431     return StatepointAL;
1432 
1433   // Remove the readonly, readnone, and statepoint function attributes.
1434   LLVMContext &Ctx = Call->getContext();
1435   AttrBuilder FnAttrs(Ctx, OrigAL.getFnAttrs());
1436   for (auto Attr : FnAttrsToStrip)
1437     FnAttrs.removeAttribute(Attr);
1438 
1439   for (Attribute A : OrigAL.getFnAttrs()) {
1440     if (isStatepointDirectiveAttr(A))
1441       FnAttrs.removeAttribute(A);
1442   }
1443 
1444   StatepointAL = StatepointAL.addFnAttributes(Ctx, FnAttrs);
1445 
1446   // The memory intrinsics do not have a 1:1 correspondence of the original
1447   // call arguments to the produced statepoint. Do not transfer the argument
1448   // attributes to avoid putting them on incorrect arguments.
1449   if (IsMemIntrinsic)
1450     return StatepointAL;
1451 
1452   // Attach the argument attributes from the original call at the corresponding
1453   // arguments in the statepoint. Note that any argument attributes that are
1454   // invalid after lowering are stripped in stripNonValidDataFromBody.
1455   for (unsigned I : llvm::seq(Call->arg_size()))
1456     StatepointAL = StatepointAL.addParamAttributes(
1457         Ctx, GCStatepointInst::CallArgsBeginPos + I,
1458         AttrBuilder(Ctx, OrigAL.getParamAttrs(I)));
1459 
1460   // Return attributes are later attached to the gc.result intrinsic.
1461   return StatepointAL;
1462 }
1463 
1464 /// Helper function to place all gc relocates necessary for the given
1465 /// statepoint.
1466 /// Inputs:
1467 ///   liveVariables - list of variables to be relocated.
1468 ///   basePtrs - base pointers.
1469 ///   statepointToken - statepoint instruction to which relocates should be
1470 ///   bound.
1471 ///   Builder - Llvm IR builder to be used to construct new calls.
1472 static void CreateGCRelocates(ArrayRef<Value *> LiveVariables,
1473                               ArrayRef<Value *> BasePtrs,
1474                               Instruction *StatepointToken,
1475                               IRBuilder<> &Builder, GCStrategy *GC) {
1476   if (LiveVariables.empty())
1477     return;
1478 
1479   auto FindIndex = [](ArrayRef<Value *> LiveVec, Value *Val) {
1480     auto ValIt = llvm::find(LiveVec, Val);
1481     assert(ValIt != LiveVec.end() && "Val not found in LiveVec!");
1482     size_t Index = std::distance(LiveVec.begin(), ValIt);
1483     assert(Index < LiveVec.size() && "Bug in std::find?");
1484     return Index;
1485   };
1486   Module *M = StatepointToken->getModule();
1487 
1488   // All gc_relocate are generated as i8 addrspace(1)* (or a vector type whose
1489   // element type is i8 addrspace(1)*). We originally generated unique
1490   // declarations for each pointer type, but this proved problematic because
1491   // the intrinsic mangling code is incomplete and fragile.  Since we're moving
1492   // towards a single unified pointer type anyways, we can just cast everything
1493   // to an i8* of the right address space.  A bitcast is added later to convert
1494   // gc_relocate to the actual value's type.
1495   auto getGCRelocateDecl = [&](Type *Ty) {
1496     assert(isHandledGCPointerType(Ty, GC));
1497     auto AS = Ty->getScalarType()->getPointerAddressSpace();
1498     Type *NewTy = Type::getInt8PtrTy(M->getContext(), AS);
1499     if (auto *VT = dyn_cast<VectorType>(Ty))
1500       NewTy = FixedVectorType::get(NewTy,
1501                                    cast<FixedVectorType>(VT)->getNumElements());
1502     return Intrinsic::getDeclaration(M, Intrinsic::experimental_gc_relocate,
1503                                      {NewTy});
1504   };
1505 
1506   // Lazily populated map from input types to the canonicalized form mentioned
1507   // in the comment above.  This should probably be cached somewhere more
1508   // broadly.
1509   DenseMap<Type *, Function *> TypeToDeclMap;
1510 
1511   for (unsigned i = 0; i < LiveVariables.size(); i++) {
1512     // Generate the gc.relocate call and save the result
1513     Value *BaseIdx = Builder.getInt32(FindIndex(LiveVariables, BasePtrs[i]));
1514     Value *LiveIdx = Builder.getInt32(i);
1515 
1516     Type *Ty = LiveVariables[i]->getType();
1517     if (!TypeToDeclMap.count(Ty))
1518       TypeToDeclMap[Ty] = getGCRelocateDecl(Ty);
1519     Function *GCRelocateDecl = TypeToDeclMap[Ty];
1520 
1521     // only specify a debug name if we can give a useful one
1522     CallInst *Reloc = Builder.CreateCall(
1523         GCRelocateDecl, {StatepointToken, BaseIdx, LiveIdx},
1524         suffixed_name_or(LiveVariables[i], ".relocated", ""));
1525     // Trick CodeGen into thinking there are lots of free registers at this
1526     // fake call.
1527     Reloc->setCallingConv(CallingConv::Cold);
1528   }
1529 }
1530 
1531 namespace {
1532 
1533 /// This struct is used to defer RAUWs and `eraseFromParent` s.  Using this
1534 /// avoids having to worry about keeping around dangling pointers to Values.
1535 class DeferredReplacement {
1536   AssertingVH<Instruction> Old;
1537   AssertingVH<Instruction> New;
1538   bool IsDeoptimize = false;
1539 
1540   DeferredReplacement() = default;
1541 
1542 public:
1543   static DeferredReplacement createRAUW(Instruction *Old, Instruction *New) {
1544     assert(Old != New && Old && New &&
1545            "Cannot RAUW equal values or to / from null!");
1546 
1547     DeferredReplacement D;
1548     D.Old = Old;
1549     D.New = New;
1550     return D;
1551   }
1552 
1553   static DeferredReplacement createDelete(Instruction *ToErase) {
1554     DeferredReplacement D;
1555     D.Old = ToErase;
1556     return D;
1557   }
1558 
1559   static DeferredReplacement createDeoptimizeReplacement(Instruction *Old) {
1560 #ifndef NDEBUG
1561     auto *F = cast<CallInst>(Old)->getCalledFunction();
1562     assert(F && F->getIntrinsicID() == Intrinsic::experimental_deoptimize &&
1563            "Only way to construct a deoptimize deferred replacement");
1564 #endif
1565     DeferredReplacement D;
1566     D.Old = Old;
1567     D.IsDeoptimize = true;
1568     return D;
1569   }
1570 
1571   /// Does the task represented by this instance.
1572   void doReplacement() {
1573     Instruction *OldI = Old;
1574     Instruction *NewI = New;
1575 
1576     assert(OldI != NewI && "Disallowed at construction?!");
1577     assert((!IsDeoptimize || !New) &&
1578            "Deoptimize intrinsics are not replaced!");
1579 
1580     Old = nullptr;
1581     New = nullptr;
1582 
1583     if (NewI)
1584       OldI->replaceAllUsesWith(NewI);
1585 
1586     if (IsDeoptimize) {
1587       // Note: we've inserted instructions, so the call to llvm.deoptimize may
1588       // not necessarily be followed by the matching return.
1589       auto *RI = cast<ReturnInst>(OldI->getParent()->getTerminator());
1590       new UnreachableInst(RI->getContext(), RI);
1591       RI->eraseFromParent();
1592     }
1593 
1594     OldI->eraseFromParent();
1595   }
1596 };
1597 
1598 } // end anonymous namespace
1599 
1600 static StringRef getDeoptLowering(CallBase *Call) {
1601   const char *DeoptLowering = "deopt-lowering";
1602   if (Call->hasFnAttr(DeoptLowering)) {
1603     // FIXME: Calls have a *really* confusing interface around attributes
1604     // with values.
1605     const AttributeList &CSAS = Call->getAttributes();
1606     if (CSAS.hasFnAttr(DeoptLowering))
1607       return CSAS.getFnAttr(DeoptLowering).getValueAsString();
1608     Function *F = Call->getCalledFunction();
1609     assert(F && F->hasFnAttribute(DeoptLowering));
1610     return F->getFnAttribute(DeoptLowering).getValueAsString();
1611   }
1612   return "live-through";
1613 }
1614 
1615 static void
1616 makeStatepointExplicitImpl(CallBase *Call, /* to replace */
1617                            const SmallVectorImpl<Value *> &BasePtrs,
1618                            const SmallVectorImpl<Value *> &LiveVariables,
1619                            PartiallyConstructedSafepointRecord &Result,
1620                            std::vector<DeferredReplacement> &Replacements,
1621                            const PointerToBaseTy &PointerToBase,
1622                            GCStrategy *GC) {
1623   assert(BasePtrs.size() == LiveVariables.size());
1624 
1625   // Then go ahead and use the builder do actually do the inserts.  We insert
1626   // immediately before the previous instruction under the assumption that all
1627   // arguments will be available here.  We can't insert afterwards since we may
1628   // be replacing a terminator.
1629   IRBuilder<> Builder(Call);
1630 
1631   ArrayRef<Value *> GCArgs(LiveVariables);
1632   uint64_t StatepointID = StatepointDirectives::DefaultStatepointID;
1633   uint32_t NumPatchBytes = 0;
1634   uint32_t Flags = uint32_t(StatepointFlags::None);
1635 
1636   SmallVector<Value *, 8> CallArgs(Call->args());
1637   std::optional<ArrayRef<Use>> DeoptArgs;
1638   if (auto Bundle = Call->getOperandBundle(LLVMContext::OB_deopt))
1639     DeoptArgs = Bundle->Inputs;
1640   std::optional<ArrayRef<Use>> TransitionArgs;
1641   if (auto Bundle = Call->getOperandBundle(LLVMContext::OB_gc_transition)) {
1642     TransitionArgs = Bundle->Inputs;
1643     // TODO: This flag no longer serves a purpose and can be removed later
1644     Flags |= uint32_t(StatepointFlags::GCTransition);
1645   }
1646 
1647   // Instead of lowering calls to @llvm.experimental.deoptimize as normal calls
1648   // with a return value, we lower then as never returning calls to
1649   // __llvm_deoptimize that are followed by unreachable to get better codegen.
1650   bool IsDeoptimize = false;
1651   bool IsMemIntrinsic = false;
1652 
1653   StatepointDirectives SD =
1654       parseStatepointDirectivesFromAttrs(Call->getAttributes());
1655   if (SD.NumPatchBytes)
1656     NumPatchBytes = *SD.NumPatchBytes;
1657   if (SD.StatepointID)
1658     StatepointID = *SD.StatepointID;
1659 
1660   // Pass through the requested lowering if any.  The default is live-through.
1661   StringRef DeoptLowering = getDeoptLowering(Call);
1662   if (DeoptLowering.equals("live-in"))
1663     Flags |= uint32_t(StatepointFlags::DeoptLiveIn);
1664   else {
1665     assert(DeoptLowering.equals("live-through") && "Unsupported value!");
1666   }
1667 
1668   FunctionCallee CallTarget(Call->getFunctionType(), Call->getCalledOperand());
1669   if (Function *F = dyn_cast<Function>(CallTarget.getCallee())) {
1670     auto IID = F->getIntrinsicID();
1671     if (IID == Intrinsic::experimental_deoptimize) {
1672       // Calls to llvm.experimental.deoptimize are lowered to calls to the
1673       // __llvm_deoptimize symbol.  We want to resolve this now, since the
1674       // verifier does not allow taking the address of an intrinsic function.
1675 
1676       SmallVector<Type *, 8> DomainTy;
1677       for (Value *Arg : CallArgs)
1678         DomainTy.push_back(Arg->getType());
1679       auto *FTy = FunctionType::get(Type::getVoidTy(F->getContext()), DomainTy,
1680                                     /* isVarArg = */ false);
1681 
1682       // Note: CallTarget can be a bitcast instruction of a symbol if there are
1683       // calls to @llvm.experimental.deoptimize with different argument types in
1684       // the same module.  This is fine -- we assume the frontend knew what it
1685       // was doing when generating this kind of IR.
1686       CallTarget = F->getParent()
1687                        ->getOrInsertFunction("__llvm_deoptimize", FTy);
1688 
1689       IsDeoptimize = true;
1690     } else if (IID == Intrinsic::memcpy_element_unordered_atomic ||
1691                IID == Intrinsic::memmove_element_unordered_atomic) {
1692       IsMemIntrinsic = true;
1693 
1694       // Unordered atomic memcpy and memmove intrinsics which are not explicitly
1695       // marked as "gc-leaf-function" should be lowered in a GC parseable way.
1696       // Specifically, these calls should be lowered to the
1697       // __llvm_{memcpy|memmove}_element_unordered_atomic_safepoint symbols.
1698       // Similarly to __llvm_deoptimize we want to resolve this now, since the
1699       // verifier does not allow taking the address of an intrinsic function.
1700       //
1701       // Moreover we need to shuffle the arguments for the call in order to
1702       // accommodate GC. The underlying source and destination objects might be
1703       // relocated during copy operation should the GC occur. To relocate the
1704       // derived source and destination pointers the implementation of the
1705       // intrinsic should know the corresponding base pointers.
1706       //
1707       // To make the base pointers available pass them explicitly as arguments:
1708       //   memcpy(dest_derived, source_derived, ...) =>
1709       //   memcpy(dest_base, dest_offset, source_base, source_offset, ...)
1710       auto &Context = Call->getContext();
1711       auto &DL = Call->getModule()->getDataLayout();
1712       auto GetBaseAndOffset = [&](Value *Derived) {
1713         Value *Base = nullptr;
1714         // Optimizations in unreachable code might substitute the real pointer
1715         // with undef, poison or null-derived constant. Return null base for
1716         // them to be consistent with the handling in the main algorithm in
1717         // findBaseDefiningValue.
1718         if (isa<Constant>(Derived))
1719           Base =
1720               ConstantPointerNull::get(cast<PointerType>(Derived->getType()));
1721         else {
1722           assert(PointerToBase.count(Derived));
1723           Base = PointerToBase.find(Derived)->second;
1724         }
1725         unsigned AddressSpace = Derived->getType()->getPointerAddressSpace();
1726         unsigned IntPtrSize = DL.getPointerSizeInBits(AddressSpace);
1727         Value *Base_int = Builder.CreatePtrToInt(
1728             Base, Type::getIntNTy(Context, IntPtrSize));
1729         Value *Derived_int = Builder.CreatePtrToInt(
1730             Derived, Type::getIntNTy(Context, IntPtrSize));
1731         return std::make_pair(Base, Builder.CreateSub(Derived_int, Base_int));
1732       };
1733 
1734       auto *Dest = CallArgs[0];
1735       Value *DestBase, *DestOffset;
1736       std::tie(DestBase, DestOffset) = GetBaseAndOffset(Dest);
1737 
1738       auto *Source = CallArgs[1];
1739       Value *SourceBase, *SourceOffset;
1740       std::tie(SourceBase, SourceOffset) = GetBaseAndOffset(Source);
1741 
1742       auto *LengthInBytes = CallArgs[2];
1743       auto *ElementSizeCI = cast<ConstantInt>(CallArgs[3]);
1744 
1745       CallArgs.clear();
1746       CallArgs.push_back(DestBase);
1747       CallArgs.push_back(DestOffset);
1748       CallArgs.push_back(SourceBase);
1749       CallArgs.push_back(SourceOffset);
1750       CallArgs.push_back(LengthInBytes);
1751 
1752       SmallVector<Type *, 8> DomainTy;
1753       for (Value *Arg : CallArgs)
1754         DomainTy.push_back(Arg->getType());
1755       auto *FTy = FunctionType::get(Type::getVoidTy(F->getContext()), DomainTy,
1756                                     /* isVarArg = */ false);
1757 
1758       auto GetFunctionName = [](Intrinsic::ID IID, ConstantInt *ElementSizeCI) {
1759         uint64_t ElementSize = ElementSizeCI->getZExtValue();
1760         if (IID == Intrinsic::memcpy_element_unordered_atomic) {
1761           switch (ElementSize) {
1762           case 1:
1763             return "__llvm_memcpy_element_unordered_atomic_safepoint_1";
1764           case 2:
1765             return "__llvm_memcpy_element_unordered_atomic_safepoint_2";
1766           case 4:
1767             return "__llvm_memcpy_element_unordered_atomic_safepoint_4";
1768           case 8:
1769             return "__llvm_memcpy_element_unordered_atomic_safepoint_8";
1770           case 16:
1771             return "__llvm_memcpy_element_unordered_atomic_safepoint_16";
1772           default:
1773             llvm_unreachable("unexpected element size!");
1774           }
1775         }
1776         assert(IID == Intrinsic::memmove_element_unordered_atomic);
1777         switch (ElementSize) {
1778         case 1:
1779           return "__llvm_memmove_element_unordered_atomic_safepoint_1";
1780         case 2:
1781           return "__llvm_memmove_element_unordered_atomic_safepoint_2";
1782         case 4:
1783           return "__llvm_memmove_element_unordered_atomic_safepoint_4";
1784         case 8:
1785           return "__llvm_memmove_element_unordered_atomic_safepoint_8";
1786         case 16:
1787           return "__llvm_memmove_element_unordered_atomic_safepoint_16";
1788         default:
1789           llvm_unreachable("unexpected element size!");
1790         }
1791       };
1792 
1793       CallTarget =
1794           F->getParent()
1795               ->getOrInsertFunction(GetFunctionName(IID, ElementSizeCI), FTy);
1796     }
1797   }
1798 
1799   // Create the statepoint given all the arguments
1800   GCStatepointInst *Token = nullptr;
1801   if (auto *CI = dyn_cast<CallInst>(Call)) {
1802     CallInst *SPCall = Builder.CreateGCStatepointCall(
1803         StatepointID, NumPatchBytes, CallTarget, Flags, CallArgs,
1804         TransitionArgs, DeoptArgs, GCArgs, "safepoint_token");
1805 
1806     SPCall->setTailCallKind(CI->getTailCallKind());
1807     SPCall->setCallingConv(CI->getCallingConv());
1808 
1809     // Set up function attrs directly on statepoint and return attrs later for
1810     // gc_result intrinsic.
1811     SPCall->setAttributes(
1812         legalizeCallAttributes(CI, IsMemIntrinsic, SPCall->getAttributes()));
1813 
1814     Token = cast<GCStatepointInst>(SPCall);
1815 
1816     // Put the following gc_result and gc_relocate calls immediately after the
1817     // the old call (which we're about to delete)
1818     assert(CI->getNextNode() && "Not a terminator, must have next!");
1819     Builder.SetInsertPoint(CI->getNextNode());
1820     Builder.SetCurrentDebugLocation(CI->getNextNode()->getDebugLoc());
1821   } else {
1822     auto *II = cast<InvokeInst>(Call);
1823 
1824     // Insert the new invoke into the old block.  We'll remove the old one in a
1825     // moment at which point this will become the new terminator for the
1826     // original block.
1827     InvokeInst *SPInvoke = Builder.CreateGCStatepointInvoke(
1828         StatepointID, NumPatchBytes, CallTarget, II->getNormalDest(),
1829         II->getUnwindDest(), Flags, CallArgs, TransitionArgs, DeoptArgs, GCArgs,
1830         "statepoint_token");
1831 
1832     SPInvoke->setCallingConv(II->getCallingConv());
1833 
1834     // Set up function attrs directly on statepoint and return attrs later for
1835     // gc_result intrinsic.
1836     SPInvoke->setAttributes(
1837         legalizeCallAttributes(II, IsMemIntrinsic, SPInvoke->getAttributes()));
1838 
1839     Token = cast<GCStatepointInst>(SPInvoke);
1840 
1841     // Generate gc relocates in exceptional path
1842     BasicBlock *UnwindBlock = II->getUnwindDest();
1843     assert(!isa<PHINode>(UnwindBlock->begin()) &&
1844            UnwindBlock->getUniquePredecessor() &&
1845            "can't safely insert in this block!");
1846 
1847     Builder.SetInsertPoint(UnwindBlock, UnwindBlock->getFirstInsertionPt());
1848     Builder.SetCurrentDebugLocation(II->getDebugLoc());
1849 
1850     // Attach exceptional gc relocates to the landingpad.
1851     Instruction *ExceptionalToken = UnwindBlock->getLandingPadInst();
1852     Result.UnwindToken = ExceptionalToken;
1853 
1854     CreateGCRelocates(LiveVariables, BasePtrs, ExceptionalToken, Builder, GC);
1855 
1856     // Generate gc relocates and returns for normal block
1857     BasicBlock *NormalDest = II->getNormalDest();
1858     assert(!isa<PHINode>(NormalDest->begin()) &&
1859            NormalDest->getUniquePredecessor() &&
1860            "can't safely insert in this block!");
1861 
1862     Builder.SetInsertPoint(NormalDest, NormalDest->getFirstInsertionPt());
1863 
1864     // gc relocates will be generated later as if it were regular call
1865     // statepoint
1866   }
1867   assert(Token && "Should be set in one of the above branches!");
1868 
1869   if (IsDeoptimize) {
1870     // If we're wrapping an @llvm.experimental.deoptimize in a statepoint, we
1871     // transform the tail-call like structure to a call to a void function
1872     // followed by unreachable to get better codegen.
1873     Replacements.push_back(
1874         DeferredReplacement::createDeoptimizeReplacement(Call));
1875   } else {
1876     Token->setName("statepoint_token");
1877     if (!Call->getType()->isVoidTy() && !Call->use_empty()) {
1878       StringRef Name = Call->hasName() ? Call->getName() : "";
1879       CallInst *GCResult = Builder.CreateGCResult(Token, Call->getType(), Name);
1880       GCResult->setAttributes(
1881           AttributeList::get(GCResult->getContext(), AttributeList::ReturnIndex,
1882                              Call->getAttributes().getRetAttrs()));
1883 
1884       // We cannot RAUW or delete CS.getInstruction() because it could be in the
1885       // live set of some other safepoint, in which case that safepoint's
1886       // PartiallyConstructedSafepointRecord will hold a raw pointer to this
1887       // llvm::Instruction.  Instead, we defer the replacement and deletion to
1888       // after the live sets have been made explicit in the IR, and we no longer
1889       // have raw pointers to worry about.
1890       Replacements.emplace_back(
1891           DeferredReplacement::createRAUW(Call, GCResult));
1892     } else {
1893       Replacements.emplace_back(DeferredReplacement::createDelete(Call));
1894     }
1895   }
1896 
1897   Result.StatepointToken = Token;
1898 
1899   // Second, create a gc.relocate for every live variable
1900   CreateGCRelocates(LiveVariables, BasePtrs, Token, Builder, GC);
1901 }
1902 
1903 // Replace an existing gc.statepoint with a new one and a set of gc.relocates
1904 // which make the relocations happening at this safepoint explicit.
1905 //
1906 // WARNING: Does not do any fixup to adjust users of the original live
1907 // values.  That's the callers responsibility.
1908 static void
1909 makeStatepointExplicit(DominatorTree &DT, CallBase *Call,
1910                        PartiallyConstructedSafepointRecord &Result,
1911                        std::vector<DeferredReplacement> &Replacements,
1912                        const PointerToBaseTy &PointerToBase, GCStrategy *GC) {
1913   const auto &LiveSet = Result.LiveSet;
1914 
1915   // Convert to vector for efficient cross referencing.
1916   SmallVector<Value *, 64> BaseVec, LiveVec;
1917   LiveVec.reserve(LiveSet.size());
1918   BaseVec.reserve(LiveSet.size());
1919   for (Value *L : LiveSet) {
1920     LiveVec.push_back(L);
1921     assert(PointerToBase.count(L));
1922     Value *Base = PointerToBase.find(L)->second;
1923     BaseVec.push_back(Base);
1924   }
1925   assert(LiveVec.size() == BaseVec.size());
1926 
1927   // Do the actual rewriting and delete the old statepoint
1928   makeStatepointExplicitImpl(Call, BaseVec, LiveVec, Result, Replacements,
1929                              PointerToBase, GC);
1930 }
1931 
1932 // Helper function for the relocationViaAlloca.
1933 //
1934 // It receives iterator to the statepoint gc relocates and emits a store to the
1935 // assigned location (via allocaMap) for the each one of them.  It adds the
1936 // visited values into the visitedLiveValues set, which we will later use them
1937 // for validation checking.
1938 static void
1939 insertRelocationStores(iterator_range<Value::user_iterator> GCRelocs,
1940                        DenseMap<Value *, AllocaInst *> &AllocaMap,
1941                        DenseSet<Value *> &VisitedLiveValues) {
1942   for (User *U : GCRelocs) {
1943     GCRelocateInst *Relocate = dyn_cast<GCRelocateInst>(U);
1944     if (!Relocate)
1945       continue;
1946 
1947     Value *OriginalValue = Relocate->getDerivedPtr();
1948     assert(AllocaMap.count(OriginalValue));
1949     Value *Alloca = AllocaMap[OriginalValue];
1950 
1951     // Emit store into the related alloca
1952     // All gc_relocates are i8 addrspace(1)* typed, and it must be bitcasted to
1953     // the correct type according to alloca.
1954     assert(Relocate->getNextNode() &&
1955            "Should always have one since it's not a terminator");
1956     IRBuilder<> Builder(Relocate->getNextNode());
1957     Value *CastedRelocatedValue =
1958       Builder.CreateBitCast(Relocate,
1959                             cast<AllocaInst>(Alloca)->getAllocatedType(),
1960                             suffixed_name_or(Relocate, ".casted", ""));
1961 
1962     new StoreInst(CastedRelocatedValue, Alloca,
1963                   cast<Instruction>(CastedRelocatedValue)->getNextNode());
1964 
1965 #ifndef NDEBUG
1966     VisitedLiveValues.insert(OriginalValue);
1967 #endif
1968   }
1969 }
1970 
1971 // Helper function for the "relocationViaAlloca". Similar to the
1972 // "insertRelocationStores" but works for rematerialized values.
1973 static void insertRematerializationStores(
1974     const RematerializedValueMapTy &RematerializedValues,
1975     DenseMap<Value *, AllocaInst *> &AllocaMap,
1976     DenseSet<Value *> &VisitedLiveValues) {
1977   for (auto RematerializedValuePair: RematerializedValues) {
1978     Instruction *RematerializedValue = RematerializedValuePair.first;
1979     Value *OriginalValue = RematerializedValuePair.second;
1980 
1981     assert(AllocaMap.count(OriginalValue) &&
1982            "Can not find alloca for rematerialized value");
1983     Value *Alloca = AllocaMap[OriginalValue];
1984 
1985     new StoreInst(RematerializedValue, Alloca,
1986                   RematerializedValue->getNextNode());
1987 
1988 #ifndef NDEBUG
1989     VisitedLiveValues.insert(OriginalValue);
1990 #endif
1991   }
1992 }
1993 
1994 /// Do all the relocation update via allocas and mem2reg
1995 static void relocationViaAlloca(
1996     Function &F, DominatorTree &DT, ArrayRef<Value *> Live,
1997     ArrayRef<PartiallyConstructedSafepointRecord> Records) {
1998 #ifndef NDEBUG
1999   // record initial number of (static) allocas; we'll check we have the same
2000   // number when we get done.
2001   int InitialAllocaNum = 0;
2002   for (Instruction &I : F.getEntryBlock())
2003     if (isa<AllocaInst>(I))
2004       InitialAllocaNum++;
2005 #endif
2006 
2007   // TODO-PERF: change data structures, reserve
2008   DenseMap<Value *, AllocaInst *> AllocaMap;
2009   SmallVector<AllocaInst *, 200> PromotableAllocas;
2010   // Used later to chack that we have enough allocas to store all values
2011   std::size_t NumRematerializedValues = 0;
2012   PromotableAllocas.reserve(Live.size());
2013 
2014   // Emit alloca for "LiveValue" and record it in "allocaMap" and
2015   // "PromotableAllocas"
2016   const DataLayout &DL = F.getParent()->getDataLayout();
2017   auto emitAllocaFor = [&](Value *LiveValue) {
2018     AllocaInst *Alloca = new AllocaInst(LiveValue->getType(),
2019                                         DL.getAllocaAddrSpace(), "",
2020                                         F.getEntryBlock().getFirstNonPHI());
2021     AllocaMap[LiveValue] = Alloca;
2022     PromotableAllocas.push_back(Alloca);
2023   };
2024 
2025   // Emit alloca for each live gc pointer
2026   for (Value *V : Live)
2027     emitAllocaFor(V);
2028 
2029   // Emit allocas for rematerialized values
2030   for (const auto &Info : Records)
2031     for (auto RematerializedValuePair : Info.RematerializedValues) {
2032       Value *OriginalValue = RematerializedValuePair.second;
2033       if (AllocaMap.count(OriginalValue) != 0)
2034         continue;
2035 
2036       emitAllocaFor(OriginalValue);
2037       ++NumRematerializedValues;
2038     }
2039 
2040   // The next two loops are part of the same conceptual operation.  We need to
2041   // insert a store to the alloca after the original def and at each
2042   // redefinition.  We need to insert a load before each use.  These are split
2043   // into distinct loops for performance reasons.
2044 
2045   // Update gc pointer after each statepoint: either store a relocated value or
2046   // null (if no relocated value was found for this gc pointer and it is not a
2047   // gc_result).  This must happen before we update the statepoint with load of
2048   // alloca otherwise we lose the link between statepoint and old def.
2049   for (const auto &Info : Records) {
2050     Value *Statepoint = Info.StatepointToken;
2051 
2052     // This will be used for consistency check
2053     DenseSet<Value *> VisitedLiveValues;
2054 
2055     // Insert stores for normal statepoint gc relocates
2056     insertRelocationStores(Statepoint->users(), AllocaMap, VisitedLiveValues);
2057 
2058     // In case if it was invoke statepoint
2059     // we will insert stores for exceptional path gc relocates.
2060     if (isa<InvokeInst>(Statepoint)) {
2061       insertRelocationStores(Info.UnwindToken->users(), AllocaMap,
2062                              VisitedLiveValues);
2063     }
2064 
2065     // Do similar thing with rematerialized values
2066     insertRematerializationStores(Info.RematerializedValues, AllocaMap,
2067                                   VisitedLiveValues);
2068 
2069     if (ClobberNonLive) {
2070       // As a debugging aid, pretend that an unrelocated pointer becomes null at
2071       // the gc.statepoint.  This will turn some subtle GC problems into
2072       // slightly easier to debug SEGVs.  Note that on large IR files with
2073       // lots of gc.statepoints this is extremely costly both memory and time
2074       // wise.
2075       SmallVector<AllocaInst *, 64> ToClobber;
2076       for (auto Pair : AllocaMap) {
2077         Value *Def = Pair.first;
2078         AllocaInst *Alloca = Pair.second;
2079 
2080         // This value was relocated
2081         if (VisitedLiveValues.count(Def)) {
2082           continue;
2083         }
2084         ToClobber.push_back(Alloca);
2085       }
2086 
2087       auto InsertClobbersAt = [&](Instruction *IP) {
2088         for (auto *AI : ToClobber) {
2089           auto AT = AI->getAllocatedType();
2090           Constant *CPN;
2091           if (AT->isVectorTy())
2092             CPN = ConstantAggregateZero::get(AT);
2093           else
2094             CPN = ConstantPointerNull::get(cast<PointerType>(AT));
2095           new StoreInst(CPN, AI, IP);
2096         }
2097       };
2098 
2099       // Insert the clobbering stores.  These may get intermixed with the
2100       // gc.results and gc.relocates, but that's fine.
2101       if (auto II = dyn_cast<InvokeInst>(Statepoint)) {
2102         InsertClobbersAt(&*II->getNormalDest()->getFirstInsertionPt());
2103         InsertClobbersAt(&*II->getUnwindDest()->getFirstInsertionPt());
2104       } else {
2105         InsertClobbersAt(cast<Instruction>(Statepoint)->getNextNode());
2106       }
2107     }
2108   }
2109 
2110   // Update use with load allocas and add store for gc_relocated.
2111   for (auto Pair : AllocaMap) {
2112     Value *Def = Pair.first;
2113     AllocaInst *Alloca = Pair.second;
2114 
2115     // We pre-record the uses of allocas so that we dont have to worry about
2116     // later update that changes the user information..
2117 
2118     SmallVector<Instruction *, 20> Uses;
2119     // PERF: trade a linear scan for repeated reallocation
2120     Uses.reserve(Def->getNumUses());
2121     for (User *U : Def->users()) {
2122       if (!isa<ConstantExpr>(U)) {
2123         // If the def has a ConstantExpr use, then the def is either a
2124         // ConstantExpr use itself or null.  In either case
2125         // (recursively in the first, directly in the second), the oop
2126         // it is ultimately dependent on is null and this particular
2127         // use does not need to be fixed up.
2128         Uses.push_back(cast<Instruction>(U));
2129       }
2130     }
2131 
2132     llvm::sort(Uses);
2133     auto Last = std::unique(Uses.begin(), Uses.end());
2134     Uses.erase(Last, Uses.end());
2135 
2136     for (Instruction *Use : Uses) {
2137       if (isa<PHINode>(Use)) {
2138         PHINode *Phi = cast<PHINode>(Use);
2139         for (unsigned i = 0; i < Phi->getNumIncomingValues(); i++) {
2140           if (Def == Phi->getIncomingValue(i)) {
2141             LoadInst *Load =
2142                 new LoadInst(Alloca->getAllocatedType(), Alloca, "",
2143                              Phi->getIncomingBlock(i)->getTerminator());
2144             Phi->setIncomingValue(i, Load);
2145           }
2146         }
2147       } else {
2148         LoadInst *Load =
2149             new LoadInst(Alloca->getAllocatedType(), Alloca, "", Use);
2150         Use->replaceUsesOfWith(Def, Load);
2151       }
2152     }
2153 
2154     // Emit store for the initial gc value.  Store must be inserted after load,
2155     // otherwise store will be in alloca's use list and an extra load will be
2156     // inserted before it.
2157     StoreInst *Store = new StoreInst(Def, Alloca, /*volatile*/ false,
2158                                      DL.getABITypeAlign(Def->getType()));
2159     if (Instruction *Inst = dyn_cast<Instruction>(Def)) {
2160       if (InvokeInst *Invoke = dyn_cast<InvokeInst>(Inst)) {
2161         // InvokeInst is a terminator so the store need to be inserted into its
2162         // normal destination block.
2163         BasicBlock *NormalDest = Invoke->getNormalDest();
2164         Store->insertBefore(NormalDest->getFirstNonPHI());
2165       } else {
2166         assert(!Inst->isTerminator() &&
2167                "The only terminator that can produce a value is "
2168                "InvokeInst which is handled above.");
2169         Store->insertAfter(Inst);
2170       }
2171     } else {
2172       assert(isa<Argument>(Def));
2173       Store->insertAfter(cast<Instruction>(Alloca));
2174     }
2175   }
2176 
2177   assert(PromotableAllocas.size() == Live.size() + NumRematerializedValues &&
2178          "we must have the same allocas with lives");
2179   (void) NumRematerializedValues;
2180   if (!PromotableAllocas.empty()) {
2181     // Apply mem2reg to promote alloca to SSA
2182     PromoteMemToReg(PromotableAllocas, DT);
2183   }
2184 
2185 #ifndef NDEBUG
2186   for (auto &I : F.getEntryBlock())
2187     if (isa<AllocaInst>(I))
2188       InitialAllocaNum--;
2189   assert(InitialAllocaNum == 0 && "We must not introduce any extra allocas");
2190 #endif
2191 }
2192 
2193 /// Implement a unique function which doesn't require we sort the input
2194 /// vector.  Doing so has the effect of changing the output of a couple of
2195 /// tests in ways which make them less useful in testing fused safepoints.
2196 template <typename T> static void unique_unsorted(SmallVectorImpl<T> &Vec) {
2197   SmallSet<T, 8> Seen;
2198   erase_if(Vec, [&](const T &V) { return !Seen.insert(V).second; });
2199 }
2200 
2201 /// Insert holders so that each Value is obviously live through the entire
2202 /// lifetime of the call.
2203 static void insertUseHolderAfter(CallBase *Call, const ArrayRef<Value *> Values,
2204                                  SmallVectorImpl<CallInst *> &Holders) {
2205   if (Values.empty())
2206     // No values to hold live, might as well not insert the empty holder
2207     return;
2208 
2209   Module *M = Call->getModule();
2210   // Use a dummy vararg function to actually hold the values live
2211   FunctionCallee Func = M->getOrInsertFunction(
2212       "__tmp_use", FunctionType::get(Type::getVoidTy(M->getContext()), true));
2213   if (isa<CallInst>(Call)) {
2214     // For call safepoints insert dummy calls right after safepoint
2215     Holders.push_back(
2216         CallInst::Create(Func, Values, "", &*++Call->getIterator()));
2217     return;
2218   }
2219   // For invoke safepooints insert dummy calls both in normal and
2220   // exceptional destination blocks
2221   auto *II = cast<InvokeInst>(Call);
2222   Holders.push_back(CallInst::Create(
2223       Func, Values, "", &*II->getNormalDest()->getFirstInsertionPt()));
2224   Holders.push_back(CallInst::Create(
2225       Func, Values, "", &*II->getUnwindDest()->getFirstInsertionPt()));
2226 }
2227 
2228 static void findLiveReferences(
2229     Function &F, DominatorTree &DT, ArrayRef<CallBase *> toUpdate,
2230     MutableArrayRef<struct PartiallyConstructedSafepointRecord> records,
2231     GCStrategy *GC) {
2232   GCPtrLivenessData OriginalLivenessData;
2233   computeLiveInValues(DT, F, OriginalLivenessData, GC);
2234   for (size_t i = 0; i < records.size(); i++) {
2235     struct PartiallyConstructedSafepointRecord &info = records[i];
2236     analyzeParsePointLiveness(DT, OriginalLivenessData, toUpdate[i], info, GC);
2237   }
2238 }
2239 
2240 // Helper function for the "rematerializeLiveValues". It walks use chain
2241 // starting from the "CurrentValue" until it reaches the root of the chain, i.e.
2242 // the base or a value it cannot process. Only "simple" values are processed
2243 // (currently it is GEP's and casts). The returned root is  examined by the
2244 // callers of findRematerializableChainToBasePointer.  Fills "ChainToBase" array
2245 // with all visited values.
2246 static Value* findRematerializableChainToBasePointer(
2247   SmallVectorImpl<Instruction*> &ChainToBase,
2248   Value *CurrentValue) {
2249   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurrentValue)) {
2250     ChainToBase.push_back(GEP);
2251     return findRematerializableChainToBasePointer(ChainToBase,
2252                                                   GEP->getPointerOperand());
2253   }
2254 
2255   if (CastInst *CI = dyn_cast<CastInst>(CurrentValue)) {
2256     if (!CI->isNoopCast(CI->getModule()->getDataLayout()))
2257       return CI;
2258 
2259     ChainToBase.push_back(CI);
2260     return findRematerializableChainToBasePointer(ChainToBase,
2261                                                   CI->getOperand(0));
2262   }
2263 
2264   // We have reached the root of the chain, which is either equal to the base or
2265   // is the first unsupported value along the use chain.
2266   return CurrentValue;
2267 }
2268 
2269 // Helper function for the "rematerializeLiveValues". Compute cost of the use
2270 // chain we are going to rematerialize.
2271 static InstructionCost
2272 chainToBasePointerCost(SmallVectorImpl<Instruction *> &Chain,
2273                        TargetTransformInfo &TTI) {
2274   InstructionCost Cost = 0;
2275 
2276   for (Instruction *Instr : Chain) {
2277     if (CastInst *CI = dyn_cast<CastInst>(Instr)) {
2278       assert(CI->isNoopCast(CI->getModule()->getDataLayout()) &&
2279              "non noop cast is found during rematerialization");
2280 
2281       Type *SrcTy = CI->getOperand(0)->getType();
2282       Cost += TTI.getCastInstrCost(CI->getOpcode(), CI->getType(), SrcTy,
2283                                    TTI::getCastContextHint(CI),
2284                                    TargetTransformInfo::TCK_SizeAndLatency, CI);
2285 
2286     } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Instr)) {
2287       // Cost of the address calculation
2288       Type *ValTy = GEP->getSourceElementType();
2289       Cost += TTI.getAddressComputationCost(ValTy);
2290 
2291       // And cost of the GEP itself
2292       // TODO: Use TTI->getGEPCost here (it exists, but appears to be not
2293       //       allowed for the external usage)
2294       if (!GEP->hasAllConstantIndices())
2295         Cost += 2;
2296 
2297     } else {
2298       llvm_unreachable("unsupported instruction type during rematerialization");
2299     }
2300   }
2301 
2302   return Cost;
2303 }
2304 
2305 static bool AreEquivalentPhiNodes(PHINode &OrigRootPhi, PHINode &AlternateRootPhi) {
2306   unsigned PhiNum = OrigRootPhi.getNumIncomingValues();
2307   if (PhiNum != AlternateRootPhi.getNumIncomingValues() ||
2308       OrigRootPhi.getParent() != AlternateRootPhi.getParent())
2309     return false;
2310   // Map of incoming values and their corresponding basic blocks of
2311   // OrigRootPhi.
2312   SmallDenseMap<Value *, BasicBlock *, 8> CurrentIncomingValues;
2313   for (unsigned i = 0; i < PhiNum; i++)
2314     CurrentIncomingValues[OrigRootPhi.getIncomingValue(i)] =
2315         OrigRootPhi.getIncomingBlock(i);
2316 
2317   // Both current and base PHIs should have same incoming values and
2318   // the same basic blocks corresponding to the incoming values.
2319   for (unsigned i = 0; i < PhiNum; i++) {
2320     auto CIVI =
2321         CurrentIncomingValues.find(AlternateRootPhi.getIncomingValue(i));
2322     if (CIVI == CurrentIncomingValues.end())
2323       return false;
2324     BasicBlock *CurrentIncomingBB = CIVI->second;
2325     if (CurrentIncomingBB != AlternateRootPhi.getIncomingBlock(i))
2326       return false;
2327   }
2328   return true;
2329 }
2330 
2331 // Find derived pointers that can be recomputed cheap enough and fill
2332 // RematerizationCandidates with such candidates.
2333 static void
2334 findRematerializationCandidates(PointerToBaseTy PointerToBase,
2335                                 RematCandTy &RematerizationCandidates,
2336                                 TargetTransformInfo &TTI) {
2337   const unsigned int ChainLengthThreshold = 10;
2338 
2339   for (auto P2B : PointerToBase) {
2340     auto *Derived = P2B.first;
2341     auto *Base = P2B.second;
2342     // Consider only derived pointers.
2343     if (Derived == Base)
2344       continue;
2345 
2346     // For each live pointer find its defining chain.
2347     SmallVector<Instruction *, 3> ChainToBase;
2348     Value *RootOfChain =
2349         findRematerializableChainToBasePointer(ChainToBase, Derived);
2350 
2351     // Nothing to do, or chain is too long
2352     if ( ChainToBase.size() == 0 ||
2353         ChainToBase.size() > ChainLengthThreshold)
2354       continue;
2355 
2356     // Handle the scenario where the RootOfChain is not equal to the
2357     // Base Value, but they are essentially the same phi values.
2358     if (RootOfChain != PointerToBase[Derived]) {
2359       PHINode *OrigRootPhi = dyn_cast<PHINode>(RootOfChain);
2360       PHINode *AlternateRootPhi = dyn_cast<PHINode>(PointerToBase[Derived]);
2361       if (!OrigRootPhi || !AlternateRootPhi)
2362         continue;
2363       // PHI nodes that have the same incoming values, and belonging to the same
2364       // basic blocks are essentially the same SSA value.  When the original phi
2365       // has incoming values with different base pointers, the original phi is
2366       // marked as conflict, and an additional `AlternateRootPhi` with the same
2367       // incoming values get generated by the findBasePointer function. We need
2368       // to identify the newly generated AlternateRootPhi (.base version of phi)
2369       // and RootOfChain (the original phi node itself) are the same, so that we
2370       // can rematerialize the gep and casts. This is a workaround for the
2371       // deficiency in the findBasePointer algorithm.
2372       if (!AreEquivalentPhiNodes(*OrigRootPhi, *AlternateRootPhi))
2373         continue;
2374     }
2375     // Compute cost of this chain.
2376     InstructionCost Cost = chainToBasePointerCost(ChainToBase, TTI);
2377     // TODO: We can also account for cases when we will be able to remove some
2378     //       of the rematerialized values by later optimization passes. I.e if
2379     //       we rematerialized several intersecting chains. Or if original values
2380     //       don't have any uses besides this statepoint.
2381 
2382     // Ok, there is a candidate.
2383     RematerizlizationCandidateRecord Record;
2384     Record.ChainToBase = ChainToBase;
2385     Record.RootOfChain = RootOfChain;
2386     Record.Cost = Cost;
2387     RematerizationCandidates.insert({ Derived, Record });
2388   }
2389 }
2390 
2391 // Try to rematerialize derived pointers immediately before their uses
2392 // (instead of rematerializing after every statepoint it is live through).
2393 // This can be beneficial when derived pointer is live across many
2394 // statepoints, but uses are rare.
2395 static void rematerializeLiveValuesAtUses(
2396     RematCandTy &RematerizationCandidates,
2397     MutableArrayRef<PartiallyConstructedSafepointRecord> Records,
2398     PointerToBaseTy &PointerToBase) {
2399   if (!RematDerivedAtUses)
2400     return;
2401 
2402   SmallVector<Instruction *, 32> LiveValuesToBeDeleted;
2403 
2404   LLVM_DEBUG(dbgs() << "Rematerialize derived pointers at uses, "
2405                     << "Num statepoints: " << Records.size() << '\n');
2406 
2407   for (auto &It : RematerizationCandidates) {
2408     Instruction *Cand = cast<Instruction>(It.first);
2409     auto &Record = It.second;
2410 
2411     if (Record.Cost >= RematerializationThreshold)
2412       continue;
2413 
2414     if (Cand->user_empty())
2415       continue;
2416 
2417     if (Cand->hasOneUse())
2418       if (auto *U = dyn_cast<Instruction>(Cand->getUniqueUndroppableUser()))
2419         if (U->getParent() == Cand->getParent())
2420           continue;
2421 
2422     // Rematerialization before PHI nodes is not implemented.
2423     if (llvm::any_of(Cand->users(),
2424                      [](const auto *U) { return isa<PHINode>(U); }))
2425       continue;
2426 
2427     LLVM_DEBUG(dbgs() << "Trying cand " << *Cand << " ... ");
2428 
2429     // Count of rematerialization instructions we introduce is equal to number
2430     // of candidate uses.
2431     // Count of rematerialization instructions we eliminate is equal to number
2432     // of statepoints it is live through.
2433     // Consider transformation profitable if latter is greater than former
2434     // (in other words, we create less than eliminate).
2435     unsigned NumLiveStatepoints = llvm::count_if(
2436         Records, [Cand](const auto &R) { return R.LiveSet.contains(Cand); });
2437     unsigned NumUses = Cand->getNumUses();
2438 
2439     LLVM_DEBUG(dbgs() << "Num uses: " << NumUses << " Num live statepoints: "
2440                       << NumLiveStatepoints << " ");
2441 
2442     if (NumLiveStatepoints < NumUses) {
2443       LLVM_DEBUG(dbgs() << "not profitable\n");
2444       continue;
2445     }
2446 
2447     // If rematerialization is 'free', then favor rematerialization at
2448     // uses as it generally shortens live ranges.
2449     // TODO: Short (size ==1) chains only?
2450     if (NumLiveStatepoints == NumUses && Record.Cost > 0) {
2451       LLVM_DEBUG(dbgs() << "not profitable\n");
2452       continue;
2453     }
2454 
2455     LLVM_DEBUG(dbgs() << "looks profitable\n");
2456 
2457     // ChainToBase may contain another remat candidate (as a sub chain) which
2458     // has been rewritten by now. Need to recollect chain to have up to date
2459     // value.
2460     // TODO: sort records in findRematerializationCandidates() in
2461     // decreasing chain size order?
2462     if (Record.ChainToBase.size() > 1) {
2463       Record.ChainToBase.clear();
2464       findRematerializableChainToBasePointer(Record.ChainToBase, Cand);
2465     }
2466 
2467     // Current rematerialization algorithm is very simple: we rematerialize
2468     // immediately before EVERY use, even if there are several uses in same
2469     // block or if use is local to Cand Def. The reason is that this allows
2470     // us to avoid recomputing liveness without complicated analysis:
2471     // - If we did not eliminate all uses of original Candidate, we do not
2472     //   know exaclty in what BBs it is still live.
2473     // - If we rematerialize once per BB, we need to find proper insertion
2474     //   place (first use in block, but after Def) and analyze if there is
2475     //   statepoint between uses in the block.
2476     while (!Cand->user_empty()) {
2477       Instruction *UserI = cast<Instruction>(*Cand->user_begin());
2478       Instruction *RematChain = rematerializeChain(
2479           Record.ChainToBase, UserI, Record.RootOfChain, PointerToBase[Cand]);
2480       UserI->replaceUsesOfWith(Cand, RematChain);
2481       PointerToBase[RematChain] = PointerToBase[Cand];
2482     }
2483     LiveValuesToBeDeleted.push_back(Cand);
2484   }
2485 
2486   LLVM_DEBUG(dbgs() << "Rematerialized " << LiveValuesToBeDeleted.size()
2487                     << " derived pointers\n");
2488   for (auto *Cand : LiveValuesToBeDeleted) {
2489     assert(Cand->use_empty() && "Unexpected user remain");
2490     RematerizationCandidates.erase(Cand);
2491     for (auto &R : Records) {
2492       assert(!R.LiveSet.contains(Cand) ||
2493              R.LiveSet.contains(PointerToBase[Cand]));
2494       R.LiveSet.remove(Cand);
2495     }
2496   }
2497 
2498   // Recollect not rematerialized chains - we might have rewritten
2499   // their sub-chains.
2500   if (!LiveValuesToBeDeleted.empty()) {
2501     for (auto &P : RematerizationCandidates) {
2502       auto &R = P.second;
2503       if (R.ChainToBase.size() > 1) {
2504         R.ChainToBase.clear();
2505         findRematerializableChainToBasePointer(R.ChainToBase, P.first);
2506       }
2507     }
2508   }
2509 }
2510 
2511 // From the statepoint live set pick values that are cheaper to recompute then
2512 // to relocate. Remove this values from the live set, rematerialize them after
2513 // statepoint and record them in "Info" structure. Note that similar to
2514 // relocated values we don't do any user adjustments here.
2515 static void rematerializeLiveValues(CallBase *Call,
2516                                     PartiallyConstructedSafepointRecord &Info,
2517                                     PointerToBaseTy &PointerToBase,
2518                                     RematCandTy &RematerizationCandidates,
2519                                     TargetTransformInfo &TTI) {
2520   // Record values we are going to delete from this statepoint live set.
2521   // We can not di this in following loop due to iterator invalidation.
2522   SmallVector<Value *, 32> LiveValuesToBeDeleted;
2523 
2524   for (Value *LiveValue : Info.LiveSet) {
2525     auto It = RematerizationCandidates.find(LiveValue);
2526     if (It == RematerizationCandidates.end())
2527       continue;
2528 
2529     RematerizlizationCandidateRecord &Record = It->second;
2530 
2531     InstructionCost Cost = Record.Cost;
2532     // For invokes we need to rematerialize each chain twice - for normal and
2533     // for unwind basic blocks. Model this by multiplying cost by two.
2534     if (isa<InvokeInst>(Call))
2535       Cost *= 2;
2536 
2537     // If it's too expensive - skip it.
2538     if (Cost >= RematerializationThreshold)
2539       continue;
2540 
2541     // Remove value from the live set
2542     LiveValuesToBeDeleted.push_back(LiveValue);
2543 
2544     // Clone instructions and record them inside "Info" structure.
2545 
2546     // Different cases for calls and invokes. For invokes we need to clone
2547     // instructions both on normal and unwind path.
2548     if (isa<CallInst>(Call)) {
2549       Instruction *InsertBefore = Call->getNextNode();
2550       assert(InsertBefore);
2551       Instruction *RematerializedValue =
2552           rematerializeChain(Record.ChainToBase, InsertBefore,
2553                              Record.RootOfChain, PointerToBase[LiveValue]);
2554       Info.RematerializedValues[RematerializedValue] = LiveValue;
2555     } else {
2556       auto *Invoke = cast<InvokeInst>(Call);
2557 
2558       Instruction *NormalInsertBefore =
2559           &*Invoke->getNormalDest()->getFirstInsertionPt();
2560       Instruction *UnwindInsertBefore =
2561           &*Invoke->getUnwindDest()->getFirstInsertionPt();
2562 
2563       Instruction *NormalRematerializedValue =
2564           rematerializeChain(Record.ChainToBase, NormalInsertBefore,
2565                              Record.RootOfChain, PointerToBase[LiveValue]);
2566       Instruction *UnwindRematerializedValue =
2567           rematerializeChain(Record.ChainToBase, UnwindInsertBefore,
2568                              Record.RootOfChain, PointerToBase[LiveValue]);
2569 
2570       Info.RematerializedValues[NormalRematerializedValue] = LiveValue;
2571       Info.RematerializedValues[UnwindRematerializedValue] = LiveValue;
2572     }
2573   }
2574 
2575   // Remove rematerialized values from the live set.
2576   for (auto *LiveValue: LiveValuesToBeDeleted) {
2577     Info.LiveSet.remove(LiveValue);
2578   }
2579 }
2580 
2581 static bool inlineGetBaseAndOffset(Function &F,
2582                                    SmallVectorImpl<CallInst *> &Intrinsics,
2583                                    DefiningValueMapTy &DVCache,
2584                                    IsKnownBaseMapTy &KnownBases) {
2585   auto &Context = F.getContext();
2586   auto &DL = F.getParent()->getDataLayout();
2587   bool Changed = false;
2588 
2589   for (auto *Callsite : Intrinsics)
2590     switch (Callsite->getIntrinsicID()) {
2591     case Intrinsic::experimental_gc_get_pointer_base: {
2592       Changed = true;
2593       Value *Base =
2594           findBasePointer(Callsite->getOperand(0), DVCache, KnownBases);
2595       assert(!DVCache.count(Callsite));
2596       auto *BaseBC = IRBuilder<>(Callsite).CreateBitCast(
2597           Base, Callsite->getType(), suffixed_name_or(Base, ".cast", ""));
2598       if (BaseBC != Base)
2599         DVCache[BaseBC] = Base;
2600       Callsite->replaceAllUsesWith(BaseBC);
2601       if (!BaseBC->hasName())
2602         BaseBC->takeName(Callsite);
2603       Callsite->eraseFromParent();
2604       break;
2605     }
2606     case Intrinsic::experimental_gc_get_pointer_offset: {
2607       Changed = true;
2608       Value *Derived = Callsite->getOperand(0);
2609       Value *Base = findBasePointer(Derived, DVCache, KnownBases);
2610       assert(!DVCache.count(Callsite));
2611       unsigned AddressSpace = Derived->getType()->getPointerAddressSpace();
2612       unsigned IntPtrSize = DL.getPointerSizeInBits(AddressSpace);
2613       IRBuilder<> Builder(Callsite);
2614       Value *BaseInt =
2615           Builder.CreatePtrToInt(Base, Type::getIntNTy(Context, IntPtrSize),
2616                                  suffixed_name_or(Base, ".int", ""));
2617       Value *DerivedInt =
2618           Builder.CreatePtrToInt(Derived, Type::getIntNTy(Context, IntPtrSize),
2619                                  suffixed_name_or(Derived, ".int", ""));
2620       Value *Offset = Builder.CreateSub(DerivedInt, BaseInt);
2621       Callsite->replaceAllUsesWith(Offset);
2622       Offset->takeName(Callsite);
2623       Callsite->eraseFromParent();
2624       break;
2625     }
2626     default:
2627       llvm_unreachable("Unknown intrinsic");
2628     }
2629 
2630   return Changed;
2631 }
2632 
2633 static bool insertParsePoints(Function &F, DominatorTree &DT,
2634                               TargetTransformInfo &TTI,
2635                               SmallVectorImpl<CallBase *> &ToUpdate,
2636                               DefiningValueMapTy &DVCache,
2637                               IsKnownBaseMapTy &KnownBases) {
2638   std::unique_ptr<GCStrategy> GC = findGCStrategy(F);
2639 
2640 #ifndef NDEBUG
2641   // Validate the input
2642   std::set<CallBase *> Uniqued;
2643   Uniqued.insert(ToUpdate.begin(), ToUpdate.end());
2644   assert(Uniqued.size() == ToUpdate.size() && "no duplicates please!");
2645 
2646   for (CallBase *Call : ToUpdate)
2647     assert(Call->getFunction() == &F);
2648 #endif
2649 
2650   // When inserting gc.relocates for invokes, we need to be able to insert at
2651   // the top of the successor blocks.  See the comment on
2652   // normalForInvokeSafepoint on exactly what is needed.  Note that this step
2653   // may restructure the CFG.
2654   for (CallBase *Call : ToUpdate) {
2655     auto *II = dyn_cast<InvokeInst>(Call);
2656     if (!II)
2657       continue;
2658     normalizeForInvokeSafepoint(II->getNormalDest(), II->getParent(), DT);
2659     normalizeForInvokeSafepoint(II->getUnwindDest(), II->getParent(), DT);
2660   }
2661 
2662   // A list of dummy calls added to the IR to keep various values obviously
2663   // live in the IR.  We'll remove all of these when done.
2664   SmallVector<CallInst *, 64> Holders;
2665 
2666   // Insert a dummy call with all of the deopt operands we'll need for the
2667   // actual safepoint insertion as arguments.  This ensures reference operands
2668   // in the deopt argument list are considered live through the safepoint (and
2669   // thus makes sure they get relocated.)
2670   for (CallBase *Call : ToUpdate) {
2671     SmallVector<Value *, 64> DeoptValues;
2672 
2673     for (Value *Arg : GetDeoptBundleOperands(Call)) {
2674       assert(!isUnhandledGCPointerType(Arg->getType(), GC.get()) &&
2675              "support for FCA unimplemented");
2676       if (isHandledGCPointerType(Arg->getType(), GC.get()))
2677         DeoptValues.push_back(Arg);
2678     }
2679 
2680     insertUseHolderAfter(Call, DeoptValues, Holders);
2681   }
2682 
2683   SmallVector<PartiallyConstructedSafepointRecord, 64> Records(ToUpdate.size());
2684 
2685   // A) Identify all gc pointers which are statically live at the given call
2686   // site.
2687   findLiveReferences(F, DT, ToUpdate, Records, GC.get());
2688 
2689   /// Global mapping from live pointers to a base-defining-value.
2690   PointerToBaseTy PointerToBase;
2691 
2692   // B) Find the base pointers for each live pointer
2693   for (size_t i = 0; i < Records.size(); i++) {
2694     PartiallyConstructedSafepointRecord &info = Records[i];
2695     findBasePointers(DT, DVCache, ToUpdate[i], info, PointerToBase, KnownBases);
2696   }
2697   if (PrintBasePointers) {
2698     errs() << "Base Pairs (w/o Relocation):\n";
2699     for (auto &Pair : PointerToBase) {
2700       errs() << " derived ";
2701       Pair.first->printAsOperand(errs(), false);
2702       errs() << " base ";
2703       Pair.second->printAsOperand(errs(), false);
2704       errs() << "\n";
2705       ;
2706     }
2707   }
2708 
2709   // The base phi insertion logic (for any safepoint) may have inserted new
2710   // instructions which are now live at some safepoint.  The simplest such
2711   // example is:
2712   // loop:
2713   //   phi a  <-- will be a new base_phi here
2714   //   safepoint 1 <-- that needs to be live here
2715   //   gep a + 1
2716   //   safepoint 2
2717   //   br loop
2718   // We insert some dummy calls after each safepoint to definitely hold live
2719   // the base pointers which were identified for that safepoint.  We'll then
2720   // ask liveness for _every_ base inserted to see what is now live.  Then we
2721   // remove the dummy calls.
2722   Holders.reserve(Holders.size() + Records.size());
2723   for (size_t i = 0; i < Records.size(); i++) {
2724     PartiallyConstructedSafepointRecord &Info = Records[i];
2725 
2726     SmallVector<Value *, 128> Bases;
2727     for (auto *Derived : Info.LiveSet) {
2728       assert(PointerToBase.count(Derived) && "Missed base for derived pointer");
2729       Bases.push_back(PointerToBase[Derived]);
2730     }
2731 
2732     insertUseHolderAfter(ToUpdate[i], Bases, Holders);
2733   }
2734 
2735   // By selecting base pointers, we've effectively inserted new uses. Thus, we
2736   // need to rerun liveness.  We may *also* have inserted new defs, but that's
2737   // not the key issue.
2738   recomputeLiveInValues(F, DT, ToUpdate, Records, PointerToBase, GC.get());
2739 
2740   if (PrintBasePointers) {
2741     errs() << "Base Pairs: (w/Relocation)\n";
2742     for (auto Pair : PointerToBase) {
2743       errs() << " derived ";
2744       Pair.first->printAsOperand(errs(), false);
2745       errs() << " base ";
2746       Pair.second->printAsOperand(errs(), false);
2747       errs() << "\n";
2748     }
2749   }
2750 
2751   // It is possible that non-constant live variables have a constant base.  For
2752   // example, a GEP with a variable offset from a global.  In this case we can
2753   // remove it from the liveset.  We already don't add constants to the liveset
2754   // because we assume they won't move at runtime and the GC doesn't need to be
2755   // informed about them.  The same reasoning applies if the base is constant.
2756   // Note that the relocation placement code relies on this filtering for
2757   // correctness as it expects the base to be in the liveset, which isn't true
2758   // if the base is constant.
2759   for (auto &Info : Records) {
2760     Info.LiveSet.remove_if([&](Value *LiveV) {
2761       assert(PointerToBase.count(LiveV) && "Missed base for derived pointer");
2762       return isa<Constant>(PointerToBase[LiveV]);
2763     });
2764   }
2765 
2766   for (CallInst *CI : Holders)
2767     CI->eraseFromParent();
2768 
2769   Holders.clear();
2770 
2771   // Compute the cost of possible re-materialization of derived pointers.
2772   RematCandTy RematerizationCandidates;
2773   findRematerializationCandidates(PointerToBase, RematerizationCandidates, TTI);
2774 
2775   // In order to reduce live set of statepoint we might choose to rematerialize
2776   // some values instead of relocating them. This is purely an optimization and
2777   // does not influence correctness.
2778   // First try rematerialization at uses, then after statepoints.
2779   rematerializeLiveValuesAtUses(RematerizationCandidates, Records,
2780                                 PointerToBase);
2781   for (size_t i = 0; i < Records.size(); i++)
2782     rematerializeLiveValues(ToUpdate[i], Records[i], PointerToBase,
2783                             RematerizationCandidates, TTI);
2784 
2785   // We need this to safely RAUW and delete call or invoke return values that
2786   // may themselves be live over a statepoint.  For details, please see usage in
2787   // makeStatepointExplicitImpl.
2788   std::vector<DeferredReplacement> Replacements;
2789 
2790   // Now run through and replace the existing statepoints with new ones with
2791   // the live variables listed.  We do not yet update uses of the values being
2792   // relocated. We have references to live variables that need to
2793   // survive to the last iteration of this loop.  (By construction, the
2794   // previous statepoint can not be a live variable, thus we can and remove
2795   // the old statepoint calls as we go.)
2796   for (size_t i = 0; i < Records.size(); i++)
2797     makeStatepointExplicit(DT, ToUpdate[i], Records[i], Replacements,
2798                            PointerToBase, GC.get());
2799 
2800   ToUpdate.clear(); // prevent accident use of invalid calls.
2801 
2802   for (auto &PR : Replacements)
2803     PR.doReplacement();
2804 
2805   Replacements.clear();
2806 
2807   for (auto &Info : Records) {
2808     // These live sets may contain state Value pointers, since we replaced calls
2809     // with operand bundles with calls wrapped in gc.statepoint, and some of
2810     // those calls may have been def'ing live gc pointers.  Clear these out to
2811     // avoid accidentally using them.
2812     //
2813     // TODO: We should create a separate data structure that does not contain
2814     // these live sets, and migrate to using that data structure from this point
2815     // onward.
2816     Info.LiveSet.clear();
2817   }
2818   PointerToBase.clear();
2819 
2820   // Do all the fixups of the original live variables to their relocated selves
2821   SmallVector<Value *, 128> Live;
2822   for (const PartiallyConstructedSafepointRecord &Info : Records) {
2823     // We can't simply save the live set from the original insertion.  One of
2824     // the live values might be the result of a call which needs a safepoint.
2825     // That Value* no longer exists and we need to use the new gc_result.
2826     // Thankfully, the live set is embedded in the statepoint (and updated), so
2827     // we just grab that.
2828     llvm::append_range(Live, Info.StatepointToken->gc_args());
2829 #ifndef NDEBUG
2830     // Do some basic validation checking on our liveness results before
2831     // performing relocation.  Relocation can and will turn mistakes in liveness
2832     // results into non-sensical code which is must harder to debug.
2833     // TODO: It would be nice to test consistency as well
2834     assert(DT.isReachableFromEntry(Info.StatepointToken->getParent()) &&
2835            "statepoint must be reachable or liveness is meaningless");
2836     for (Value *V : Info.StatepointToken->gc_args()) {
2837       if (!isa<Instruction>(V))
2838         // Non-instruction values trivial dominate all possible uses
2839         continue;
2840       auto *LiveInst = cast<Instruction>(V);
2841       assert(DT.isReachableFromEntry(LiveInst->getParent()) &&
2842              "unreachable values should never be live");
2843       assert(DT.dominates(LiveInst, Info.StatepointToken) &&
2844              "basic SSA liveness expectation violated by liveness analysis");
2845     }
2846 #endif
2847   }
2848   unique_unsorted(Live);
2849 
2850 #ifndef NDEBUG
2851   // Validation check
2852   for (auto *Ptr : Live)
2853     assert(isHandledGCPointerType(Ptr->getType(), GC.get()) &&
2854            "must be a gc pointer type");
2855 #endif
2856 
2857   relocationViaAlloca(F, DT, Live, Records);
2858   return !Records.empty();
2859 }
2860 
2861 // List of all parameter and return attributes which must be stripped when
2862 // lowering from the abstract machine model.  Note that we list attributes
2863 // here which aren't valid as return attributes, that is okay.
2864 static AttributeMask getParamAndReturnAttributesToRemove() {
2865   AttributeMask R;
2866   R.addAttribute(Attribute::Dereferenceable);
2867   R.addAttribute(Attribute::DereferenceableOrNull);
2868   R.addAttribute(Attribute::ReadNone);
2869   R.addAttribute(Attribute::ReadOnly);
2870   R.addAttribute(Attribute::WriteOnly);
2871   R.addAttribute(Attribute::NoAlias);
2872   R.addAttribute(Attribute::NoFree);
2873   return R;
2874 }
2875 
2876 static void stripNonValidAttributesFromPrototype(Function &F) {
2877   LLVMContext &Ctx = F.getContext();
2878 
2879   // Intrinsics are very delicate.  Lowering sometimes depends the presence
2880   // of certain attributes for correctness, but we may have also inferred
2881   // additional ones in the abstract machine model which need stripped.  This
2882   // assumes that the attributes defined in Intrinsic.td are conservatively
2883   // correct for both physical and abstract model.
2884   if (Intrinsic::ID id = F.getIntrinsicID()) {
2885     F.setAttributes(Intrinsic::getAttributes(Ctx, id));
2886     return;
2887   }
2888 
2889   AttributeMask R = getParamAndReturnAttributesToRemove();
2890   for (Argument &A : F.args())
2891     if (isa<PointerType>(A.getType()))
2892       F.removeParamAttrs(A.getArgNo(), R);
2893 
2894   if (isa<PointerType>(F.getReturnType()))
2895     F.removeRetAttrs(R);
2896 
2897   for (auto Attr : FnAttrsToStrip)
2898     F.removeFnAttr(Attr);
2899 }
2900 
2901 /// Certain metadata on instructions are invalid after running RS4GC.
2902 /// Optimizations that run after RS4GC can incorrectly use this metadata to
2903 /// optimize functions. We drop such metadata on the instruction.
2904 static void stripInvalidMetadataFromInstruction(Instruction &I) {
2905   if (!isa<LoadInst>(I) && !isa<StoreInst>(I))
2906     return;
2907   // These are the attributes that are still valid on loads and stores after
2908   // RS4GC.
2909   // The metadata implying dereferenceability and noalias are (conservatively)
2910   // dropped.  This is because semantically, after RewriteStatepointsForGC runs,
2911   // all calls to gc.statepoint "free" the entire heap. Also, gc.statepoint can
2912   // touch the entire heap including noalias objects. Note: The reasoning is
2913   // same as stripping the dereferenceability and noalias attributes that are
2914   // analogous to the metadata counterparts.
2915   // We also drop the invariant.load metadata on the load because that metadata
2916   // implies the address operand to the load points to memory that is never
2917   // changed once it became dereferenceable. This is no longer true after RS4GC.
2918   // Similar reasoning applies to invariant.group metadata, which applies to
2919   // loads within a group.
2920   unsigned ValidMetadataAfterRS4GC[] = {LLVMContext::MD_tbaa,
2921                          LLVMContext::MD_range,
2922                          LLVMContext::MD_alias_scope,
2923                          LLVMContext::MD_nontemporal,
2924                          LLVMContext::MD_nonnull,
2925                          LLVMContext::MD_align,
2926                          LLVMContext::MD_type};
2927 
2928   // Drops all metadata on the instruction other than ValidMetadataAfterRS4GC.
2929   I.dropUnknownNonDebugMetadata(ValidMetadataAfterRS4GC);
2930 }
2931 
2932 static void stripNonValidDataFromBody(Function &F) {
2933   if (F.empty())
2934     return;
2935 
2936   LLVMContext &Ctx = F.getContext();
2937   MDBuilder Builder(Ctx);
2938 
2939   // Set of invariantstart instructions that we need to remove.
2940   // Use this to avoid invalidating the instruction iterator.
2941   SmallVector<IntrinsicInst*, 12> InvariantStartInstructions;
2942 
2943   for (Instruction &I : instructions(F)) {
2944     // invariant.start on memory location implies that the referenced memory
2945     // location is constant and unchanging. This is no longer true after
2946     // RewriteStatepointsForGC runs because there can be calls to gc.statepoint
2947     // which frees the entire heap and the presence of invariant.start allows
2948     // the optimizer to sink the load of a memory location past a statepoint,
2949     // which is incorrect.
2950     if (auto *II = dyn_cast<IntrinsicInst>(&I))
2951       if (II->getIntrinsicID() == Intrinsic::invariant_start) {
2952         InvariantStartInstructions.push_back(II);
2953         continue;
2954       }
2955 
2956     if (MDNode *Tag = I.getMetadata(LLVMContext::MD_tbaa)) {
2957       MDNode *MutableTBAA = Builder.createMutableTBAAAccessTag(Tag);
2958       I.setMetadata(LLVMContext::MD_tbaa, MutableTBAA);
2959     }
2960 
2961     stripInvalidMetadataFromInstruction(I);
2962 
2963     AttributeMask R = getParamAndReturnAttributesToRemove();
2964     if (auto *Call = dyn_cast<CallBase>(&I)) {
2965       for (int i = 0, e = Call->arg_size(); i != e; i++)
2966         if (isa<PointerType>(Call->getArgOperand(i)->getType()))
2967           Call->removeParamAttrs(i, R);
2968       if (isa<PointerType>(Call->getType()))
2969         Call->removeRetAttrs(R);
2970     }
2971   }
2972 
2973   // Delete the invariant.start instructions and RAUW poison.
2974   for (auto *II : InvariantStartInstructions) {
2975     II->replaceAllUsesWith(PoisonValue::get(II->getType()));
2976     II->eraseFromParent();
2977   }
2978 }
2979 
2980 /// Looks up the GC strategy for a given function, returning null if the
2981 /// function doesn't have a GC tag. The strategy is stored in the cache.
2982 static std::unique_ptr<GCStrategy> findGCStrategy(Function &F) {
2983   if (!F.hasGC())
2984     return nullptr;
2985 
2986   return getGCStrategy(F.getGC());
2987 }
2988 
2989 /// Returns true if this function should be rewritten by this pass.  The main
2990 /// point of this function is as an extension point for custom logic.
2991 static bool shouldRewriteStatepointsIn(Function &F) {
2992   if (!F.hasGC())
2993     return false;
2994 
2995   std::unique_ptr<GCStrategy> Strategy = findGCStrategy(F);
2996 
2997   assert(Strategy && "GC strategy is required by function, but was not found");
2998 
2999   return Strategy->useRS4GC();
3000 }
3001 
3002 static void stripNonValidData(Module &M) {
3003 #ifndef NDEBUG
3004   assert(llvm::any_of(M, shouldRewriteStatepointsIn) && "precondition!");
3005 #endif
3006 
3007   for (Function &F : M)
3008     stripNonValidAttributesFromPrototype(F);
3009 
3010   for (Function &F : M)
3011     stripNonValidDataFromBody(F);
3012 }
3013 
3014 bool RewriteStatepointsForGC::runOnFunction(Function &F, DominatorTree &DT,
3015                                             TargetTransformInfo &TTI,
3016                                             const TargetLibraryInfo &TLI) {
3017   assert(!F.isDeclaration() && !F.empty() &&
3018          "need function body to rewrite statepoints in");
3019   assert(shouldRewriteStatepointsIn(F) && "mismatch in rewrite decision");
3020 
3021   auto NeedsRewrite = [&TLI](Instruction &I) {
3022     if (const auto *Call = dyn_cast<CallBase>(&I)) {
3023       if (isa<GCStatepointInst>(Call))
3024         return false;
3025       if (callsGCLeafFunction(Call, TLI))
3026         return false;
3027 
3028       // Normally it's up to the frontend to make sure that non-leaf calls also
3029       // have proper deopt state if it is required. We make an exception for
3030       // element atomic memcpy/memmove intrinsics here. Unlike other intrinsics
3031       // these are non-leaf by default. They might be generated by the optimizer
3032       // which doesn't know how to produce a proper deopt state. So if we see a
3033       // non-leaf memcpy/memmove without deopt state just treat it as a leaf
3034       // copy and don't produce a statepoint.
3035       if (!AllowStatepointWithNoDeoptInfo &&
3036           !Call->getOperandBundle(LLVMContext::OB_deopt)) {
3037         assert((isa<AtomicMemCpyInst>(Call) || isa<AtomicMemMoveInst>(Call)) &&
3038                "Don't expect any other calls here!");
3039         return false;
3040       }
3041       return true;
3042     }
3043     return false;
3044   };
3045 
3046   // Delete any unreachable statepoints so that we don't have unrewritten
3047   // statepoints surviving this pass.  This makes testing easier and the
3048   // resulting IR less confusing to human readers.
3049   DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
3050   bool MadeChange = removeUnreachableBlocks(F, &DTU);
3051   // Flush the Dominator Tree.
3052   DTU.getDomTree();
3053 
3054   // Gather all the statepoints which need rewritten.  Be careful to only
3055   // consider those in reachable code since we need to ask dominance queries
3056   // when rewriting.  We'll delete the unreachable ones in a moment.
3057   SmallVector<CallBase *, 64> ParsePointNeeded;
3058   SmallVector<CallInst *, 64> Intrinsics;
3059   for (Instruction &I : instructions(F)) {
3060     // TODO: only the ones with the flag set!
3061     if (NeedsRewrite(I)) {
3062       // NOTE removeUnreachableBlocks() is stronger than
3063       // DominatorTree::isReachableFromEntry(). In other words
3064       // removeUnreachableBlocks can remove some blocks for which
3065       // isReachableFromEntry() returns true.
3066       assert(DT.isReachableFromEntry(I.getParent()) &&
3067             "no unreachable blocks expected");
3068       ParsePointNeeded.push_back(cast<CallBase>(&I));
3069     }
3070     if (auto *CI = dyn_cast<CallInst>(&I))
3071       if (CI->getIntrinsicID() == Intrinsic::experimental_gc_get_pointer_base ||
3072           CI->getIntrinsicID() == Intrinsic::experimental_gc_get_pointer_offset)
3073         Intrinsics.emplace_back(CI);
3074   }
3075 
3076   // Return early if no work to do.
3077   if (ParsePointNeeded.empty() && Intrinsics.empty())
3078     return MadeChange;
3079 
3080   // As a prepass, go ahead and aggressively destroy single entry phi nodes.
3081   // These are created by LCSSA.  They have the effect of increasing the size
3082   // of liveness sets for no good reason.  It may be harder to do this post
3083   // insertion since relocations and base phis can confuse things.
3084   for (BasicBlock &BB : F)
3085     if (BB.getUniquePredecessor())
3086       MadeChange |= FoldSingleEntryPHINodes(&BB);
3087 
3088   // Before we start introducing relocations, we want to tweak the IR a bit to
3089   // avoid unfortunate code generation effects.  The main example is that we
3090   // want to try to make sure the comparison feeding a branch is after any
3091   // safepoints.  Otherwise, we end up with a comparison of pre-relocation
3092   // values feeding a branch after relocation.  This is semantically correct,
3093   // but results in extra register pressure since both the pre-relocation and
3094   // post-relocation copies must be available in registers.  For code without
3095   // relocations this is handled elsewhere, but teaching the scheduler to
3096   // reverse the transform we're about to do would be slightly complex.
3097   // Note: This may extend the live range of the inputs to the icmp and thus
3098   // increase the liveset of any statepoint we move over.  This is profitable
3099   // as long as all statepoints are in rare blocks.  If we had in-register
3100   // lowering for live values this would be a much safer transform.
3101   auto getConditionInst = [](Instruction *TI) -> Instruction * {
3102     if (auto *BI = dyn_cast<BranchInst>(TI))
3103       if (BI->isConditional())
3104         return dyn_cast<Instruction>(BI->getCondition());
3105     // TODO: Extend this to handle switches
3106     return nullptr;
3107   };
3108   for (BasicBlock &BB : F) {
3109     Instruction *TI = BB.getTerminator();
3110     if (auto *Cond = getConditionInst(TI))
3111       // TODO: Handle more than just ICmps here.  We should be able to move
3112       // most instructions without side effects or memory access.
3113       if (isa<ICmpInst>(Cond) && Cond->hasOneUse()) {
3114         MadeChange = true;
3115         Cond->moveBefore(TI);
3116       }
3117   }
3118 
3119   // Nasty workaround - The base computation code in the main algorithm doesn't
3120   // consider the fact that a GEP can be used to convert a scalar to a vector.
3121   // The right fix for this is to integrate GEPs into the base rewriting
3122   // algorithm properly, this is just a short term workaround to prevent
3123   // crashes by canonicalizing such GEPs into fully vector GEPs.
3124   for (Instruction &I : instructions(F)) {
3125     if (!isa<GetElementPtrInst>(I))
3126       continue;
3127 
3128     unsigned VF = 0;
3129     for (unsigned i = 0; i < I.getNumOperands(); i++)
3130       if (auto *OpndVTy = dyn_cast<VectorType>(I.getOperand(i)->getType())) {
3131         assert(VF == 0 ||
3132                VF == cast<FixedVectorType>(OpndVTy)->getNumElements());
3133         VF = cast<FixedVectorType>(OpndVTy)->getNumElements();
3134       }
3135 
3136     // It's the vector to scalar traversal through the pointer operand which
3137     // confuses base pointer rewriting, so limit ourselves to that case.
3138     if (!I.getOperand(0)->getType()->isVectorTy() && VF != 0) {
3139       IRBuilder<> B(&I);
3140       auto *Splat = B.CreateVectorSplat(VF, I.getOperand(0));
3141       I.setOperand(0, Splat);
3142       MadeChange = true;
3143     }
3144   }
3145 
3146   // Cache the 'defining value' relation used in the computation and
3147   // insertion of base phis and selects.  This ensures that we don't insert
3148   // large numbers of duplicate base_phis. Use one cache for both
3149   // inlineGetBaseAndOffset() and insertParsePoints().
3150   DefiningValueMapTy DVCache;
3151 
3152   // Mapping between a base values and a flag indicating whether it's a known
3153   // base or not.
3154   IsKnownBaseMapTy KnownBases;
3155 
3156   if (!Intrinsics.empty())
3157     // Inline @gc.get.pointer.base() and @gc.get.pointer.offset() before finding
3158     // live references.
3159     MadeChange |= inlineGetBaseAndOffset(F, Intrinsics, DVCache, KnownBases);
3160 
3161   if (!ParsePointNeeded.empty())
3162     MadeChange |=
3163         insertParsePoints(F, DT, TTI, ParsePointNeeded, DVCache, KnownBases);
3164 
3165   return MadeChange;
3166 }
3167 
3168 // liveness computation via standard dataflow
3169 // -------------------------------------------------------------------
3170 
3171 // TODO: Consider using bitvectors for liveness, the set of potentially
3172 // interesting values should be small and easy to pre-compute.
3173 
3174 /// Compute the live-in set for the location rbegin starting from
3175 /// the live-out set of the basic block
3176 static void computeLiveInValues(BasicBlock::reverse_iterator Begin,
3177                                 BasicBlock::reverse_iterator End,
3178                                 SetVector<Value *> &LiveTmp, GCStrategy *GC) {
3179   for (auto &I : make_range(Begin, End)) {
3180     // KILL/Def - Remove this definition from LiveIn
3181     LiveTmp.remove(&I);
3182 
3183     // Don't consider *uses* in PHI nodes, we handle their contribution to
3184     // predecessor blocks when we seed the LiveOut sets
3185     if (isa<PHINode>(I))
3186       continue;
3187 
3188     // USE - Add to the LiveIn set for this instruction
3189     for (Value *V : I.operands()) {
3190       assert(!isUnhandledGCPointerType(V->getType(), GC) &&
3191              "support for FCA unimplemented");
3192       if (isHandledGCPointerType(V->getType(), GC) && !isa<Constant>(V)) {
3193         // The choice to exclude all things constant here is slightly subtle.
3194         // There are two independent reasons:
3195         // - We assume that things which are constant (from LLVM's definition)
3196         // do not move at runtime.  For example, the address of a global
3197         // variable is fixed, even though it's contents may not be.
3198         // - Second, we can't disallow arbitrary inttoptr constants even
3199         // if the language frontend does.  Optimization passes are free to
3200         // locally exploit facts without respect to global reachability.  This
3201         // can create sections of code which are dynamically unreachable and
3202         // contain just about anything.  (see constants.ll in tests)
3203         LiveTmp.insert(V);
3204       }
3205     }
3206   }
3207 }
3208 
3209 static void computeLiveOutSeed(BasicBlock *BB, SetVector<Value *> &LiveTmp,
3210                                GCStrategy *GC) {
3211   for (BasicBlock *Succ : successors(BB)) {
3212     for (auto &I : *Succ) {
3213       PHINode *PN = dyn_cast<PHINode>(&I);
3214       if (!PN)
3215         break;
3216 
3217       Value *V = PN->getIncomingValueForBlock(BB);
3218       assert(!isUnhandledGCPointerType(V->getType(), GC) &&
3219              "support for FCA unimplemented");
3220       if (isHandledGCPointerType(V->getType(), GC) && !isa<Constant>(V))
3221         LiveTmp.insert(V);
3222     }
3223   }
3224 }
3225 
3226 static SetVector<Value *> computeKillSet(BasicBlock *BB, GCStrategy *GC) {
3227   SetVector<Value *> KillSet;
3228   for (Instruction &I : *BB)
3229     if (isHandledGCPointerType(I.getType(), GC))
3230       KillSet.insert(&I);
3231   return KillSet;
3232 }
3233 
3234 #ifndef NDEBUG
3235 /// Check that the items in 'Live' dominate 'TI'.  This is used as a basic
3236 /// validation check for the liveness computation.
3237 static void checkBasicSSA(DominatorTree &DT, SetVector<Value *> &Live,
3238                           Instruction *TI, bool TermOkay = false) {
3239   for (Value *V : Live) {
3240     if (auto *I = dyn_cast<Instruction>(V)) {
3241       // The terminator can be a member of the LiveOut set.  LLVM's definition
3242       // of instruction dominance states that V does not dominate itself.  As
3243       // such, we need to special case this to allow it.
3244       if (TermOkay && TI == I)
3245         continue;
3246       assert(DT.dominates(I, TI) &&
3247              "basic SSA liveness expectation violated by liveness analysis");
3248     }
3249   }
3250 }
3251 
3252 /// Check that all the liveness sets used during the computation of liveness
3253 /// obey basic SSA properties.  This is useful for finding cases where we miss
3254 /// a def.
3255 static void checkBasicSSA(DominatorTree &DT, GCPtrLivenessData &Data,
3256                           BasicBlock &BB) {
3257   checkBasicSSA(DT, Data.LiveSet[&BB], BB.getTerminator());
3258   checkBasicSSA(DT, Data.LiveOut[&BB], BB.getTerminator(), true);
3259   checkBasicSSA(DT, Data.LiveIn[&BB], BB.getTerminator());
3260 }
3261 #endif
3262 
3263 static void computeLiveInValues(DominatorTree &DT, Function &F,
3264                                 GCPtrLivenessData &Data, GCStrategy *GC) {
3265   SmallSetVector<BasicBlock *, 32> Worklist;
3266 
3267   // Seed the liveness for each individual block
3268   for (BasicBlock &BB : F) {
3269     Data.KillSet[&BB] = computeKillSet(&BB, GC);
3270     Data.LiveSet[&BB].clear();
3271     computeLiveInValues(BB.rbegin(), BB.rend(), Data.LiveSet[&BB], GC);
3272 
3273 #ifndef NDEBUG
3274     for (Value *Kill : Data.KillSet[&BB])
3275       assert(!Data.LiveSet[&BB].count(Kill) && "live set contains kill");
3276 #endif
3277 
3278     Data.LiveOut[&BB] = SetVector<Value *>();
3279     computeLiveOutSeed(&BB, Data.LiveOut[&BB], GC);
3280     Data.LiveIn[&BB] = Data.LiveSet[&BB];
3281     Data.LiveIn[&BB].set_union(Data.LiveOut[&BB]);
3282     Data.LiveIn[&BB].set_subtract(Data.KillSet[&BB]);
3283     if (!Data.LiveIn[&BB].empty())
3284       Worklist.insert(pred_begin(&BB), pred_end(&BB));
3285   }
3286 
3287   // Propagate that liveness until stable
3288   while (!Worklist.empty()) {
3289     BasicBlock *BB = Worklist.pop_back_val();
3290 
3291     // Compute our new liveout set, then exit early if it hasn't changed despite
3292     // the contribution of our successor.
3293     SetVector<Value *> LiveOut = Data.LiveOut[BB];
3294     const auto OldLiveOutSize = LiveOut.size();
3295     for (BasicBlock *Succ : successors(BB)) {
3296       assert(Data.LiveIn.count(Succ));
3297       LiveOut.set_union(Data.LiveIn[Succ]);
3298     }
3299     // assert OutLiveOut is a subset of LiveOut
3300     if (OldLiveOutSize == LiveOut.size()) {
3301       // If the sets are the same size, then we didn't actually add anything
3302       // when unioning our successors LiveIn.  Thus, the LiveIn of this block
3303       // hasn't changed.
3304       continue;
3305     }
3306     Data.LiveOut[BB] = LiveOut;
3307 
3308     // Apply the effects of this basic block
3309     SetVector<Value *> LiveTmp = LiveOut;
3310     LiveTmp.set_union(Data.LiveSet[BB]);
3311     LiveTmp.set_subtract(Data.KillSet[BB]);
3312 
3313     assert(Data.LiveIn.count(BB));
3314     const SetVector<Value *> &OldLiveIn = Data.LiveIn[BB];
3315     // assert: OldLiveIn is a subset of LiveTmp
3316     if (OldLiveIn.size() != LiveTmp.size()) {
3317       Data.LiveIn[BB] = LiveTmp;
3318       Worklist.insert(pred_begin(BB), pred_end(BB));
3319     }
3320   } // while (!Worklist.empty())
3321 
3322 #ifndef NDEBUG
3323   // Verify our output against SSA properties.  This helps catch any
3324   // missing kills during the above iteration.
3325   for (BasicBlock &BB : F)
3326     checkBasicSSA(DT, Data, BB);
3327 #endif
3328 }
3329 
3330 static void findLiveSetAtInst(Instruction *Inst, GCPtrLivenessData &Data,
3331                               StatepointLiveSetTy &Out, GCStrategy *GC) {
3332   BasicBlock *BB = Inst->getParent();
3333 
3334   // Note: The copy is intentional and required
3335   assert(Data.LiveOut.count(BB));
3336   SetVector<Value *> LiveOut = Data.LiveOut[BB];
3337 
3338   // We want to handle the statepoint itself oddly.  It's
3339   // call result is not live (normal), nor are it's arguments
3340   // (unless they're used again later).  This adjustment is
3341   // specifically what we need to relocate
3342   computeLiveInValues(BB->rbegin(), ++Inst->getIterator().getReverse(), LiveOut,
3343                       GC);
3344   LiveOut.remove(Inst);
3345   Out.insert(LiveOut.begin(), LiveOut.end());
3346 }
3347 
3348 static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData,
3349                                   CallBase *Call,
3350                                   PartiallyConstructedSafepointRecord &Info,
3351                                   PointerToBaseTy &PointerToBase,
3352                                   GCStrategy *GC) {
3353   StatepointLiveSetTy Updated;
3354   findLiveSetAtInst(Call, RevisedLivenessData, Updated, GC);
3355 
3356   // We may have base pointers which are now live that weren't before.  We need
3357   // to update the PointerToBase structure to reflect this.
3358   for (auto *V : Updated)
3359     PointerToBase.insert({ V, V });
3360 
3361   Info.LiveSet = Updated;
3362 }
3363