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