blob: a73e9aec06170652d944f14b8becfded690e1977 [file] [log] [blame]
Philip Reamesd16a9b12015-02-20 01:06:44 +00001//===- RewriteStatepointsForGC.cpp - Make GC relocations explicit ---------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Philip Reamesae800452017-06-02 01:52:06 +000010// Rewrite call/invoke instructions so as to make potential relocations
11// performed by the garbage collector explicit in the IR.
Philip Reamesd16a9b12015-02-20 01:06:44 +000012//
13//===----------------------------------------------------------------------===//
14
Chandler Carruth6bda14b2017-06-06 11:49:48 +000015#include "llvm/ADT/DenseSet.h"
16#include "llvm/ADT/MapVector.h"
17#include "llvm/ADT/SetOperations.h"
18#include "llvm/ADT/SetVector.h"
19#include "llvm/ADT/Statistic.h"
20#include "llvm/ADT/StringRef.h"
Philip Reamesd16a9b12015-02-20 01:06:44 +000021#include "llvm/Analysis/CFG.h"
Igor Laevskye0317182015-05-19 15:59:05 +000022#include "llvm/Analysis/TargetTransformInfo.h"
Philip Reamesd16a9b12015-02-20 01:06:44 +000023#include "llvm/IR/BasicBlock.h"
24#include "llvm/IR/CallSite.h"
25#include "llvm/IR/Dominators.h"
26#include "llvm/IR/Function.h"
27#include "llvm/IR/IRBuilder.h"
28#include "llvm/IR/InstIterator.h"
29#include "llvm/IR/Instructions.h"
Philip Reamesd16a9b12015-02-20 01:06:44 +000030#include "llvm/IR/IntrinsicInst.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000031#include "llvm/IR/Intrinsics.h"
Sanjoy Das353a19e2015-06-02 22:33:37 +000032#include "llvm/IR/MDBuilder.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000033#include "llvm/IR/Module.h"
Philip Reamesd16a9b12015-02-20 01:06:44 +000034#include "llvm/IR/Statepoint.h"
35#include "llvm/IR/Value.h"
36#include "llvm/IR/Verifier.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000037#include "llvm/Pass.h"
Philip Reamesd16a9b12015-02-20 01:06:44 +000038#include "llvm/Support/CommandLine.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000039#include "llvm/Support/Debug.h"
Philip Reamesd16a9b12015-02-20 01:06:44 +000040#include "llvm/Transforms/Scalar.h"
41#include "llvm/Transforms/Utils/BasicBlockUtils.h"
42#include "llvm/Transforms/Utils/Cloning.h"
43#include "llvm/Transforms/Utils/Local.h"
44#include "llvm/Transforms/Utils/PromoteMemToReg.h"
45
46#define DEBUG_TYPE "rewrite-statepoints-for-gc"
47
48using namespace llvm;
49
Philip Reamesd16a9b12015-02-20 01:06:44 +000050// Print the liveset found at the insert location
51static cl::opt<bool> PrintLiveSet("spp-print-liveset", cl::Hidden,
52 cl::init(false));
Philip Reames704e78b2015-04-10 22:34:56 +000053static cl::opt<bool> PrintLiveSetSize("spp-print-liveset-size", cl::Hidden,
54 cl::init(false));
Philip Reamesd16a9b12015-02-20 01:06:44 +000055// Print out the base pointers for debugging
Philip Reames704e78b2015-04-10 22:34:56 +000056static cl::opt<bool> PrintBasePointers("spp-print-base-pointers", cl::Hidden,
57 cl::init(false));
Philip Reamesd16a9b12015-02-20 01:06:44 +000058
Igor Laevskye0317182015-05-19 15:59:05 +000059// Cost threshold measuring when it is profitable to rematerialize value instead
60// of relocating it
61static cl::opt<unsigned>
62RematerializationThreshold("spp-rematerialization-threshold", cl::Hidden,
63 cl::init(6));
64
Filipe Cabecinhas0da99372016-04-29 15:22:48 +000065#ifdef EXPENSIVE_CHECKS
Philip Reamese73300b2015-04-13 16:41:32 +000066static bool ClobberNonLive = true;
67#else
68static bool ClobberNonLive = false;
69#endif
70static cl::opt<bool, true> ClobberNonLiveOverride("rs4gc-clobber-non-live",
71 cl::location(ClobberNonLive),
72 cl::Hidden);
73
Sanjoy Das25ec1a32015-10-16 02:41:00 +000074static cl::opt<bool>
75 AllowStatepointWithNoDeoptInfo("rs4gc-allow-statepoint-with-no-deopt-info",
76 cl::Hidden, cl::init(true));
77
Benjamin Kramer6f665452015-02-20 14:00:58 +000078namespace {
Sanjoy Dasea45f0e2015-06-02 22:33:34 +000079struct RewriteStatepointsForGC : public ModulePass {
Philip Reamesd16a9b12015-02-20 01:06:44 +000080 static char ID; // Pass identification, replacement for typeid
81
Sanjoy Dasea45f0e2015-06-02 22:33:34 +000082 RewriteStatepointsForGC() : ModulePass(ID) {
Philip Reamesd16a9b12015-02-20 01:06:44 +000083 initializeRewriteStatepointsForGCPass(*PassRegistry::getPassRegistry());
84 }
Sanjoy Dasea45f0e2015-06-02 22:33:34 +000085 bool runOnFunction(Function &F);
86 bool runOnModule(Module &M) override {
87 bool Changed = false;
88 for (Function &F : M)
89 Changed |= runOnFunction(F);
Sanjoy Das353a19e2015-06-02 22:33:37 +000090
91 if (Changed) {
Anna Thomas4b027e82017-06-12 21:26:53 +000092 // stripNonValidAttributesAndMetadata asserts that shouldRewriteStatepointsIn
Sanjoy Das353a19e2015-06-02 22:33:37 +000093 // returns true for at least one function in the module. Since at least
94 // one function changed, we know that the precondition is satisfied.
Anna Thomas4b027e82017-06-12 21:26:53 +000095 stripNonValidAttributesAndMetadata(M);
Sanjoy Das353a19e2015-06-02 22:33:37 +000096 }
97
Sanjoy Dasea45f0e2015-06-02 22:33:34 +000098 return Changed;
99 }
Philip Reamesd16a9b12015-02-20 01:06:44 +0000100
101 void getAnalysisUsage(AnalysisUsage &AU) const override {
102 // We add and rewrite a bunch of instructions, but don't really do much
103 // else. We could in theory preserve a lot more analyses here.
104 AU.addRequired<DominatorTreeWrapperPass>();
Igor Laevskye0317182015-05-19 15:59:05 +0000105 AU.addRequired<TargetTransformInfoWrapperPass>();
Philip Reamesd16a9b12015-02-20 01:06:44 +0000106 }
Sanjoy Das353a19e2015-06-02 22:33:37 +0000107
Anna Thomas4b027e82017-06-12 21:26:53 +0000108 /// The IR fed into RewriteStatepointsForGC may have had attributes and
109 /// metadata implying dereferenceability that are no longer valid/correct after
110 /// RewriteStatepointsForGC has run. This is because semantically, after
Sanjoy Das353a19e2015-06-02 22:33:37 +0000111 /// RewriteStatepointsForGC runs, all calls to gc.statepoint "free" the entire
Anna Thomas4b027e82017-06-12 21:26:53 +0000112 /// heap. stripNonValidAttributesAndMetadata (conservatively) restores
113 /// correctness by erasing all attributes in the module that externally imply
114 /// dereferenceability. Similar reasoning also applies to the noalias
115 /// attributes and metadata. gc.statepoint can touch the entire heap including
116 /// noalias objects.
117 void stripNonValidAttributesAndMetadata(Module &M);
Sanjoy Das353a19e2015-06-02 22:33:37 +0000118
Anna Thomas4b027e82017-06-12 21:26:53 +0000119 // Helpers for stripNonValidAttributesAndMetadata
120 void stripNonValidAttributesAndMetadataFromBody(Function &F);
Igor Laevskydde00292015-10-23 22:42:44 +0000121 void stripNonValidAttributesFromPrototype(Function &F);
Anna Thomas4b027e82017-06-12 21:26:53 +0000122 // Certain metadata on instructions are invalid after running RS4GC.
123 // Optimizations that run after RS4GC can incorrectly use this metadata to
124 // optimize functions. We drop such metadata on the instruction.
125 void stripInvalidMetadataFromInstruction(Instruction &I);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000126};
Benjamin Kramer6f665452015-02-20 14:00:58 +0000127} // namespace
Philip Reamesd16a9b12015-02-20 01:06:44 +0000128
129char RewriteStatepointsForGC::ID = 0;
130
Sanjoy Dasea45f0e2015-06-02 22:33:34 +0000131ModulePass *llvm::createRewriteStatepointsForGCPass() {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000132 return new RewriteStatepointsForGC();
133}
134
135INITIALIZE_PASS_BEGIN(RewriteStatepointsForGC, "rewrite-statepoints-for-gc",
136 "Make relocations explicit at statepoints", false, false)
137INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Davide Italiano6f852ee2016-05-16 02:29:53 +0000138INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
Philip Reamesd16a9b12015-02-20 01:06:44 +0000139INITIALIZE_PASS_END(RewriteStatepointsForGC, "rewrite-statepoints-for-gc",
140 "Make relocations explicit at statepoints", false, false)
141
142namespace {
Philip Reamesdf1ef082015-04-10 22:53:14 +0000143struct GCPtrLivenessData {
144 /// Values defined in this block.
Igor Laevskyfb1811d2016-05-04 14:55:36 +0000145 MapVector<BasicBlock *, SetVector<Value *>> KillSet;
Philip Reamesdf1ef082015-04-10 22:53:14 +0000146 /// Values used in this block (and thus live); does not included values
147 /// killed within this block.
Igor Laevskyfb1811d2016-05-04 14:55:36 +0000148 MapVector<BasicBlock *, SetVector<Value *>> LiveSet;
Philip Reamesdf1ef082015-04-10 22:53:14 +0000149
150 /// Values live into this basic block (i.e. used by any
151 /// instruction in this basic block or ones reachable from here)
Igor Laevskyfb1811d2016-05-04 14:55:36 +0000152 MapVector<BasicBlock *, SetVector<Value *>> LiveIn;
Philip Reamesdf1ef082015-04-10 22:53:14 +0000153
154 /// Values live out of this basic block (i.e. live into
155 /// any successor block)
Igor Laevskyfb1811d2016-05-04 14:55:36 +0000156 MapVector<BasicBlock *, SetVector<Value *>> LiveOut;
Philip Reamesdf1ef082015-04-10 22:53:14 +0000157};
158
Philip Reamesd16a9b12015-02-20 01:06:44 +0000159// The type of the internal cache used inside the findBasePointers family
160// of functions. From the callers perspective, this is an opaque type and
161// should not be inspected.
162//
163// In the actual implementation this caches two relations:
164// - The base relation itself (i.e. this pointer is based on that one)
165// - The base defining value relation (i.e. before base_phi insertion)
166// Generally, after the execution of a full findBasePointer call, only the
167// base relation will remain. Internally, we add a mixture of the two
168// types, then update all the second type to the first type
Igor Laevskyfb1811d2016-05-04 14:55:36 +0000169typedef MapVector<Value *, Value *> DefiningValueMapTy;
170typedef SetVector<Value *> StatepointLiveSetTy;
171typedef MapVector<AssertingVH<Instruction>, AssertingVH<Value>>
Sanjoy Das40bdd042015-10-07 21:32:35 +0000172 RematerializedValueMapTy;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000173
Philip Reamesd16a9b12015-02-20 01:06:44 +0000174struct PartiallyConstructedSafepointRecord {
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000175 /// The set of values known to be live across this safepoint
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +0000176 StatepointLiveSetTy LiveSet;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000177
178 /// Mapping from live pointers to a base-defining-value
Igor Laevskyfb1811d2016-05-04 14:55:36 +0000179 MapVector<Value *, Value *> PointerToBase;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000180
Philip Reames0a3240f2015-02-20 21:34:11 +0000181 /// The *new* gc.statepoint instruction itself. This produces the token
182 /// that normal path gc.relocates and the gc.result are tied to.
183 Instruction *StatepointToken;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000184
Philip Reamesf2041322015-02-20 19:26:04 +0000185 /// Instruction to which exceptional gc relocates are attached
186 /// Makes it easier to iterate through them during relocationViaAlloca.
187 Instruction *UnwindToken;
Igor Laevskye0317182015-05-19 15:59:05 +0000188
189 /// Record live values we are rematerialized instead of relocating.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +0000190 /// They are not included into 'LiveSet' field.
Igor Laevskye0317182015-05-19 15:59:05 +0000191 /// Maps rematerialized copy to it's original value.
192 RematerializedValueMapTy RematerializedValues;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000193};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000194}
Philip Reamesd16a9b12015-02-20 01:06:44 +0000195
Sanjoy Das25ec1a32015-10-16 02:41:00 +0000196static ArrayRef<Use> GetDeoptBundleOperands(ImmutableCallSite CS) {
Sanjoy Dasacc43d12016-01-22 19:20:40 +0000197 Optional<OperandBundleUse> DeoptBundle =
198 CS.getOperandBundle(LLVMContext::OB_deopt);
Sanjoy Das25ec1a32015-10-16 02:41:00 +0000199
200 if (!DeoptBundle.hasValue()) {
201 assert(AllowStatepointWithNoDeoptInfo &&
202 "Found non-leaf call without deopt info!");
203 return None;
204 }
205
206 return DeoptBundle.getValue().Inputs;
207}
208
Philip Reamesdf1ef082015-04-10 22:53:14 +0000209/// Compute the live-in set for every basic block in the function
210static void computeLiveInValues(DominatorTree &DT, Function &F,
211 GCPtrLivenessData &Data);
212
213/// Given results from the dataflow liveness computation, find the set of live
214/// Values at a particular instruction.
215static void findLiveSetAtInst(Instruction *inst, GCPtrLivenessData &Data,
216 StatepointLiveSetTy &out);
217
Philip Reamesd16a9b12015-02-20 01:06:44 +0000218// TODO: Once we can get to the GCStrategy, this becomes
Philip Reamesee8f0552015-12-23 01:42:15 +0000219// Optional<bool> isGCManagedPointer(const Type *Ty) const override {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000220
Craig Toppere3dcce92015-08-01 22:20:21 +0000221static bool isGCPointerType(Type *T) {
222 if (auto *PT = dyn_cast<PointerType>(T))
Philip Reamesd16a9b12015-02-20 01:06:44 +0000223 // For the sake of this example GC, we arbitrarily pick addrspace(1) as our
224 // GC managed heap. We know that a pointer into this heap needs to be
225 // updated and that no other pointer does.
Sanjoy Das73c7f262016-06-26 04:55:19 +0000226 return PT->getAddressSpace() == 1;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000227 return false;
228}
229
Philip Reames8531d8c2015-04-10 21:48:25 +0000230// Return true if this type is one which a) is a gc pointer or contains a GC
231// pointer and b) is of a type this code expects to encounter as a live value.
232// (The insertion code will assert that a type which matches (a) and not (b)
Philip Reames704e78b2015-04-10 22:34:56 +0000233// is not encountered.)
Philip Reames8531d8c2015-04-10 21:48:25 +0000234static bool isHandledGCPointerType(Type *T) {
235 // We fully support gc pointers
236 if (isGCPointerType(T))
237 return true;
238 // We partially support vectors of gc pointers. The code will assert if it
239 // can't handle something.
240 if (auto VT = dyn_cast<VectorType>(T))
241 if (isGCPointerType(VT->getElementType()))
242 return true;
243 return false;
244}
245
246#ifndef NDEBUG
247/// Returns true if this type contains a gc pointer whether we know how to
248/// handle that type or not.
249static bool containsGCPtrType(Type *Ty) {
Philip Reames704e78b2015-04-10 22:34:56 +0000250 if (isGCPointerType(Ty))
Philip Reames8531d8c2015-04-10 21:48:25 +0000251 return true;
252 if (VectorType *VT = dyn_cast<VectorType>(Ty))
253 return isGCPointerType(VT->getScalarType());
254 if (ArrayType *AT = dyn_cast<ArrayType>(Ty))
255 return containsGCPtrType(AT->getElementType());
256 if (StructType *ST = dyn_cast<StructType>(Ty))
Sanjoy Das73c7f262016-06-26 04:55:19 +0000257 return any_of(ST->subtypes(), containsGCPtrType);
Philip Reames8531d8c2015-04-10 21:48:25 +0000258 return false;
259}
260
261// Returns true if this is a type which a) is a gc pointer or contains a GC
262// pointer and b) is of a type which the code doesn't expect (i.e. first class
263// aggregates). Used to trip assertions.
264static bool isUnhandledGCPointerType(Type *Ty) {
265 return containsGCPtrType(Ty) && !isHandledGCPointerType(Ty);
266}
267#endif
268
Philip Reamesece70b82015-09-09 23:57:18 +0000269// Return the name of the value suffixed with the provided value, or if the
270// value didn't have a name, the default value specified.
271static std::string suffixed_name_or(Value *V, StringRef Suffix,
272 StringRef DefaultName) {
273 return V->hasName() ? (V->getName() + Suffix).str() : DefaultName.str();
274}
275
Philip Reamesdf1ef082015-04-10 22:53:14 +0000276// Conservatively identifies any definitions which might be live at the
277// given instruction. The analysis is performed immediately before the
278// given instruction. Values defined by that instruction are not considered
279// live. Values used by that instruction are considered live.
Sanjoy Dasa3244872016-06-17 00:45:00 +0000280static void
281analyzeParsePointLiveness(DominatorTree &DT,
282 GCPtrLivenessData &OriginalLivenessData, CallSite CS,
Sanjoy Das1e7eeb42016-06-26 04:55:17 +0000283 PartiallyConstructedSafepointRecord &Result) {
284 Instruction *Inst = CS.getInstruction();
Philip Reamesd16a9b12015-02-20 01:06:44 +0000285
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +0000286 StatepointLiveSetTy LiveSet;
Sanjoy Das1e7eeb42016-06-26 04:55:17 +0000287 findLiveSetAtInst(Inst, OriginalLivenessData, LiveSet);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000288
289 if (PrintLiveSet) {
Sanjoy Das1e7eeb42016-06-26 04:55:17 +0000290 dbgs() << "Live Variables:\n";
Igor Laevskyfb1811d2016-05-04 14:55:36 +0000291 for (Value *V : LiveSet)
Philip Reamesdab35f32015-09-02 21:11:44 +0000292 dbgs() << " " << V->getName() << " " << *V << "\n";
Philip Reamesd16a9b12015-02-20 01:06:44 +0000293 }
294 if (PrintLiveSetSize) {
Sanjoy Das1e7eeb42016-06-26 04:55:17 +0000295 dbgs() << "Safepoint For: " << CS.getCalledValue()->getName() << "\n";
296 dbgs() << "Number live values: " << LiveSet.size() << "\n";
Philip Reamesd16a9b12015-02-20 01:06:44 +0000297 }
Sanjoy Das1e7eeb42016-06-26 04:55:17 +0000298 Result.LiveSet = LiveSet;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000299}
300
Philip Reamesf5b8e472015-09-03 21:34:30 +0000301static bool isKnownBaseResult(Value *V);
302namespace {
303/// A single base defining value - An immediate base defining value for an
304/// instruction 'Def' is an input to 'Def' whose base is also a base of 'Def'.
305/// For instructions which have multiple pointer [vector] inputs or that
306/// transition between vector and scalar types, there is no immediate base
307/// defining value. The 'base defining value' for 'Def' is the transitive
308/// closure of this relation stopping at the first instruction which has no
309/// immediate base defining value. The b.d.v. might itself be a base pointer,
310/// but it can also be an arbitrary derived pointer.
311struct BaseDefiningValueResult {
312 /// Contains the value which is the base defining value.
313 Value * const BDV;
314 /// True if the base defining value is also known to be an actual base
315 /// pointer.
316 const bool IsKnownBase;
317 BaseDefiningValueResult(Value *BDV, bool IsKnownBase)
318 : BDV(BDV), IsKnownBase(IsKnownBase) {
319#ifndef NDEBUG
320 // Check consistency between new and old means of checking whether a BDV is
321 // a base.
322 bool MustBeBase = isKnownBaseResult(BDV);
323 assert(!MustBeBase || MustBeBase == IsKnownBase);
324#endif
325 }
326};
327}
328
329static BaseDefiningValueResult findBaseDefiningValue(Value *I);
Philip Reames311f7102015-05-12 22:19:52 +0000330
Philip Reames8fe7f132015-06-26 22:47:37 +0000331/// Return a base defining value for the 'Index' element of the given vector
332/// instruction 'I'. If Index is null, returns a BDV for the entire vector
333/// 'I'. As an optimization, this method will try to determine when the
334/// element is known to already be a base pointer. If this can be established,
335/// the second value in the returned pair will be true. Note that either a
336/// vector or a pointer typed value can be returned. For the former, the
337/// vector returned is a BDV (and possibly a base) of the entire vector 'I'.
338/// If the later, the return pointer is a BDV (or possibly a base) for the
339/// particular element in 'I'.
Philip Reamesf5b8e472015-09-03 21:34:30 +0000340static BaseDefiningValueResult
Philip Reames66287132015-09-09 23:40:12 +0000341findBaseDefiningValueOfVector(Value *I) {
Philip Reames8531d8c2015-04-10 21:48:25 +0000342 // Each case parallels findBaseDefiningValue below, see that code for
343 // detailed motivation.
344
345 if (isa<Argument>(I))
346 // An incoming argument to the function is a base pointer
Philip Reamesf5b8e472015-09-03 21:34:30 +0000347 return BaseDefiningValueResult(I, true);
Philip Reames8531d8c2015-04-10 21:48:25 +0000348
Manuel Jacob734e7332016-01-09 04:02:16 +0000349 if (isa<Constant>(I))
Igor Laevskydf9db452016-05-27 13:13:59 +0000350 // Base of constant vector consists only of constant null pointers.
351 // For reasoning see similar case inside 'findBaseDefiningValue' function.
352 return BaseDefiningValueResult(ConstantAggregateZero::get(I->getType()),
353 true);
Philip Reames8531d8c2015-04-10 21:48:25 +0000354
Philip Reames8531d8c2015-04-10 21:48:25 +0000355 if (isa<LoadInst>(I))
Philip Reamesf5b8e472015-09-03 21:34:30 +0000356 return BaseDefiningValueResult(I, true);
Philip Reamesf5b8e472015-09-03 21:34:30 +0000357
Philip Reames66287132015-09-09 23:40:12 +0000358 if (isa<InsertElementInst>(I))
Philip Reames8fe7f132015-06-26 22:47:37 +0000359 // We don't know whether this vector contains entirely base pointers or
360 // not. To be conservatively correct, we treat it as a BDV and will
361 // duplicate code as needed to construct a parallel vector of bases.
Philip Reames66287132015-09-09 23:40:12 +0000362 return BaseDefiningValueResult(I, false);
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +0000363
Philip Reames8fe7f132015-06-26 22:47:37 +0000364 if (isa<ShuffleVectorInst>(I))
365 // We don't know whether this vector contains entirely base pointers or
366 // not. To be conservatively correct, we treat it as a BDV and will
367 // duplicate code as needed to construct a parallel vector of bases.
368 // TODO: There a number of local optimizations which could be applied here
369 // for particular sufflevector patterns.
Philip Reamesf5b8e472015-09-03 21:34:30 +0000370 return BaseDefiningValueResult(I, false);
Philip Reames8fe7f132015-06-26 22:47:37 +0000371
Sanjoy Dasc4e4dcd2017-03-17 00:55:53 +0000372 // The behavior of getelementptr instructions is the same for vector and
373 // non-vector data types.
374 if (auto *GEP = dyn_cast<GetElementPtrInst>(I))
375 return findBaseDefiningValue(GEP->getPointerOperand());
376
Philip Reames8fe7f132015-06-26 22:47:37 +0000377 // A PHI or Select is a base defining value. The outer findBasePointer
378 // algorithm is responsible for constructing a base value for this BDV.
379 assert((isa<SelectInst>(I) || isa<PHINode>(I)) &&
380 "unknown vector instruction - no base found for vector element");
Philip Reamesf5b8e472015-09-03 21:34:30 +0000381 return BaseDefiningValueResult(I, false);
Philip Reames8531d8c2015-04-10 21:48:25 +0000382}
383
Philip Reamesd16a9b12015-02-20 01:06:44 +0000384/// Helper function for findBasePointer - Will return a value which either a)
Philip Reames9ac4e382015-08-12 21:00:20 +0000385/// defines the base pointer for the input, b) blocks the simple search
386/// (i.e. a PHI or Select of two derived pointers), or c) involves a change
387/// from pointer to vector type or back.
Philip Reamesf5b8e472015-09-03 21:34:30 +0000388static BaseDefiningValueResult findBaseDefiningValue(Value *I) {
Manuel Jacob0593cfd2016-01-09 03:08:49 +0000389 assert(I->getType()->isPtrOrPtrVectorTy() &&
390 "Illegal to ask for the base pointer of a non-pointer type");
391
Philip Reames8fe7f132015-06-26 22:47:37 +0000392 if (I->getType()->isVectorTy())
Philip Reamesf5b8e472015-09-03 21:34:30 +0000393 return findBaseDefiningValueOfVector(I);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000394
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000395 if (isa<Argument>(I))
Philip Reamesd16a9b12015-02-20 01:06:44 +0000396 // An incoming argument to the function is a base pointer
397 // We should have never reached here if this argument isn't an gc value
Philip Reamesf5b8e472015-09-03 21:34:30 +0000398 return BaseDefiningValueResult(I, true);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000399
Igor Laevskydf9db452016-05-27 13:13:59 +0000400 if (isa<Constant>(I)) {
Manuel Jacob75cbfdc2016-01-05 04:06:21 +0000401 // We assume that objects with a constant base (e.g. a global) can't move
402 // and don't need to be reported to the collector because they are always
Igor Laevskydf9db452016-05-27 13:13:59 +0000403 // live. Besides global references, all kinds of constants (e.g. undef,
404 // constant expressions, null pointers) can be introduced by the inliner or
405 // the optimizer, especially on dynamically dead paths.
406 // Here we treat all of them as having single null base. By doing this we
407 // trying to avoid problems reporting various conflicts in a form of
408 // "phi (const1, const2)" or "phi (const, regular gc ptr)".
409 // See constant.ll file for relevant test cases.
410
411 return BaseDefiningValueResult(
412 ConstantPointerNull::get(cast<PointerType>(I->getType())), true);
413 }
Philip Reamesd16a9b12015-02-20 01:06:44 +0000414
Philip Reamesd16a9b12015-02-20 01:06:44 +0000415 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000416 Value *Def = CI->stripPointerCasts();
Manuel Jacob8050a492015-12-21 01:26:46 +0000417 // If stripping pointer casts changes the address space there is an
418 // addrspacecast in between.
419 assert(cast<PointerType>(Def->getType())->getAddressSpace() ==
420 cast<PointerType>(CI->getType())->getAddressSpace() &&
421 "unsupported addrspacecast");
David Blaikie82ad7872015-02-20 23:44:24 +0000422 // If we find a cast instruction here, it means we've found a cast which is
423 // not simply a pointer cast (i.e. an inttoptr). We don't know how to
424 // handle int->ptr conversion.
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000425 assert(!isa<CastInst>(Def) && "shouldn't find another cast here");
426 return findBaseDefiningValue(Def);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000427 }
428
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000429 if (isa<LoadInst>(I))
Philip Reamesf5b8e472015-09-03 21:34:30 +0000430 // The value loaded is an gc base itself
431 return BaseDefiningValueResult(I, true);
432
Philip Reamesd16a9b12015-02-20 01:06:44 +0000433
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000434 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I))
435 // The base of this GEP is the base
436 return findBaseDefiningValue(GEP->getPointerOperand());
Philip Reamesd16a9b12015-02-20 01:06:44 +0000437
438 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
439 switch (II->getIntrinsicID()) {
440 default:
441 // fall through to general call handling
442 break;
443 case Intrinsic::experimental_gc_statepoint:
Manuel Jacob4e4f60d2015-12-22 18:44:45 +0000444 llvm_unreachable("statepoints don't produce pointers");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000445 case Intrinsic::experimental_gc_relocate: {
446 // Rerunning safepoint insertion after safepoints are already
447 // inserted is not supported. It could probably be made to work,
448 // but why are you doing this? There's no good reason.
449 llvm_unreachable("repeat safepoint insertion is not supported");
450 }
451 case Intrinsic::gcroot:
452 // Currently, this mechanism hasn't been extended to work with gcroot.
453 // There's no reason it couldn't be, but I haven't thought about the
454 // implications much.
455 llvm_unreachable(
456 "interaction with the gcroot mechanism is not supported");
457 }
458 }
459 // We assume that functions in the source language only return base
460 // pointers. This should probably be generalized via attributes to support
461 // both source language and internal functions.
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000462 if (isa<CallInst>(I) || isa<InvokeInst>(I))
Philip Reamesf5b8e472015-09-03 21:34:30 +0000463 return BaseDefiningValueResult(I, true);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000464
Anna Thomas488c0572016-10-06 13:24:20 +0000465 // TODO: I have absolutely no idea how to implement this part yet. It's not
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000466 // necessarily hard, I just haven't really looked at it yet.
Philip Reamesd16a9b12015-02-20 01:06:44 +0000467 assert(!isa<LandingPadInst>(I) && "Landing Pad is unimplemented");
468
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000469 if (isa<AtomicCmpXchgInst>(I))
Philip Reamesd16a9b12015-02-20 01:06:44 +0000470 // A CAS is effectively a atomic store and load combined under a
471 // predicate. From the perspective of base pointers, we just treat it
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000472 // like a load.
Philip Reamesf5b8e472015-09-03 21:34:30 +0000473 return BaseDefiningValueResult(I, true);
Philip Reames704e78b2015-04-10 22:34:56 +0000474
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000475 assert(!isa<AtomicRMWInst>(I) && "Xchg handled above, all others are "
Philip Reames704e78b2015-04-10 22:34:56 +0000476 "binary ops which don't apply to pointers");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000477
478 // The aggregate ops. Aggregates can either be in the heap or on the
479 // stack, but in either case, this is simply a field load. As a result,
480 // this is a defining definition of the base just like a load is.
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000481 if (isa<ExtractValueInst>(I))
Philip Reamesf5b8e472015-09-03 21:34:30 +0000482 return BaseDefiningValueResult(I, true);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000483
484 // We should never see an insert vector since that would require we be
485 // tracing back a struct value not a pointer value.
486 assert(!isa<InsertValueInst>(I) &&
487 "Base pointer for a struct is meaningless");
488
Philip Reames9ac4e382015-08-12 21:00:20 +0000489 // An extractelement produces a base result exactly when it's input does.
490 // We may need to insert a parallel instruction to extract the appropriate
491 // element out of the base vector corresponding to the input. Given this,
492 // it's analogous to the phi and select case even though it's not a merge.
Philip Reames66287132015-09-09 23:40:12 +0000493 if (isa<ExtractElementInst>(I))
494 // Note: There a lot of obvious peephole cases here. This are deliberately
495 // handled after the main base pointer inference algorithm to make writing
496 // test cases to exercise that code easier.
497 return BaseDefiningValueResult(I, false);
Philip Reames9ac4e382015-08-12 21:00:20 +0000498
Philip Reamesd16a9b12015-02-20 01:06:44 +0000499 // The last two cases here don't return a base pointer. Instead, they
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000500 // return a value which dynamically selects from among several base
Philip Reamesd16a9b12015-02-20 01:06:44 +0000501 // derived pointers (each with it's own base potentially). It's the job of
502 // the caller to resolve these.
Philip Reames704e78b2015-04-10 22:34:56 +0000503 assert((isa<SelectInst>(I) || isa<PHINode>(I)) &&
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000504 "missing instruction case in findBaseDefiningValing");
Philip Reamesf5b8e472015-09-03 21:34:30 +0000505 return BaseDefiningValueResult(I, false);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000506}
507
508/// Returns the base defining value for this value.
Philip Reames18d0feb2015-03-27 05:39:32 +0000509static Value *findBaseDefiningValueCached(Value *I, DefiningValueMapTy &Cache) {
510 Value *&Cached = Cache[I];
Benjamin Kramer6f665452015-02-20 14:00:58 +0000511 if (!Cached) {
Philip Reamesf5b8e472015-09-03 21:34:30 +0000512 Cached = findBaseDefiningValue(I).BDV;
Philip Reames2a892a62015-07-23 22:25:26 +0000513 DEBUG(dbgs() << "fBDV-cached: " << I->getName() << " -> "
514 << Cached->getName() << "\n");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000515 }
Philip Reames18d0feb2015-03-27 05:39:32 +0000516 assert(Cache[I] != nullptr);
Benjamin Kramer6f665452015-02-20 14:00:58 +0000517 return Cached;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000518}
519
520/// Return a base pointer for this value if known. Otherwise, return it's
521/// base defining value.
Philip Reames18d0feb2015-03-27 05:39:32 +0000522static Value *findBaseOrBDV(Value *I, DefiningValueMapTy &Cache) {
523 Value *Def = findBaseDefiningValueCached(I, Cache);
524 auto Found = Cache.find(Def);
525 if (Found != Cache.end()) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000526 // Either a base-of relation, or a self reference. Caller must check.
Benjamin Kramer6f665452015-02-20 14:00:58 +0000527 return Found->second;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000528 }
529 // Only a BDV available
Philip Reames18d0feb2015-03-27 05:39:32 +0000530 return Def;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000531}
532
533/// Given the result of a call to findBaseDefiningValue, or findBaseOrBDV,
534/// is it known to be a base pointer? Or do we need to continue searching.
Philip Reames18d0feb2015-03-27 05:39:32 +0000535static bool isKnownBaseResult(Value *V) {
Philip Reames66287132015-09-09 23:40:12 +0000536 if (!isa<PHINode>(V) && !isa<SelectInst>(V) &&
537 !isa<ExtractElementInst>(V) && !isa<InsertElementInst>(V) &&
538 !isa<ShuffleVectorInst>(V)) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000539 // no recursion possible
540 return true;
541 }
Philip Reames18d0feb2015-03-27 05:39:32 +0000542 if (isa<Instruction>(V) &&
543 cast<Instruction>(V)->getMetadata("is_base_value")) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000544 // This is a previously inserted base phi or select. We know
545 // that this is a base value.
546 return true;
547 }
548
549 // We need to keep searching
550 return false;
551}
552
Philip Reamesd16a9b12015-02-20 01:06:44 +0000553namespace {
Philip Reames9b141ed2015-07-23 22:49:14 +0000554/// Models the state of a single base defining value in the findBasePointer
555/// algorithm for determining where a new instruction is needed to propagate
556/// the base of this BDV.
557class BDVState {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000558public:
559 enum Status { Unknown, Base, Conflict };
560
Sanjoy Das7dda0ed2016-06-26 04:55:35 +0000561 BDVState() : Status(Unknown), BaseValue(nullptr) {}
Philip Reamesd16a9b12015-02-20 01:06:44 +0000562
Sanjoy Das7dda0ed2016-06-26 04:55:35 +0000563 explicit BDVState(Status Status, Value *BaseValue = nullptr)
564 : Status(Status), BaseValue(BaseValue) {
565 assert(Status != Base || BaseValue);
566 }
567
568 explicit BDVState(Value *BaseValue) : Status(Base), BaseValue(BaseValue) {}
569
570 Status getStatus() const { return Status; }
571 Value *getBaseValue() const { return BaseValue; }
Philip Reamesd16a9b12015-02-20 01:06:44 +0000572
573 bool isBase() const { return getStatus() == Base; }
574 bool isUnknown() const { return getStatus() == Unknown; }
575 bool isConflict() const { return getStatus() == Conflict; }
576
Sanjoy Das7dda0ed2016-06-26 04:55:35 +0000577 bool operator==(const BDVState &Other) const {
578 return BaseValue == Other.BaseValue && Status == Other.Status;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000579 }
580
Philip Reames9b141ed2015-07-23 22:49:14 +0000581 bool operator!=(const BDVState &other) const { return !(*this == other); }
Philip Reamesd16a9b12015-02-20 01:06:44 +0000582
Philip Reames2a892a62015-07-23 22:25:26 +0000583 LLVM_DUMP_METHOD
Sanjoy Das7dda0ed2016-06-26 04:55:35 +0000584 void dump() const {
585 print(dbgs());
586 dbgs() << '\n';
587 }
588
Philip Reames2a892a62015-07-23 22:25:26 +0000589 void print(raw_ostream &OS) const {
Sanjoy Das7dda0ed2016-06-26 04:55:35 +0000590 switch (getStatus()) {
Philip Reamesdab35f32015-09-02 21:11:44 +0000591 case Unknown:
592 OS << "U";
593 break;
594 case Base:
595 OS << "B";
596 break;
597 case Conflict:
598 OS << "C";
599 break;
600 };
Sanjoy Das7dda0ed2016-06-26 04:55:35 +0000601 OS << " (" << getBaseValue() << " - "
602 << (getBaseValue() ? getBaseValue()->getName() : "nullptr") << "): ";
Philip Reamesd16a9b12015-02-20 01:06:44 +0000603 }
604
605private:
Sanjoy Das7dda0ed2016-06-26 04:55:35 +0000606 Status Status;
607 AssertingVH<Value> BaseValue; // Non-null only if Status == Base.
Philip Reamesd16a9b12015-02-20 01:06:44 +0000608};
Philip Reamesb3967cd2015-09-02 22:30:53 +0000609}
Philip Reamesd16a9b12015-02-20 01:06:44 +0000610
Philip Reames6906e922015-09-02 21:57:17 +0000611#ifndef NDEBUG
Philip Reamesb3967cd2015-09-02 22:30:53 +0000612static raw_ostream &operator<<(raw_ostream &OS, const BDVState &State) {
Philip Reames2a892a62015-07-23 22:25:26 +0000613 State.print(OS);
614 return OS;
615}
Philip Reames6906e922015-09-02 21:57:17 +0000616#endif
Philip Reames2a892a62015-07-23 22:25:26 +0000617
Sanjoy Das6cf88092016-06-26 04:55:13 +0000618static BDVState meetBDVStateImpl(const BDVState &LHS, const BDVState &RHS) {
619 switch (LHS.getStatus()) {
Sanjoy Dasbd43d0e2016-06-26 04:55:10 +0000620 case BDVState::Unknown:
Sanjoy Das6cf88092016-06-26 04:55:13 +0000621 return RHS;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000622
Sanjoy Dasbd43d0e2016-06-26 04:55:10 +0000623 case BDVState::Base:
Sanjoy Das7dda0ed2016-06-26 04:55:35 +0000624 assert(LHS.getBaseValue() && "can't be null");
Sanjoy Das6cf88092016-06-26 04:55:13 +0000625 if (RHS.isUnknown())
626 return LHS;
Sanjoy Dasbd43d0e2016-06-26 04:55:10 +0000627
Sanjoy Das6cf88092016-06-26 04:55:13 +0000628 if (RHS.isBase()) {
Sanjoy Das7dda0ed2016-06-26 04:55:35 +0000629 if (LHS.getBaseValue() == RHS.getBaseValue()) {
Sanjoy Das6cf88092016-06-26 04:55:13 +0000630 assert(LHS == RHS && "equality broken!");
631 return LHS;
Sanjoy Dasbd43d0e2016-06-26 04:55:10 +0000632 }
633 return BDVState(BDVState::Conflict);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000634 }
Sanjoy Das6cf88092016-06-26 04:55:13 +0000635 assert(RHS.isConflict() && "only three states!");
Sanjoy Dasbd43d0e2016-06-26 04:55:10 +0000636 return BDVState(BDVState::Conflict);
637
638 case BDVState::Conflict:
Sanjoy Das6cf88092016-06-26 04:55:13 +0000639 return LHS;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000640 }
Sanjoy Dasbd43d0e2016-06-26 04:55:10 +0000641 llvm_unreachable("only three states!");
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000642}
Philip Reamesb3967cd2015-09-02 22:30:53 +0000643
Sanjoy Dasbd43d0e2016-06-26 04:55:10 +0000644// Values of type BDVState form a lattice, and this function implements the meet
645// operation.
Benjamin Kramer061f4a52017-01-13 14:39:03 +0000646static BDVState meetBDVState(const BDVState &LHS, const BDVState &RHS) {
Sanjoy Dasbd43d0e2016-06-26 04:55:10 +0000647 BDVState Result = meetBDVStateImpl(LHS, RHS);
648 assert(Result == meetBDVStateImpl(RHS, LHS) &&
649 "Math is wrong: meet does not commute!");
650 return Result;
651}
Philip Reamesb3967cd2015-09-02 22:30:53 +0000652
Sanjoy Das90547f12016-06-26 04:55:05 +0000653/// For a given value or instruction, figure out what base ptr its derived from.
654/// For gc objects, this is simply itself. On success, returns a value which is
655/// the base pointer. (This is reliable and can be used for relocation.) On
656/// failure, returns nullptr.
657static Value *findBasePointer(Value *I, DefiningValueMapTy &Cache) {
658 Value *Def = findBaseOrBDV(I, Cache);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000659
Sanjoy Das90547f12016-06-26 04:55:05 +0000660 if (isKnownBaseResult(Def))
661 return Def;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000662
663 // Here's the rough algorithm:
664 // - For every SSA value, construct a mapping to either an actual base
665 // pointer or a PHI which obscures the base pointer.
666 // - Construct a mapping from PHI to unknown TOP state. Use an
667 // optimistic algorithm to propagate base pointer information. Lattice
668 // looks like:
669 // UNKNOWN
670 // b1 b2 b3 b4
671 // CONFLICT
672 // When algorithm terminates, all PHIs will either have a single concrete
673 // base or be in a conflict state.
674 // - For every conflict, insert a dummy PHI node without arguments. Add
675 // these to the base[Instruction] = BasePtr mapping. For every
676 // non-conflict, add the actual base.
677 // - For every conflict, add arguments for the base[a] of each input
678 // arguments.
679 //
680 // Note: A simpler form of this would be to add the conflict form of all
681 // PHIs without running the optimistic algorithm. This would be
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000682 // analogous to pessimistic data flow and would likely lead to an
Philip Reamesd16a9b12015-02-20 01:06:44 +0000683 // overall worse solution.
684
Philip Reames29e9ae72015-07-24 00:42:55 +0000685#ifndef NDEBUG
Philip Reames88958b22015-07-24 00:02:11 +0000686 auto isExpectedBDVType = [](Value *BDV) {
Philip Reames66287132015-09-09 23:40:12 +0000687 return isa<PHINode>(BDV) || isa<SelectInst>(BDV) ||
Anna Thomas479cbb92016-10-04 13:48:37 +0000688 isa<ExtractElementInst>(BDV) || isa<InsertElementInst>(BDV) ||
689 isa<ShuffleVectorInst>(BDV);
Philip Reames88958b22015-07-24 00:02:11 +0000690 };
Philip Reames29e9ae72015-07-24 00:42:55 +0000691#endif
Philip Reames88958b22015-07-24 00:02:11 +0000692
693 // Once populated, will contain a mapping from each potentially non-base BDV
694 // to a lattice value (described above) which corresponds to that BDV.
Philip Reames15d55632015-09-09 23:26:08 +0000695 // We use the order of insertion (DFS over the def/use graph) to provide a
696 // stable deterministic ordering for visiting DenseMaps (which are unordered)
697 // below. This is important for deterministic compilation.
Philip Reames34d7a742015-09-10 00:22:49 +0000698 MapVector<Value *, BDVState> States;
Philip Reames15d55632015-09-09 23:26:08 +0000699
700 // Recursively fill in all base defining values reachable from the initial
701 // one for which we don't already know a definite base value for
Philip Reames88958b22015-07-24 00:02:11 +0000702 /* scope */ {
Philip Reames88958b22015-07-24 00:02:11 +0000703 SmallVector<Value*, 16> Worklist;
Sanjoy Das90547f12016-06-26 04:55:05 +0000704 Worklist.push_back(Def);
705 States.insert({Def, BDVState()});
Philip Reames88958b22015-07-24 00:02:11 +0000706 while (!Worklist.empty()) {
707 Value *Current = Worklist.pop_back_val();
708 assert(!isKnownBaseResult(Current) && "why did it get added?");
709
710 auto visitIncomingValue = [&](Value *InVal) {
Sanjoy Das90547f12016-06-26 04:55:05 +0000711 Value *Base = findBaseOrBDV(InVal, Cache);
Philip Reames88958b22015-07-24 00:02:11 +0000712 if (isKnownBaseResult(Base))
713 // Known bases won't need new instructions introduced and can be
714 // ignored safely
715 return;
716 assert(isExpectedBDVType(Base) && "the only non-base values "
717 "we see should be base defining values");
Philip Reames34d7a742015-09-10 00:22:49 +0000718 if (States.insert(std::make_pair(Base, BDVState())).second)
Philip Reames88958b22015-07-24 00:02:11 +0000719 Worklist.push_back(Base);
720 };
Sanjoy Das90547f12016-06-26 04:55:05 +0000721 if (PHINode *PN = dyn_cast<PHINode>(Current)) {
722 for (Value *InVal : PN->incoming_values())
Philip Reames88958b22015-07-24 00:02:11 +0000723 visitIncomingValue(InVal);
Sanjoy Das90547f12016-06-26 04:55:05 +0000724 } else if (SelectInst *SI = dyn_cast<SelectInst>(Current)) {
725 visitIncomingValue(SI->getTrueValue());
726 visitIncomingValue(SI->getFalseValue());
Philip Reames9ac4e382015-08-12 21:00:20 +0000727 } else if (auto *EE = dyn_cast<ExtractElementInst>(Current)) {
728 visitIncomingValue(EE->getVectorOperand());
Philip Reames66287132015-09-09 23:40:12 +0000729 } else if (auto *IE = dyn_cast<InsertElementInst>(Current)) {
730 visitIncomingValue(IE->getOperand(0)); // vector operand
731 visitIncomingValue(IE->getOperand(1)); // scalar operand
Anna Thomas479cbb92016-10-04 13:48:37 +0000732 } else if (auto *SV = dyn_cast<ShuffleVectorInst>(Current)) {
733 visitIncomingValue(SV->getOperand(0));
734 visitIncomingValue(SV->getOperand(1));
735 }
736 else {
Sanjoy Das90547f12016-06-26 04:55:05 +0000737 llvm_unreachable("Unimplemented instruction case");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000738 }
739 }
740 }
741
Philip Reamesdab35f32015-09-02 21:11:44 +0000742#ifndef NDEBUG
743 DEBUG(dbgs() << "States after initialization:\n");
Sanjoy Das9d086422016-06-26 05:42:52 +0000744 for (auto Pair : States) {
Philip Reamesdab35f32015-09-02 21:11:44 +0000745 DEBUG(dbgs() << " " << Pair.second << " for " << *Pair.first << "\n");
Sanjoy Das9d086422016-06-26 05:42:52 +0000746 }
Philip Reamesdab35f32015-09-02 21:11:44 +0000747#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +0000748
Philip Reames273e6bb2015-07-23 21:41:27 +0000749 // Return a phi state for a base defining value. We'll generate a new
750 // base state for known bases and expect to find a cached state otherwise.
751 auto getStateForBDV = [&](Value *baseValue) {
752 if (isKnownBaseResult(baseValue))
Philip Reames9b141ed2015-07-23 22:49:14 +0000753 return BDVState(baseValue);
Philip Reames34d7a742015-09-10 00:22:49 +0000754 auto I = States.find(baseValue);
755 assert(I != States.end() && "lookup failed!");
Philip Reames273e6bb2015-07-23 21:41:27 +0000756 return I->second;
757 };
758
Sanjoy Das90547f12016-06-26 04:55:05 +0000759 bool Progress = true;
760 while (Progress) {
Yaron Keren42a7adf2015-02-28 13:11:24 +0000761#ifndef NDEBUG
Sanjoy Das90547f12016-06-26 04:55:05 +0000762 const size_t OldSize = States.size();
Yaron Keren42a7adf2015-02-28 13:11:24 +0000763#endif
Sanjoy Das90547f12016-06-26 04:55:05 +0000764 Progress = false;
Philip Reames15d55632015-09-09 23:26:08 +0000765 // We're only changing values in this loop, thus safe to keep iterators.
766 // Since this is computing a fixed point, the order of visit does not
767 // effect the result. TODO: We could use a worklist here and make this run
768 // much faster.
Philip Reames34d7a742015-09-10 00:22:49 +0000769 for (auto Pair : States) {
Philip Reamesece70b82015-09-09 23:57:18 +0000770 Value *BDV = Pair.first;
771 assert(!isKnownBaseResult(BDV) && "why did it get added?");
Philip Reames273e6bb2015-07-23 21:41:27 +0000772
Philip Reames9b141ed2015-07-23 22:49:14 +0000773 // Given an input value for the current instruction, return a BDVState
Philip Reames273e6bb2015-07-23 21:41:27 +0000774 // instance which represents the BDV of that value.
775 auto getStateForInput = [&](Value *V) mutable {
Sanjoy Das90547f12016-06-26 04:55:05 +0000776 Value *BDV = findBaseOrBDV(V, Cache);
Philip Reames273e6bb2015-07-23 21:41:27 +0000777 return getStateForBDV(BDV);
778 };
779
Sanjoy Dasbd43d0e2016-06-26 04:55:10 +0000780 BDVState NewState;
Sanjoy Das90547f12016-06-26 04:55:05 +0000781 if (SelectInst *SI = dyn_cast<SelectInst>(BDV)) {
Sanjoy Dasbd43d0e2016-06-26 04:55:10 +0000782 NewState = meetBDVState(NewState, getStateForInput(SI->getTrueValue()));
783 NewState =
784 meetBDVState(NewState, getStateForInput(SI->getFalseValue()));
Sanjoy Das90547f12016-06-26 04:55:05 +0000785 } else if (PHINode *PN = dyn_cast<PHINode>(BDV)) {
786 for (Value *Val : PN->incoming_values())
Sanjoy Dasbd43d0e2016-06-26 04:55:10 +0000787 NewState = meetBDVState(NewState, getStateForInput(Val));
Philip Reamesece70b82015-09-09 23:57:18 +0000788 } else if (auto *EE = dyn_cast<ExtractElementInst>(BDV)) {
Philip Reames9ac4e382015-08-12 21:00:20 +0000789 // The 'meet' for an extractelement is slightly trivial, but it's still
790 // useful in that it drives us to conflict if our input is.
Sanjoy Dasbd43d0e2016-06-26 04:55:10 +0000791 NewState =
792 meetBDVState(NewState, getStateForInput(EE->getVectorOperand()));
Anna Thomas479cbb92016-10-04 13:48:37 +0000793 } else if (auto *IE = dyn_cast<InsertElementInst>(BDV)){
Philip Reames66287132015-09-09 23:40:12 +0000794 // Given there's a inherent type mismatch between the operands, will
795 // *always* produce Conflict.
Sanjoy Dasbd43d0e2016-06-26 04:55:10 +0000796 NewState = meetBDVState(NewState, getStateForInput(IE->getOperand(0)));
797 NewState = meetBDVState(NewState, getStateForInput(IE->getOperand(1)));
Anna Thomas479cbb92016-10-04 13:48:37 +0000798 } else {
799 // The only instance this does not return a Conflict is when both the
800 // vector operands are the same vector.
801 auto *SV = cast<ShuffleVectorInst>(BDV);
802 NewState = meetBDVState(NewState, getStateForInput(SV->getOperand(0)));
803 NewState = meetBDVState(NewState, getStateForInput(SV->getOperand(1)));
Philip Reames9ac4e382015-08-12 21:00:20 +0000804 }
805
Sanjoy Das90547f12016-06-26 04:55:05 +0000806 BDVState OldState = States[BDV];
Sanjoy Das90547f12016-06-26 04:55:05 +0000807 if (OldState != NewState) {
808 Progress = true;
809 States[BDV] = NewState;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000810 }
811 }
812
Sanjoy Das90547f12016-06-26 04:55:05 +0000813 assert(OldSize == States.size() &&
Philip Reamesb4e55f32015-09-10 00:32:56 +0000814 "fixed point shouldn't be adding any new nodes to state");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000815 }
816
Philip Reamesdab35f32015-09-02 21:11:44 +0000817#ifndef NDEBUG
818 DEBUG(dbgs() << "States after meet iteration:\n");
Sanjoy Das9d086422016-06-26 05:42:52 +0000819 for (auto Pair : States) {
Philip Reamesdab35f32015-09-02 21:11:44 +0000820 DEBUG(dbgs() << " " << Pair.second << " for " << *Pair.first << "\n");
Sanjoy Das9d086422016-06-26 05:42:52 +0000821 }
Philip Reamesdab35f32015-09-02 21:11:44 +0000822#endif
Sanjoy Das90547f12016-06-26 04:55:05 +0000823
Philip Reamesd16a9b12015-02-20 01:06:44 +0000824 // Insert Phis for all conflicts
Philip Reames2e5bcbe2015-02-28 01:52:09 +0000825 // TODO: adjust naming patterns to avoid this order of iteration dependency
Philip Reames34d7a742015-09-10 00:22:49 +0000826 for (auto Pair : States) {
Philip Reames15d55632015-09-09 23:26:08 +0000827 Instruction *I = cast<Instruction>(Pair.first);
828 BDVState State = Pair.second;
Philip Reames6ff1a1e32015-07-21 19:04:38 +0000829 assert(!isKnownBaseResult(I) && "why did it get added?");
830 assert(!State.isUnknown() && "Optimistic algorithm didn't complete!");
Philip Reames9ac4e382015-08-12 21:00:20 +0000831
832 // extractelement instructions are a bit special in that we may need to
833 // insert an extract even when we know an exact base for the instruction.
834 // The problem is that we need to convert from a vector base to a scalar
835 // base for the particular indice we're interested in.
836 if (State.isBase() && isa<ExtractElementInst>(I) &&
Sanjoy Das7dda0ed2016-06-26 04:55:35 +0000837 isa<VectorType>(State.getBaseValue()->getType())) {
Philip Reames9ac4e382015-08-12 21:00:20 +0000838 auto *EE = cast<ExtractElementInst>(I);
839 // TODO: In many cases, the new instruction is just EE itself. We should
840 // exploit this, but can't do it here since it would break the invariant
841 // about the BDV not being known to be a base.
Sanjoy Das90547f12016-06-26 04:55:05 +0000842 auto *BaseInst = ExtractElementInst::Create(
Sanjoy Das7dda0ed2016-06-26 04:55:35 +0000843 State.getBaseValue(), EE->getIndexOperand(), "base_ee", EE);
Philip Reames9ac4e382015-08-12 21:00:20 +0000844 BaseInst->setMetadata("is_base_value", MDNode::get(I->getContext(), {}));
Philip Reames34d7a742015-09-10 00:22:49 +0000845 States[I] = BDVState(BDVState::Base, BaseInst);
Philip Reames9ac4e382015-08-12 21:00:20 +0000846 }
Philip Reames66287132015-09-09 23:40:12 +0000847
848 // Since we're joining a vector and scalar base, they can never be the
849 // same. As a result, we should always see insert element having reached
850 // the conflict state.
Sanjoy Das90547f12016-06-26 04:55:05 +0000851 assert(!isa<InsertElementInst>(I) || State.isConflict());
852
Philip Reames6ff1a1e32015-07-21 19:04:38 +0000853 if (!State.isConflict())
Philip Reamesf986d682015-02-28 00:54:41 +0000854 continue;
Philip Reames704e78b2015-04-10 22:34:56 +0000855
Philip Reames6ff1a1e32015-07-21 19:04:38 +0000856 /// Create and insert a new instruction which will represent the base of
857 /// the given instruction 'I'.
858 auto MakeBaseInstPlaceholder = [](Instruction *I) -> Instruction* {
859 if (isa<PHINode>(I)) {
860 BasicBlock *BB = I->getParent();
861 int NumPreds = std::distance(pred_begin(BB), pred_end(BB));
862 assert(NumPreds > 0 && "how did we reach here");
Philip Reamesece70b82015-09-09 23:57:18 +0000863 std::string Name = suffixed_name_or(I, ".base", "base_phi");
Philip Reamesfa2c6302015-07-24 19:01:39 +0000864 return PHINode::Create(I->getType(), NumPreds, Name, I);
Sanjoy Das90547f12016-06-26 04:55:05 +0000865 } else if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
Philip Reames9ac4e382015-08-12 21:00:20 +0000866 // The undef will be replaced later
Sanjoy Das90547f12016-06-26 04:55:05 +0000867 UndefValue *Undef = UndefValue::get(SI->getType());
Philip Reamesece70b82015-09-09 23:57:18 +0000868 std::string Name = suffixed_name_or(I, ".base", "base_select");
Sanjoy Das90547f12016-06-26 04:55:05 +0000869 return SelectInst::Create(SI->getCondition(), Undef, Undef, Name, SI);
Philip Reames66287132015-09-09 23:40:12 +0000870 } else if (auto *EE = dyn_cast<ExtractElementInst>(I)) {
Philip Reames9ac4e382015-08-12 21:00:20 +0000871 UndefValue *Undef = UndefValue::get(EE->getVectorOperand()->getType());
Philip Reamesece70b82015-09-09 23:57:18 +0000872 std::string Name = suffixed_name_or(I, ".base", "base_ee");
Philip Reames9ac4e382015-08-12 21:00:20 +0000873 return ExtractElementInst::Create(Undef, EE->getIndexOperand(), Name,
874 EE);
Anna Thomas479cbb92016-10-04 13:48:37 +0000875 } else if (auto *IE = dyn_cast<InsertElementInst>(I)) {
Philip Reames66287132015-09-09 23:40:12 +0000876 UndefValue *VecUndef = UndefValue::get(IE->getOperand(0)->getType());
877 UndefValue *ScalarUndef = UndefValue::get(IE->getOperand(1)->getType());
Philip Reamesece70b82015-09-09 23:57:18 +0000878 std::string Name = suffixed_name_or(I, ".base", "base_ie");
Philip Reames66287132015-09-09 23:40:12 +0000879 return InsertElementInst::Create(VecUndef, ScalarUndef,
880 IE->getOperand(2), Name, IE);
Anna Thomas479cbb92016-10-04 13:48:37 +0000881 } else {
882 auto *SV = cast<ShuffleVectorInst>(I);
883 UndefValue *VecUndef = UndefValue::get(SV->getOperand(0)->getType());
884 std::string Name = suffixed_name_or(I, ".base", "base_sv");
885 return new ShuffleVectorInst(VecUndef, VecUndef, SV->getOperand(2),
886 Name, SV);
Philip Reames6ff1a1e32015-07-21 19:04:38 +0000887 }
Philip Reames6ff1a1e32015-07-21 19:04:38 +0000888 };
889 Instruction *BaseInst = MakeBaseInstPlaceholder(I);
890 // Add metadata marking this as a base value
891 BaseInst->setMetadata("is_base_value", MDNode::get(I->getContext(), {}));
Philip Reames34d7a742015-09-10 00:22:49 +0000892 States[I] = BDVState(BDVState::Conflict, BaseInst);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000893 }
894
Philip Reames3ea15892015-09-03 21:57:40 +0000895 // Returns a instruction which produces the base pointer for a given
896 // instruction. The instruction is assumed to be an input to one of the BDVs
897 // seen in the inference algorithm above. As such, we must either already
898 // know it's base defining value is a base, or have inserted a new
899 // instruction to propagate the base of it's BDV and have entered that newly
900 // introduced instruction into the state table. In either case, we are
901 // assured to be able to determine an instruction which produces it's base
Sanjoy Das90547f12016-06-26 04:55:05 +0000902 // pointer.
Philip Reames3ea15892015-09-03 21:57:40 +0000903 auto getBaseForInput = [&](Value *Input, Instruction *InsertPt) {
Sanjoy Das90547f12016-06-26 04:55:05 +0000904 Value *BDV = findBaseOrBDV(Input, Cache);
Philip Reames3ea15892015-09-03 21:57:40 +0000905 Value *Base = nullptr;
906 if (isKnownBaseResult(BDV)) {
907 Base = BDV;
908 } else {
909 // Either conflict or base.
Philip Reames34d7a742015-09-10 00:22:49 +0000910 assert(States.count(BDV));
Sanjoy Das7dda0ed2016-06-26 04:55:35 +0000911 Base = States[BDV].getBaseValue();
Philip Reames3ea15892015-09-03 21:57:40 +0000912 }
Sanjoy Das90547f12016-06-26 04:55:05 +0000913 assert(Base && "Can't be null");
Philip Reames3ea15892015-09-03 21:57:40 +0000914 // The cast is needed since base traversal may strip away bitcasts
Sanjoy Das90547f12016-06-26 04:55:05 +0000915 if (Base->getType() != Input->getType() && InsertPt)
916 Base = new BitCastInst(Base, Input->getType(), "cast", InsertPt);
Philip Reames3ea15892015-09-03 21:57:40 +0000917 return Base;
918 };
919
Philip Reames15d55632015-09-09 23:26:08 +0000920 // Fixup all the inputs of the new PHIs. Visit order needs to be
921 // deterministic and predictable because we're naming newly created
922 // instructions.
Philip Reames34d7a742015-09-10 00:22:49 +0000923 for (auto Pair : States) {
Philip Reames7540e3a2015-09-10 00:01:53 +0000924 Instruction *BDV = cast<Instruction>(Pair.first);
Philip Reamesc8ded462015-09-10 00:27:50 +0000925 BDVState State = Pair.second;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000926
Philip Reames7540e3a2015-09-10 00:01:53 +0000927 assert(!isKnownBaseResult(BDV) && "why did it get added?");
Philip Reamesc8ded462015-09-10 00:27:50 +0000928 assert(!State.isUnknown() && "Optimistic algorithm didn't complete!");
929 if (!State.isConflict())
Philip Reames28e61ce2015-02-28 01:57:44 +0000930 continue;
Philip Reames704e78b2015-04-10 22:34:56 +0000931
Sanjoy Das7dda0ed2016-06-26 04:55:35 +0000932 if (PHINode *BasePHI = dyn_cast<PHINode>(State.getBaseValue())) {
Sanjoy Das90547f12016-06-26 04:55:05 +0000933 PHINode *PN = cast<PHINode>(BDV);
934 unsigned NumPHIValues = PN->getNumIncomingValues();
Philip Reames28e61ce2015-02-28 01:57:44 +0000935 for (unsigned i = 0; i < NumPHIValues; i++) {
Sanjoy Das90547f12016-06-26 04:55:05 +0000936 Value *InVal = PN->getIncomingValue(i);
937 BasicBlock *InBB = PN->getIncomingBlock(i);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000938
Philip Reames28e61ce2015-02-28 01:57:44 +0000939 // If we've already seen InBB, add the same incoming value
940 // we added for it earlier. The IR verifier requires phi
941 // nodes with multiple entries from the same basic block
942 // to have the same incoming value for each of those
943 // entries. If we don't do this check here and basephi
944 // has a different type than base, we'll end up adding two
945 // bitcasts (and hence two distinct values) as incoming
946 // values for the same basic block.
Philip Reamesd16a9b12015-02-20 01:06:44 +0000947
Sanjoy Das90547f12016-06-26 04:55:05 +0000948 int BlockIndex = BasePHI->getBasicBlockIndex(InBB);
949 if (BlockIndex != -1) {
950 Value *OldBase = BasePHI->getIncomingValue(BlockIndex);
951 BasePHI->addIncoming(OldBase, InBB);
952
Philip Reamesd16a9b12015-02-20 01:06:44 +0000953#ifndef NDEBUG
Philip Reames3ea15892015-09-03 21:57:40 +0000954 Value *Base = getBaseForInput(InVal, nullptr);
Sanjoy Das90547f12016-06-26 04:55:05 +0000955 // In essence this assert states: the only way two values
956 // incoming from the same basic block may be different is by
957 // being different bitcasts of the same value. A cleanup
958 // that remains TODO is changing findBaseOrBDV to return an
959 // llvm::Value of the correct type (and still remain pure).
960 // This will remove the need to add bitcasts.
961 assert(Base->stripPointerCasts() == OldBase->stripPointerCasts() &&
962 "Sanity -- findBaseOrBDV should be pure!");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000963#endif
Philip Reames28e61ce2015-02-28 01:57:44 +0000964 continue;
965 }
Philip Reamesd16a9b12015-02-20 01:06:44 +0000966
Philip Reames3ea15892015-09-03 21:57:40 +0000967 // Find the instruction which produces the base for each input. We may
968 // need to insert a bitcast in the incoming block.
969 // TODO: Need to split critical edges if insertion is needed
970 Value *Base = getBaseForInput(InVal, InBB->getTerminator());
Sanjoy Das90547f12016-06-26 04:55:05 +0000971 BasePHI->addIncoming(Base, InBB);
Philip Reames28e61ce2015-02-28 01:57:44 +0000972 }
Sanjoy Das90547f12016-06-26 04:55:05 +0000973 assert(BasePHI->getNumIncomingValues() == NumPHIValues);
Sanjoy Das7dda0ed2016-06-26 04:55:35 +0000974 } else if (SelectInst *BaseSI =
975 dyn_cast<SelectInst>(State.getBaseValue())) {
Sanjoy Das90547f12016-06-26 04:55:05 +0000976 SelectInst *SI = cast<SelectInst>(BDV);
977
978 // Find the instruction which produces the base for each input.
979 // We may need to insert a bitcast.
980 BaseSI->setTrueValue(getBaseForInput(SI->getTrueValue(), BaseSI));
981 BaseSI->setFalseValue(getBaseForInput(SI->getFalseValue(), BaseSI));
Sanjoy Das7dda0ed2016-06-26 04:55:35 +0000982 } else if (auto *BaseEE =
983 dyn_cast<ExtractElementInst>(State.getBaseValue())) {
Philip Reames7540e3a2015-09-10 00:01:53 +0000984 Value *InVal = cast<ExtractElementInst>(BDV)->getVectorOperand();
Philip Reames3ea15892015-09-03 21:57:40 +0000985 // Find the instruction which produces the base for each input. We may
986 // need to insert a bitcast.
Sanjoy Das90547f12016-06-26 04:55:05 +0000987 BaseEE->setOperand(0, getBaseForInput(InVal, BaseEE));
Anna Thomas479cbb92016-10-04 13:48:37 +0000988 } else if (auto *BaseIE = dyn_cast<InsertElementInst>(State.getBaseValue())){
Philip Reames7540e3a2015-09-10 00:01:53 +0000989 auto *BdvIE = cast<InsertElementInst>(BDV);
Philip Reames66287132015-09-09 23:40:12 +0000990 auto UpdateOperand = [&](int OperandIdx) {
991 Value *InVal = BdvIE->getOperand(OperandIdx);
Philip Reames953817b2015-09-10 00:44:10 +0000992 Value *Base = getBaseForInput(InVal, BaseIE);
Philip Reames66287132015-09-09 23:40:12 +0000993 BaseIE->setOperand(OperandIdx, Base);
994 };
995 UpdateOperand(0); // vector operand
996 UpdateOperand(1); // scalar operand
Anna Thomas479cbb92016-10-04 13:48:37 +0000997 } else {
998 auto *BaseSV = cast<ShuffleVectorInst>(State.getBaseValue());
999 auto *BdvSV = cast<ShuffleVectorInst>(BDV);
1000 auto UpdateOperand = [&](int OperandIdx) {
1001 Value *InVal = BdvSV->getOperand(OperandIdx);
1002 Value *Base = getBaseForInput(InVal, BaseSV);
1003 BaseSV->setOperand(OperandIdx, Base);
1004 };
1005 UpdateOperand(0); // vector operand
1006 UpdateOperand(1); // vector operand
Philip Reamesd16a9b12015-02-20 01:06:44 +00001007 }
1008 }
1009
1010 // Cache all of our results so we can cheaply reuse them
1011 // NOTE: This is actually two caches: one of the base defining value
1012 // relation and one of the base pointer relation! FIXME
Philip Reames34d7a742015-09-10 00:22:49 +00001013 for (auto Pair : States) {
Philip Reames15d55632015-09-09 23:26:08 +00001014 auto *BDV = Pair.first;
Sanjoy Das7dda0ed2016-06-26 04:55:35 +00001015 Value *Base = Pair.second.getBaseValue();
Sanjoy Das90547f12016-06-26 04:55:05 +00001016 assert(BDV && Base);
Philip Reames79fa9b72016-02-22 20:45:56 +00001017 assert(!isKnownBaseResult(BDV) && "why did it get added?");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001018
Philip Reamesdab35f32015-09-02 21:11:44 +00001019 DEBUG(dbgs() << "Updating base value cache"
Eric Christopherd3d9cbf2016-06-23 00:42:00 +00001020 << " for: " << BDV->getName() << " from: "
Sanjoy Das90547f12016-06-26 04:55:05 +00001021 << (Cache.count(BDV) ? Cache[BDV]->getName().str() : "none")
1022 << " to: " << Base->getName() << "\n");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001023
Sanjoy Das90547f12016-06-26 04:55:05 +00001024 if (Cache.count(BDV)) {
1025 assert(isKnownBaseResult(Base) &&
Philip Reames79fa9b72016-02-22 20:45:56 +00001026 "must be something we 'know' is a base pointer");
Sanjoy Das90547f12016-06-26 04:55:05 +00001027 // Once we transition from the BDV relation being store in the Cache to
Philip Reamesd16a9b12015-02-20 01:06:44 +00001028 // the base relation being stored, it must be stable
Sanjoy Das90547f12016-06-26 04:55:05 +00001029 assert((!isKnownBaseResult(Cache[BDV]) || Cache[BDV] == Base) &&
Philip Reamesd16a9b12015-02-20 01:06:44 +00001030 "base relation should be stable");
1031 }
Sanjoy Das90547f12016-06-26 04:55:05 +00001032 Cache[BDV] = Base;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001033 }
Sanjoy Das90547f12016-06-26 04:55:05 +00001034 assert(Cache.count(Def));
1035 return Cache[Def];
Philip Reamesd16a9b12015-02-20 01:06:44 +00001036}
1037
1038// For a set of live pointers (base and/or derived), identify the base
1039// pointer of the object which they are derived from. This routine will
1040// mutate the IR graph as needed to make the 'base' pointer live at the
1041// definition site of 'derived'. This ensures that any use of 'derived' can
1042// also use 'base'. This may involve the insertion of a number of
1043// additional PHI nodes.
1044//
1045// preconditions: live is a set of pointer type Values
1046//
1047// side effects: may insert PHI nodes into the existing CFG, will preserve
1048// CFG, will not remove or mutate any existing nodes
1049//
Philip Reamesf2041322015-02-20 19:26:04 +00001050// post condition: PointerToBase contains one (derived, base) pair for every
Philip Reamesd16a9b12015-02-20 01:06:44 +00001051// pointer in live. Note that derived can be equal to base if the original
1052// pointer was a base pointer.
Philip Reames704e78b2015-04-10 22:34:56 +00001053static void
1054findBasePointers(const StatepointLiveSetTy &live,
Igor Laevskyfb1811d2016-05-04 14:55:36 +00001055 MapVector<Value *, Value *> &PointerToBase,
Philip Reamesba198492015-04-14 00:41:34 +00001056 DominatorTree *DT, DefiningValueMapTy &DVCache) {
Igor Laevskyfb1811d2016-05-04 14:55:36 +00001057 for (Value *ptr : live) {
Philip Reamesba198492015-04-14 00:41:34 +00001058 Value *base = findBasePointer(ptr, DVCache);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001059 assert(base && "failed to find base pointer");
Philip Reamesf2041322015-02-20 19:26:04 +00001060 PointerToBase[ptr] = base;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001061 assert((!isa<Instruction>(base) || !isa<Instruction>(ptr) ||
1062 DT->dominates(cast<Instruction>(base)->getParent(),
1063 cast<Instruction>(ptr)->getParent())) &&
1064 "The base we found better dominate the derived pointer");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001065 }
1066}
1067
1068/// Find the required based pointers (and adjust the live set) for the given
1069/// parse point.
1070static void findBasePointers(DominatorTree &DT, DefiningValueMapTy &DVCache,
Sanjoy Dasa3244872016-06-17 00:45:00 +00001071 CallSite CS,
Philip Reamesd16a9b12015-02-20 01:06:44 +00001072 PartiallyConstructedSafepointRecord &result) {
Igor Laevskyfb1811d2016-05-04 14:55:36 +00001073 MapVector<Value *, Value *> PointerToBase;
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001074 findBasePointers(result.LiveSet, PointerToBase, &DT, DVCache);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001075
1076 if (PrintBasePointers) {
1077 errs() << "Base Pairs (w/o Relocation):\n";
Igor Laevskyfb1811d2016-05-04 14:55:36 +00001078 for (auto &Pair : PointerToBase) {
Manuel Jacoba4efd8a2015-12-23 00:19:45 +00001079 errs() << " derived ";
Igor Laevskyfb1811d2016-05-04 14:55:36 +00001080 Pair.first->printAsOperand(errs(), false);
Manuel Jacoba4efd8a2015-12-23 00:19:45 +00001081 errs() << " base ";
Igor Laevskyfb1811d2016-05-04 14:55:36 +00001082 Pair.second->printAsOperand(errs(), false);
Manuel Jacoba4efd8a2015-12-23 00:19:45 +00001083 errs() << "\n";;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001084 }
1085 }
1086
Philip Reamesf2041322015-02-20 19:26:04 +00001087 result.PointerToBase = PointerToBase;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001088}
1089
Philip Reamesdf1ef082015-04-10 22:53:14 +00001090/// Given an updated version of the dataflow liveness results, update the
1091/// liveset and base pointer maps for the call site CS.
1092static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData,
Sanjoy Dasa3244872016-06-17 00:45:00 +00001093 CallSite CS,
Philip Reamesdf1ef082015-04-10 22:53:14 +00001094 PartiallyConstructedSafepointRecord &result);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001095
Philip Reamesdf1ef082015-04-10 22:53:14 +00001096static void recomputeLiveInValues(
Justin Bogner843fb202015-12-15 19:40:57 +00001097 Function &F, DominatorTree &DT, ArrayRef<CallSite> toUpdate,
Philip Reamesd2b66462015-02-20 22:39:41 +00001098 MutableArrayRef<struct PartiallyConstructedSafepointRecord> records) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00001099 // TODO-PERF: reuse the original liveness, then simply run the dataflow
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001100 // again. The old values are still live and will help it stabilize quickly.
Philip Reamesdf1ef082015-04-10 22:53:14 +00001101 GCPtrLivenessData RevisedLivenessData;
1102 computeLiveInValues(DT, F, RevisedLivenessData);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001103 for (size_t i = 0; i < records.size(); i++) {
1104 struct PartiallyConstructedSafepointRecord &info = records[i];
Sanjoy Dasa3244872016-06-17 00:45:00 +00001105 recomputeLiveInValues(RevisedLivenessData, toUpdate[i], info);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001106 }
1107}
1108
Sanjoy Das7ad67642015-10-20 01:06:24 +00001109// When inserting gc.relocate and gc.result calls, we need to ensure there are
1110// no uses of the original value / return value between the gc.statepoint and
1111// the gc.relocate / gc.result call. One case which can arise is a phi node
1112// starting one of the successor blocks. We also need to be able to insert the
1113// gc.relocates only on the path which goes through the statepoint. We might
1114// need to split an edge to make this possible.
Philip Reamesf209a152015-04-13 20:00:30 +00001115static BasicBlock *
Sanjoy Dasea45f0e2015-06-02 22:33:34 +00001116normalizeForInvokeSafepoint(BasicBlock *BB, BasicBlock *InvokeParent,
1117 DominatorTree &DT) {
Philip Reames69e51ca2015-04-13 18:07:21 +00001118 BasicBlock *Ret = BB;
Sanjoy Dasff3dba72015-10-20 01:06:17 +00001119 if (!BB->getUniquePredecessor())
Chandler Carruth96ada252015-07-22 09:52:54 +00001120 Ret = SplitBlockPredecessors(BB, InvokeParent, "", &DT);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001121
Sanjoy Das7ad67642015-10-20 01:06:24 +00001122 // Now that 'Ret' has unique predecessor we can safely remove all phi nodes
Philip Reames69e51ca2015-04-13 18:07:21 +00001123 // from it
1124 FoldSingleEntryPHINodes(Ret);
Sanjoy Dasff3dba72015-10-20 01:06:17 +00001125 assert(!isa<PHINode>(Ret->begin()) &&
1126 "All PHI nodes should have been removed!");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001127
Sanjoy Das7ad67642015-10-20 01:06:24 +00001128 // At this point, we can safely insert a gc.relocate or gc.result as the first
1129 // instruction in Ret if needed.
Philip Reames69e51ca2015-04-13 18:07:21 +00001130 return Ret;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001131}
1132
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001133// Create new attribute set containing only attributes which can be transferred
Philip Reamesd16a9b12015-02-20 01:06:44 +00001134// from original call to the safepoint.
Reid Kleckner99351962017-04-28 19:22:40 +00001135static AttributeList legalizeCallAttributes(AttributeList AL) {
1136 if (AL.isEmpty())
1137 return AL;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001138
Reid Kleckner99351962017-04-28 19:22:40 +00001139 // Remove the readonly, readnone, and statepoint function attributes.
1140 AttrBuilder FnAttrs = AL.getFnAttributes();
1141 FnAttrs.removeAttribute(Attribute::ReadNone);
1142 FnAttrs.removeAttribute(Attribute::ReadOnly);
1143 for (Attribute A : AL.getFnAttributes()) {
1144 if (isStatepointDirectiveAttr(A))
1145 FnAttrs.remove(A);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001146 }
1147
Reid Kleckner99351962017-04-28 19:22:40 +00001148 // Just skip parameter and return attributes for now
1149 LLVMContext &Ctx = AL.getContext();
1150 return AttributeList::get(Ctx, AttributeList::FunctionIndex,
1151 AttributeSet::get(Ctx, FnAttrs));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001152}
1153
1154/// Helper function to place all gc relocates necessary for the given
1155/// statepoint.
1156/// Inputs:
1157/// liveVariables - list of variables to be relocated.
1158/// liveStart - index of the first live variable.
1159/// basePtrs - base pointers.
1160/// statepointToken - statepoint instruction to which relocates should be
1161/// bound.
1162/// Builder - Llvm IR builder to be used to construct new calls.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001163static void CreateGCRelocates(ArrayRef<Value *> LiveVariables,
Sanjoy Das5665c992015-05-11 23:47:27 +00001164 const int LiveStart,
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001165 ArrayRef<Value *> BasePtrs,
Sanjoy Das5665c992015-05-11 23:47:27 +00001166 Instruction *StatepointToken,
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00001167 IRBuilder<> Builder) {
Philip Reames94babb72015-07-21 17:18:03 +00001168 if (LiveVariables.empty())
1169 return;
Sanjoy Dasb1942f12015-10-20 01:06:28 +00001170
1171 auto FindIndex = [](ArrayRef<Value *> LiveVec, Value *Val) {
David Majnemer0d955d02016-08-11 22:21:41 +00001172 auto ValIt = find(LiveVec, Val);
Sanjoy Dasb1942f12015-10-20 01:06:28 +00001173 assert(ValIt != LiveVec.end() && "Val not found in LiveVec!");
1174 size_t Index = std::distance(LiveVec.begin(), ValIt);
1175 assert(Index < LiveVec.size() && "Bug in std::find?");
1176 return Index;
1177 };
Philip Reames74ce2e72015-07-21 16:51:17 +00001178 Module *M = StatepointToken->getModule();
Philip Reames5715f572016-01-09 01:31:13 +00001179
1180 // All gc_relocate are generated as i8 addrspace(1)* (or a vector type whose
1181 // element type is i8 addrspace(1)*). We originally generated unique
1182 // declarations for each pointer type, but this proved problematic because
1183 // the intrinsic mangling code is incomplete and fragile. Since we're moving
1184 // towards a single unified pointer type anyways, we can just cast everything
1185 // to an i8* of the right address space. A bitcast is added later to convert
1186 // gc_relocate to the actual value's type.
1187 auto getGCRelocateDecl = [&] (Type *Ty) {
1188 assert(isHandledGCPointerType(Ty));
1189 auto AS = Ty->getScalarType()->getPointerAddressSpace();
1190 Type *NewTy = Type::getInt8PtrTy(M->getContext(), AS);
1191 if (auto *VT = dyn_cast<VectorType>(Ty))
1192 NewTy = VectorType::get(NewTy, VT->getNumElements());
1193 return Intrinsic::getDeclaration(M, Intrinsic::experimental_gc_relocate,
1194 {NewTy});
1195 };
1196
1197 // Lazily populated map from input types to the canonicalized form mentioned
1198 // in the comment above. This should probably be cached somewhere more
1199 // broadly.
1200 DenseMap<Type*, Value*> TypeToDeclMap;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001201
Sanjoy Das5665c992015-05-11 23:47:27 +00001202 for (unsigned i = 0; i < LiveVariables.size(); i++) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001203 // Generate the gc.relocate call and save the result
Sanjoy Das5665c992015-05-11 23:47:27 +00001204 Value *BaseIdx =
Sanjoy Dasb1942f12015-10-20 01:06:28 +00001205 Builder.getInt32(LiveStart + FindIndex(LiveVariables, BasePtrs[i]));
Sanjoy Das3020b1b2015-10-20 01:06:31 +00001206 Value *LiveIdx = Builder.getInt32(LiveStart + i);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001207
Philip Reames5715f572016-01-09 01:31:13 +00001208 Type *Ty = LiveVariables[i]->getType();
1209 if (!TypeToDeclMap.count(Ty))
1210 TypeToDeclMap[Ty] = getGCRelocateDecl(Ty);
1211 Value *GCRelocateDecl = TypeToDeclMap[Ty];
1212
Philip Reamesd16a9b12015-02-20 01:06:44 +00001213 // only specify a debug name if we can give a useful one
Philip Reames74ce2e72015-07-21 16:51:17 +00001214 CallInst *Reloc = Builder.CreateCall(
David Blaikieff6409d2015-05-18 22:13:54 +00001215 GCRelocateDecl, {StatepointToken, BaseIdx, LiveIdx},
Philip Reamesece70b82015-09-09 23:57:18 +00001216 suffixed_name_or(LiveVariables[i], ".relocated", ""));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001217 // Trick CodeGen into thinking there are lots of free registers at this
1218 // fake call.
Philip Reames74ce2e72015-07-21 16:51:17 +00001219 Reloc->setCallingConv(CallingConv::Cold);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001220 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00001221}
1222
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001223namespace {
1224
1225/// This struct is used to defer RAUWs and `eraseFromParent` s. Using this
1226/// avoids having to worry about keeping around dangling pointers to Values.
1227class DeferredReplacement {
1228 AssertingVH<Instruction> Old;
1229 AssertingVH<Instruction> New;
Sanjoy Das49e974b2016-04-05 23:18:35 +00001230 bool IsDeoptimize = false;
1231
1232 DeferredReplacement() {}
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001233
1234public:
Sanjoy Das8d89a2b2016-04-05 23:18:53 +00001235 static DeferredReplacement createRAUW(Instruction *Old, Instruction *New) {
1236 assert(Old != New && Old && New &&
1237 "Cannot RAUW equal values or to / from null!");
1238
1239 DeferredReplacement D;
1240 D.Old = Old;
1241 D.New = New;
1242 return D;
1243 }
1244
1245 static DeferredReplacement createDelete(Instruction *ToErase) {
1246 DeferredReplacement D;
1247 D.Old = ToErase;
1248 return D;
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001249 }
1250
Sanjoy Das49e974b2016-04-05 23:18:35 +00001251 static DeferredReplacement createDeoptimizeReplacement(Instruction *Old) {
1252#ifndef NDEBUG
1253 auto *F = cast<CallInst>(Old)->getCalledFunction();
1254 assert(F && F->getIntrinsicID() == Intrinsic::experimental_deoptimize &&
1255 "Only way to construct a deoptimize deferred replacement");
1256#endif
1257 DeferredReplacement D;
1258 D.Old = Old;
1259 D.IsDeoptimize = true;
1260 return D;
1261 }
1262
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001263 /// Does the task represented by this instance.
1264 void doReplacement() {
1265 Instruction *OldI = Old;
1266 Instruction *NewI = New;
1267
1268 assert(OldI != NewI && "Disallowed at construction?!");
Richard Trieuf35d4b02016-04-06 04:22:00 +00001269 assert((!IsDeoptimize || !New) &&
1270 "Deoptimize instrinsics are not replaced!");
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001271
1272 Old = nullptr;
1273 New = nullptr;
1274
1275 if (NewI)
1276 OldI->replaceAllUsesWith(NewI);
Sanjoy Das49e974b2016-04-05 23:18:35 +00001277
1278 if (IsDeoptimize) {
1279 // Note: we've inserted instructions, so the call to llvm.deoptimize may
1280 // not necessarilly be followed by the matching return.
1281 auto *RI = cast<ReturnInst>(OldI->getParent()->getTerminator());
1282 new UnreachableInst(RI->getContext(), RI);
1283 RI->eraseFromParent();
1284 }
1285
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001286 OldI->eraseFromParent();
1287 }
1288};
1289}
1290
Philip Reames2b1084a2016-08-31 15:12:17 +00001291static StringRef getDeoptLowering(CallSite CS) {
1292 const char *DeoptLowering = "deopt-lowering";
1293 if (CS.hasFnAttr(DeoptLowering)) {
1294 // FIXME: CallSite has a *really* confusing interface around attributes
Reid Klecknerb5180542017-03-21 16:57:19 +00001295 // with values.
1296 const AttributeList &CSAS = CS.getAttributes();
1297 if (CSAS.hasAttribute(AttributeList::FunctionIndex, DeoptLowering))
1298 return CSAS.getAttribute(AttributeList::FunctionIndex, DeoptLowering)
1299 .getValueAsString();
Philip Reames2b1084a2016-08-31 15:12:17 +00001300 Function *F = CS.getCalledFunction();
1301 assert(F && F->hasFnAttribute(DeoptLowering));
1302 return F->getFnAttribute(DeoptLowering).getValueAsString();
1303 }
1304 return "live-through";
1305}
1306
1307
Philip Reamesd16a9b12015-02-20 01:06:44 +00001308static void
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001309makeStatepointExplicitImpl(const CallSite CS, /* to replace */
1310 const SmallVectorImpl<Value *> &BasePtrs,
1311 const SmallVectorImpl<Value *> &LiveVariables,
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001312 PartiallyConstructedSafepointRecord &Result,
1313 std::vector<DeferredReplacement> &Replacements) {
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001314 assert(BasePtrs.size() == LiveVariables.size());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001315
Philip Reamesd16a9b12015-02-20 01:06:44 +00001316 // Then go ahead and use the builder do actually do the inserts. We insert
1317 // immediately before the previous instruction under the assumption that all
1318 // arguments will be available here. We can't insert afterwards since we may
1319 // be replacing a terminator.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001320 Instruction *InsertBefore = CS.getInstruction();
1321 IRBuilder<> Builder(InsertBefore);
1322
Sanjoy Das3c520a12015-10-08 23:18:38 +00001323 ArrayRef<Value *> GCArgs(LiveVariables);
Sanjoy Dasc9058ca2016-03-17 18:42:17 +00001324 uint64_t StatepointID = StatepointDirectives::DefaultStatepointID;
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001325 uint32_t NumPatchBytes = 0;
1326 uint32_t Flags = uint32_t(StatepointFlags::None);
Sanjoy Das3c520a12015-10-08 23:18:38 +00001327
Sanjoy Dasbcf27522016-01-29 01:03:20 +00001328 ArrayRef<Use> CallArgs(CS.arg_begin(), CS.arg_end());
1329 ArrayRef<Use> DeoptArgs = GetDeoptBundleOperands(CS);
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001330 ArrayRef<Use> TransitionArgs;
Sanjoy Das40992972016-01-29 01:03:17 +00001331 if (auto TransitionBundle =
1332 CS.getOperandBundle(LLVMContext::OB_gc_transition)) {
1333 Flags |= uint32_t(StatepointFlags::GCTransition);
1334 TransitionArgs = TransitionBundle->Inputs;
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001335 }
Sanjoy Das99abb272016-04-06 01:33:54 +00001336
1337 // Instead of lowering calls to @llvm.experimental.deoptimize as normal calls
1338 // with a return value, we lower then as never returning calls to
1339 // __llvm_deoptimize that are followed by unreachable to get better codegen.
Sanjoy Das49e974b2016-04-05 23:18:35 +00001340 bool IsDeoptimize = false;
Sanjoy Das40992972016-01-29 01:03:17 +00001341
Sanjoy Das31203882016-03-17 01:56:10 +00001342 StatepointDirectives SD =
1343 parseStatepointDirectivesFromAttrs(CS.getAttributes());
1344 if (SD.NumPatchBytes)
1345 NumPatchBytes = *SD.NumPatchBytes;
1346 if (SD.StatepointID)
1347 StatepointID = *SD.StatepointID;
Sanjoy Das40992972016-01-29 01:03:17 +00001348
Philip Reames2b1084a2016-08-31 15:12:17 +00001349 // Pass through the requested lowering if any. The default is live-through.
1350 StringRef DeoptLowering = getDeoptLowering(CS);
1351 if (DeoptLowering.equals("live-in"))
1352 Flags |= uint32_t(StatepointFlags::DeoptLiveIn);
1353 else {
1354 assert(DeoptLowering.equals("live-through") && "Unsupported value!");
1355 }
1356
Sanjoy Das31203882016-03-17 01:56:10 +00001357 Value *CallTarget = CS.getCalledValue();
Sanjoy Dasd4c78332016-03-25 20:12:13 +00001358 if (Function *F = dyn_cast<Function>(CallTarget)) {
1359 if (F->getIntrinsicID() == Intrinsic::experimental_deoptimize) {
Sanjoy Das091fcfa2016-05-06 20:39:33 +00001360 // Calls to llvm.experimental.deoptimize are lowered to calls to the
Sanjoy Dasd4c78332016-03-25 20:12:13 +00001361 // __llvm_deoptimize symbol. We want to resolve this now, since the
1362 // verifier does not allow taking the address of an intrinsic function.
1363
1364 SmallVector<Type *, 8> DomainTy;
1365 for (Value *Arg : CallArgs)
1366 DomainTy.push_back(Arg->getType());
Sanjoy Das49e974b2016-04-05 23:18:35 +00001367 auto *FTy = FunctionType::get(Type::getVoidTy(F->getContext()), DomainTy,
Sanjoy Dasd4c78332016-03-25 20:12:13 +00001368 /* isVarArg = */ false);
1369
1370 // Note: CallTarget can be a bitcast instruction of a symbol if there are
1371 // calls to @llvm.experimental.deoptimize with different argument types in
1372 // the same module. This is fine -- we assume the frontend knew what it
1373 // was doing when generating this kind of IR.
1374 CallTarget =
1375 F->getParent()->getOrInsertFunction("__llvm_deoptimize", FTy);
Sanjoy Das49e974b2016-04-05 23:18:35 +00001376
1377 IsDeoptimize = true;
Sanjoy Dasd4c78332016-03-25 20:12:13 +00001378 }
1379 }
Sanjoy Das40992972016-01-29 01:03:17 +00001380
Philip Reamesd16a9b12015-02-20 01:06:44 +00001381 // Create the statepoint given all the arguments
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001382 Instruction *Token = nullptr;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001383 if (CS.isCall()) {
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001384 CallInst *ToReplace = cast<CallInst>(CS.getInstruction());
Sanjoy Das3c520a12015-10-08 23:18:38 +00001385 CallInst *Call = Builder.CreateGCStatepointCall(
1386 StatepointID, NumPatchBytes, CallTarget, Flags, CallArgs,
1387 TransitionArgs, DeoptArgs, GCArgs, "safepoint_token");
1388
David Majnemerd5648c72016-11-25 22:35:09 +00001389 Call->setTailCallKind(ToReplace->getTailCallKind());
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001390 Call->setCallingConv(ToReplace->getCallingConv());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001391
1392 // Currently we will fail on parameter attributes and on certain
Reid Kleckner99351962017-04-28 19:22:40 +00001393 // function attributes. In case if we can handle this set of attributes -
1394 // set up function attrs directly on statepoint and return attrs later for
1395 // gc_result intrinsic.
1396 Call->setAttributes(legalizeCallAttributes(ToReplace->getAttributes()));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001397
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001398 Token = Call;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001399
1400 // Put the following gc_result and gc_relocate calls immediately after the
1401 // the old call (which we're about to delete)
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001402 assert(ToReplace->getNextNode() && "Not a terminator, must have next!");
1403 Builder.SetInsertPoint(ToReplace->getNextNode());
1404 Builder.SetCurrentDebugLocation(ToReplace->getNextNode()->getDebugLoc());
David Blaikie82ad7872015-02-20 23:44:24 +00001405 } else {
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001406 InvokeInst *ToReplace = cast<InvokeInst>(CS.getInstruction());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001407
1408 // Insert the new invoke into the old block. We'll remove the old one in a
1409 // moment at which point this will become the new terminator for the
1410 // original block.
Sanjoy Das3c520a12015-10-08 23:18:38 +00001411 InvokeInst *Invoke = Builder.CreateGCStatepointInvoke(
1412 StatepointID, NumPatchBytes, CallTarget, ToReplace->getNormalDest(),
1413 ToReplace->getUnwindDest(), Flags, CallArgs, TransitionArgs, DeoptArgs,
1414 GCArgs, "statepoint_token");
1415
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001416 Invoke->setCallingConv(ToReplace->getCallingConv());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001417
1418 // Currently we will fail on parameter attributes and on certain
Reid Kleckner99351962017-04-28 19:22:40 +00001419 // function attributes. In case if we can handle this set of attributes -
1420 // set up function attrs directly on statepoint and return attrs later for
1421 // gc_result intrinsic.
1422 Invoke->setAttributes(legalizeCallAttributes(ToReplace->getAttributes()));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001423
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001424 Token = Invoke;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001425
1426 // Generate gc relocates in exceptional path
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001427 BasicBlock *UnwindBlock = ToReplace->getUnwindDest();
1428 assert(!isa<PHINode>(UnwindBlock->begin()) &&
1429 UnwindBlock->getUniquePredecessor() &&
Philip Reames69e51ca2015-04-13 18:07:21 +00001430 "can't safely insert in this block!");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001431
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001432 Builder.SetInsertPoint(&*UnwindBlock->getFirstInsertionPt());
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001433 Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001434
Chen Lid71999e2015-12-26 07:54:32 +00001435 // Attach exceptional gc relocates to the landingpad.
1436 Instruction *ExceptionalToken = UnwindBlock->getLandingPadInst();
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001437 Result.UnwindToken = ExceptionalToken;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001438
Sanjoy Das3c520a12015-10-08 23:18:38 +00001439 const unsigned LiveStartIdx = Statepoint(Token).gcArgsStartIdx();
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001440 CreateGCRelocates(LiveVariables, LiveStartIdx, BasePtrs, ExceptionalToken,
1441 Builder);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001442
1443 // Generate gc relocates and returns for normal block
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001444 BasicBlock *NormalDest = ToReplace->getNormalDest();
1445 assert(!isa<PHINode>(NormalDest->begin()) &&
1446 NormalDest->getUniquePredecessor() &&
Philip Reames69e51ca2015-04-13 18:07:21 +00001447 "can't safely insert in this block!");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001448
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001449 Builder.SetInsertPoint(&*NormalDest->getFirstInsertionPt());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001450
1451 // gc relocates will be generated later as if it were regular call
1452 // statepoint
Philip Reamesd16a9b12015-02-20 01:06:44 +00001453 }
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001454 assert(Token && "Should be set in one of the above branches!");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001455
Sanjoy Das49e974b2016-04-05 23:18:35 +00001456 if (IsDeoptimize) {
1457 // If we're wrapping an @llvm.experimental.deoptimize in a statepoint, we
1458 // transform the tail-call like structure to a call to a void function
1459 // followed by unreachable to get better codegen.
1460 Replacements.push_back(
1461 DeferredReplacement::createDeoptimizeReplacement(CS.getInstruction()));
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001462 } else {
Sanjoy Das49e974b2016-04-05 23:18:35 +00001463 Token->setName("statepoint_token");
1464 if (!CS.getType()->isVoidTy() && !CS.getInstruction()->use_empty()) {
1465 StringRef Name =
1466 CS.getInstruction()->hasName() ? CS.getInstruction()->getName() : "";
1467 CallInst *GCResult = Builder.CreateGCResult(Token, CS.getType(), Name);
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00001468 GCResult->setAttributes(
1469 AttributeList::get(GCResult->getContext(), AttributeList::ReturnIndex,
1470 CS.getAttributes().getRetAttributes()));
Sanjoy Das49e974b2016-04-05 23:18:35 +00001471
1472 // We cannot RAUW or delete CS.getInstruction() because it could be in the
1473 // live set of some other safepoint, in which case that safepoint's
1474 // PartiallyConstructedSafepointRecord will hold a raw pointer to this
1475 // llvm::Instruction. Instead, we defer the replacement and deletion to
1476 // after the live sets have been made explicit in the IR, and we no longer
1477 // have raw pointers to worry about.
Sanjoy Das8d89a2b2016-04-05 23:18:53 +00001478 Replacements.emplace_back(
1479 DeferredReplacement::createRAUW(CS.getInstruction(), GCResult));
Sanjoy Das49e974b2016-04-05 23:18:35 +00001480 } else {
Sanjoy Das8d89a2b2016-04-05 23:18:53 +00001481 Replacements.emplace_back(
1482 DeferredReplacement::createDelete(CS.getInstruction()));
Sanjoy Das49e974b2016-04-05 23:18:35 +00001483 }
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001484 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00001485
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001486 Result.StatepointToken = Token;
Philip Reames0a3240f2015-02-20 21:34:11 +00001487
Philip Reamesd16a9b12015-02-20 01:06:44 +00001488 // Second, create a gc.relocate for every live variable
Sanjoy Das3c520a12015-10-08 23:18:38 +00001489 const unsigned LiveStartIdx = Statepoint(Token).gcArgsStartIdx();
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001490 CreateGCRelocates(LiveVariables, LiveStartIdx, BasePtrs, Token, Builder);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001491}
1492
Philip Reamesd16a9b12015-02-20 01:06:44 +00001493// Replace an existing gc.statepoint with a new one and a set of gc.relocates
1494// which make the relocations happening at this safepoint explicit.
Philip Reames704e78b2015-04-10 22:34:56 +00001495//
Philip Reamesd16a9b12015-02-20 01:06:44 +00001496// WARNING: Does not do any fixup to adjust users of the original live
1497// values. That's the callers responsibility.
1498static void
Sanjoy Dasa3244872016-06-17 00:45:00 +00001499makeStatepointExplicit(DominatorTree &DT, CallSite CS,
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001500 PartiallyConstructedSafepointRecord &Result,
1501 std::vector<DeferredReplacement> &Replacements) {
Sanjoy Das1ede5362015-10-08 23:18:22 +00001502 const auto &LiveSet = Result.LiveSet;
1503 const auto &PointerToBase = Result.PointerToBase;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001504
1505 // Convert to vector for efficient cross referencing.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001506 SmallVector<Value *, 64> BaseVec, LiveVec;
1507 LiveVec.reserve(LiveSet.size());
1508 BaseVec.reserve(LiveSet.size());
1509 for (Value *L : LiveSet) {
1510 LiveVec.push_back(L);
Philip Reames74ce2e72015-07-21 16:51:17 +00001511 assert(PointerToBase.count(L));
Sanjoy Das1ede5362015-10-08 23:18:22 +00001512 Value *Base = PointerToBase.find(L)->second;
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001513 BaseVec.push_back(Base);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001514 }
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001515 assert(LiveVec.size() == BaseVec.size());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001516
Philip Reamesd16a9b12015-02-20 01:06:44 +00001517 // Do the actual rewriting and delete the old statepoint
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001518 makeStatepointExplicitImpl(CS, BaseVec, LiveVec, Result, Replacements);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001519}
1520
1521// Helper function for the relocationViaAlloca.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001522//
1523// It receives iterator to the statepoint gc relocates and emits a store to the
1524// assigned location (via allocaMap) for the each one of them. It adds the
1525// visited values into the visitedLiveValues set, which we will later use them
1526// for sanity checking.
Philip Reamesd16a9b12015-02-20 01:06:44 +00001527static void
Sanjoy Das5665c992015-05-11 23:47:27 +00001528insertRelocationStores(iterator_range<Value::user_iterator> GCRelocs,
1529 DenseMap<Value *, Value *> &AllocaMap,
1530 DenseSet<Value *> &VisitedLiveValues) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001531
Sanjoy Das5665c992015-05-11 23:47:27 +00001532 for (User *U : GCRelocs) {
Manuel Jacob83eefa62016-01-05 04:03:00 +00001533 GCRelocateInst *Relocate = dyn_cast<GCRelocateInst>(U);
1534 if (!Relocate)
Philip Reamesd16a9b12015-02-20 01:06:44 +00001535 continue;
1536
Sanjoy Das565f7862016-01-29 16:54:49 +00001537 Value *OriginalValue = Relocate->getDerivedPtr();
Sanjoy Das5665c992015-05-11 23:47:27 +00001538 assert(AllocaMap.count(OriginalValue));
1539 Value *Alloca = AllocaMap[OriginalValue];
Philip Reamesd16a9b12015-02-20 01:06:44 +00001540
1541 // Emit store into the related alloca
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001542 // All gc_relocates are i8 addrspace(1)* typed, and it must be bitcasted to
Sanjoy Das89c54912015-05-11 18:49:34 +00001543 // the correct type according to alloca.
Manuel Jacob83eefa62016-01-05 04:03:00 +00001544 assert(Relocate->getNextNode() &&
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001545 "Should always have one since it's not a terminator");
Manuel Jacob83eefa62016-01-05 04:03:00 +00001546 IRBuilder<> Builder(Relocate->getNextNode());
Sanjoy Das89c54912015-05-11 18:49:34 +00001547 Value *CastedRelocatedValue =
Manuel Jacob83eefa62016-01-05 04:03:00 +00001548 Builder.CreateBitCast(Relocate,
Philip Reamesece70b82015-09-09 23:57:18 +00001549 cast<AllocaInst>(Alloca)->getAllocatedType(),
Manuel Jacob83eefa62016-01-05 04:03:00 +00001550 suffixed_name_or(Relocate, ".casted", ""));
Sanjoy Das89c54912015-05-11 18:49:34 +00001551
Sanjoy Das5665c992015-05-11 23:47:27 +00001552 StoreInst *Store = new StoreInst(CastedRelocatedValue, Alloca);
1553 Store->insertAfter(cast<Instruction>(CastedRelocatedValue));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001554
1555#ifndef NDEBUG
Sanjoy Das5665c992015-05-11 23:47:27 +00001556 VisitedLiveValues.insert(OriginalValue);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001557#endif
1558 }
1559}
1560
Igor Laevskye0317182015-05-19 15:59:05 +00001561// Helper function for the "relocationViaAlloca". Similar to the
1562// "insertRelocationStores" but works for rematerialized values.
Joseph Tremouletadc23762016-02-05 01:42:52 +00001563static void insertRematerializationStores(
1564 const RematerializedValueMapTy &RematerializedValues,
1565 DenseMap<Value *, Value *> &AllocaMap,
1566 DenseSet<Value *> &VisitedLiveValues) {
Igor Laevskye0317182015-05-19 15:59:05 +00001567
1568 for (auto RematerializedValuePair: RematerializedValues) {
1569 Instruction *RematerializedValue = RematerializedValuePair.first;
1570 Value *OriginalValue = RematerializedValuePair.second;
1571
1572 assert(AllocaMap.count(OriginalValue) &&
1573 "Can not find alloca for rematerialized value");
1574 Value *Alloca = AllocaMap[OriginalValue];
1575
1576 StoreInst *Store = new StoreInst(RematerializedValue, Alloca);
1577 Store->insertAfter(RematerializedValue);
1578
1579#ifndef NDEBUG
1580 VisitedLiveValues.insert(OriginalValue);
1581#endif
1582 }
1583}
1584
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001585/// Do all the relocation update via allocas and mem2reg
Philip Reamesd16a9b12015-02-20 01:06:44 +00001586static void relocationViaAlloca(
Igor Laevsky285fe842015-05-19 16:29:43 +00001587 Function &F, DominatorTree &DT, ArrayRef<Value *> Live,
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001588 ArrayRef<PartiallyConstructedSafepointRecord> Records) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001589#ifndef NDEBUG
Philip Reamesa6ebf072015-03-27 05:53:16 +00001590 // record initial number of (static) allocas; we'll check we have the same
1591 // number when we get done.
1592 int InitialAllocaNum = 0;
Benjamin Kramer135f7352016-06-26 12:28:59 +00001593 for (Instruction &I : F.getEntryBlock())
1594 if (isa<AllocaInst>(I))
Philip Reamesa6ebf072015-03-27 05:53:16 +00001595 InitialAllocaNum++;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001596#endif
1597
1598 // TODO-PERF: change data structures, reserve
Igor Laevsky285fe842015-05-19 16:29:43 +00001599 DenseMap<Value *, Value *> AllocaMap;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001600 SmallVector<AllocaInst *, 200> PromotableAllocas;
Igor Laevskye0317182015-05-19 15:59:05 +00001601 // Used later to chack that we have enough allocas to store all values
1602 std::size_t NumRematerializedValues = 0;
Igor Laevsky285fe842015-05-19 16:29:43 +00001603 PromotableAllocas.reserve(Live.size());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001604
Igor Laevskye0317182015-05-19 15:59:05 +00001605 // Emit alloca for "LiveValue" and record it in "allocaMap" and
1606 // "PromotableAllocas"
Matt Arsenault3c1fc762017-04-10 22:27:50 +00001607 const DataLayout &DL = F.getParent()->getDataLayout();
Igor Laevskye0317182015-05-19 15:59:05 +00001608 auto emitAllocaFor = [&](Value *LiveValue) {
Matt Arsenault3c1fc762017-04-10 22:27:50 +00001609 AllocaInst *Alloca = new AllocaInst(LiveValue->getType(),
1610 DL.getAllocaAddrSpace(), "",
Igor Laevskye0317182015-05-19 15:59:05 +00001611 F.getEntryBlock().getFirstNonPHI());
Igor Laevsky285fe842015-05-19 16:29:43 +00001612 AllocaMap[LiveValue] = Alloca;
Igor Laevskye0317182015-05-19 15:59:05 +00001613 PromotableAllocas.push_back(Alloca);
1614 };
1615
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001616 // Emit alloca for each live gc pointer
1617 for (Value *V : Live)
1618 emitAllocaFor(V);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001619
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001620 // Emit allocas for rematerialized values
1621 for (const auto &Info : Records)
Igor Laevsky285fe842015-05-19 16:29:43 +00001622 for (auto RematerializedValuePair : Info.RematerializedValues) {
Igor Laevskye0317182015-05-19 15:59:05 +00001623 Value *OriginalValue = RematerializedValuePair.second;
Igor Laevsky285fe842015-05-19 16:29:43 +00001624 if (AllocaMap.count(OriginalValue) != 0)
Igor Laevskye0317182015-05-19 15:59:05 +00001625 continue;
1626
1627 emitAllocaFor(OriginalValue);
1628 ++NumRematerializedValues;
1629 }
Igor Laevsky285fe842015-05-19 16:29:43 +00001630
Philip Reamesd16a9b12015-02-20 01:06:44 +00001631 // The next two loops are part of the same conceptual operation. We need to
1632 // insert a store to the alloca after the original def and at each
1633 // redefinition. We need to insert a load before each use. These are split
1634 // into distinct loops for performance reasons.
1635
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001636 // Update gc pointer after each statepoint: either store a relocated value or
1637 // null (if no relocated value was found for this gc pointer and it is not a
1638 // gc_result). This must happen before we update the statepoint with load of
1639 // alloca otherwise we lose the link between statepoint and old def.
1640 for (const auto &Info : Records) {
Igor Laevsky285fe842015-05-19 16:29:43 +00001641 Value *Statepoint = Info.StatepointToken;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001642
1643 // This will be used for consistency check
Igor Laevsky285fe842015-05-19 16:29:43 +00001644 DenseSet<Value *> VisitedLiveValues;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001645
1646 // Insert stores for normal statepoint gc relocates
Igor Laevsky285fe842015-05-19 16:29:43 +00001647 insertRelocationStores(Statepoint->users(), AllocaMap, VisitedLiveValues);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001648
1649 // In case if it was invoke statepoint
1650 // we will insert stores for exceptional path gc relocates.
Philip Reames0a3240f2015-02-20 21:34:11 +00001651 if (isa<InvokeInst>(Statepoint)) {
Igor Laevsky285fe842015-05-19 16:29:43 +00001652 insertRelocationStores(Info.UnwindToken->users(), AllocaMap,
1653 VisitedLiveValues);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001654 }
1655
Igor Laevskye0317182015-05-19 15:59:05 +00001656 // Do similar thing with rematerialized values
Igor Laevsky285fe842015-05-19 16:29:43 +00001657 insertRematerializationStores(Info.RematerializedValues, AllocaMap,
1658 VisitedLiveValues);
Igor Laevskye0317182015-05-19 15:59:05 +00001659
Philip Reamese73300b2015-04-13 16:41:32 +00001660 if (ClobberNonLive) {
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001661 // As a debugging aid, pretend that an unrelocated pointer becomes null at
Philip Reamese73300b2015-04-13 16:41:32 +00001662 // the gc.statepoint. This will turn some subtle GC problems into
1663 // slightly easier to debug SEGVs. Note that on large IR files with
1664 // lots of gc.statepoints this is extremely costly both memory and time
1665 // wise.
1666 SmallVector<AllocaInst *, 64> ToClobber;
Igor Laevsky285fe842015-05-19 16:29:43 +00001667 for (auto Pair : AllocaMap) {
Philip Reamese73300b2015-04-13 16:41:32 +00001668 Value *Def = Pair.first;
1669 AllocaInst *Alloca = cast<AllocaInst>(Pair.second);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001670
Philip Reamese73300b2015-04-13 16:41:32 +00001671 // This value was relocated
Igor Laevsky285fe842015-05-19 16:29:43 +00001672 if (VisitedLiveValues.count(Def)) {
Philip Reamese73300b2015-04-13 16:41:32 +00001673 continue;
1674 }
1675 ToClobber.push_back(Alloca);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001676 }
Philip Reamesfa2fcf172015-02-20 19:51:56 +00001677
Philip Reamese73300b2015-04-13 16:41:32 +00001678 auto InsertClobbersAt = [&](Instruction *IP) {
1679 for (auto *AI : ToClobber) {
Eduard Burtescu90c44492016-01-18 00:10:01 +00001680 auto PT = cast<PointerType>(AI->getAllocatedType());
Philip Reamese73300b2015-04-13 16:41:32 +00001681 Constant *CPN = ConstantPointerNull::get(PT);
Igor Laevsky285fe842015-05-19 16:29:43 +00001682 StoreInst *Store = new StoreInst(CPN, AI);
1683 Store->insertBefore(IP);
Philip Reamese73300b2015-04-13 16:41:32 +00001684 }
1685 };
1686
1687 // Insert the clobbering stores. These may get intermixed with the
1688 // gc.results and gc.relocates, but that's fine.
1689 if (auto II = dyn_cast<InvokeInst>(Statepoint)) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001690 InsertClobbersAt(&*II->getNormalDest()->getFirstInsertionPt());
1691 InsertClobbersAt(&*II->getUnwindDest()->getFirstInsertionPt());
Philip Reamese73300b2015-04-13 16:41:32 +00001692 } else {
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001693 InsertClobbersAt(cast<Instruction>(Statepoint)->getNextNode());
Philip Reamesfa2fcf172015-02-20 19:51:56 +00001694 }
David Blaikie82ad7872015-02-20 23:44:24 +00001695 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00001696 }
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001697
1698 // Update use with load allocas and add store for gc_relocated.
Igor Laevsky285fe842015-05-19 16:29:43 +00001699 for (auto Pair : AllocaMap) {
1700 Value *Def = Pair.first;
1701 Value *Alloca = Pair.second;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001702
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001703 // We pre-record the uses of allocas so that we dont have to worry about
1704 // later update that changes the user information..
1705
Igor Laevsky285fe842015-05-19 16:29:43 +00001706 SmallVector<Instruction *, 20> Uses;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001707 // PERF: trade a linear scan for repeated reallocation
Igor Laevsky285fe842015-05-19 16:29:43 +00001708 Uses.reserve(std::distance(Def->user_begin(), Def->user_end()));
1709 for (User *U : Def->users()) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001710 if (!isa<ConstantExpr>(U)) {
1711 // If the def has a ConstantExpr use, then the def is either a
1712 // ConstantExpr use itself or null. In either case
1713 // (recursively in the first, directly in the second), the oop
1714 // it is ultimately dependent on is null and this particular
1715 // use does not need to be fixed up.
Igor Laevsky285fe842015-05-19 16:29:43 +00001716 Uses.push_back(cast<Instruction>(U));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001717 }
1718 }
1719
Igor Laevsky285fe842015-05-19 16:29:43 +00001720 std::sort(Uses.begin(), Uses.end());
1721 auto Last = std::unique(Uses.begin(), Uses.end());
1722 Uses.erase(Last, Uses.end());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001723
Igor Laevsky285fe842015-05-19 16:29:43 +00001724 for (Instruction *Use : Uses) {
1725 if (isa<PHINode>(Use)) {
1726 PHINode *Phi = cast<PHINode>(Use);
1727 for (unsigned i = 0; i < Phi->getNumIncomingValues(); i++) {
1728 if (Def == Phi->getIncomingValue(i)) {
1729 LoadInst *Load = new LoadInst(
1730 Alloca, "", Phi->getIncomingBlock(i)->getTerminator());
1731 Phi->setIncomingValue(i, Load);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001732 }
1733 }
1734 } else {
Igor Laevsky285fe842015-05-19 16:29:43 +00001735 LoadInst *Load = new LoadInst(Alloca, "", Use);
1736 Use->replaceUsesOfWith(Def, Load);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001737 }
1738 }
1739
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001740 // Emit store for the initial gc value. Store must be inserted after load,
1741 // otherwise store will be in alloca's use list and an extra load will be
1742 // inserted before it.
Igor Laevsky285fe842015-05-19 16:29:43 +00001743 StoreInst *Store = new StoreInst(Def, Alloca);
1744 if (Instruction *Inst = dyn_cast<Instruction>(Def)) {
1745 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(Inst)) {
Philip Reames6da37852015-03-04 00:13:52 +00001746 // InvokeInst is a TerminatorInst so the store need to be inserted
1747 // into its normal destination block.
Igor Laevsky285fe842015-05-19 16:29:43 +00001748 BasicBlock *NormalDest = Invoke->getNormalDest();
1749 Store->insertBefore(NormalDest->getFirstNonPHI());
Philip Reames6da37852015-03-04 00:13:52 +00001750 } else {
Igor Laevsky285fe842015-05-19 16:29:43 +00001751 assert(!Inst->isTerminator() &&
Philip Reames6da37852015-03-04 00:13:52 +00001752 "The only TerminatorInst that can produce a value is "
1753 "InvokeInst which is handled above.");
Igor Laevsky285fe842015-05-19 16:29:43 +00001754 Store->insertAfter(Inst);
Philip Reames6da37852015-03-04 00:13:52 +00001755 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00001756 } else {
Igor Laevsky285fe842015-05-19 16:29:43 +00001757 assert(isa<Argument>(Def));
1758 Store->insertAfter(cast<Instruction>(Alloca));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001759 }
1760 }
1761
Igor Laevsky285fe842015-05-19 16:29:43 +00001762 assert(PromotableAllocas.size() == Live.size() + NumRematerializedValues &&
Philip Reamesd16a9b12015-02-20 01:06:44 +00001763 "we must have the same allocas with lives");
1764 if (!PromotableAllocas.empty()) {
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001765 // Apply mem2reg to promote alloca to SSA
Philip Reamesd16a9b12015-02-20 01:06:44 +00001766 PromoteMemToReg(PromotableAllocas, DT);
1767 }
1768
1769#ifndef NDEBUG
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001770 for (auto &I : F.getEntryBlock())
1771 if (isa<AllocaInst>(I))
Philip Reamesa6ebf072015-03-27 05:53:16 +00001772 InitialAllocaNum--;
1773 assert(InitialAllocaNum == 0 && "We must not introduce any extra allocas");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001774#endif
1775}
1776
1777/// Implement a unique function which doesn't require we sort the input
1778/// vector. Doing so has the effect of changing the output of a couple of
1779/// tests in ways which make them less useful in testing fused safepoints.
Philip Reamesd2b66462015-02-20 22:39:41 +00001780template <typename T> static void unique_unsorted(SmallVectorImpl<T> &Vec) {
Benjamin Kramer258ea0d2015-06-13 19:50:38 +00001781 SmallSet<T, 8> Seen;
David Majnemerc7004902016-08-12 04:32:37 +00001782 Vec.erase(remove_if(Vec, [&](const T &V) { return !Seen.insert(V).second; }),
1783 Vec.end());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001784}
1785
Philip Reamesd16a9b12015-02-20 01:06:44 +00001786/// Insert holders so that each Value is obviously live through the entire
Philip Reamesf209a152015-04-13 20:00:30 +00001787/// lifetime of the call.
Philip Reamesd16a9b12015-02-20 01:06:44 +00001788static void insertUseHolderAfter(CallSite &CS, const ArrayRef<Value *> Values,
Philip Reamesf209a152015-04-13 20:00:30 +00001789 SmallVectorImpl<CallInst *> &Holders) {
Philip Reames21142752015-04-13 19:07:47 +00001790 if (Values.empty())
1791 // No values to hold live, might as well not insert the empty holder
1792 return;
1793
Sanjay Patelaf674fb2015-12-14 17:24:23 +00001794 Module *M = CS.getInstruction()->getModule();
Philip Reamesf209a152015-04-13 20:00:30 +00001795 // Use a dummy vararg function to actually hold the values live
1796 Function *Func = cast<Function>(M->getOrInsertFunction(
1797 "__tmp_use", FunctionType::get(Type::getVoidTy(M->getContext()), true)));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001798 if (CS.isCall()) {
1799 // For call safepoints insert dummy calls right after safepoint
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001800 Holders.push_back(CallInst::Create(Func, Values, "",
1801 &*++CS.getInstruction()->getIterator()));
Philip Reamesf209a152015-04-13 20:00:30 +00001802 return;
1803 }
1804 // For invoke safepooints insert dummy calls both in normal and
1805 // exceptional destination blocks
1806 auto *II = cast<InvokeInst>(CS.getInstruction());
1807 Holders.push_back(CallInst::Create(
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001808 Func, Values, "", &*II->getNormalDest()->getFirstInsertionPt()));
Philip Reamesf209a152015-04-13 20:00:30 +00001809 Holders.push_back(CallInst::Create(
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001810 Func, Values, "", &*II->getUnwindDest()->getFirstInsertionPt()));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001811}
1812
1813static void findLiveReferences(
Justin Bogner843fb202015-12-15 19:40:57 +00001814 Function &F, DominatorTree &DT, ArrayRef<CallSite> toUpdate,
Philip Reamesd2b66462015-02-20 22:39:41 +00001815 MutableArrayRef<struct PartiallyConstructedSafepointRecord> records) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00001816 GCPtrLivenessData OriginalLivenessData;
1817 computeLiveInValues(DT, F, OriginalLivenessData);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001818 for (size_t i = 0; i < records.size(); i++) {
1819 struct PartiallyConstructedSafepointRecord &info = records[i];
Sanjoy Dasa3244872016-06-17 00:45:00 +00001820 analyzeParsePointLiveness(DT, OriginalLivenessData, toUpdate[i], info);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001821 }
1822}
1823
Igor Laevskye0317182015-05-19 15:59:05 +00001824// Helper function for the "rematerializeLiveValues". It walks use chain
Anna Thomas8cd7de12016-09-20 21:36:02 +00001825// starting from the "CurrentValue" until it reaches the root of the chain, i.e.
1826// the base or a value it cannot process. Only "simple" values are processed
1827// (currently it is GEP's and casts). The returned root is examined by the
1828// callers of findRematerializableChainToBasePointer. Fills "ChainToBase" array
1829// with all visited values.
1830static Value* findRematerializableChainToBasePointer(
Igor Laevskye0317182015-05-19 15:59:05 +00001831 SmallVectorImpl<Instruction*> &ChainToBase,
Anna Thomas8cd7de12016-09-20 21:36:02 +00001832 Value *CurrentValue) {
Anna Thomas2bc129c2016-08-29 15:41:59 +00001833
Igor Laevskye0317182015-05-19 15:59:05 +00001834 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurrentValue)) {
1835 ChainToBase.push_back(GEP);
1836 return findRematerializableChainToBasePointer(ChainToBase,
Anna Thomas8cd7de12016-09-20 21:36:02 +00001837 GEP->getPointerOperand());
Igor Laevskye0317182015-05-19 15:59:05 +00001838 }
1839
1840 if (CastInst *CI = dyn_cast<CastInst>(CurrentValue)) {
Igor Laevskye0317182015-05-19 15:59:05 +00001841 if (!CI->isNoopCast(CI->getModule()->getDataLayout()))
Anna Thomas8cd7de12016-09-20 21:36:02 +00001842 return CI;
Igor Laevskye0317182015-05-19 15:59:05 +00001843
1844 ChainToBase.push_back(CI);
Manuel Jacob9db5b932015-12-28 20:14:05 +00001845 return findRematerializableChainToBasePointer(ChainToBase,
Anna Thomas8cd7de12016-09-20 21:36:02 +00001846 CI->getOperand(0));
Igor Laevskye0317182015-05-19 15:59:05 +00001847 }
1848
Anna Thomas8cd7de12016-09-20 21:36:02 +00001849 // We have reached the root of the chain, which is either equal to the base or
1850 // is the first unsupported value along the use chain.
1851 return CurrentValue;
Igor Laevskye0317182015-05-19 15:59:05 +00001852}
1853
1854// Helper function for the "rematerializeLiveValues". Compute cost of the use
1855// chain we are going to rematerialize.
1856static unsigned
1857chainToBasePointerCost(SmallVectorImpl<Instruction*> &Chain,
1858 TargetTransformInfo &TTI) {
1859 unsigned Cost = 0;
1860
1861 for (Instruction *Instr : Chain) {
1862 if (CastInst *CI = dyn_cast<CastInst>(Instr)) {
1863 assert(CI->isNoopCast(CI->getModule()->getDataLayout()) &&
1864 "non noop cast is found during rematerialization");
1865
1866 Type *SrcTy = CI->getOperand(0)->getType();
Jonas Paulssonfccc7d62017-04-12 11:49:08 +00001867 Cost += TTI.getCastInstrCost(CI->getOpcode(), CI->getType(), SrcTy, CI);
Igor Laevskye0317182015-05-19 15:59:05 +00001868
1869 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Instr)) {
1870 // Cost of the address calculation
Eduard Burtescu19eb0312016-01-19 17:28:00 +00001871 Type *ValTy = GEP->getSourceElementType();
Igor Laevskye0317182015-05-19 15:59:05 +00001872 Cost += TTI.getAddressComputationCost(ValTy);
1873
1874 // And cost of the GEP itself
1875 // TODO: Use TTI->getGEPCost here (it exists, but appears to be not
1876 // allowed for the external usage)
1877 if (!GEP->hasAllConstantIndices())
1878 Cost += 2;
1879
1880 } else {
1881 llvm_unreachable("unsupported instruciton type during rematerialization");
1882 }
1883 }
1884
1885 return Cost;
1886}
1887
Anna Thomas8cd7de12016-09-20 21:36:02 +00001888static bool AreEquivalentPhiNodes(PHINode &OrigRootPhi, PHINode &AlternateRootPhi) {
1889
1890 unsigned PhiNum = OrigRootPhi.getNumIncomingValues();
1891 if (PhiNum != AlternateRootPhi.getNumIncomingValues() ||
1892 OrigRootPhi.getParent() != AlternateRootPhi.getParent())
1893 return false;
1894 // Map of incoming values and their corresponding basic blocks of
1895 // OrigRootPhi.
1896 SmallDenseMap<Value *, BasicBlock *, 8> CurrentIncomingValues;
1897 for (unsigned i = 0; i < PhiNum; i++)
1898 CurrentIncomingValues[OrigRootPhi.getIncomingValue(i)] =
1899 OrigRootPhi.getIncomingBlock(i);
1900
1901 // Both current and base PHIs should have same incoming values and
1902 // the same basic blocks corresponding to the incoming values.
1903 for (unsigned i = 0; i < PhiNum; i++) {
1904 auto CIVI =
1905 CurrentIncomingValues.find(AlternateRootPhi.getIncomingValue(i));
1906 if (CIVI == CurrentIncomingValues.end())
1907 return false;
1908 BasicBlock *CurrentIncomingBB = CIVI->second;
1909 if (CurrentIncomingBB != AlternateRootPhi.getIncomingBlock(i))
1910 return false;
1911 }
1912 return true;
1913
1914}
1915
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001916// From the statepoint live set pick values that are cheaper to recompute then
1917// to relocate. Remove this values from the live set, rematerialize them after
Igor Laevskye0317182015-05-19 15:59:05 +00001918// statepoint and record them in "Info" structure. Note that similar to
1919// relocated values we don't do any user adjustments here.
1920static void rematerializeLiveValues(CallSite CS,
1921 PartiallyConstructedSafepointRecord &Info,
1922 TargetTransformInfo &TTI) {
Aaron Ballmanff7d4fa2015-05-20 14:53:50 +00001923 const unsigned int ChainLengthThreshold = 10;
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +00001924
Igor Laevskye0317182015-05-19 15:59:05 +00001925 // Record values we are going to delete from this statepoint live set.
1926 // We can not di this in following loop due to iterator invalidation.
1927 SmallVector<Value *, 32> LiveValuesToBeDeleted;
1928
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001929 for (Value *LiveValue: Info.LiveSet) {
Igor Laevskye0317182015-05-19 15:59:05 +00001930 // For each live pointer find it's defining chain
1931 SmallVector<Instruction *, 3> ChainToBase;
Philip Reames74ce2e72015-07-21 16:51:17 +00001932 assert(Info.PointerToBase.count(LiveValue));
Anna Thomas8cd7de12016-09-20 21:36:02 +00001933 Value *RootOfChain =
Igor Laevskye0317182015-05-19 15:59:05 +00001934 findRematerializableChainToBasePointer(ChainToBase,
Anna Thomas8cd7de12016-09-20 21:36:02 +00001935 LiveValue);
1936
Igor Laevskye0317182015-05-19 15:59:05 +00001937 // Nothing to do, or chain is too long
Anna Thomas8cd7de12016-09-20 21:36:02 +00001938 if ( ChainToBase.size() == 0 ||
Igor Laevskye0317182015-05-19 15:59:05 +00001939 ChainToBase.size() > ChainLengthThreshold)
1940 continue;
1941
Anna Thomas8cd7de12016-09-20 21:36:02 +00001942 // Handle the scenario where the RootOfChain is not equal to the
1943 // Base Value, but they are essentially the same phi values.
1944 if (RootOfChain != Info.PointerToBase[LiveValue]) {
1945 PHINode *OrigRootPhi = dyn_cast<PHINode>(RootOfChain);
1946 PHINode *AlternateRootPhi = dyn_cast<PHINode>(Info.PointerToBase[LiveValue]);
1947 if (!OrigRootPhi || !AlternateRootPhi)
1948 continue;
1949 // PHI nodes that have the same incoming values, and belonging to the same
1950 // basic blocks are essentially the same SSA value. When the original phi
1951 // has incoming values with different base pointers, the original phi is
1952 // marked as conflict, and an additional `AlternateRootPhi` with the same
1953 // incoming values get generated by the findBasePointer function. We need
1954 // to identify the newly generated AlternateRootPhi (.base version of phi)
1955 // and RootOfChain (the original phi node itself) are the same, so that we
1956 // can rematerialize the gep and casts. This is a workaround for the
Hiroshi Inoueef1c2ba2017-07-01 07:12:15 +00001957 // deficiency in the findBasePointer algorithm.
Anna Thomas8cd7de12016-09-20 21:36:02 +00001958 if (!AreEquivalentPhiNodes(*OrigRootPhi, *AlternateRootPhi))
1959 continue;
1960 // Now that the phi nodes are proved to be the same, assert that
1961 // findBasePointer's newly generated AlternateRootPhi is present in the
1962 // liveset of the call.
1963 assert(Info.LiveSet.count(AlternateRootPhi));
1964 }
Igor Laevskye0317182015-05-19 15:59:05 +00001965 // Compute cost of this chain
1966 unsigned Cost = chainToBasePointerCost(ChainToBase, TTI);
1967 // TODO: We can also account for cases when we will be able to remove some
1968 // of the rematerialized values by later optimization passes. I.e if
1969 // we rematerialized several intersecting chains. Or if original values
1970 // don't have any uses besides this statepoint.
1971
1972 // For invokes we need to rematerialize each chain twice - for normal and
1973 // for unwind basic blocks. Model this by multiplying cost by two.
1974 if (CS.isInvoke()) {
1975 Cost *= 2;
1976 }
1977 // If it's too expensive - skip it
1978 if (Cost >= RematerializationThreshold)
1979 continue;
1980
1981 // Remove value from the live set
1982 LiveValuesToBeDeleted.push_back(LiveValue);
1983
1984 // Clone instructions and record them inside "Info" structure
1985
1986 // Walk backwards to visit top-most instructions first
1987 std::reverse(ChainToBase.begin(), ChainToBase.end());
1988
1989 // Utility function which clones all instructions from "ChainToBase"
1990 // and inserts them before "InsertBefore". Returns rematerialized value
1991 // which should be used after statepoint.
Anna Thomas82c37172016-09-22 13:13:06 +00001992 auto rematerializeChain = [&ChainToBase](
1993 Instruction *InsertBefore, Value *RootOfChain, Value *AlternateLiveBase) {
Igor Laevskye0317182015-05-19 15:59:05 +00001994 Instruction *LastClonedValue = nullptr;
1995 Instruction *LastValue = nullptr;
1996 for (Instruction *Instr: ChainToBase) {
1997 // Only GEP's and casts are suported as we need to be careful to not
1998 // introduce any new uses of pointers not in the liveset.
1999 // Note that it's fine to introduce new uses of pointers which were
2000 // otherwise not used after this statepoint.
2001 assert(isa<GetElementPtrInst>(Instr) || isa<CastInst>(Instr));
2002
2003 Instruction *ClonedValue = Instr->clone();
2004 ClonedValue->insertBefore(InsertBefore);
2005 ClonedValue->setName(Instr->getName() + ".remat");
2006
2007 // If it is not first instruction in the chain then it uses previously
2008 // cloned value. We should update it to use cloned value.
2009 if (LastClonedValue) {
2010 assert(LastValue);
2011 ClonedValue->replaceUsesOfWith(LastValue, LastClonedValue);
2012#ifndef NDEBUG
Igor Laevskyd83f6972015-05-21 13:02:14 +00002013 for (auto OpValue : ClonedValue->operand_values()) {
Anna Thomas82c37172016-09-22 13:13:06 +00002014 // Assert that cloned instruction does not use any instructions from
2015 // this chain other than LastClonedValue
David Majnemer0d955d02016-08-11 22:21:41 +00002016 assert(!is_contained(ChainToBase, OpValue) &&
Igor Laevskyd83f6972015-05-21 13:02:14 +00002017 "incorrect use in rematerialization chain");
Anna Thomas82c37172016-09-22 13:13:06 +00002018 // Assert that the cloned instruction does not use the RootOfChain
2019 // or the AlternateLiveBase.
2020 assert(OpValue != RootOfChain && OpValue != AlternateLiveBase);
Igor Laevskye0317182015-05-19 15:59:05 +00002021 }
2022#endif
Anna Thomas82c37172016-09-22 13:13:06 +00002023 } else {
2024 // For the first instruction, replace the use of unrelocated base i.e.
2025 // RootOfChain/OrigRootPhi, with the corresponding PHI present in the
2026 // live set. They have been proved to be the same PHI nodes. Note
2027 // that the *only* use of the RootOfChain in the ChainToBase list is
2028 // the first Value in the list.
2029 if (RootOfChain != AlternateLiveBase)
2030 ClonedValue->replaceUsesOfWith(RootOfChain, AlternateLiveBase);
Igor Laevskye0317182015-05-19 15:59:05 +00002031 }
2032
2033 LastClonedValue = ClonedValue;
2034 LastValue = Instr;
2035 }
2036 assert(LastClonedValue);
2037 return LastClonedValue;
2038 };
2039
2040 // Different cases for calls and invokes. For invokes we need to clone
2041 // instructions both on normal and unwind path.
2042 if (CS.isCall()) {
2043 Instruction *InsertBefore = CS.getInstruction()->getNextNode();
2044 assert(InsertBefore);
Anna Thomas82c37172016-09-22 13:13:06 +00002045 Instruction *RematerializedValue = rematerializeChain(
2046 InsertBefore, RootOfChain, Info.PointerToBase[LiveValue]);
Igor Laevskye0317182015-05-19 15:59:05 +00002047 Info.RematerializedValues[RematerializedValue] = LiveValue;
2048 } else {
2049 InvokeInst *Invoke = cast<InvokeInst>(CS.getInstruction());
2050
2051 Instruction *NormalInsertBefore =
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00002052 &*Invoke->getNormalDest()->getFirstInsertionPt();
Igor Laevskye0317182015-05-19 15:59:05 +00002053 Instruction *UnwindInsertBefore =
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00002054 &*Invoke->getUnwindDest()->getFirstInsertionPt();
Igor Laevskye0317182015-05-19 15:59:05 +00002055
Anna Thomas82c37172016-09-22 13:13:06 +00002056 Instruction *NormalRematerializedValue = rematerializeChain(
2057 NormalInsertBefore, RootOfChain, Info.PointerToBase[LiveValue]);
2058 Instruction *UnwindRematerializedValue = rematerializeChain(
2059 UnwindInsertBefore, RootOfChain, Info.PointerToBase[LiveValue]);
Igor Laevskye0317182015-05-19 15:59:05 +00002060
2061 Info.RematerializedValues[NormalRematerializedValue] = LiveValue;
2062 Info.RematerializedValues[UnwindRematerializedValue] = LiveValue;
2063 }
2064 }
2065
2066 // Remove rematerializaed values from the live set
2067 for (auto LiveValue: LiveValuesToBeDeleted) {
Igor Laevskyfb1811d2016-05-04 14:55:36 +00002068 Info.LiveSet.remove(LiveValue);
Igor Laevskye0317182015-05-19 15:59:05 +00002069 }
2070}
2071
Justin Bogner843fb202015-12-15 19:40:57 +00002072static bool insertParsePoints(Function &F, DominatorTree &DT,
2073 TargetTransformInfo &TTI,
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002074 SmallVectorImpl<CallSite> &ToUpdate) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00002075#ifndef NDEBUG
2076 // sanity check the input
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002077 std::set<CallSite> Uniqued;
2078 Uniqued.insert(ToUpdate.begin(), ToUpdate.end());
2079 assert(Uniqued.size() == ToUpdate.size() && "no duplicates please!");
Philip Reamesd16a9b12015-02-20 01:06:44 +00002080
Sanjoy Dasbcf27522016-01-29 01:03:20 +00002081 for (CallSite CS : ToUpdate)
2082 assert(CS.getInstruction()->getFunction() == &F);
Philip Reamesd16a9b12015-02-20 01:06:44 +00002083#endif
2084
Philip Reames69e51ca2015-04-13 18:07:21 +00002085 // When inserting gc.relocates for invokes, we need to be able to insert at
2086 // the top of the successor blocks. See the comment on
2087 // normalForInvokeSafepoint on exactly what is needed. Note that this step
Philip Reamesf209a152015-04-13 20:00:30 +00002088 // may restructure the CFG.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002089 for (CallSite CS : ToUpdate) {
Philip Reamesf209a152015-04-13 20:00:30 +00002090 if (!CS.isInvoke())
2091 continue;
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002092 auto *II = cast<InvokeInst>(CS.getInstruction());
2093 normalizeForInvokeSafepoint(II->getNormalDest(), II->getParent(), DT);
2094 normalizeForInvokeSafepoint(II->getUnwindDest(), II->getParent(), DT);
Philip Reamesf209a152015-04-13 20:00:30 +00002095 }
Philip Reames69e51ca2015-04-13 18:07:21 +00002096
Philip Reamesd16a9b12015-02-20 01:06:44 +00002097 // A list of dummy calls added to the IR to keep various values obviously
2098 // live in the IR. We'll remove all of these when done.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002099 SmallVector<CallInst *, 64> Holders;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002100
Philip Reamesb70cecd2017-06-02 23:03:26 +00002101 // Insert a dummy call with all of the deopt operands we'll need for the
2102 // actual safepoint insertion as arguments. This ensures reference operands
2103 // in the deopt argument list are considered live through the safepoint (and
Philip Reamesd16a9b12015-02-20 01:06:44 +00002104 // thus makes sure they get relocated.)
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002105 for (CallSite CS : ToUpdate) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00002106 SmallVector<Value *, 64> DeoptValues;
Sanjoy Das25ec1a32015-10-16 02:41:00 +00002107
Sanjoy Das40992972016-01-29 01:03:17 +00002108 for (Value *Arg : GetDeoptBundleOperands(CS)) {
Philip Reames8531d8c2015-04-10 21:48:25 +00002109 assert(!isUnhandledGCPointerType(Arg->getType()) &&
2110 "support for FCA unimplemented");
2111 if (isHandledGCPointerType(Arg->getType()))
Philip Reamesd16a9b12015-02-20 01:06:44 +00002112 DeoptValues.push_back(Arg);
2113 }
Sanjoy Das25ec1a32015-10-16 02:41:00 +00002114
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002115 insertUseHolderAfter(CS, DeoptValues, Holders);
Philip Reamesd16a9b12015-02-20 01:06:44 +00002116 }
2117
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002118 SmallVector<PartiallyConstructedSafepointRecord, 64> Records(ToUpdate.size());
Philip Reamesd16a9b12015-02-20 01:06:44 +00002119
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002120 // A) Identify all gc pointers which are statically live at the given call
Philip Reamesd16a9b12015-02-20 01:06:44 +00002121 // site.
Justin Bogner843fb202015-12-15 19:40:57 +00002122 findLiveReferences(F, DT, ToUpdate, Records);
Philip Reamesd16a9b12015-02-20 01:06:44 +00002123
2124 // B) Find the base pointers for each live pointer
2125 /* scope for caching */ {
2126 // Cache the 'defining value' relation used in the computation and
2127 // insertion of base phis and selects. This ensures that we don't insert
2128 // large numbers of duplicate base_phis.
2129 DefiningValueMapTy DVCache;
2130
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002131 for (size_t i = 0; i < Records.size(); i++) {
2132 PartiallyConstructedSafepointRecord &info = Records[i];
2133 findBasePointers(DT, DVCache, ToUpdate[i], info);
Philip Reamesd16a9b12015-02-20 01:06:44 +00002134 }
2135 } // end of cache scope
2136
2137 // The base phi insertion logic (for any safepoint) may have inserted new
2138 // instructions which are now live at some safepoint. The simplest such
2139 // example is:
2140 // loop:
2141 // phi a <-- will be a new base_phi here
2142 // safepoint 1 <-- that needs to be live here
2143 // gep a + 1
2144 // safepoint 2
2145 // br loop
Philip Reamesd16a9b12015-02-20 01:06:44 +00002146 // We insert some dummy calls after each safepoint to definitely hold live
2147 // the base pointers which were identified for that safepoint. We'll then
2148 // ask liveness for _every_ base inserted to see what is now live. Then we
2149 // remove the dummy calls.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002150 Holders.reserve(Holders.size() + Records.size());
2151 for (size_t i = 0; i < Records.size(); i++) {
2152 PartiallyConstructedSafepointRecord &Info = Records[i];
Philip Reamesd16a9b12015-02-20 01:06:44 +00002153
2154 SmallVector<Value *, 128> Bases;
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002155 for (auto Pair : Info.PointerToBase)
Philip Reamesd16a9b12015-02-20 01:06:44 +00002156 Bases.push_back(Pair.second);
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002157
2158 insertUseHolderAfter(ToUpdate[i], Bases, Holders);
Philip Reamesd16a9b12015-02-20 01:06:44 +00002159 }
2160
Philip Reamesdf1ef082015-04-10 22:53:14 +00002161 // By selecting base pointers, we've effectively inserted new uses. Thus, we
2162 // need to rerun liveness. We may *also* have inserted new defs, but that's
2163 // not the key issue.
Justin Bogner843fb202015-12-15 19:40:57 +00002164 recomputeLiveInValues(F, DT, ToUpdate, Records);
Philip Reamesd16a9b12015-02-20 01:06:44 +00002165
Philip Reamesd16a9b12015-02-20 01:06:44 +00002166 if (PrintBasePointers) {
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002167 for (auto &Info : Records) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00002168 errs() << "Base Pairs: (w/Relocation)\n";
Manuel Jacoba4efd8a2015-12-23 00:19:45 +00002169 for (auto Pair : Info.PointerToBase) {
2170 errs() << " derived ";
2171 Pair.first->printAsOperand(errs(), false);
2172 errs() << " base ";
2173 Pair.second->printAsOperand(errs(), false);
2174 errs() << "\n";
2175 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00002176 }
2177 }
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002178
Manuel Jacob990dfa62015-12-22 16:50:44 +00002179 // It is possible that non-constant live variables have a constant base. For
2180 // example, a GEP with a variable offset from a global. In this case we can
2181 // remove it from the liveset. We already don't add constants to the liveset
2182 // because we assume they won't move at runtime and the GC doesn't need to be
2183 // informed about them. The same reasoning applies if the base is constant.
2184 // Note that the relocation placement code relies on this filtering for
2185 // correctness as it expects the base to be in the liveset, which isn't true
2186 // if the base is constant.
2187 for (auto &Info : Records)
2188 for (auto &BasePair : Info.PointerToBase)
2189 if (isa<Constant>(BasePair.second))
Igor Laevskyfb1811d2016-05-04 14:55:36 +00002190 Info.LiveSet.remove(BasePair.first);
Manuel Jacob990dfa62015-12-22 16:50:44 +00002191
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002192 for (CallInst *CI : Holders)
2193 CI->eraseFromParent();
2194
2195 Holders.clear();
Philip Reamesd16a9b12015-02-20 01:06:44 +00002196
Igor Laevskye0317182015-05-19 15:59:05 +00002197 // In order to reduce live set of statepoint we might choose to rematerialize
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002198 // some values instead of relocating them. This is purely an optimization and
Igor Laevskye0317182015-05-19 15:59:05 +00002199 // does not influence correctness.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002200 for (size_t i = 0; i < Records.size(); i++)
2201 rematerializeLiveValues(ToUpdate[i], Records[i], TTI);
Igor Laevskye0317182015-05-19 15:59:05 +00002202
Sanjoy Das25ec1a32015-10-16 02:41:00 +00002203 // We need this to safely RAUW and delete call or invoke return values that
2204 // may themselves be live over a statepoint. For details, please see usage in
2205 // makeStatepointExplicitImpl.
2206 std::vector<DeferredReplacement> Replacements;
2207
Philip Reamesd16a9b12015-02-20 01:06:44 +00002208 // Now run through and replace the existing statepoints with new ones with
2209 // the live variables listed. We do not yet update uses of the values being
2210 // relocated. We have references to live variables that need to
2211 // survive to the last iteration of this loop. (By construction, the
2212 // previous statepoint can not be a live variable, thus we can and remove
2213 // the old statepoint calls as we go.)
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002214 for (size_t i = 0; i < Records.size(); i++)
Sanjoy Das25ec1a32015-10-16 02:41:00 +00002215 makeStatepointExplicit(DT, ToUpdate[i], Records[i], Replacements);
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002216
2217 ToUpdate.clear(); // prevent accident use of invalid CallSites
Philip Reamesd16a9b12015-02-20 01:06:44 +00002218
Sanjoy Das25ec1a32015-10-16 02:41:00 +00002219 for (auto &PR : Replacements)
2220 PR.doReplacement();
2221
2222 Replacements.clear();
2223
2224 for (auto &Info : Records) {
2225 // These live sets may contain state Value pointers, since we replaced calls
2226 // with operand bundles with calls wrapped in gc.statepoint, and some of
2227 // those calls may have been def'ing live gc pointers. Clear these out to
2228 // avoid accidentally using them.
2229 //
2230 // TODO: We should create a separate data structure that does not contain
2231 // these live sets, and migrate to using that data structure from this point
2232 // onward.
2233 Info.LiveSet.clear();
2234 Info.PointerToBase.clear();
2235 }
2236
Philip Reamesd16a9b12015-02-20 01:06:44 +00002237 // Do all the fixups of the original live variables to their relocated selves
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002238 SmallVector<Value *, 128> Live;
2239 for (size_t i = 0; i < Records.size(); i++) {
2240 PartiallyConstructedSafepointRecord &Info = Records[i];
Sanjoy Das25ec1a32015-10-16 02:41:00 +00002241
Philip Reamesd16a9b12015-02-20 01:06:44 +00002242 // We can't simply save the live set from the original insertion. One of
2243 // the live values might be the result of a call which needs a safepoint.
2244 // That Value* no longer exists and we need to use the new gc_result.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002245 // Thankfully, the live set is embedded in the statepoint (and updated), so
Philip Reamesd16a9b12015-02-20 01:06:44 +00002246 // we just grab that.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002247 Statepoint Statepoint(Info.StatepointToken);
2248 Live.insert(Live.end(), Statepoint.gc_args_begin(),
2249 Statepoint.gc_args_end());
Philip Reames9a2e01d2015-04-13 17:35:55 +00002250#ifndef NDEBUG
2251 // Do some basic sanity checks on our liveness results before performing
2252 // relocation. Relocation can and will turn mistakes in liveness results
2253 // into non-sensical code which is must harder to debug.
2254 // TODO: It would be nice to test consistency as well
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002255 assert(DT.isReachableFromEntry(Info.StatepointToken->getParent()) &&
Philip Reames9a2e01d2015-04-13 17:35:55 +00002256 "statepoint must be reachable or liveness is meaningless");
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002257 for (Value *V : Statepoint.gc_args()) {
Philip Reames9a2e01d2015-04-13 17:35:55 +00002258 if (!isa<Instruction>(V))
2259 // Non-instruction values trivial dominate all possible uses
2260 continue;
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002261 auto *LiveInst = cast<Instruction>(V);
Philip Reames9a2e01d2015-04-13 17:35:55 +00002262 assert(DT.isReachableFromEntry(LiveInst->getParent()) &&
2263 "unreachable values should never be live");
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002264 assert(DT.dominates(LiveInst, Info.StatepointToken) &&
Philip Reames9a2e01d2015-04-13 17:35:55 +00002265 "basic SSA liveness expectation violated by liveness analysis");
2266 }
2267#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +00002268 }
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002269 unique_unsorted(Live);
Philip Reamesd16a9b12015-02-20 01:06:44 +00002270
Nick Lewyckyeb3231e2015-02-20 07:14:02 +00002271#ifndef NDEBUG
Philip Reamesd16a9b12015-02-20 01:06:44 +00002272 // sanity check
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002273 for (auto *Ptr : Live)
Philip Reames5715f572016-01-09 01:31:13 +00002274 assert(isHandledGCPointerType(Ptr->getType()) &&
2275 "must be a gc pointer type");
Nick Lewyckyeb3231e2015-02-20 07:14:02 +00002276#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +00002277
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002278 relocationViaAlloca(F, DT, Live, Records);
2279 return !Records.empty();
Philip Reamesd16a9b12015-02-20 01:06:44 +00002280}
2281
Sanjoy Das353a19e2015-06-02 22:33:37 +00002282// Handles both return values and arguments for Functions and CallSites.
2283template <typename AttrHolder>
Igor Laevskydde00292015-10-23 22:42:44 +00002284static void RemoveNonValidAttrAtIndex(LLVMContext &Ctx, AttrHolder &AH,
2285 unsigned Index) {
Sanjoy Das353a19e2015-06-02 22:33:37 +00002286 AttrBuilder R;
2287 if (AH.getDereferenceableBytes(Index))
2288 R.addAttribute(Attribute::get(Ctx, Attribute::Dereferenceable,
2289 AH.getDereferenceableBytes(Index)));
2290 if (AH.getDereferenceableOrNullBytes(Index))
2291 R.addAttribute(Attribute::get(Ctx, Attribute::DereferenceableOrNull,
2292 AH.getDereferenceableOrNullBytes(Index)));
Reid Klecknera0b45f42017-05-03 18:17:31 +00002293 if (AH.getAttributes().hasAttribute(Index, Attribute::NoAlias))
Igor Laevsky1ef06552015-10-26 19:06:01 +00002294 R.addAttribute(Attribute::NoAlias);
Sanjoy Das353a19e2015-06-02 22:33:37 +00002295
2296 if (!R.empty())
Reid Kleckneree4930b2017-05-02 22:07:37 +00002297 AH.setAttributes(AH.getAttributes().removeAttributes(Ctx, Index, R));
Vasileios Kalintiris9f77f612015-06-03 08:51:30 +00002298}
Sanjoy Das353a19e2015-06-02 22:33:37 +00002299
2300void
Igor Laevskydde00292015-10-23 22:42:44 +00002301RewriteStatepointsForGC::stripNonValidAttributesFromPrototype(Function &F) {
Sanjoy Das353a19e2015-06-02 22:33:37 +00002302 LLVMContext &Ctx = F.getContext();
2303
2304 for (Argument &A : F.args())
2305 if (isa<PointerType>(A.getType()))
Reid Klecknera0b45f42017-05-03 18:17:31 +00002306 RemoveNonValidAttrAtIndex(Ctx, F,
2307 A.getArgNo() + AttributeList::FirstArgIndex);
Sanjoy Das353a19e2015-06-02 22:33:37 +00002308
2309 if (isa<PointerType>(F.getReturnType()))
Reid Klecknerb5180542017-03-21 16:57:19 +00002310 RemoveNonValidAttrAtIndex(Ctx, F, AttributeList::ReturnIndex);
Sanjoy Das353a19e2015-06-02 22:33:37 +00002311}
2312
Anna Thomas4b027e82017-06-12 21:26:53 +00002313void RewriteStatepointsForGC::stripInvalidMetadataFromInstruction(Instruction &I) {
2314
2315 if (!isa<LoadInst>(I) && !isa<StoreInst>(I))
2316 return;
2317 // These are the attributes that are still valid on loads and stores after
2318 // RS4GC.
2319 // The metadata implying dereferenceability and noalias are (conservatively)
2320 // dropped. This is because semantically, after RewriteStatepointsForGC runs,
2321 // all calls to gc.statepoint "free" the entire heap. Also, gc.statepoint can
2322 // touch the entire heap including noalias objects. Note: The reasoning is
2323 // same as stripping the dereferenceability and noalias attributes that are
2324 // analogous to the metadata counterparts.
2325 // We also drop the invariant.load metadata on the load because that metadata
2326 // implies the address operand to the load points to memory that is never
2327 // changed once it became dereferenceable. This is no longer true after RS4GC.
2328 // Similar reasoning applies to invariant.group metadata, which applies to
2329 // loads within a group.
2330 unsigned ValidMetadataAfterRS4GC[] = {LLVMContext::MD_tbaa,
2331 LLVMContext::MD_range,
2332 LLVMContext::MD_alias_scope,
2333 LLVMContext::MD_nontemporal,
2334 LLVMContext::MD_nonnull,
2335 LLVMContext::MD_align,
2336 LLVMContext::MD_type};
2337
2338 // Drops all metadata on the instruction other than ValidMetadataAfterRS4GC.
2339 I.dropUnknownNonDebugMetadata(ValidMetadataAfterRS4GC);
2340
2341}
2342
2343void RewriteStatepointsForGC::stripNonValidAttributesAndMetadataFromBody(Function &F) {
Sanjoy Das353a19e2015-06-02 22:33:37 +00002344 if (F.empty())
2345 return;
2346
2347 LLVMContext &Ctx = F.getContext();
2348 MDBuilder Builder(Ctx);
2349
Anna Thomas4b027e82017-06-12 21:26:53 +00002350
Nico Rieck78199512015-08-06 19:10:45 +00002351 for (Instruction &I : instructions(F)) {
Sanjoy Das353a19e2015-06-02 22:33:37 +00002352 if (const MDNode *MD = I.getMetadata(LLVMContext::MD_tbaa)) {
2353 assert(MD->getNumOperands() < 5 && "unrecognized metadata shape!");
2354 bool IsImmutableTBAA =
2355 MD->getNumOperands() == 4 &&
2356 mdconst::extract<ConstantInt>(MD->getOperand(3))->getValue() == 1;
2357
2358 if (!IsImmutableTBAA)
2359 continue; // no work to do, MD_tbaa is already marked mutable
2360
2361 MDNode *Base = cast<MDNode>(MD->getOperand(0));
2362 MDNode *Access = cast<MDNode>(MD->getOperand(1));
2363 uint64_t Offset =
2364 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue();
2365
2366 MDNode *MutableTBAA =
2367 Builder.createTBAAStructTagNode(Base, Access, Offset);
2368 I.setMetadata(LLVMContext::MD_tbaa, MutableTBAA);
2369 }
2370
Anna Thomas4b027e82017-06-12 21:26:53 +00002371 stripInvalidMetadataFromInstruction(I);
2372
Sanjoy Das353a19e2015-06-02 22:33:37 +00002373 if (CallSite CS = CallSite(&I)) {
2374 for (int i = 0, e = CS.arg_size(); i != e; i++)
2375 if (isa<PointerType>(CS.getArgument(i)->getType()))
Reid Klecknera0b45f42017-05-03 18:17:31 +00002376 RemoveNonValidAttrAtIndex(Ctx, CS, i + AttributeList::FirstArgIndex);
Sanjoy Das353a19e2015-06-02 22:33:37 +00002377 if (isa<PointerType>(CS.getType()))
Reid Klecknerb5180542017-03-21 16:57:19 +00002378 RemoveNonValidAttrAtIndex(Ctx, CS, AttributeList::ReturnIndex);
Sanjoy Das353a19e2015-06-02 22:33:37 +00002379 }
2380 }
2381}
2382
Philip Reamesd16a9b12015-02-20 01:06:44 +00002383/// Returns true if this function should be rewritten by this pass. The main
2384/// point of this function is as an extension point for custom logic.
2385static bool shouldRewriteStatepointsIn(Function &F) {
2386 // TODO: This should check the GCStrategy
Philip Reames2ef029c2015-02-20 18:56:14 +00002387 if (F.hasGC()) {
Mehdi Amini599ebf22016-01-08 02:28:20 +00002388 const auto &FunctionGCName = F.getGC();
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +00002389 const StringRef StatepointExampleName("statepoint-example");
2390 const StringRef CoreCLRName("coreclr");
2391 return (StatepointExampleName == FunctionGCName) ||
NAKAMURA Takumi5582a6a2015-05-25 01:43:34 +00002392 (CoreCLRName == FunctionGCName);
2393 } else
Philip Reames2ef029c2015-02-20 18:56:14 +00002394 return false;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002395}
2396
Anna Thomas4b027e82017-06-12 21:26:53 +00002397void RewriteStatepointsForGC::stripNonValidAttributesAndMetadata(Module &M) {
Sanjoy Das353a19e2015-06-02 22:33:37 +00002398#ifndef NDEBUG
David Majnemer0a16c222016-08-11 21:15:00 +00002399 assert(any_of(M, shouldRewriteStatepointsIn) && "precondition!");
Sanjoy Das353a19e2015-06-02 22:33:37 +00002400#endif
2401
2402 for (Function &F : M)
Igor Laevskydde00292015-10-23 22:42:44 +00002403 stripNonValidAttributesFromPrototype(F);
Sanjoy Das353a19e2015-06-02 22:33:37 +00002404
2405 for (Function &F : M)
Anna Thomas4b027e82017-06-12 21:26:53 +00002406 stripNonValidAttributesAndMetadataFromBody(F);
Sanjoy Das353a19e2015-06-02 22:33:37 +00002407}
2408
Philip Reamesd16a9b12015-02-20 01:06:44 +00002409bool RewriteStatepointsForGC::runOnFunction(Function &F) {
2410 // Nothing to do for declarations.
2411 if (F.isDeclaration() || F.empty())
2412 return false;
2413
2414 // Policy choice says not to rewrite - the most common reason is that we're
2415 // compiling code without a GCStrategy.
2416 if (!shouldRewriteStatepointsIn(F))
2417 return false;
2418
Sanjoy Dasea45f0e2015-06-02 22:33:34 +00002419 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
Justin Bogner843fb202015-12-15 19:40:57 +00002420 TargetTransformInfo &TTI =
2421 getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
Philip Reames704e78b2015-04-10 22:34:56 +00002422
Sanjoy Das25ec1a32015-10-16 02:41:00 +00002423 auto NeedsRewrite = [](Instruction &I) {
Sanjoy Das40992972016-01-29 01:03:17 +00002424 if (ImmutableCallSite CS = ImmutableCallSite(&I))
Sanjoy Dasd4c78332016-03-25 20:12:13 +00002425 return !callsGCLeafFunction(CS) && !isStatepoint(CS);
Sanjoy Das40992972016-01-29 01:03:17 +00002426 return false;
Sanjoy Das25ec1a32015-10-16 02:41:00 +00002427 };
2428
Philip Reames85b36a82015-04-10 22:07:04 +00002429 // Gather all the statepoints which need rewritten. Be careful to only
2430 // consider those in reachable code since we need to ask dominance queries
2431 // when rewriting. We'll delete the unreachable ones in a moment.
Philip Reamesd2b66462015-02-20 22:39:41 +00002432 SmallVector<CallSite, 64> ParsePointNeeded;
Philip Reamesf66d7372015-04-10 22:16:58 +00002433 bool HasUnreachableStatepoint = false;
Nico Rieck78199512015-08-06 19:10:45 +00002434 for (Instruction &I : instructions(F)) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00002435 // TODO: only the ones with the flag set!
Sanjoy Das25ec1a32015-10-16 02:41:00 +00002436 if (NeedsRewrite(I)) {
Philip Reames85b36a82015-04-10 22:07:04 +00002437 if (DT.isReachableFromEntry(I.getParent()))
2438 ParsePointNeeded.push_back(CallSite(&I));
2439 else
Philip Reamesf66d7372015-04-10 22:16:58 +00002440 HasUnreachableStatepoint = true;
Philip Reames85b36a82015-04-10 22:07:04 +00002441 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00002442 }
2443
Philip Reames85b36a82015-04-10 22:07:04 +00002444 bool MadeChange = false;
Philip Reames704e78b2015-04-10 22:34:56 +00002445
Philip Reames85b36a82015-04-10 22:07:04 +00002446 // Delete any unreachable statepoints so that we don't have unrewritten
2447 // statepoints surviving this pass. This makes testing easier and the
2448 // resulting IR less confusing to human readers. Rather than be fancy, we
2449 // just reuse a utility function which removes the unreachable blocks.
Philip Reamesf66d7372015-04-10 22:16:58 +00002450 if (HasUnreachableStatepoint)
Philip Reames85b36a82015-04-10 22:07:04 +00002451 MadeChange |= removeUnreachableBlocks(F);
2452
Philip Reamesd16a9b12015-02-20 01:06:44 +00002453 // Return early if no work to do.
2454 if (ParsePointNeeded.empty())
Philip Reames85b36a82015-04-10 22:07:04 +00002455 return MadeChange;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002456
Philip Reames85b36a82015-04-10 22:07:04 +00002457 // As a prepass, go ahead and aggressively destroy single entry phi nodes.
2458 // These are created by LCSSA. They have the effect of increasing the size
2459 // of liveness sets for no good reason. It may be harder to do this post
2460 // insertion since relocations and base phis can confuse things.
2461 for (BasicBlock &BB : F)
2462 if (BB.getUniquePredecessor()) {
2463 MadeChange = true;
2464 FoldSingleEntryPHINodes(&BB);
2465 }
2466
Philip Reames971dc3a2015-08-12 22:11:45 +00002467 // Before we start introducing relocations, we want to tweak the IR a bit to
2468 // avoid unfortunate code generation effects. The main example is that we
2469 // want to try to make sure the comparison feeding a branch is after any
2470 // safepoints. Otherwise, we end up with a comparison of pre-relocation
2471 // values feeding a branch after relocation. This is semantically correct,
2472 // but results in extra register pressure since both the pre-relocation and
2473 // post-relocation copies must be available in registers. For code without
2474 // relocations this is handled elsewhere, but teaching the scheduler to
2475 // reverse the transform we're about to do would be slightly complex.
2476 // Note: This may extend the live range of the inputs to the icmp and thus
2477 // increase the liveset of any statepoint we move over. This is profitable
2478 // as long as all statepoints are in rare blocks. If we had in-register
2479 // lowering for live values this would be a much safer transform.
2480 auto getConditionInst = [](TerminatorInst *TI) -> Instruction* {
2481 if (auto *BI = dyn_cast<BranchInst>(TI))
2482 if (BI->isConditional())
2483 return dyn_cast<Instruction>(BI->getCondition());
2484 // TODO: Extend this to handle switches
2485 return nullptr;
2486 };
2487 for (BasicBlock &BB : F) {
2488 TerminatorInst *TI = BB.getTerminator();
2489 if (auto *Cond = getConditionInst(TI))
2490 // TODO: Handle more than just ICmps here. We should be able to move
2491 // most instructions without side effects or memory access.
2492 if (isa<ICmpInst>(Cond) && Cond->hasOneUse()) {
2493 MadeChange = true;
2494 Cond->moveBefore(TI);
2495 }
2496 }
2497
Justin Bogner843fb202015-12-15 19:40:57 +00002498 MadeChange |= insertParsePoints(F, DT, TTI, ParsePointNeeded);
Philip Reames85b36a82015-04-10 22:07:04 +00002499 return MadeChange;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002500}
Philip Reamesdf1ef082015-04-10 22:53:14 +00002501
2502// liveness computation via standard dataflow
2503// -------------------------------------------------------------------
2504
2505// TODO: Consider using bitvectors for liveness, the set of potentially
2506// interesting values should be small and easy to pre-compute.
2507
Philip Reamesdf1ef082015-04-10 22:53:14 +00002508/// Compute the live-in set for the location rbegin starting from
2509/// the live-out set of the basic block
Sanjoy Das61c76e32016-06-26 04:55:32 +00002510static void computeLiveInValues(BasicBlock::reverse_iterator Begin,
2511 BasicBlock::reverse_iterator End,
Igor Laevskyfb1811d2016-05-04 14:55:36 +00002512 SetVector<Value *> &LiveTmp) {
Sanjoy Das61c76e32016-06-26 04:55:32 +00002513 for (auto &I : make_range(Begin, End)) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00002514 // KILL/Def - Remove this definition from LiveIn
Sanjoy Das61c76e32016-06-26 04:55:32 +00002515 LiveTmp.remove(&I);
Philip Reamesdf1ef082015-04-10 22:53:14 +00002516
2517 // Don't consider *uses* in PHI nodes, we handle their contribution to
2518 // predecessor blocks when we seed the LiveOut sets
2519 if (isa<PHINode>(I))
2520 continue;
2521
2522 // USE - Add to the LiveIn set for this instruction
Sanjoy Das61c76e32016-06-26 04:55:32 +00002523 for (Value *V : I.operands()) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00002524 assert(!isUnhandledGCPointerType(V->getType()) &&
2525 "support for FCA unimplemented");
Philip Reames63294cb2015-04-26 19:48:03 +00002526 if (isHandledGCPointerType(V->getType()) && !isa<Constant>(V)) {
2527 // The choice to exclude all things constant here is slightly subtle.
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002528 // There are two independent reasons:
Philip Reames63294cb2015-04-26 19:48:03 +00002529 // - We assume that things which are constant (from LLVM's definition)
2530 // do not move at runtime. For example, the address of a global
2531 // variable is fixed, even though it's contents may not be.
2532 // - Second, we can't disallow arbitrary inttoptr constants even
2533 // if the language frontend does. Optimization passes are free to
2534 // locally exploit facts without respect to global reachability. This
2535 // can create sections of code which are dynamically unreachable and
2536 // contain just about anything. (see constants.ll in tests)
Philip Reamesdf1ef082015-04-10 22:53:14 +00002537 LiveTmp.insert(V);
2538 }
2539 }
2540 }
2541}
2542
Igor Laevskyfb1811d2016-05-04 14:55:36 +00002543static void computeLiveOutSeed(BasicBlock *BB, SetVector<Value *> &LiveTmp) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00002544 for (BasicBlock *Succ : successors(BB)) {
Sanjoy Das83186b02016-06-26 04:55:30 +00002545 for (auto &I : *Succ) {
2546 PHINode *PN = dyn_cast<PHINode>(&I);
2547 if (!PN)
2548 break;
2549
2550 Value *V = PN->getIncomingValueForBlock(BB);
Philip Reamesdf1ef082015-04-10 22:53:14 +00002551 assert(!isUnhandledGCPointerType(V->getType()) &&
2552 "support for FCA unimplemented");
Sanjoy Das83186b02016-06-26 04:55:30 +00002553 if (isHandledGCPointerType(V->getType()) && !isa<Constant>(V))
Philip Reamesdf1ef082015-04-10 22:53:14 +00002554 LiveTmp.insert(V);
Philip Reamesdf1ef082015-04-10 22:53:14 +00002555 }
2556 }
2557}
2558
Igor Laevskyfb1811d2016-05-04 14:55:36 +00002559static SetVector<Value *> computeKillSet(BasicBlock *BB) {
2560 SetVector<Value *> KillSet;
Philip Reamesdf1ef082015-04-10 22:53:14 +00002561 for (Instruction &I : *BB)
2562 if (isHandledGCPointerType(I.getType()))
2563 KillSet.insert(&I);
2564 return KillSet;
2565}
2566
Philip Reames9638ff92015-04-11 00:06:47 +00002567#ifndef NDEBUG
Philip Reamesdf1ef082015-04-10 22:53:14 +00002568/// Check that the items in 'Live' dominate 'TI'. This is used as a basic
2569/// sanity check for the liveness computation.
Igor Laevskyfb1811d2016-05-04 14:55:36 +00002570static void checkBasicSSA(DominatorTree &DT, SetVector<Value *> &Live,
Philip Reamesdf1ef082015-04-10 22:53:14 +00002571 TerminatorInst *TI, bool TermOkay = false) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00002572 for (Value *V : Live) {
2573 if (auto *I = dyn_cast<Instruction>(V)) {
2574 // The terminator can be a member of the LiveOut set. LLVM's definition
2575 // of instruction dominance states that V does not dominate itself. As
2576 // such, we need to special case this to allow it.
2577 if (TermOkay && TI == I)
2578 continue;
2579 assert(DT.dominates(I, TI) &&
2580 "basic SSA liveness expectation violated by liveness analysis");
2581 }
2582 }
Philip Reamesdf1ef082015-04-10 22:53:14 +00002583}
2584
2585/// Check that all the liveness sets used during the computation of liveness
2586/// obey basic SSA properties. This is useful for finding cases where we miss
2587/// a def.
2588static void checkBasicSSA(DominatorTree &DT, GCPtrLivenessData &Data,
2589 BasicBlock &BB) {
2590 checkBasicSSA(DT, Data.LiveSet[&BB], BB.getTerminator());
2591 checkBasicSSA(DT, Data.LiveOut[&BB], BB.getTerminator(), true);
2592 checkBasicSSA(DT, Data.LiveIn[&BB], BB.getTerminator());
2593}
Philip Reames9638ff92015-04-11 00:06:47 +00002594#endif
Philip Reamesdf1ef082015-04-10 22:53:14 +00002595
2596static void computeLiveInValues(DominatorTree &DT, Function &F,
2597 GCPtrLivenessData &Data) {
Matthias Braunb30f2f512016-01-30 01:24:31 +00002598 SmallSetVector<BasicBlock *, 32> Worklist;
Philip Reamesdf1ef082015-04-10 22:53:14 +00002599
2600 // Seed the liveness for each individual block
2601 for (BasicBlock &BB : F) {
2602 Data.KillSet[&BB] = computeKillSet(&BB);
2603 Data.LiveSet[&BB].clear();
2604 computeLiveInValues(BB.rbegin(), BB.rend(), Data.LiveSet[&BB]);
2605
2606#ifndef NDEBUG
2607 for (Value *Kill : Data.KillSet[&BB])
2608 assert(!Data.LiveSet[&BB].count(Kill) && "live set contains kill");
2609#endif
2610
Igor Laevskyfb1811d2016-05-04 14:55:36 +00002611 Data.LiveOut[&BB] = SetVector<Value *>();
Philip Reamesdf1ef082015-04-10 22:53:14 +00002612 computeLiveOutSeed(&BB, Data.LiveOut[&BB]);
2613 Data.LiveIn[&BB] = Data.LiveSet[&BB];
Igor Laevskyfb1811d2016-05-04 14:55:36 +00002614 Data.LiveIn[&BB].set_union(Data.LiveOut[&BB]);
2615 Data.LiveIn[&BB].set_subtract(Data.KillSet[&BB]);
Philip Reamesdf1ef082015-04-10 22:53:14 +00002616 if (!Data.LiveIn[&BB].empty())
Sanjoy Dasb2df57a2016-06-26 04:55:26 +00002617 Worklist.insert(pred_begin(&BB), pred_end(&BB));
Philip Reamesdf1ef082015-04-10 22:53:14 +00002618 }
2619
2620 // Propagate that liveness until stable
2621 while (!Worklist.empty()) {
Sanjoy Dasb2df57a2016-06-26 04:55:26 +00002622 BasicBlock *BB = Worklist.pop_back_val();
Philip Reamesdf1ef082015-04-10 22:53:14 +00002623
Sanjoy Dasb2df57a2016-06-26 04:55:26 +00002624 // Compute our new liveout set, then exit early if it hasn't changed despite
2625 // the contribution of our successor.
Igor Laevskyfb1811d2016-05-04 14:55:36 +00002626 SetVector<Value *> LiveOut = Data.LiveOut[BB];
Philip Reamesdf1ef082015-04-10 22:53:14 +00002627 const auto OldLiveOutSize = LiveOut.size();
2628 for (BasicBlock *Succ : successors(BB)) {
2629 assert(Data.LiveIn.count(Succ));
Igor Laevskyfb1811d2016-05-04 14:55:36 +00002630 LiveOut.set_union(Data.LiveIn[Succ]);
Philip Reamesdf1ef082015-04-10 22:53:14 +00002631 }
2632 // assert OutLiveOut is a subset of LiveOut
2633 if (OldLiveOutSize == LiveOut.size()) {
2634 // If the sets are the same size, then we didn't actually add anything
Sanjoy Dasb2df57a2016-06-26 04:55:26 +00002635 // when unioning our successors LiveIn. Thus, the LiveIn of this block
Philip Reamesdf1ef082015-04-10 22:53:14 +00002636 // hasn't changed.
2637 continue;
2638 }
2639 Data.LiveOut[BB] = LiveOut;
2640
2641 // Apply the effects of this basic block
Igor Laevskyfb1811d2016-05-04 14:55:36 +00002642 SetVector<Value *> LiveTmp = LiveOut;
2643 LiveTmp.set_union(Data.LiveSet[BB]);
2644 LiveTmp.set_subtract(Data.KillSet[BB]);
Philip Reamesdf1ef082015-04-10 22:53:14 +00002645
2646 assert(Data.LiveIn.count(BB));
Igor Laevskyfb1811d2016-05-04 14:55:36 +00002647 const SetVector<Value *> &OldLiveIn = Data.LiveIn[BB];
Philip Reamesdf1ef082015-04-10 22:53:14 +00002648 // assert: OldLiveIn is a subset of LiveTmp
2649 if (OldLiveIn.size() != LiveTmp.size()) {
2650 Data.LiveIn[BB] = LiveTmp;
Sanjoy Dasb2df57a2016-06-26 04:55:26 +00002651 Worklist.insert(pred_begin(BB), pred_end(BB));
Philip Reamesdf1ef082015-04-10 22:53:14 +00002652 }
Sanjoy Dasb2df57a2016-06-26 04:55:26 +00002653 } // while (!Worklist.empty())
Philip Reamesdf1ef082015-04-10 22:53:14 +00002654
2655#ifndef NDEBUG
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002656 // Sanity check our output against SSA properties. This helps catch any
Philip Reamesdf1ef082015-04-10 22:53:14 +00002657 // missing kills during the above iteration.
Sanjoy Dasb2df57a2016-06-26 04:55:26 +00002658 for (BasicBlock &BB : F)
Philip Reamesdf1ef082015-04-10 22:53:14 +00002659 checkBasicSSA(DT, Data, BB);
Philip Reamesdf1ef082015-04-10 22:53:14 +00002660#endif
2661}
2662
2663static void findLiveSetAtInst(Instruction *Inst, GCPtrLivenessData &Data,
2664 StatepointLiveSetTy &Out) {
2665
2666 BasicBlock *BB = Inst->getParent();
2667
2668 // Note: The copy is intentional and required
2669 assert(Data.LiveOut.count(BB));
Igor Laevskyfb1811d2016-05-04 14:55:36 +00002670 SetVector<Value *> LiveOut = Data.LiveOut[BB];
Philip Reamesdf1ef082015-04-10 22:53:14 +00002671
2672 // We want to handle the statepoint itself oddly. It's
2673 // call result is not live (normal), nor are it's arguments
2674 // (unless they're used again later). This adjustment is
2675 // specifically what we need to relocate
Duncan P. N. Exon Smith5c001c32016-08-30 00:13:12 +00002676 computeLiveInValues(BB->rbegin(), ++Inst->getIterator().getReverse(),
2677 LiveOut);
Igor Laevskyfb1811d2016-05-04 14:55:36 +00002678 LiveOut.remove(Inst);
Philip Reamesdf1ef082015-04-10 22:53:14 +00002679 Out.insert(LiveOut.begin(), LiveOut.end());
2680}
2681
2682static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData,
Sanjoy Dasa3244872016-06-17 00:45:00 +00002683 CallSite CS,
Philip Reamesdf1ef082015-04-10 22:53:14 +00002684 PartiallyConstructedSafepointRecord &Info) {
2685 Instruction *Inst = CS.getInstruction();
2686 StatepointLiveSetTy Updated;
2687 findLiveSetAtInst(Inst, RevisedLivenessData, Updated);
2688
2689#ifndef NDEBUG
2690 DenseSet<Value *> Bases;
Sanjoy Das255532f2016-06-26 04:55:23 +00002691 for (auto KVPair : Info.PointerToBase)
Philip Reamesdf1ef082015-04-10 22:53:14 +00002692 Bases.insert(KVPair.second);
Philip Reamesdf1ef082015-04-10 22:53:14 +00002693#endif
Sanjoy Das255532f2016-06-26 04:55:23 +00002694
Philip Reamesdf1ef082015-04-10 22:53:14 +00002695 // We may have base pointers which are now live that weren't before. We need
2696 // to update the PointerToBase structure to reflect this.
2697 for (auto V : Updated)
Sanjoy Das255532f2016-06-26 04:55:23 +00002698 if (Info.PointerToBase.insert({V, V}).second) {
2699 assert(Bases.count(V) && "Can't find base for unexpected live value!");
Philip Reamesdf1ef082015-04-10 22:53:14 +00002700 continue;
2701 }
2702
2703#ifndef NDEBUG
Sanjoy Das255532f2016-06-26 04:55:23 +00002704 for (auto V : Updated)
Philip Reamesdf1ef082015-04-10 22:53:14 +00002705 assert(Info.PointerToBase.count(V) &&
Sanjoy Das255532f2016-06-26 04:55:23 +00002706 "Must be able to find base for live value!");
Philip Reamesdf1ef082015-04-10 22:53:14 +00002707#endif
2708
2709 // Remove any stale base mappings - this can happen since our liveness is
Sanjoy Das255532f2016-06-26 04:55:23 +00002710 // more precise then the one inherent in the base pointer analysis.
Philip Reamesdf1ef082015-04-10 22:53:14 +00002711 DenseSet<Value *> ToErase;
2712 for (auto KVPair : Info.PointerToBase)
2713 if (!Updated.count(KVPair.first))
2714 ToErase.insert(KVPair.first);
Sanjoy Das255532f2016-06-26 04:55:23 +00002715
2716 for (auto *V : ToErase)
Philip Reamesdf1ef082015-04-10 22:53:14 +00002717 Info.PointerToBase.erase(V);
2718
2719#ifndef NDEBUG
2720 for (auto KVPair : Info.PointerToBase)
2721 assert(Updated.count(KVPair.first) && "record for non-live value");
2722#endif
2723
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002724 Info.LiveSet = Updated;
Philip Reamesdf1ef082015-04-10 22:53:14 +00002725}