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