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