blob: 1ca77cfec32922813f0272278fb827f2d112fe2c [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
Eugene Zelenko75075ef2017-09-01 21:37:29 +000015#include "llvm/ADT/ArrayRef.h"
16#include "llvm/ADT/DenseMap.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000017#include "llvm/ADT/DenseSet.h"
18#include "llvm/ADT/MapVector.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000019#include "llvm/ADT/None.h"
20#include "llvm/ADT/Optional.h"
21#include "llvm/ADT/STLExtras.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000022#include "llvm/ADT/SetVector.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000023#include "llvm/ADT/SmallSet.h"
24#include "llvm/ADT/SmallVector.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000025#include "llvm/ADT/StringRef.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000026#include "llvm/ADT/iterator_range.h"
Daniel Neilson2574d7c2017-07-27 16:49:39 +000027#include "llvm/Analysis/TargetLibraryInfo.h"
Igor Laevskye0317182015-05-19 15:59:05 +000028#include "llvm/Analysis/TargetTransformInfo.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000029#include "llvm/IR/Argument.h"
30#include "llvm/IR/Attributes.h"
Philip Reamesd16a9b12015-02-20 01:06:44 +000031#include "llvm/IR/BasicBlock.h"
32#include "llvm/IR/CallSite.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000033#include "llvm/IR/CallingConv.h"
34#include "llvm/IR/Constant.h"
35#include "llvm/IR/Constants.h"
36#include "llvm/IR/DataLayout.h"
37#include "llvm/IR/DerivedTypes.h"
Philip Reamesd16a9b12015-02-20 01:06:44 +000038#include "llvm/IR/Dominators.h"
39#include "llvm/IR/Function.h"
40#include "llvm/IR/IRBuilder.h"
41#include "llvm/IR/InstIterator.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000042#include "llvm/IR/InstrTypes.h"
43#include "llvm/IR/Instruction.h"
Philip Reamesd16a9b12015-02-20 01:06:44 +000044#include "llvm/IR/Instructions.h"
Philip Reamesd16a9b12015-02-20 01:06:44 +000045#include "llvm/IR/IntrinsicInst.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000046#include "llvm/IR/Intrinsics.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000047#include "llvm/IR/LLVMContext.h"
Sanjoy Das353a19e2015-06-02 22:33:37 +000048#include "llvm/IR/MDBuilder.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000049#include "llvm/IR/Metadata.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000050#include "llvm/IR/Module.h"
Philip Reamesd16a9b12015-02-20 01:06:44 +000051#include "llvm/IR/Statepoint.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000052#include "llvm/IR/Type.h"
53#include "llvm/IR/User.h"
Philip Reamesd16a9b12015-02-20 01:06:44 +000054#include "llvm/IR/Value.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000055#include "llvm/IR/ValueHandle.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000056#include "llvm/Pass.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000057#include "llvm/Support/Casting.h"
Philip Reamesd16a9b12015-02-20 01:06:44 +000058#include "llvm/Support/CommandLine.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000059#include "llvm/Support/Compiler.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000060#include "llvm/Support/Debug.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000061#include "llvm/Support/ErrorHandling.h"
62#include "llvm/Support/raw_ostream.h"
Philip Reamesd16a9b12015-02-20 01:06:44 +000063#include "llvm/Transforms/Scalar.h"
64#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Philip Reamesd16a9b12015-02-20 01:06:44 +000065#include "llvm/Transforms/Utils/Local.h"
66#include "llvm/Transforms/Utils/PromoteMemToReg.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000067#include <algorithm>
68#include <cassert>
69#include <cstddef>
70#include <cstdint>
71#include <iterator>
72#include <set>
73#include <string>
74#include <utility>
75#include <vector>
Philip Reamesd16a9b12015-02-20 01:06:44 +000076
77#define DEBUG_TYPE "rewrite-statepoints-for-gc"
78
79using namespace llvm;
80
Philip Reamesd16a9b12015-02-20 01:06:44 +000081// Print the liveset found at the insert location
82static cl::opt<bool> PrintLiveSet("spp-print-liveset", cl::Hidden,
83 cl::init(false));
Philip Reames704e78b2015-04-10 22:34:56 +000084static cl::opt<bool> PrintLiveSetSize("spp-print-liveset-size", cl::Hidden,
85 cl::init(false));
Eugene Zelenko75075ef2017-09-01 21:37:29 +000086
Philip Reamesd16a9b12015-02-20 01:06:44 +000087// Print out the base pointers for debugging
Philip Reames704e78b2015-04-10 22:34:56 +000088static cl::opt<bool> PrintBasePointers("spp-print-base-pointers", cl::Hidden,
89 cl::init(false));
Philip Reamesd16a9b12015-02-20 01:06:44 +000090
Igor Laevskye0317182015-05-19 15:59:05 +000091// Cost threshold measuring when it is profitable to rematerialize value instead
92// of relocating it
93static cl::opt<unsigned>
94RematerializationThreshold("spp-rematerialization-threshold", cl::Hidden,
95 cl::init(6));
96
Filipe Cabecinhas0da99372016-04-29 15:22:48 +000097#ifdef EXPENSIVE_CHECKS
Philip Reamese73300b2015-04-13 16:41:32 +000098static bool ClobberNonLive = true;
99#else
100static bool ClobberNonLive = false;
101#endif
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000102
Philip Reamese73300b2015-04-13 16:41:32 +0000103static cl::opt<bool, true> ClobberNonLiveOverride("rs4gc-clobber-non-live",
104 cl::location(ClobberNonLive),
105 cl::Hidden);
106
Sanjoy Das25ec1a32015-10-16 02:41:00 +0000107static cl::opt<bool>
108 AllowStatepointWithNoDeoptInfo("rs4gc-allow-statepoint-with-no-deopt-info",
109 cl::Hidden, cl::init(true));
110
Benjamin Kramer6f665452015-02-20 14:00:58 +0000111namespace {
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000112
Sanjoy Dasea45f0e2015-06-02 22:33:34 +0000113struct RewriteStatepointsForGC : public ModulePass {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000114 static char ID; // Pass identification, replacement for typeid
115
Sanjoy Dasea45f0e2015-06-02 22:33:34 +0000116 RewriteStatepointsForGC() : ModulePass(ID) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000117 initializeRewriteStatepointsForGCPass(*PassRegistry::getPassRegistry());
118 }
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000119
Sanjoy Dasea45f0e2015-06-02 22:33:34 +0000120 bool runOnFunction(Function &F);
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000121
Sanjoy Dasea45f0e2015-06-02 22:33:34 +0000122 bool runOnModule(Module &M) override {
123 bool Changed = false;
124 for (Function &F : M)
125 Changed |= runOnFunction(F);
Sanjoy Das353a19e2015-06-02 22:33:37 +0000126
127 if (Changed) {
Anna Thomas4b027e82017-06-12 21:26:53 +0000128 // stripNonValidAttributesAndMetadata asserts that shouldRewriteStatepointsIn
Sanjoy Das353a19e2015-06-02 22:33:37 +0000129 // returns true for at least one function in the module. Since at least
130 // one function changed, we know that the precondition is satisfied.
Anna Thomas4b027e82017-06-12 21:26:53 +0000131 stripNonValidAttributesAndMetadata(M);
Sanjoy Das353a19e2015-06-02 22:33:37 +0000132 }
133
Sanjoy Dasea45f0e2015-06-02 22:33:34 +0000134 return Changed;
135 }
Philip Reamesd16a9b12015-02-20 01:06:44 +0000136
137 void getAnalysisUsage(AnalysisUsage &AU) const override {
138 // We add and rewrite a bunch of instructions, but don't really do much
139 // else. We could in theory preserve a lot more analyses here.
140 AU.addRequired<DominatorTreeWrapperPass>();
Igor Laevskye0317182015-05-19 15:59:05 +0000141 AU.addRequired<TargetTransformInfoWrapperPass>();
Daniel Neilson2574d7c2017-07-27 16:49:39 +0000142 AU.addRequired<TargetLibraryInfoWrapperPass>();
Philip Reamesd16a9b12015-02-20 01:06:44 +0000143 }
Sanjoy Das353a19e2015-06-02 22:33:37 +0000144
Anna Thomas4b027e82017-06-12 21:26:53 +0000145 /// The IR fed into RewriteStatepointsForGC may have had attributes and
146 /// metadata implying dereferenceability that are no longer valid/correct after
147 /// RewriteStatepointsForGC has run. This is because semantically, after
Sanjoy Das353a19e2015-06-02 22:33:37 +0000148 /// RewriteStatepointsForGC runs, all calls to gc.statepoint "free" the entire
Anna Thomas4b027e82017-06-12 21:26:53 +0000149 /// heap. stripNonValidAttributesAndMetadata (conservatively) restores
150 /// correctness by erasing all attributes in the module that externally imply
151 /// dereferenceability. Similar reasoning also applies to the noalias
152 /// attributes and metadata. gc.statepoint can touch the entire heap including
153 /// noalias objects.
154 void stripNonValidAttributesAndMetadata(Module &M);
Sanjoy Das353a19e2015-06-02 22:33:37 +0000155
Anna Thomas4b027e82017-06-12 21:26:53 +0000156 // Helpers for stripNonValidAttributesAndMetadata
157 void stripNonValidAttributesAndMetadataFromBody(Function &F);
Igor Laevskydde00292015-10-23 22:42:44 +0000158 void stripNonValidAttributesFromPrototype(Function &F);
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000159
Anna Thomas4b027e82017-06-12 21:26:53 +0000160 // Certain metadata on instructions are invalid after running RS4GC.
161 // Optimizations that run after RS4GC can incorrectly use this metadata to
162 // optimize functions. We drop such metadata on the instruction.
163 void stripInvalidMetadataFromInstruction(Instruction &I);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000164};
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000165
166} // end anonymous namespace
Philip Reamesd16a9b12015-02-20 01:06:44 +0000167
168char RewriteStatepointsForGC::ID = 0;
169
Sanjoy Dasea45f0e2015-06-02 22:33:34 +0000170ModulePass *llvm::createRewriteStatepointsForGCPass() {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000171 return new RewriteStatepointsForGC();
172}
173
174INITIALIZE_PASS_BEGIN(RewriteStatepointsForGC, "rewrite-statepoints-for-gc",
175 "Make relocations explicit at statepoints", false, false)
176INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Davide Italiano6f852ee2016-05-16 02:29:53 +0000177INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
Philip Reamesd16a9b12015-02-20 01:06:44 +0000178INITIALIZE_PASS_END(RewriteStatepointsForGC, "rewrite-statepoints-for-gc",
179 "Make relocations explicit at statepoints", false, false)
180
181namespace {
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000182
Philip Reamesdf1ef082015-04-10 22:53:14 +0000183struct GCPtrLivenessData {
184 /// Values defined in this block.
Igor Laevskyfb1811d2016-05-04 14:55:36 +0000185 MapVector<BasicBlock *, SetVector<Value *>> KillSet;
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000186
Philip Reamesdf1ef082015-04-10 22:53:14 +0000187 /// Values used in this block (and thus live); does not included values
188 /// killed within this block.
Igor Laevskyfb1811d2016-05-04 14:55:36 +0000189 MapVector<BasicBlock *, SetVector<Value *>> LiveSet;
Philip Reamesdf1ef082015-04-10 22:53:14 +0000190
191 /// Values live into this basic block (i.e. used by any
192 /// instruction in this basic block or ones reachable from here)
Igor Laevskyfb1811d2016-05-04 14:55:36 +0000193 MapVector<BasicBlock *, SetVector<Value *>> LiveIn;
Philip Reamesdf1ef082015-04-10 22:53:14 +0000194
195 /// Values live out of this basic block (i.e. live into
196 /// any successor block)
Igor Laevskyfb1811d2016-05-04 14:55:36 +0000197 MapVector<BasicBlock *, SetVector<Value *>> LiveOut;
Philip Reamesdf1ef082015-04-10 22:53:14 +0000198};
199
Philip Reamesd16a9b12015-02-20 01:06:44 +0000200// The type of the internal cache used inside the findBasePointers family
201// of functions. From the callers perspective, this is an opaque type and
202// should not be inspected.
203//
204// In the actual implementation this caches two relations:
205// - The base relation itself (i.e. this pointer is based on that one)
206// - The base defining value relation (i.e. before base_phi insertion)
207// Generally, after the execution of a full findBasePointer call, only the
208// base relation will remain. Internally, we add a mixture of the two
209// types, then update all the second type to the first type
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000210using DefiningValueMapTy = MapVector<Value *, Value *>;
211using StatepointLiveSetTy = SetVector<Value *>;
212using RematerializedValueMapTy =
213 MapVector<AssertingVH<Instruction>, AssertingVH<Value>>;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000214
Philip Reamesd16a9b12015-02-20 01:06:44 +0000215struct PartiallyConstructedSafepointRecord {
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000216 /// The set of values known to be live across this safepoint
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +0000217 StatepointLiveSetTy LiveSet;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000218
219 /// Mapping from live pointers to a base-defining-value
Igor Laevskyfb1811d2016-05-04 14:55:36 +0000220 MapVector<Value *, Value *> PointerToBase;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000221
Philip Reames0a3240f2015-02-20 21:34:11 +0000222 /// The *new* gc.statepoint instruction itself. This produces the token
223 /// that normal path gc.relocates and the gc.result are tied to.
224 Instruction *StatepointToken;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000225
Philip Reamesf2041322015-02-20 19:26:04 +0000226 /// Instruction to which exceptional gc relocates are attached
227 /// Makes it easier to iterate through them during relocationViaAlloca.
228 Instruction *UnwindToken;
Igor Laevskye0317182015-05-19 15:59:05 +0000229
230 /// Record live values we are rematerialized instead of relocating.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +0000231 /// They are not included into 'LiveSet' field.
Igor Laevskye0317182015-05-19 15:59:05 +0000232 /// Maps rematerialized copy to it's original value.
233 RematerializedValueMapTy RematerializedValues;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000234};
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000235
236} // end anonymous namespace
Philip Reamesd16a9b12015-02-20 01:06:44 +0000237
Sanjoy Das25ec1a32015-10-16 02:41:00 +0000238static ArrayRef<Use> GetDeoptBundleOperands(ImmutableCallSite CS) {
Sanjoy Dasacc43d12016-01-22 19:20:40 +0000239 Optional<OperandBundleUse> DeoptBundle =
240 CS.getOperandBundle(LLVMContext::OB_deopt);
Sanjoy Das25ec1a32015-10-16 02:41:00 +0000241
242 if (!DeoptBundle.hasValue()) {
243 assert(AllowStatepointWithNoDeoptInfo &&
244 "Found non-leaf call without deopt info!");
245 return None;
246 }
247
248 return DeoptBundle.getValue().Inputs;
249}
250
Philip Reamesdf1ef082015-04-10 22:53:14 +0000251/// Compute the live-in set for every basic block in the function
252static void computeLiveInValues(DominatorTree &DT, Function &F,
253 GCPtrLivenessData &Data);
254
255/// Given results from the dataflow liveness computation, find the set of live
256/// Values at a particular instruction.
257static void findLiveSetAtInst(Instruction *inst, GCPtrLivenessData &Data,
258 StatepointLiveSetTy &out);
259
Philip Reamesd16a9b12015-02-20 01:06:44 +0000260// TODO: Once we can get to the GCStrategy, this becomes
Philip Reamesee8f0552015-12-23 01:42:15 +0000261// Optional<bool> isGCManagedPointer(const Type *Ty) const override {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000262
Craig Toppere3dcce92015-08-01 22:20:21 +0000263static bool isGCPointerType(Type *T) {
264 if (auto *PT = dyn_cast<PointerType>(T))
Philip Reamesd16a9b12015-02-20 01:06:44 +0000265 // For the sake of this example GC, we arbitrarily pick addrspace(1) as our
266 // GC managed heap. We know that a pointer into this heap needs to be
267 // updated and that no other pointer does.
Sanjoy Das73c7f262016-06-26 04:55:19 +0000268 return PT->getAddressSpace() == 1;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000269 return false;
270}
271
Philip Reames8531d8c2015-04-10 21:48:25 +0000272// Return true if this type is one which a) is a gc pointer or contains a GC
273// pointer and b) is of a type this code expects to encounter as a live value.
274// (The insertion code will assert that a type which matches (a) and not (b)
Philip Reames704e78b2015-04-10 22:34:56 +0000275// is not encountered.)
Philip Reames8531d8c2015-04-10 21:48:25 +0000276static bool isHandledGCPointerType(Type *T) {
277 // We fully support gc pointers
278 if (isGCPointerType(T))
279 return true;
280 // We partially support vectors of gc pointers. The code will assert if it
281 // can't handle something.
282 if (auto VT = dyn_cast<VectorType>(T))
283 if (isGCPointerType(VT->getElementType()))
284 return true;
285 return false;
286}
287
288#ifndef NDEBUG
289/// Returns true if this type contains a gc pointer whether we know how to
290/// handle that type or not.
291static bool containsGCPtrType(Type *Ty) {
Philip Reames704e78b2015-04-10 22:34:56 +0000292 if (isGCPointerType(Ty))
Philip Reames8531d8c2015-04-10 21:48:25 +0000293 return true;
294 if (VectorType *VT = dyn_cast<VectorType>(Ty))
295 return isGCPointerType(VT->getScalarType());
296 if (ArrayType *AT = dyn_cast<ArrayType>(Ty))
297 return containsGCPtrType(AT->getElementType());
298 if (StructType *ST = dyn_cast<StructType>(Ty))
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000299 return llvm::any_of(ST->subtypes(), containsGCPtrType);
Philip Reames8531d8c2015-04-10 21:48:25 +0000300 return false;
301}
302
303// Returns true if this is a type which a) is a gc pointer or contains a GC
304// pointer and b) is of a type which the code doesn't expect (i.e. first class
305// aggregates). Used to trip assertions.
306static bool isUnhandledGCPointerType(Type *Ty) {
307 return containsGCPtrType(Ty) && !isHandledGCPointerType(Ty);
308}
309#endif
310
Philip Reamesece70b82015-09-09 23:57:18 +0000311// Return the name of the value suffixed with the provided value, or if the
312// value didn't have a name, the default value specified.
313static std::string suffixed_name_or(Value *V, StringRef Suffix,
314 StringRef DefaultName) {
315 return V->hasName() ? (V->getName() + Suffix).str() : DefaultName.str();
316}
317
Philip Reamesdf1ef082015-04-10 22:53:14 +0000318// Conservatively identifies any definitions which might be live at the
319// given instruction. The analysis is performed immediately before the
320// given instruction. Values defined by that instruction are not considered
321// live. Values used by that instruction are considered live.
Sanjoy Dasa3244872016-06-17 00:45:00 +0000322static void
323analyzeParsePointLiveness(DominatorTree &DT,
324 GCPtrLivenessData &OriginalLivenessData, CallSite CS,
Sanjoy Das1e7eeb42016-06-26 04:55:17 +0000325 PartiallyConstructedSafepointRecord &Result) {
326 Instruction *Inst = CS.getInstruction();
Philip Reamesd16a9b12015-02-20 01:06:44 +0000327
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +0000328 StatepointLiveSetTy LiveSet;
Sanjoy Das1e7eeb42016-06-26 04:55:17 +0000329 findLiveSetAtInst(Inst, OriginalLivenessData, LiveSet);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000330
331 if (PrintLiveSet) {
Sanjoy Das1e7eeb42016-06-26 04:55:17 +0000332 dbgs() << "Live Variables:\n";
Igor Laevskyfb1811d2016-05-04 14:55:36 +0000333 for (Value *V : LiveSet)
Philip Reamesdab35f32015-09-02 21:11:44 +0000334 dbgs() << " " << V->getName() << " " << *V << "\n";
Philip Reamesd16a9b12015-02-20 01:06:44 +0000335 }
336 if (PrintLiveSetSize) {
Sanjoy Das1e7eeb42016-06-26 04:55:17 +0000337 dbgs() << "Safepoint For: " << CS.getCalledValue()->getName() << "\n";
338 dbgs() << "Number live values: " << LiveSet.size() << "\n";
Philip Reamesd16a9b12015-02-20 01:06:44 +0000339 }
Sanjoy Das1e7eeb42016-06-26 04:55:17 +0000340 Result.LiveSet = LiveSet;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000341}
342
Philip Reamesf5b8e472015-09-03 21:34:30 +0000343static bool isKnownBaseResult(Value *V);
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000344
Philip Reamesf5b8e472015-09-03 21:34:30 +0000345namespace {
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000346
Philip Reamesf5b8e472015-09-03 21:34:30 +0000347/// A single base defining value - An immediate base defining value for an
348/// instruction 'Def' is an input to 'Def' whose base is also a base of 'Def'.
349/// For instructions which have multiple pointer [vector] inputs or that
350/// transition between vector and scalar types, there is no immediate base
351/// defining value. The 'base defining value' for 'Def' is the transitive
352/// closure of this relation stopping at the first instruction which has no
353/// immediate base defining value. The b.d.v. might itself be a base pointer,
354/// but it can also be an arbitrary derived pointer.
355struct BaseDefiningValueResult {
356 /// Contains the value which is the base defining value.
357 Value * const BDV;
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000358
Philip Reamesf5b8e472015-09-03 21:34:30 +0000359 /// True if the base defining value is also known to be an actual base
360 /// pointer.
361 const bool IsKnownBase;
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000362
Philip Reamesf5b8e472015-09-03 21:34:30 +0000363 BaseDefiningValueResult(Value *BDV, bool IsKnownBase)
364 : BDV(BDV), IsKnownBase(IsKnownBase) {
365#ifndef NDEBUG
366 // Check consistency between new and old means of checking whether a BDV is
367 // a base.
368 bool MustBeBase = isKnownBaseResult(BDV);
369 assert(!MustBeBase || MustBeBase == IsKnownBase);
370#endif
371 }
372};
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000373
374} // end anonymous namespace
Philip Reamesf5b8e472015-09-03 21:34:30 +0000375
376static BaseDefiningValueResult findBaseDefiningValue(Value *I);
Philip Reames311f7102015-05-12 22:19:52 +0000377
Philip Reames8fe7f132015-06-26 22:47:37 +0000378/// Return a base defining value for the 'Index' element of the given vector
379/// instruction 'I'. If Index is null, returns a BDV for the entire vector
380/// 'I'. As an optimization, this method will try to determine when the
381/// element is known to already be a base pointer. If this can be established,
382/// the second value in the returned pair will be true. Note that either a
383/// vector or a pointer typed value can be returned. For the former, the
384/// vector returned is a BDV (and possibly a base) of the entire vector 'I'.
385/// If the later, the return pointer is a BDV (or possibly a base) for the
386/// particular element in 'I'.
Philip Reamesf5b8e472015-09-03 21:34:30 +0000387static BaseDefiningValueResult
Philip Reames66287132015-09-09 23:40:12 +0000388findBaseDefiningValueOfVector(Value *I) {
Philip Reames8531d8c2015-04-10 21:48:25 +0000389 // Each case parallels findBaseDefiningValue below, see that code for
390 // detailed motivation.
391
392 if (isa<Argument>(I))
393 // An incoming argument to the function is a base pointer
Philip Reamesf5b8e472015-09-03 21:34:30 +0000394 return BaseDefiningValueResult(I, true);
Philip Reames8531d8c2015-04-10 21:48:25 +0000395
Manuel Jacob734e7332016-01-09 04:02:16 +0000396 if (isa<Constant>(I))
Igor Laevskydf9db452016-05-27 13:13:59 +0000397 // Base of constant vector consists only of constant null pointers.
398 // For reasoning see similar case inside 'findBaseDefiningValue' function.
399 return BaseDefiningValueResult(ConstantAggregateZero::get(I->getType()),
400 true);
Philip Reames8531d8c2015-04-10 21:48:25 +0000401
Philip Reames8531d8c2015-04-10 21:48:25 +0000402 if (isa<LoadInst>(I))
Philip Reamesf5b8e472015-09-03 21:34:30 +0000403 return BaseDefiningValueResult(I, true);
Philip Reamesf5b8e472015-09-03 21:34:30 +0000404
Philip Reames66287132015-09-09 23:40:12 +0000405 if (isa<InsertElementInst>(I))
Philip Reames8fe7f132015-06-26 22:47:37 +0000406 // We don't know whether this vector contains entirely base pointers or
407 // not. To be conservatively correct, we treat it as a BDV and will
408 // duplicate code as needed to construct a parallel vector of bases.
Philip Reames66287132015-09-09 23:40:12 +0000409 return BaseDefiningValueResult(I, false);
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +0000410
Philip Reames8fe7f132015-06-26 22:47:37 +0000411 if (isa<ShuffleVectorInst>(I))
412 // We don't know whether this vector contains entirely base pointers or
413 // not. To be conservatively correct, we treat it as a BDV and will
414 // duplicate code as needed to construct a parallel vector of bases.
415 // TODO: There a number of local optimizations which could be applied here
416 // for particular sufflevector patterns.
Philip Reamesf5b8e472015-09-03 21:34:30 +0000417 return BaseDefiningValueResult(I, false);
Philip Reames8fe7f132015-06-26 22:47:37 +0000418
Sanjoy Dasc4e4dcd2017-03-17 00:55:53 +0000419 // The behavior of getelementptr instructions is the same for vector and
420 // non-vector data types.
421 if (auto *GEP = dyn_cast<GetElementPtrInst>(I))
422 return findBaseDefiningValue(GEP->getPointerOperand());
423
Daniel Neilsonfa14ebd2017-10-13 15:59:13 +0000424 // If the pointer comes through a bitcast of a vector of pointers to
425 // a vector of another type of pointer, then look through the bitcast
426 if (auto *BC = dyn_cast<BitCastInst>(I))
427 return findBaseDefiningValue(BC->getOperand(0));
428
Philip Reames8fe7f132015-06-26 22:47:37 +0000429 // A PHI or Select is a base defining value. The outer findBasePointer
430 // algorithm is responsible for constructing a base value for this BDV.
431 assert((isa<SelectInst>(I) || isa<PHINode>(I)) &&
432 "unknown vector instruction - no base found for vector element");
Philip Reamesf5b8e472015-09-03 21:34:30 +0000433 return BaseDefiningValueResult(I, false);
Philip Reames8531d8c2015-04-10 21:48:25 +0000434}
435
Philip Reamesd16a9b12015-02-20 01:06:44 +0000436/// Helper function for findBasePointer - Will return a value which either a)
Philip Reames9ac4e382015-08-12 21:00:20 +0000437/// defines the base pointer for the input, b) blocks the simple search
438/// (i.e. a PHI or Select of two derived pointers), or c) involves a change
439/// from pointer to vector type or back.
Philip Reamesf5b8e472015-09-03 21:34:30 +0000440static BaseDefiningValueResult findBaseDefiningValue(Value *I) {
Manuel Jacob0593cfd2016-01-09 03:08:49 +0000441 assert(I->getType()->isPtrOrPtrVectorTy() &&
442 "Illegal to ask for the base pointer of a non-pointer type");
443
Philip Reames8fe7f132015-06-26 22:47:37 +0000444 if (I->getType()->isVectorTy())
Philip Reamesf5b8e472015-09-03 21:34:30 +0000445 return findBaseDefiningValueOfVector(I);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000446
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000447 if (isa<Argument>(I))
Philip Reamesd16a9b12015-02-20 01:06:44 +0000448 // An incoming argument to the function is a base pointer
449 // We should have never reached here if this argument isn't an gc value
Philip Reamesf5b8e472015-09-03 21:34:30 +0000450 return BaseDefiningValueResult(I, true);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000451
Igor Laevskydf9db452016-05-27 13:13:59 +0000452 if (isa<Constant>(I)) {
Manuel Jacob75cbfdc2016-01-05 04:06:21 +0000453 // We assume that objects with a constant base (e.g. a global) can't move
454 // and don't need to be reported to the collector because they are always
Igor Laevskydf9db452016-05-27 13:13:59 +0000455 // live. Besides global references, all kinds of constants (e.g. undef,
456 // constant expressions, null pointers) can be introduced by the inliner or
457 // the optimizer, especially on dynamically dead paths.
458 // Here we treat all of them as having single null base. By doing this we
459 // trying to avoid problems reporting various conflicts in a form of
460 // "phi (const1, const2)" or "phi (const, regular gc ptr)".
461 // See constant.ll file for relevant test cases.
462
463 return BaseDefiningValueResult(
464 ConstantPointerNull::get(cast<PointerType>(I->getType())), true);
465 }
Philip Reamesd16a9b12015-02-20 01:06:44 +0000466
Philip Reamesd16a9b12015-02-20 01:06:44 +0000467 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000468 Value *Def = CI->stripPointerCasts();
Manuel Jacob8050a492015-12-21 01:26:46 +0000469 // If stripping pointer casts changes the address space there is an
470 // addrspacecast in between.
471 assert(cast<PointerType>(Def->getType())->getAddressSpace() ==
472 cast<PointerType>(CI->getType())->getAddressSpace() &&
473 "unsupported addrspacecast");
David Blaikie82ad7872015-02-20 23:44:24 +0000474 // If we find a cast instruction here, it means we've found a cast which is
475 // not simply a pointer cast (i.e. an inttoptr). We don't know how to
476 // handle int->ptr conversion.
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000477 assert(!isa<CastInst>(Def) && "shouldn't find another cast here");
478 return findBaseDefiningValue(Def);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000479 }
480
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000481 if (isa<LoadInst>(I))
Philip Reamesf5b8e472015-09-03 21:34:30 +0000482 // The value loaded is an gc base itself
483 return BaseDefiningValueResult(I, true);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000484
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000485 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I))
486 // The base of this GEP is the base
487 return findBaseDefiningValue(GEP->getPointerOperand());
Philip Reamesd16a9b12015-02-20 01:06:44 +0000488
489 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
490 switch (II->getIntrinsicID()) {
491 default:
492 // fall through to general call handling
493 break;
494 case Intrinsic::experimental_gc_statepoint:
Manuel Jacob4e4f60d2015-12-22 18:44:45 +0000495 llvm_unreachable("statepoints don't produce pointers");
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000496 case Intrinsic::experimental_gc_relocate:
Philip Reamesd16a9b12015-02-20 01:06:44 +0000497 // Rerunning safepoint insertion after safepoints are already
498 // inserted is not supported. It could probably be made to work,
499 // but why are you doing this? There's no good reason.
500 llvm_unreachable("repeat safepoint insertion is not supported");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000501 case Intrinsic::gcroot:
502 // Currently, this mechanism hasn't been extended to work with gcroot.
503 // There's no reason it couldn't be, but I haven't thought about the
504 // implications much.
505 llvm_unreachable(
506 "interaction with the gcroot mechanism is not supported");
507 }
508 }
509 // We assume that functions in the source language only return base
510 // pointers. This should probably be generalized via attributes to support
511 // both source language and internal functions.
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000512 if (isa<CallInst>(I) || isa<InvokeInst>(I))
Philip Reamesf5b8e472015-09-03 21:34:30 +0000513 return BaseDefiningValueResult(I, true);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000514
Anna Thomas488c0572016-10-06 13:24:20 +0000515 // TODO: I have absolutely no idea how to implement this part yet. It's not
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000516 // necessarily hard, I just haven't really looked at it yet.
Philip Reamesd16a9b12015-02-20 01:06:44 +0000517 assert(!isa<LandingPadInst>(I) && "Landing Pad is unimplemented");
518
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000519 if (isa<AtomicCmpXchgInst>(I))
Philip Reamesd16a9b12015-02-20 01:06:44 +0000520 // A CAS is effectively a atomic store and load combined under a
521 // predicate. From the perspective of base pointers, we just treat it
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000522 // like a load.
Philip Reamesf5b8e472015-09-03 21:34:30 +0000523 return BaseDefiningValueResult(I, true);
Philip Reames704e78b2015-04-10 22:34:56 +0000524
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000525 assert(!isa<AtomicRMWInst>(I) && "Xchg handled above, all others are "
Philip Reames704e78b2015-04-10 22:34:56 +0000526 "binary ops which don't apply to pointers");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000527
528 // The aggregate ops. Aggregates can either be in the heap or on the
529 // stack, but in either case, this is simply a field load. As a result,
530 // this is a defining definition of the base just like a load is.
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000531 if (isa<ExtractValueInst>(I))
Philip Reamesf5b8e472015-09-03 21:34:30 +0000532 return BaseDefiningValueResult(I, true);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000533
534 // We should never see an insert vector since that would require we be
535 // tracing back a struct value not a pointer value.
536 assert(!isa<InsertValueInst>(I) &&
537 "Base pointer for a struct is meaningless");
538
Philip Reames9ac4e382015-08-12 21:00:20 +0000539 // An extractelement produces a base result exactly when it's input does.
540 // We may need to insert a parallel instruction to extract the appropriate
541 // element out of the base vector corresponding to the input. Given this,
542 // it's analogous to the phi and select case even though it's not a merge.
Philip Reames66287132015-09-09 23:40:12 +0000543 if (isa<ExtractElementInst>(I))
544 // Note: There a lot of obvious peephole cases here. This are deliberately
545 // handled after the main base pointer inference algorithm to make writing
546 // test cases to exercise that code easier.
547 return BaseDefiningValueResult(I, false);
Philip Reames9ac4e382015-08-12 21:00:20 +0000548
Philip Reamesd16a9b12015-02-20 01:06:44 +0000549 // The last two cases here don't return a base pointer. Instead, they
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000550 // return a value which dynamically selects from among several base
Philip Reamesd16a9b12015-02-20 01:06:44 +0000551 // derived pointers (each with it's own base potentially). It's the job of
552 // the caller to resolve these.
Philip Reames704e78b2015-04-10 22:34:56 +0000553 assert((isa<SelectInst>(I) || isa<PHINode>(I)) &&
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000554 "missing instruction case in findBaseDefiningValing");
Philip Reamesf5b8e472015-09-03 21:34:30 +0000555 return BaseDefiningValueResult(I, false);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000556}
557
558/// Returns the base defining value for this value.
Philip Reames18d0feb2015-03-27 05:39:32 +0000559static Value *findBaseDefiningValueCached(Value *I, DefiningValueMapTy &Cache) {
560 Value *&Cached = Cache[I];
Benjamin Kramer6f665452015-02-20 14:00:58 +0000561 if (!Cached) {
Philip Reamesf5b8e472015-09-03 21:34:30 +0000562 Cached = findBaseDefiningValue(I).BDV;
Philip Reames2a892a62015-07-23 22:25:26 +0000563 DEBUG(dbgs() << "fBDV-cached: " << I->getName() << " -> "
564 << Cached->getName() << "\n");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000565 }
Philip Reames18d0feb2015-03-27 05:39:32 +0000566 assert(Cache[I] != nullptr);
Benjamin Kramer6f665452015-02-20 14:00:58 +0000567 return Cached;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000568}
569
570/// Return a base pointer for this value if known. Otherwise, return it's
571/// base defining value.
Philip Reames18d0feb2015-03-27 05:39:32 +0000572static Value *findBaseOrBDV(Value *I, DefiningValueMapTy &Cache) {
573 Value *Def = findBaseDefiningValueCached(I, Cache);
574 auto Found = Cache.find(Def);
575 if (Found != Cache.end()) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000576 // Either a base-of relation, or a self reference. Caller must check.
Benjamin Kramer6f665452015-02-20 14:00:58 +0000577 return Found->second;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000578 }
579 // Only a BDV available
Philip Reames18d0feb2015-03-27 05:39:32 +0000580 return Def;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000581}
582
583/// Given the result of a call to findBaseDefiningValue, or findBaseOrBDV,
584/// is it known to be a base pointer? Or do we need to continue searching.
Philip Reames18d0feb2015-03-27 05:39:32 +0000585static bool isKnownBaseResult(Value *V) {
Philip Reames66287132015-09-09 23:40:12 +0000586 if (!isa<PHINode>(V) && !isa<SelectInst>(V) &&
587 !isa<ExtractElementInst>(V) && !isa<InsertElementInst>(V) &&
588 !isa<ShuffleVectorInst>(V)) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000589 // no recursion possible
590 return true;
591 }
Philip Reames18d0feb2015-03-27 05:39:32 +0000592 if (isa<Instruction>(V) &&
593 cast<Instruction>(V)->getMetadata("is_base_value")) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000594 // This is a previously inserted base phi or select. We know
595 // that this is a base value.
596 return true;
597 }
598
599 // We need to keep searching
600 return false;
601}
602
Philip Reamesd16a9b12015-02-20 01:06:44 +0000603namespace {
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000604
Philip Reames9b141ed2015-07-23 22:49:14 +0000605/// Models the state of a single base defining value in the findBasePointer
606/// algorithm for determining where a new instruction is needed to propagate
607/// the base of this BDV.
608class BDVState {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000609public:
610 enum Status { Unknown, Base, Conflict };
611
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000612 BDVState() : BaseValue(nullptr) {}
Philip Reamesd16a9b12015-02-20 01:06:44 +0000613
Sanjoy Das7dda0ed2016-06-26 04:55:35 +0000614 explicit BDVState(Status Status, Value *BaseValue = nullptr)
615 : Status(Status), BaseValue(BaseValue) {
616 assert(Status != Base || BaseValue);
617 }
618
619 explicit BDVState(Value *BaseValue) : Status(Base), BaseValue(BaseValue) {}
620
621 Status getStatus() const { return Status; }
622 Value *getBaseValue() const { return BaseValue; }
Philip Reamesd16a9b12015-02-20 01:06:44 +0000623
624 bool isBase() const { return getStatus() == Base; }
625 bool isUnknown() const { return getStatus() == Unknown; }
626 bool isConflict() const { return getStatus() == Conflict; }
627
Sanjoy Das7dda0ed2016-06-26 04:55:35 +0000628 bool operator==(const BDVState &Other) const {
629 return BaseValue == Other.BaseValue && Status == Other.Status;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000630 }
631
Philip Reames9b141ed2015-07-23 22:49:14 +0000632 bool operator!=(const BDVState &other) const { return !(*this == other); }
Philip Reamesd16a9b12015-02-20 01:06:44 +0000633
Philip Reames2a892a62015-07-23 22:25:26 +0000634 LLVM_DUMP_METHOD
Sanjoy Das7dda0ed2016-06-26 04:55:35 +0000635 void dump() const {
636 print(dbgs());
637 dbgs() << '\n';
638 }
639
Philip Reames2a892a62015-07-23 22:25:26 +0000640 void print(raw_ostream &OS) const {
Sanjoy Das7dda0ed2016-06-26 04:55:35 +0000641 switch (getStatus()) {
Philip Reamesdab35f32015-09-02 21:11:44 +0000642 case Unknown:
643 OS << "U";
644 break;
645 case Base:
646 OS << "B";
647 break;
648 case Conflict:
649 OS << "C";
650 break;
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000651 }
Sanjoy Das7dda0ed2016-06-26 04:55:35 +0000652 OS << " (" << getBaseValue() << " - "
653 << (getBaseValue() ? getBaseValue()->getName() : "nullptr") << "): ";
Philip Reamesd16a9b12015-02-20 01:06:44 +0000654 }
655
656private:
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000657 Status Status = Unknown;
Sanjoy Das7dda0ed2016-06-26 04:55:35 +0000658 AssertingVH<Value> BaseValue; // Non-null only if Status == Base.
Philip Reamesd16a9b12015-02-20 01:06:44 +0000659};
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000660
661} // end anonymous namespace
Philip Reamesd16a9b12015-02-20 01:06:44 +0000662
Philip Reames6906e922015-09-02 21:57:17 +0000663#ifndef NDEBUG
Philip Reamesb3967cd2015-09-02 22:30:53 +0000664static raw_ostream &operator<<(raw_ostream &OS, const BDVState &State) {
Philip Reames2a892a62015-07-23 22:25:26 +0000665 State.print(OS);
666 return OS;
667}
Philip Reames6906e922015-09-02 21:57:17 +0000668#endif
Philip Reames2a892a62015-07-23 22:25:26 +0000669
Sanjoy Das6cf88092016-06-26 04:55:13 +0000670static BDVState meetBDVStateImpl(const BDVState &LHS, const BDVState &RHS) {
671 switch (LHS.getStatus()) {
Sanjoy Dasbd43d0e2016-06-26 04:55:10 +0000672 case BDVState::Unknown:
Sanjoy Das6cf88092016-06-26 04:55:13 +0000673 return RHS;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000674
Sanjoy Dasbd43d0e2016-06-26 04:55:10 +0000675 case BDVState::Base:
Sanjoy Das7dda0ed2016-06-26 04:55:35 +0000676 assert(LHS.getBaseValue() && "can't be null");
Sanjoy Das6cf88092016-06-26 04:55:13 +0000677 if (RHS.isUnknown())
678 return LHS;
Sanjoy Dasbd43d0e2016-06-26 04:55:10 +0000679
Sanjoy Das6cf88092016-06-26 04:55:13 +0000680 if (RHS.isBase()) {
Sanjoy Das7dda0ed2016-06-26 04:55:35 +0000681 if (LHS.getBaseValue() == RHS.getBaseValue()) {
Sanjoy Das6cf88092016-06-26 04:55:13 +0000682 assert(LHS == RHS && "equality broken!");
683 return LHS;
Sanjoy Dasbd43d0e2016-06-26 04:55:10 +0000684 }
685 return BDVState(BDVState::Conflict);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000686 }
Sanjoy Das6cf88092016-06-26 04:55:13 +0000687 assert(RHS.isConflict() && "only three states!");
Sanjoy Dasbd43d0e2016-06-26 04:55:10 +0000688 return BDVState(BDVState::Conflict);
689
690 case BDVState::Conflict:
Sanjoy Das6cf88092016-06-26 04:55:13 +0000691 return LHS;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000692 }
Sanjoy Dasbd43d0e2016-06-26 04:55:10 +0000693 llvm_unreachable("only three states!");
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000694}
Philip Reamesb3967cd2015-09-02 22:30:53 +0000695
Sanjoy Dasbd43d0e2016-06-26 04:55:10 +0000696// Values of type BDVState form a lattice, and this function implements the meet
697// operation.
Benjamin Kramer061f4a52017-01-13 14:39:03 +0000698static BDVState meetBDVState(const BDVState &LHS, const BDVState &RHS) {
Sanjoy Dasbd43d0e2016-06-26 04:55:10 +0000699 BDVState Result = meetBDVStateImpl(LHS, RHS);
700 assert(Result == meetBDVStateImpl(RHS, LHS) &&
701 "Math is wrong: meet does not commute!");
702 return Result;
703}
Philip Reamesb3967cd2015-09-02 22:30:53 +0000704
Sanjoy Das90547f12016-06-26 04:55:05 +0000705/// For a given value or instruction, figure out what base ptr its derived from.
706/// For gc objects, this is simply itself. On success, returns a value which is
707/// the base pointer. (This is reliable and can be used for relocation.) On
708/// failure, returns nullptr.
709static Value *findBasePointer(Value *I, DefiningValueMapTy &Cache) {
710 Value *Def = findBaseOrBDV(I, Cache);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000711
Sanjoy Das90547f12016-06-26 04:55:05 +0000712 if (isKnownBaseResult(Def))
713 return Def;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000714
715 // Here's the rough algorithm:
716 // - For every SSA value, construct a mapping to either an actual base
717 // pointer or a PHI which obscures the base pointer.
718 // - Construct a mapping from PHI to unknown TOP state. Use an
719 // optimistic algorithm to propagate base pointer information. Lattice
720 // looks like:
721 // UNKNOWN
722 // b1 b2 b3 b4
723 // CONFLICT
724 // When algorithm terminates, all PHIs will either have a single concrete
725 // base or be in a conflict state.
726 // - For every conflict, insert a dummy PHI node without arguments. Add
727 // these to the base[Instruction] = BasePtr mapping. For every
728 // non-conflict, add the actual base.
729 // - For every conflict, add arguments for the base[a] of each input
730 // arguments.
731 //
732 // Note: A simpler form of this would be to add the conflict form of all
733 // PHIs without running the optimistic algorithm. This would be
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000734 // analogous to pessimistic data flow and would likely lead to an
Philip Reamesd16a9b12015-02-20 01:06:44 +0000735 // overall worse solution.
736
Philip Reames29e9ae72015-07-24 00:42:55 +0000737#ifndef NDEBUG
Philip Reames88958b22015-07-24 00:02:11 +0000738 auto isExpectedBDVType = [](Value *BDV) {
Philip Reames66287132015-09-09 23:40:12 +0000739 return isa<PHINode>(BDV) || isa<SelectInst>(BDV) ||
Anna Thomas479cbb92016-10-04 13:48:37 +0000740 isa<ExtractElementInst>(BDV) || isa<InsertElementInst>(BDV) ||
741 isa<ShuffleVectorInst>(BDV);
Philip Reames88958b22015-07-24 00:02:11 +0000742 };
Philip Reames29e9ae72015-07-24 00:42:55 +0000743#endif
Philip Reames88958b22015-07-24 00:02:11 +0000744
745 // Once populated, will contain a mapping from each potentially non-base BDV
746 // to a lattice value (described above) which corresponds to that BDV.
Philip Reames15d55632015-09-09 23:26:08 +0000747 // We use the order of insertion (DFS over the def/use graph) to provide a
748 // stable deterministic ordering for visiting DenseMaps (which are unordered)
749 // below. This is important for deterministic compilation.
Philip Reames34d7a742015-09-10 00:22:49 +0000750 MapVector<Value *, BDVState> States;
Philip Reames15d55632015-09-09 23:26:08 +0000751
752 // Recursively fill in all base defining values reachable from the initial
753 // one for which we don't already know a definite base value for
Philip Reames88958b22015-07-24 00:02:11 +0000754 /* scope */ {
Philip Reames88958b22015-07-24 00:02:11 +0000755 SmallVector<Value*, 16> Worklist;
Sanjoy Das90547f12016-06-26 04:55:05 +0000756 Worklist.push_back(Def);
757 States.insert({Def, BDVState()});
Philip Reames88958b22015-07-24 00:02:11 +0000758 while (!Worklist.empty()) {
759 Value *Current = Worklist.pop_back_val();
760 assert(!isKnownBaseResult(Current) && "why did it get added?");
761
762 auto visitIncomingValue = [&](Value *InVal) {
Sanjoy Das90547f12016-06-26 04:55:05 +0000763 Value *Base = findBaseOrBDV(InVal, Cache);
Philip Reames88958b22015-07-24 00:02:11 +0000764 if (isKnownBaseResult(Base))
765 // Known bases won't need new instructions introduced and can be
766 // ignored safely
767 return;
768 assert(isExpectedBDVType(Base) && "the only non-base values "
769 "we see should be base defining values");
Philip Reames34d7a742015-09-10 00:22:49 +0000770 if (States.insert(std::make_pair(Base, BDVState())).second)
Philip Reames88958b22015-07-24 00:02:11 +0000771 Worklist.push_back(Base);
772 };
Sanjoy Das90547f12016-06-26 04:55:05 +0000773 if (PHINode *PN = dyn_cast<PHINode>(Current)) {
774 for (Value *InVal : PN->incoming_values())
Philip Reames88958b22015-07-24 00:02:11 +0000775 visitIncomingValue(InVal);
Sanjoy Das90547f12016-06-26 04:55:05 +0000776 } else if (SelectInst *SI = dyn_cast<SelectInst>(Current)) {
777 visitIncomingValue(SI->getTrueValue());
778 visitIncomingValue(SI->getFalseValue());
Philip Reames9ac4e382015-08-12 21:00:20 +0000779 } else if (auto *EE = dyn_cast<ExtractElementInst>(Current)) {
780 visitIncomingValue(EE->getVectorOperand());
Philip Reames66287132015-09-09 23:40:12 +0000781 } else if (auto *IE = dyn_cast<InsertElementInst>(Current)) {
782 visitIncomingValue(IE->getOperand(0)); // vector operand
783 visitIncomingValue(IE->getOperand(1)); // scalar operand
Anna Thomas479cbb92016-10-04 13:48:37 +0000784 } else if (auto *SV = dyn_cast<ShuffleVectorInst>(Current)) {
785 visitIncomingValue(SV->getOperand(0));
786 visitIncomingValue(SV->getOperand(1));
787 }
788 else {
Sanjoy Das90547f12016-06-26 04:55:05 +0000789 llvm_unreachable("Unimplemented instruction case");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000790 }
791 }
792 }
793
Philip Reamesdab35f32015-09-02 21:11:44 +0000794#ifndef NDEBUG
795 DEBUG(dbgs() << "States after initialization:\n");
Sanjoy Das9d086422016-06-26 05:42:52 +0000796 for (auto Pair : States) {
Philip Reamesdab35f32015-09-02 21:11:44 +0000797 DEBUG(dbgs() << " " << Pair.second << " for " << *Pair.first << "\n");
Sanjoy Das9d086422016-06-26 05:42:52 +0000798 }
Philip Reamesdab35f32015-09-02 21:11:44 +0000799#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +0000800
Philip Reames273e6bb2015-07-23 21:41:27 +0000801 // Return a phi state for a base defining value. We'll generate a new
802 // base state for known bases and expect to find a cached state otherwise.
803 auto getStateForBDV = [&](Value *baseValue) {
804 if (isKnownBaseResult(baseValue))
Philip Reames9b141ed2015-07-23 22:49:14 +0000805 return BDVState(baseValue);
Philip Reames34d7a742015-09-10 00:22:49 +0000806 auto I = States.find(baseValue);
807 assert(I != States.end() && "lookup failed!");
Philip Reames273e6bb2015-07-23 21:41:27 +0000808 return I->second;
809 };
810
Sanjoy Das90547f12016-06-26 04:55:05 +0000811 bool Progress = true;
812 while (Progress) {
Yaron Keren42a7adf2015-02-28 13:11:24 +0000813#ifndef NDEBUG
Sanjoy Das90547f12016-06-26 04:55:05 +0000814 const size_t OldSize = States.size();
Yaron Keren42a7adf2015-02-28 13:11:24 +0000815#endif
Sanjoy Das90547f12016-06-26 04:55:05 +0000816 Progress = false;
Philip Reames15d55632015-09-09 23:26:08 +0000817 // We're only changing values in this loop, thus safe to keep iterators.
818 // Since this is computing a fixed point, the order of visit does not
819 // effect the result. TODO: We could use a worklist here and make this run
820 // much faster.
Philip Reames34d7a742015-09-10 00:22:49 +0000821 for (auto Pair : States) {
Philip Reamesece70b82015-09-09 23:57:18 +0000822 Value *BDV = Pair.first;
823 assert(!isKnownBaseResult(BDV) && "why did it get added?");
Philip Reames273e6bb2015-07-23 21:41:27 +0000824
Philip Reames9b141ed2015-07-23 22:49:14 +0000825 // Given an input value for the current instruction, return a BDVState
Philip Reames273e6bb2015-07-23 21:41:27 +0000826 // instance which represents the BDV of that value.
827 auto getStateForInput = [&](Value *V) mutable {
Sanjoy Das90547f12016-06-26 04:55:05 +0000828 Value *BDV = findBaseOrBDV(V, Cache);
Philip Reames273e6bb2015-07-23 21:41:27 +0000829 return getStateForBDV(BDV);
830 };
831
Sanjoy Dasbd43d0e2016-06-26 04:55:10 +0000832 BDVState NewState;
Sanjoy Das90547f12016-06-26 04:55:05 +0000833 if (SelectInst *SI = dyn_cast<SelectInst>(BDV)) {
Sanjoy Dasbd43d0e2016-06-26 04:55:10 +0000834 NewState = meetBDVState(NewState, getStateForInput(SI->getTrueValue()));
835 NewState =
836 meetBDVState(NewState, getStateForInput(SI->getFalseValue()));
Sanjoy Das90547f12016-06-26 04:55:05 +0000837 } else if (PHINode *PN = dyn_cast<PHINode>(BDV)) {
838 for (Value *Val : PN->incoming_values())
Sanjoy Dasbd43d0e2016-06-26 04:55:10 +0000839 NewState = meetBDVState(NewState, getStateForInput(Val));
Philip Reamesece70b82015-09-09 23:57:18 +0000840 } else if (auto *EE = dyn_cast<ExtractElementInst>(BDV)) {
Philip Reames9ac4e382015-08-12 21:00:20 +0000841 // The 'meet' for an extractelement is slightly trivial, but it's still
842 // useful in that it drives us to conflict if our input is.
Sanjoy Dasbd43d0e2016-06-26 04:55:10 +0000843 NewState =
844 meetBDVState(NewState, getStateForInput(EE->getVectorOperand()));
Anna Thomas479cbb92016-10-04 13:48:37 +0000845 } else if (auto *IE = dyn_cast<InsertElementInst>(BDV)){
Philip Reames66287132015-09-09 23:40:12 +0000846 // Given there's a inherent type mismatch between the operands, will
847 // *always* produce Conflict.
Sanjoy Dasbd43d0e2016-06-26 04:55:10 +0000848 NewState = meetBDVState(NewState, getStateForInput(IE->getOperand(0)));
849 NewState = meetBDVState(NewState, getStateForInput(IE->getOperand(1)));
Anna Thomas479cbb92016-10-04 13:48:37 +0000850 } else {
851 // The only instance this does not return a Conflict is when both the
852 // vector operands are the same vector.
853 auto *SV = cast<ShuffleVectorInst>(BDV);
854 NewState = meetBDVState(NewState, getStateForInput(SV->getOperand(0)));
855 NewState = meetBDVState(NewState, getStateForInput(SV->getOperand(1)));
Philip Reames9ac4e382015-08-12 21:00:20 +0000856 }
857
Sanjoy Das90547f12016-06-26 04:55:05 +0000858 BDVState OldState = States[BDV];
Sanjoy Das90547f12016-06-26 04:55:05 +0000859 if (OldState != NewState) {
860 Progress = true;
861 States[BDV] = NewState;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000862 }
863 }
864
Sanjoy Das90547f12016-06-26 04:55:05 +0000865 assert(OldSize == States.size() &&
Philip Reamesb4e55f32015-09-10 00:32:56 +0000866 "fixed point shouldn't be adding any new nodes to state");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000867 }
868
Philip Reamesdab35f32015-09-02 21:11:44 +0000869#ifndef NDEBUG
870 DEBUG(dbgs() << "States after meet iteration:\n");
Sanjoy Das9d086422016-06-26 05:42:52 +0000871 for (auto Pair : States) {
Philip Reamesdab35f32015-09-02 21:11:44 +0000872 DEBUG(dbgs() << " " << Pair.second << " for " << *Pair.first << "\n");
Sanjoy Das9d086422016-06-26 05:42:52 +0000873 }
Philip Reamesdab35f32015-09-02 21:11:44 +0000874#endif
Sanjoy Das90547f12016-06-26 04:55:05 +0000875
Philip Reamesd16a9b12015-02-20 01:06:44 +0000876 // Insert Phis for all conflicts
Philip Reames2e5bcbe2015-02-28 01:52:09 +0000877 // TODO: adjust naming patterns to avoid this order of iteration dependency
Philip Reames34d7a742015-09-10 00:22:49 +0000878 for (auto Pair : States) {
Philip Reames15d55632015-09-09 23:26:08 +0000879 Instruction *I = cast<Instruction>(Pair.first);
880 BDVState State = Pair.second;
Philip Reames6ff1a1e32015-07-21 19:04:38 +0000881 assert(!isKnownBaseResult(I) && "why did it get added?");
882 assert(!State.isUnknown() && "Optimistic algorithm didn't complete!");
Philip Reames9ac4e382015-08-12 21:00:20 +0000883
884 // extractelement instructions are a bit special in that we may need to
885 // insert an extract even when we know an exact base for the instruction.
886 // The problem is that we need to convert from a vector base to a scalar
887 // base for the particular indice we're interested in.
888 if (State.isBase() && isa<ExtractElementInst>(I) &&
Sanjoy Das7dda0ed2016-06-26 04:55:35 +0000889 isa<VectorType>(State.getBaseValue()->getType())) {
Philip Reames9ac4e382015-08-12 21:00:20 +0000890 auto *EE = cast<ExtractElementInst>(I);
891 // TODO: In many cases, the new instruction is just EE itself. We should
892 // exploit this, but can't do it here since it would break the invariant
893 // about the BDV not being known to be a base.
Sanjoy Das90547f12016-06-26 04:55:05 +0000894 auto *BaseInst = ExtractElementInst::Create(
Sanjoy Das7dda0ed2016-06-26 04:55:35 +0000895 State.getBaseValue(), EE->getIndexOperand(), "base_ee", EE);
Philip Reames9ac4e382015-08-12 21:00:20 +0000896 BaseInst->setMetadata("is_base_value", MDNode::get(I->getContext(), {}));
Philip Reames34d7a742015-09-10 00:22:49 +0000897 States[I] = BDVState(BDVState::Base, BaseInst);
Philip Reames9ac4e382015-08-12 21:00:20 +0000898 }
Philip Reames66287132015-09-09 23:40:12 +0000899
900 // Since we're joining a vector and scalar base, they can never be the
901 // same. As a result, we should always see insert element having reached
902 // the conflict state.
Sanjoy Das90547f12016-06-26 04:55:05 +0000903 assert(!isa<InsertElementInst>(I) || State.isConflict());
904
Philip Reames6ff1a1e32015-07-21 19:04:38 +0000905 if (!State.isConflict())
Philip Reamesf986d682015-02-28 00:54:41 +0000906 continue;
Philip Reames704e78b2015-04-10 22:34:56 +0000907
Philip Reames6ff1a1e32015-07-21 19:04:38 +0000908 /// Create and insert a new instruction which will represent the base of
909 /// the given instruction 'I'.
910 auto MakeBaseInstPlaceholder = [](Instruction *I) -> Instruction* {
911 if (isa<PHINode>(I)) {
912 BasicBlock *BB = I->getParent();
913 int NumPreds = std::distance(pred_begin(BB), pred_end(BB));
914 assert(NumPreds > 0 && "how did we reach here");
Philip Reamesece70b82015-09-09 23:57:18 +0000915 std::string Name = suffixed_name_or(I, ".base", "base_phi");
Philip Reamesfa2c6302015-07-24 19:01:39 +0000916 return PHINode::Create(I->getType(), NumPreds, Name, I);
Sanjoy Das90547f12016-06-26 04:55:05 +0000917 } else if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
Philip Reames9ac4e382015-08-12 21:00:20 +0000918 // The undef will be replaced later
Sanjoy Das90547f12016-06-26 04:55:05 +0000919 UndefValue *Undef = UndefValue::get(SI->getType());
Philip Reamesece70b82015-09-09 23:57:18 +0000920 std::string Name = suffixed_name_or(I, ".base", "base_select");
Sanjoy Das90547f12016-06-26 04:55:05 +0000921 return SelectInst::Create(SI->getCondition(), Undef, Undef, Name, SI);
Philip Reames66287132015-09-09 23:40:12 +0000922 } else if (auto *EE = dyn_cast<ExtractElementInst>(I)) {
Philip Reames9ac4e382015-08-12 21:00:20 +0000923 UndefValue *Undef = UndefValue::get(EE->getVectorOperand()->getType());
Philip Reamesece70b82015-09-09 23:57:18 +0000924 std::string Name = suffixed_name_or(I, ".base", "base_ee");
Philip Reames9ac4e382015-08-12 21:00:20 +0000925 return ExtractElementInst::Create(Undef, EE->getIndexOperand(), Name,
926 EE);
Anna Thomas479cbb92016-10-04 13:48:37 +0000927 } else if (auto *IE = dyn_cast<InsertElementInst>(I)) {
Philip Reames66287132015-09-09 23:40:12 +0000928 UndefValue *VecUndef = UndefValue::get(IE->getOperand(0)->getType());
929 UndefValue *ScalarUndef = UndefValue::get(IE->getOperand(1)->getType());
Philip Reamesece70b82015-09-09 23:57:18 +0000930 std::string Name = suffixed_name_or(I, ".base", "base_ie");
Philip Reames66287132015-09-09 23:40:12 +0000931 return InsertElementInst::Create(VecUndef, ScalarUndef,
932 IE->getOperand(2), Name, IE);
Anna Thomas479cbb92016-10-04 13:48:37 +0000933 } else {
934 auto *SV = cast<ShuffleVectorInst>(I);
935 UndefValue *VecUndef = UndefValue::get(SV->getOperand(0)->getType());
936 std::string Name = suffixed_name_or(I, ".base", "base_sv");
937 return new ShuffleVectorInst(VecUndef, VecUndef, SV->getOperand(2),
938 Name, SV);
Philip Reames6ff1a1e32015-07-21 19:04:38 +0000939 }
Philip Reames6ff1a1e32015-07-21 19:04:38 +0000940 };
941 Instruction *BaseInst = MakeBaseInstPlaceholder(I);
942 // Add metadata marking this as a base value
943 BaseInst->setMetadata("is_base_value", MDNode::get(I->getContext(), {}));
Philip Reames34d7a742015-09-10 00:22:49 +0000944 States[I] = BDVState(BDVState::Conflict, BaseInst);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000945 }
946
Philip Reames3ea15892015-09-03 21:57:40 +0000947 // Returns a instruction which produces the base pointer for a given
948 // instruction. The instruction is assumed to be an input to one of the BDVs
949 // seen in the inference algorithm above. As such, we must either already
950 // know it's base defining value is a base, or have inserted a new
951 // instruction to propagate the base of it's BDV and have entered that newly
952 // introduced instruction into the state table. In either case, we are
953 // assured to be able to determine an instruction which produces it's base
Sanjoy Das90547f12016-06-26 04:55:05 +0000954 // pointer.
Philip Reames3ea15892015-09-03 21:57:40 +0000955 auto getBaseForInput = [&](Value *Input, Instruction *InsertPt) {
Sanjoy Das90547f12016-06-26 04:55:05 +0000956 Value *BDV = findBaseOrBDV(Input, Cache);
Philip Reames3ea15892015-09-03 21:57:40 +0000957 Value *Base = nullptr;
958 if (isKnownBaseResult(BDV)) {
959 Base = BDV;
960 } else {
961 // Either conflict or base.
Philip Reames34d7a742015-09-10 00:22:49 +0000962 assert(States.count(BDV));
Sanjoy Das7dda0ed2016-06-26 04:55:35 +0000963 Base = States[BDV].getBaseValue();
Philip Reames3ea15892015-09-03 21:57:40 +0000964 }
Sanjoy Das90547f12016-06-26 04:55:05 +0000965 assert(Base && "Can't be null");
Philip Reames3ea15892015-09-03 21:57:40 +0000966 // The cast is needed since base traversal may strip away bitcasts
Sanjoy Das90547f12016-06-26 04:55:05 +0000967 if (Base->getType() != Input->getType() && InsertPt)
968 Base = new BitCastInst(Base, Input->getType(), "cast", InsertPt);
Philip Reames3ea15892015-09-03 21:57:40 +0000969 return Base;
970 };
971
Philip Reames15d55632015-09-09 23:26:08 +0000972 // Fixup all the inputs of the new PHIs. Visit order needs to be
973 // deterministic and predictable because we're naming newly created
974 // instructions.
Philip Reames34d7a742015-09-10 00:22:49 +0000975 for (auto Pair : States) {
Philip Reames7540e3a2015-09-10 00:01:53 +0000976 Instruction *BDV = cast<Instruction>(Pair.first);
Philip Reamesc8ded462015-09-10 00:27:50 +0000977 BDVState State = Pair.second;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000978
Philip Reames7540e3a2015-09-10 00:01:53 +0000979 assert(!isKnownBaseResult(BDV) && "why did it get added?");
Philip Reamesc8ded462015-09-10 00:27:50 +0000980 assert(!State.isUnknown() && "Optimistic algorithm didn't complete!");
981 if (!State.isConflict())
Philip Reames28e61ce2015-02-28 01:57:44 +0000982 continue;
Philip Reames704e78b2015-04-10 22:34:56 +0000983
Sanjoy Das7dda0ed2016-06-26 04:55:35 +0000984 if (PHINode *BasePHI = dyn_cast<PHINode>(State.getBaseValue())) {
Sanjoy Das90547f12016-06-26 04:55:05 +0000985 PHINode *PN = cast<PHINode>(BDV);
986 unsigned NumPHIValues = PN->getNumIncomingValues();
Philip Reames28e61ce2015-02-28 01:57:44 +0000987 for (unsigned i = 0; i < NumPHIValues; i++) {
Sanjoy Das90547f12016-06-26 04:55:05 +0000988 Value *InVal = PN->getIncomingValue(i);
989 BasicBlock *InBB = PN->getIncomingBlock(i);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000990
Philip Reames28e61ce2015-02-28 01:57:44 +0000991 // If we've already seen InBB, add the same incoming value
992 // we added for it earlier. The IR verifier requires phi
993 // nodes with multiple entries from the same basic block
994 // to have the same incoming value for each of those
995 // entries. If we don't do this check here and basephi
996 // has a different type than base, we'll end up adding two
997 // bitcasts (and hence two distinct values) as incoming
998 // values for the same basic block.
Philip Reamesd16a9b12015-02-20 01:06:44 +0000999
Sanjoy Das90547f12016-06-26 04:55:05 +00001000 int BlockIndex = BasePHI->getBasicBlockIndex(InBB);
1001 if (BlockIndex != -1) {
1002 Value *OldBase = BasePHI->getIncomingValue(BlockIndex);
1003 BasePHI->addIncoming(OldBase, InBB);
1004
Philip Reamesd16a9b12015-02-20 01:06:44 +00001005#ifndef NDEBUG
Philip Reames3ea15892015-09-03 21:57:40 +00001006 Value *Base = getBaseForInput(InVal, nullptr);
Sanjoy Das90547f12016-06-26 04:55:05 +00001007 // In essence this assert states: the only way two values
1008 // incoming from the same basic block may be different is by
1009 // being different bitcasts of the same value. A cleanup
1010 // that remains TODO is changing findBaseOrBDV to return an
1011 // llvm::Value of the correct type (and still remain pure).
1012 // This will remove the need to add bitcasts.
1013 assert(Base->stripPointerCasts() == OldBase->stripPointerCasts() &&
1014 "Sanity -- findBaseOrBDV should be pure!");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001015#endif
Philip Reames28e61ce2015-02-28 01:57:44 +00001016 continue;
1017 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00001018
Philip Reames3ea15892015-09-03 21:57:40 +00001019 // Find the instruction which produces the base for each input. We may
1020 // need to insert a bitcast in the incoming block.
1021 // TODO: Need to split critical edges if insertion is needed
1022 Value *Base = getBaseForInput(InVal, InBB->getTerminator());
Sanjoy Das90547f12016-06-26 04:55:05 +00001023 BasePHI->addIncoming(Base, InBB);
Philip Reames28e61ce2015-02-28 01:57:44 +00001024 }
Sanjoy Das90547f12016-06-26 04:55:05 +00001025 assert(BasePHI->getNumIncomingValues() == NumPHIValues);
Sanjoy Das7dda0ed2016-06-26 04:55:35 +00001026 } else if (SelectInst *BaseSI =
1027 dyn_cast<SelectInst>(State.getBaseValue())) {
Sanjoy Das90547f12016-06-26 04:55:05 +00001028 SelectInst *SI = cast<SelectInst>(BDV);
1029
1030 // Find the instruction which produces the base for each input.
1031 // We may need to insert a bitcast.
1032 BaseSI->setTrueValue(getBaseForInput(SI->getTrueValue(), BaseSI));
1033 BaseSI->setFalseValue(getBaseForInput(SI->getFalseValue(), BaseSI));
Sanjoy Das7dda0ed2016-06-26 04:55:35 +00001034 } else if (auto *BaseEE =
1035 dyn_cast<ExtractElementInst>(State.getBaseValue())) {
Philip Reames7540e3a2015-09-10 00:01:53 +00001036 Value *InVal = cast<ExtractElementInst>(BDV)->getVectorOperand();
Philip Reames3ea15892015-09-03 21:57:40 +00001037 // Find the instruction which produces the base for each input. We may
1038 // need to insert a bitcast.
Sanjoy Das90547f12016-06-26 04:55:05 +00001039 BaseEE->setOperand(0, getBaseForInput(InVal, BaseEE));
Anna Thomas479cbb92016-10-04 13:48:37 +00001040 } else if (auto *BaseIE = dyn_cast<InsertElementInst>(State.getBaseValue())){
Philip Reames7540e3a2015-09-10 00:01:53 +00001041 auto *BdvIE = cast<InsertElementInst>(BDV);
Philip Reames66287132015-09-09 23:40:12 +00001042 auto UpdateOperand = [&](int OperandIdx) {
1043 Value *InVal = BdvIE->getOperand(OperandIdx);
Philip Reames953817b2015-09-10 00:44:10 +00001044 Value *Base = getBaseForInput(InVal, BaseIE);
Philip Reames66287132015-09-09 23:40:12 +00001045 BaseIE->setOperand(OperandIdx, Base);
1046 };
1047 UpdateOperand(0); // vector operand
1048 UpdateOperand(1); // scalar operand
Anna Thomas479cbb92016-10-04 13:48:37 +00001049 } else {
1050 auto *BaseSV = cast<ShuffleVectorInst>(State.getBaseValue());
1051 auto *BdvSV = cast<ShuffleVectorInst>(BDV);
1052 auto UpdateOperand = [&](int OperandIdx) {
1053 Value *InVal = BdvSV->getOperand(OperandIdx);
1054 Value *Base = getBaseForInput(InVal, BaseSV);
1055 BaseSV->setOperand(OperandIdx, Base);
1056 };
1057 UpdateOperand(0); // vector operand
1058 UpdateOperand(1); // vector operand
Philip Reamesd16a9b12015-02-20 01:06:44 +00001059 }
1060 }
1061
1062 // Cache all of our results so we can cheaply reuse them
1063 // NOTE: This is actually two caches: one of the base defining value
1064 // relation and one of the base pointer relation! FIXME
Philip Reames34d7a742015-09-10 00:22:49 +00001065 for (auto Pair : States) {
Philip Reames15d55632015-09-09 23:26:08 +00001066 auto *BDV = Pair.first;
Sanjoy Das7dda0ed2016-06-26 04:55:35 +00001067 Value *Base = Pair.second.getBaseValue();
Sanjoy Das90547f12016-06-26 04:55:05 +00001068 assert(BDV && Base);
Philip Reames79fa9b72016-02-22 20:45:56 +00001069 assert(!isKnownBaseResult(BDV) && "why did it get added?");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001070
Philip Reamesdab35f32015-09-02 21:11:44 +00001071 DEBUG(dbgs() << "Updating base value cache"
Eric Christopherd3d9cbf2016-06-23 00:42:00 +00001072 << " for: " << BDV->getName() << " from: "
Sanjoy Das90547f12016-06-26 04:55:05 +00001073 << (Cache.count(BDV) ? Cache[BDV]->getName().str() : "none")
1074 << " to: " << Base->getName() << "\n");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001075
Sanjoy Das90547f12016-06-26 04:55:05 +00001076 if (Cache.count(BDV)) {
1077 assert(isKnownBaseResult(Base) &&
Philip Reames79fa9b72016-02-22 20:45:56 +00001078 "must be something we 'know' is a base pointer");
Sanjoy Das90547f12016-06-26 04:55:05 +00001079 // Once we transition from the BDV relation being store in the Cache to
Philip Reamesd16a9b12015-02-20 01:06:44 +00001080 // the base relation being stored, it must be stable
Sanjoy Das90547f12016-06-26 04:55:05 +00001081 assert((!isKnownBaseResult(Cache[BDV]) || Cache[BDV] == Base) &&
Philip Reamesd16a9b12015-02-20 01:06:44 +00001082 "base relation should be stable");
1083 }
Sanjoy Das90547f12016-06-26 04:55:05 +00001084 Cache[BDV] = Base;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001085 }
Sanjoy Das90547f12016-06-26 04:55:05 +00001086 assert(Cache.count(Def));
1087 return Cache[Def];
Philip Reamesd16a9b12015-02-20 01:06:44 +00001088}
1089
1090// For a set of live pointers (base and/or derived), identify the base
1091// pointer of the object which they are derived from. This routine will
1092// mutate the IR graph as needed to make the 'base' pointer live at the
1093// definition site of 'derived'. This ensures that any use of 'derived' can
1094// also use 'base'. This may involve the insertion of a number of
1095// additional PHI nodes.
1096//
1097// preconditions: live is a set of pointer type Values
1098//
1099// side effects: may insert PHI nodes into the existing CFG, will preserve
1100// CFG, will not remove or mutate any existing nodes
1101//
Philip Reamesf2041322015-02-20 19:26:04 +00001102// post condition: PointerToBase contains one (derived, base) pair for every
Philip Reamesd16a9b12015-02-20 01:06:44 +00001103// pointer in live. Note that derived can be equal to base if the original
1104// pointer was a base pointer.
Philip Reames704e78b2015-04-10 22:34:56 +00001105static void
1106findBasePointers(const StatepointLiveSetTy &live,
Igor Laevskyfb1811d2016-05-04 14:55:36 +00001107 MapVector<Value *, Value *> &PointerToBase,
Philip Reamesba198492015-04-14 00:41:34 +00001108 DominatorTree *DT, DefiningValueMapTy &DVCache) {
Igor Laevskyfb1811d2016-05-04 14:55:36 +00001109 for (Value *ptr : live) {
Philip Reamesba198492015-04-14 00:41:34 +00001110 Value *base = findBasePointer(ptr, DVCache);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001111 assert(base && "failed to find base pointer");
Philip Reamesf2041322015-02-20 19:26:04 +00001112 PointerToBase[ptr] = base;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001113 assert((!isa<Instruction>(base) || !isa<Instruction>(ptr) ||
1114 DT->dominates(cast<Instruction>(base)->getParent(),
1115 cast<Instruction>(ptr)->getParent())) &&
1116 "The base we found better dominate the derived pointer");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001117 }
1118}
1119
1120/// Find the required based pointers (and adjust the live set) for the given
1121/// parse point.
1122static void findBasePointers(DominatorTree &DT, DefiningValueMapTy &DVCache,
Sanjoy Dasa3244872016-06-17 00:45:00 +00001123 CallSite CS,
Philip Reamesd16a9b12015-02-20 01:06:44 +00001124 PartiallyConstructedSafepointRecord &result) {
Igor Laevskyfb1811d2016-05-04 14:55:36 +00001125 MapVector<Value *, Value *> PointerToBase;
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001126 findBasePointers(result.LiveSet, PointerToBase, &DT, DVCache);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001127
1128 if (PrintBasePointers) {
1129 errs() << "Base Pairs (w/o Relocation):\n";
Igor Laevskyfb1811d2016-05-04 14:55:36 +00001130 for (auto &Pair : PointerToBase) {
Manuel Jacoba4efd8a2015-12-23 00:19:45 +00001131 errs() << " derived ";
Igor Laevskyfb1811d2016-05-04 14:55:36 +00001132 Pair.first->printAsOperand(errs(), false);
Manuel Jacoba4efd8a2015-12-23 00:19:45 +00001133 errs() << " base ";
Igor Laevskyfb1811d2016-05-04 14:55:36 +00001134 Pair.second->printAsOperand(errs(), false);
Manuel Jacoba4efd8a2015-12-23 00:19:45 +00001135 errs() << "\n";;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001136 }
1137 }
1138
Philip Reamesf2041322015-02-20 19:26:04 +00001139 result.PointerToBase = PointerToBase;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001140}
1141
Philip Reamesdf1ef082015-04-10 22:53:14 +00001142/// Given an updated version of the dataflow liveness results, update the
1143/// liveset and base pointer maps for the call site CS.
1144static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData,
Sanjoy Dasa3244872016-06-17 00:45:00 +00001145 CallSite CS,
Philip Reamesdf1ef082015-04-10 22:53:14 +00001146 PartiallyConstructedSafepointRecord &result);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001147
Philip Reamesdf1ef082015-04-10 22:53:14 +00001148static void recomputeLiveInValues(
Justin Bogner843fb202015-12-15 19:40:57 +00001149 Function &F, DominatorTree &DT, ArrayRef<CallSite> toUpdate,
Philip Reamesd2b66462015-02-20 22:39:41 +00001150 MutableArrayRef<struct PartiallyConstructedSafepointRecord> records) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00001151 // TODO-PERF: reuse the original liveness, then simply run the dataflow
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001152 // again. The old values are still live and will help it stabilize quickly.
Philip Reamesdf1ef082015-04-10 22:53:14 +00001153 GCPtrLivenessData RevisedLivenessData;
1154 computeLiveInValues(DT, F, RevisedLivenessData);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001155 for (size_t i = 0; i < records.size(); i++) {
1156 struct PartiallyConstructedSafepointRecord &info = records[i];
Sanjoy Dasa3244872016-06-17 00:45:00 +00001157 recomputeLiveInValues(RevisedLivenessData, toUpdate[i], info);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001158 }
1159}
1160
Sanjoy Das7ad67642015-10-20 01:06:24 +00001161// When inserting gc.relocate and gc.result calls, we need to ensure there are
1162// no uses of the original value / return value between the gc.statepoint and
1163// the gc.relocate / gc.result call. One case which can arise is a phi node
1164// starting one of the successor blocks. We also need to be able to insert the
1165// gc.relocates only on the path which goes through the statepoint. We might
1166// need to split an edge to make this possible.
Philip Reamesf209a152015-04-13 20:00:30 +00001167static BasicBlock *
Sanjoy Dasea45f0e2015-06-02 22:33:34 +00001168normalizeForInvokeSafepoint(BasicBlock *BB, BasicBlock *InvokeParent,
1169 DominatorTree &DT) {
Philip Reames69e51ca2015-04-13 18:07:21 +00001170 BasicBlock *Ret = BB;
Sanjoy Dasff3dba72015-10-20 01:06:17 +00001171 if (!BB->getUniquePredecessor())
Chandler Carruth96ada252015-07-22 09:52:54 +00001172 Ret = SplitBlockPredecessors(BB, InvokeParent, "", &DT);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001173
Sanjoy Das7ad67642015-10-20 01:06:24 +00001174 // Now that 'Ret' has unique predecessor we can safely remove all phi nodes
Philip Reames69e51ca2015-04-13 18:07:21 +00001175 // from it
1176 FoldSingleEntryPHINodes(Ret);
Sanjoy Dasff3dba72015-10-20 01:06:17 +00001177 assert(!isa<PHINode>(Ret->begin()) &&
1178 "All PHI nodes should have been removed!");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001179
Sanjoy Das7ad67642015-10-20 01:06:24 +00001180 // At this point, we can safely insert a gc.relocate or gc.result as the first
1181 // instruction in Ret if needed.
Philip Reames69e51ca2015-04-13 18:07:21 +00001182 return Ret;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001183}
1184
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001185// Create new attribute set containing only attributes which can be transferred
Philip Reamesd16a9b12015-02-20 01:06:44 +00001186// from original call to the safepoint.
Reid Kleckner99351962017-04-28 19:22:40 +00001187static AttributeList legalizeCallAttributes(AttributeList AL) {
1188 if (AL.isEmpty())
1189 return AL;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001190
Reid Kleckner99351962017-04-28 19:22:40 +00001191 // Remove the readonly, readnone, and statepoint function attributes.
1192 AttrBuilder FnAttrs = AL.getFnAttributes();
1193 FnAttrs.removeAttribute(Attribute::ReadNone);
1194 FnAttrs.removeAttribute(Attribute::ReadOnly);
1195 for (Attribute A : AL.getFnAttributes()) {
1196 if (isStatepointDirectiveAttr(A))
1197 FnAttrs.remove(A);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001198 }
1199
Reid Kleckner99351962017-04-28 19:22:40 +00001200 // Just skip parameter and return attributes for now
1201 LLVMContext &Ctx = AL.getContext();
1202 return AttributeList::get(Ctx, AttributeList::FunctionIndex,
1203 AttributeSet::get(Ctx, FnAttrs));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001204}
1205
1206/// Helper function to place all gc relocates necessary for the given
1207/// statepoint.
1208/// Inputs:
1209/// liveVariables - list of variables to be relocated.
1210/// liveStart - index of the first live variable.
1211/// basePtrs - base pointers.
1212/// statepointToken - statepoint instruction to which relocates should be
1213/// bound.
1214/// Builder - Llvm IR builder to be used to construct new calls.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001215static void CreateGCRelocates(ArrayRef<Value *> LiveVariables,
Sanjoy Das5665c992015-05-11 23:47:27 +00001216 const int LiveStart,
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001217 ArrayRef<Value *> BasePtrs,
Sanjoy Das5665c992015-05-11 23:47:27 +00001218 Instruction *StatepointToken,
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00001219 IRBuilder<> Builder) {
Philip Reames94babb72015-07-21 17:18:03 +00001220 if (LiveVariables.empty())
1221 return;
Sanjoy Dasb1942f12015-10-20 01:06:28 +00001222
1223 auto FindIndex = [](ArrayRef<Value *> LiveVec, Value *Val) {
Eugene Zelenko75075ef2017-09-01 21:37:29 +00001224 auto ValIt = llvm::find(LiveVec, Val);
Sanjoy Dasb1942f12015-10-20 01:06:28 +00001225 assert(ValIt != LiveVec.end() && "Val not found in LiveVec!");
1226 size_t Index = std::distance(LiveVec.begin(), ValIt);
1227 assert(Index < LiveVec.size() && "Bug in std::find?");
1228 return Index;
1229 };
Philip Reames74ce2e72015-07-21 16:51:17 +00001230 Module *M = StatepointToken->getModule();
Philip Reames5715f572016-01-09 01:31:13 +00001231
1232 // All gc_relocate are generated as i8 addrspace(1)* (or a vector type whose
1233 // element type is i8 addrspace(1)*). We originally generated unique
1234 // declarations for each pointer type, but this proved problematic because
1235 // the intrinsic mangling code is incomplete and fragile. Since we're moving
1236 // towards a single unified pointer type anyways, we can just cast everything
1237 // to an i8* of the right address space. A bitcast is added later to convert
1238 // gc_relocate to the actual value's type.
1239 auto getGCRelocateDecl = [&] (Type *Ty) {
1240 assert(isHandledGCPointerType(Ty));
1241 auto AS = Ty->getScalarType()->getPointerAddressSpace();
1242 Type *NewTy = Type::getInt8PtrTy(M->getContext(), AS);
1243 if (auto *VT = dyn_cast<VectorType>(Ty))
1244 NewTy = VectorType::get(NewTy, VT->getNumElements());
1245 return Intrinsic::getDeclaration(M, Intrinsic::experimental_gc_relocate,
1246 {NewTy});
1247 };
1248
1249 // Lazily populated map from input types to the canonicalized form mentioned
1250 // in the comment above. This should probably be cached somewhere more
1251 // broadly.
1252 DenseMap<Type*, Value*> TypeToDeclMap;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001253
Sanjoy Das5665c992015-05-11 23:47:27 +00001254 for (unsigned i = 0; i < LiveVariables.size(); i++) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001255 // Generate the gc.relocate call and save the result
Sanjoy Das5665c992015-05-11 23:47:27 +00001256 Value *BaseIdx =
Sanjoy Dasb1942f12015-10-20 01:06:28 +00001257 Builder.getInt32(LiveStart + FindIndex(LiveVariables, BasePtrs[i]));
Sanjoy Das3020b1b2015-10-20 01:06:31 +00001258 Value *LiveIdx = Builder.getInt32(LiveStart + i);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001259
Philip Reames5715f572016-01-09 01:31:13 +00001260 Type *Ty = LiveVariables[i]->getType();
1261 if (!TypeToDeclMap.count(Ty))
1262 TypeToDeclMap[Ty] = getGCRelocateDecl(Ty);
1263 Value *GCRelocateDecl = TypeToDeclMap[Ty];
1264
Philip Reamesd16a9b12015-02-20 01:06:44 +00001265 // only specify a debug name if we can give a useful one
Philip Reames74ce2e72015-07-21 16:51:17 +00001266 CallInst *Reloc = Builder.CreateCall(
David Blaikieff6409d2015-05-18 22:13:54 +00001267 GCRelocateDecl, {StatepointToken, BaseIdx, LiveIdx},
Philip Reamesece70b82015-09-09 23:57:18 +00001268 suffixed_name_or(LiveVariables[i], ".relocated", ""));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001269 // Trick CodeGen into thinking there are lots of free registers at this
1270 // fake call.
Philip Reames74ce2e72015-07-21 16:51:17 +00001271 Reloc->setCallingConv(CallingConv::Cold);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001272 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00001273}
1274
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001275namespace {
1276
1277/// This struct is used to defer RAUWs and `eraseFromParent` s. Using this
1278/// avoids having to worry about keeping around dangling pointers to Values.
1279class DeferredReplacement {
1280 AssertingVH<Instruction> Old;
1281 AssertingVH<Instruction> New;
Sanjoy Das49e974b2016-04-05 23:18:35 +00001282 bool IsDeoptimize = false;
1283
Eugene Zelenko75075ef2017-09-01 21:37:29 +00001284 DeferredReplacement() = default;
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001285
1286public:
Sanjoy Das8d89a2b2016-04-05 23:18:53 +00001287 static DeferredReplacement createRAUW(Instruction *Old, Instruction *New) {
1288 assert(Old != New && Old && New &&
1289 "Cannot RAUW equal values or to / from null!");
1290
1291 DeferredReplacement D;
1292 D.Old = Old;
1293 D.New = New;
1294 return D;
1295 }
1296
1297 static DeferredReplacement createDelete(Instruction *ToErase) {
1298 DeferredReplacement D;
1299 D.Old = ToErase;
1300 return D;
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001301 }
1302
Sanjoy Das49e974b2016-04-05 23:18:35 +00001303 static DeferredReplacement createDeoptimizeReplacement(Instruction *Old) {
1304#ifndef NDEBUG
1305 auto *F = cast<CallInst>(Old)->getCalledFunction();
1306 assert(F && F->getIntrinsicID() == Intrinsic::experimental_deoptimize &&
1307 "Only way to construct a deoptimize deferred replacement");
1308#endif
1309 DeferredReplacement D;
1310 D.Old = Old;
1311 D.IsDeoptimize = true;
1312 return D;
1313 }
1314
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001315 /// Does the task represented by this instance.
1316 void doReplacement() {
1317 Instruction *OldI = Old;
1318 Instruction *NewI = New;
1319
1320 assert(OldI != NewI && "Disallowed at construction?!");
Richard Trieuf35d4b02016-04-06 04:22:00 +00001321 assert((!IsDeoptimize || !New) &&
1322 "Deoptimize instrinsics are not replaced!");
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001323
1324 Old = nullptr;
1325 New = nullptr;
1326
1327 if (NewI)
1328 OldI->replaceAllUsesWith(NewI);
Sanjoy Das49e974b2016-04-05 23:18:35 +00001329
1330 if (IsDeoptimize) {
1331 // Note: we've inserted instructions, so the call to llvm.deoptimize may
1332 // not necessarilly be followed by the matching return.
1333 auto *RI = cast<ReturnInst>(OldI->getParent()->getTerminator());
1334 new UnreachableInst(RI->getContext(), RI);
1335 RI->eraseFromParent();
1336 }
1337
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001338 OldI->eraseFromParent();
1339 }
1340};
Eugene Zelenko75075ef2017-09-01 21:37:29 +00001341
1342} // end anonymous namespace
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001343
Philip Reames2b1084a2016-08-31 15:12:17 +00001344static StringRef getDeoptLowering(CallSite CS) {
1345 const char *DeoptLowering = "deopt-lowering";
1346 if (CS.hasFnAttr(DeoptLowering)) {
1347 // FIXME: CallSite has a *really* confusing interface around attributes
Reid Klecknerb5180542017-03-21 16:57:19 +00001348 // with values.
1349 const AttributeList &CSAS = CS.getAttributes();
1350 if (CSAS.hasAttribute(AttributeList::FunctionIndex, DeoptLowering))
1351 return CSAS.getAttribute(AttributeList::FunctionIndex, DeoptLowering)
1352 .getValueAsString();
Philip Reames2b1084a2016-08-31 15:12:17 +00001353 Function *F = CS.getCalledFunction();
1354 assert(F && F->hasFnAttribute(DeoptLowering));
1355 return F->getFnAttribute(DeoptLowering).getValueAsString();
1356 }
1357 return "live-through";
1358}
1359
Philip Reamesd16a9b12015-02-20 01:06:44 +00001360static void
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001361makeStatepointExplicitImpl(const CallSite CS, /* to replace */
1362 const SmallVectorImpl<Value *> &BasePtrs,
1363 const SmallVectorImpl<Value *> &LiveVariables,
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001364 PartiallyConstructedSafepointRecord &Result,
1365 std::vector<DeferredReplacement> &Replacements) {
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001366 assert(BasePtrs.size() == LiveVariables.size());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001367
Philip Reamesd16a9b12015-02-20 01:06:44 +00001368 // Then go ahead and use the builder do actually do the inserts. We insert
1369 // immediately before the previous instruction under the assumption that all
1370 // arguments will be available here. We can't insert afterwards since we may
1371 // be replacing a terminator.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001372 Instruction *InsertBefore = CS.getInstruction();
1373 IRBuilder<> Builder(InsertBefore);
1374
Sanjoy Das3c520a12015-10-08 23:18:38 +00001375 ArrayRef<Value *> GCArgs(LiveVariables);
Sanjoy Dasc9058ca2016-03-17 18:42:17 +00001376 uint64_t StatepointID = StatepointDirectives::DefaultStatepointID;
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001377 uint32_t NumPatchBytes = 0;
1378 uint32_t Flags = uint32_t(StatepointFlags::None);
Sanjoy Das3c520a12015-10-08 23:18:38 +00001379
Sanjoy Dasbcf27522016-01-29 01:03:20 +00001380 ArrayRef<Use> CallArgs(CS.arg_begin(), CS.arg_end());
1381 ArrayRef<Use> DeoptArgs = GetDeoptBundleOperands(CS);
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001382 ArrayRef<Use> TransitionArgs;
Sanjoy Das40992972016-01-29 01:03:17 +00001383 if (auto TransitionBundle =
1384 CS.getOperandBundle(LLVMContext::OB_gc_transition)) {
1385 Flags |= uint32_t(StatepointFlags::GCTransition);
1386 TransitionArgs = TransitionBundle->Inputs;
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001387 }
Sanjoy Das99abb272016-04-06 01:33:54 +00001388
1389 // Instead of lowering calls to @llvm.experimental.deoptimize as normal calls
1390 // with a return value, we lower then as never returning calls to
1391 // __llvm_deoptimize that are followed by unreachable to get better codegen.
Sanjoy Das49e974b2016-04-05 23:18:35 +00001392 bool IsDeoptimize = false;
Sanjoy Das40992972016-01-29 01:03:17 +00001393
Sanjoy Das31203882016-03-17 01:56:10 +00001394 StatepointDirectives SD =
1395 parseStatepointDirectivesFromAttrs(CS.getAttributes());
1396 if (SD.NumPatchBytes)
1397 NumPatchBytes = *SD.NumPatchBytes;
1398 if (SD.StatepointID)
1399 StatepointID = *SD.StatepointID;
Sanjoy Das40992972016-01-29 01:03:17 +00001400
Philip Reames2b1084a2016-08-31 15:12:17 +00001401 // Pass through the requested lowering if any. The default is live-through.
1402 StringRef DeoptLowering = getDeoptLowering(CS);
1403 if (DeoptLowering.equals("live-in"))
1404 Flags |= uint32_t(StatepointFlags::DeoptLiveIn);
1405 else {
1406 assert(DeoptLowering.equals("live-through") && "Unsupported value!");
1407 }
1408
Sanjoy Das31203882016-03-17 01:56:10 +00001409 Value *CallTarget = CS.getCalledValue();
Sanjoy Dasd4c78332016-03-25 20:12:13 +00001410 if (Function *F = dyn_cast<Function>(CallTarget)) {
1411 if (F->getIntrinsicID() == Intrinsic::experimental_deoptimize) {
Sanjoy Das091fcfa2016-05-06 20:39:33 +00001412 // Calls to llvm.experimental.deoptimize are lowered to calls to the
Sanjoy Dasd4c78332016-03-25 20:12:13 +00001413 // __llvm_deoptimize symbol. We want to resolve this now, since the
1414 // verifier does not allow taking the address of an intrinsic function.
1415
1416 SmallVector<Type *, 8> DomainTy;
1417 for (Value *Arg : CallArgs)
1418 DomainTy.push_back(Arg->getType());
Sanjoy Das49e974b2016-04-05 23:18:35 +00001419 auto *FTy = FunctionType::get(Type::getVoidTy(F->getContext()), DomainTy,
Sanjoy Dasd4c78332016-03-25 20:12:13 +00001420 /* isVarArg = */ false);
1421
1422 // Note: CallTarget can be a bitcast instruction of a symbol if there are
1423 // calls to @llvm.experimental.deoptimize with different argument types in
1424 // the same module. This is fine -- we assume the frontend knew what it
1425 // was doing when generating this kind of IR.
1426 CallTarget =
1427 F->getParent()->getOrInsertFunction("__llvm_deoptimize", FTy);
Sanjoy Das49e974b2016-04-05 23:18:35 +00001428
1429 IsDeoptimize = true;
Sanjoy Dasd4c78332016-03-25 20:12:13 +00001430 }
1431 }
Sanjoy Das40992972016-01-29 01:03:17 +00001432
Philip Reamesd16a9b12015-02-20 01:06:44 +00001433 // Create the statepoint given all the arguments
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001434 Instruction *Token = nullptr;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001435 if (CS.isCall()) {
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001436 CallInst *ToReplace = cast<CallInst>(CS.getInstruction());
Sanjoy Das3c520a12015-10-08 23:18:38 +00001437 CallInst *Call = Builder.CreateGCStatepointCall(
1438 StatepointID, NumPatchBytes, CallTarget, Flags, CallArgs,
1439 TransitionArgs, DeoptArgs, GCArgs, "safepoint_token");
1440
David Majnemerd5648c72016-11-25 22:35:09 +00001441 Call->setTailCallKind(ToReplace->getTailCallKind());
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001442 Call->setCallingConv(ToReplace->getCallingConv());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001443
1444 // Currently we will fail on parameter attributes and on certain
Reid Kleckner99351962017-04-28 19:22:40 +00001445 // function attributes. In case if we can handle this set of attributes -
1446 // set up function attrs directly on statepoint and return attrs later for
1447 // gc_result intrinsic.
1448 Call->setAttributes(legalizeCallAttributes(ToReplace->getAttributes()));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001449
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001450 Token = Call;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001451
1452 // Put the following gc_result and gc_relocate calls immediately after the
1453 // the old call (which we're about to delete)
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001454 assert(ToReplace->getNextNode() && "Not a terminator, must have next!");
1455 Builder.SetInsertPoint(ToReplace->getNextNode());
1456 Builder.SetCurrentDebugLocation(ToReplace->getNextNode()->getDebugLoc());
David Blaikie82ad7872015-02-20 23:44:24 +00001457 } else {
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001458 InvokeInst *ToReplace = cast<InvokeInst>(CS.getInstruction());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001459
1460 // Insert the new invoke into the old block. We'll remove the old one in a
1461 // moment at which point this will become the new terminator for the
1462 // original block.
Sanjoy Das3c520a12015-10-08 23:18:38 +00001463 InvokeInst *Invoke = Builder.CreateGCStatepointInvoke(
1464 StatepointID, NumPatchBytes, CallTarget, ToReplace->getNormalDest(),
1465 ToReplace->getUnwindDest(), Flags, CallArgs, TransitionArgs, DeoptArgs,
1466 GCArgs, "statepoint_token");
1467
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001468 Invoke->setCallingConv(ToReplace->getCallingConv());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001469
1470 // Currently we will fail on parameter attributes and on certain
Reid Kleckner99351962017-04-28 19:22:40 +00001471 // function attributes. In case if we can handle this set of attributes -
1472 // set up function attrs directly on statepoint and return attrs later for
1473 // gc_result intrinsic.
1474 Invoke->setAttributes(legalizeCallAttributes(ToReplace->getAttributes()));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001475
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001476 Token = Invoke;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001477
1478 // Generate gc relocates in exceptional path
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001479 BasicBlock *UnwindBlock = ToReplace->getUnwindDest();
1480 assert(!isa<PHINode>(UnwindBlock->begin()) &&
1481 UnwindBlock->getUniquePredecessor() &&
Philip Reames69e51ca2015-04-13 18:07:21 +00001482 "can't safely insert in this block!");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001483
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001484 Builder.SetInsertPoint(&*UnwindBlock->getFirstInsertionPt());
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001485 Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001486
Chen Lid71999e2015-12-26 07:54:32 +00001487 // Attach exceptional gc relocates to the landingpad.
1488 Instruction *ExceptionalToken = UnwindBlock->getLandingPadInst();
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001489 Result.UnwindToken = ExceptionalToken;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001490
Sanjoy Das3c520a12015-10-08 23:18:38 +00001491 const unsigned LiveStartIdx = Statepoint(Token).gcArgsStartIdx();
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001492 CreateGCRelocates(LiveVariables, LiveStartIdx, BasePtrs, ExceptionalToken,
1493 Builder);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001494
1495 // Generate gc relocates and returns for normal block
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001496 BasicBlock *NormalDest = ToReplace->getNormalDest();
1497 assert(!isa<PHINode>(NormalDest->begin()) &&
1498 NormalDest->getUniquePredecessor() &&
Philip Reames69e51ca2015-04-13 18:07:21 +00001499 "can't safely insert in this block!");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001500
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001501 Builder.SetInsertPoint(&*NormalDest->getFirstInsertionPt());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001502
1503 // gc relocates will be generated later as if it were regular call
1504 // statepoint
Philip Reamesd16a9b12015-02-20 01:06:44 +00001505 }
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001506 assert(Token && "Should be set in one of the above branches!");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001507
Sanjoy Das49e974b2016-04-05 23:18:35 +00001508 if (IsDeoptimize) {
1509 // If we're wrapping an @llvm.experimental.deoptimize in a statepoint, we
1510 // transform the tail-call like structure to a call to a void function
1511 // followed by unreachable to get better codegen.
1512 Replacements.push_back(
1513 DeferredReplacement::createDeoptimizeReplacement(CS.getInstruction()));
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001514 } else {
Sanjoy Das49e974b2016-04-05 23:18:35 +00001515 Token->setName("statepoint_token");
1516 if (!CS.getType()->isVoidTy() && !CS.getInstruction()->use_empty()) {
1517 StringRef Name =
1518 CS.getInstruction()->hasName() ? CS.getInstruction()->getName() : "";
1519 CallInst *GCResult = Builder.CreateGCResult(Token, CS.getType(), Name);
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00001520 GCResult->setAttributes(
1521 AttributeList::get(GCResult->getContext(), AttributeList::ReturnIndex,
1522 CS.getAttributes().getRetAttributes()));
Sanjoy Das49e974b2016-04-05 23:18:35 +00001523
1524 // We cannot RAUW or delete CS.getInstruction() because it could be in the
1525 // live set of some other safepoint, in which case that safepoint's
1526 // PartiallyConstructedSafepointRecord will hold a raw pointer to this
1527 // llvm::Instruction. Instead, we defer the replacement and deletion to
1528 // after the live sets have been made explicit in the IR, and we no longer
1529 // have raw pointers to worry about.
Sanjoy Das8d89a2b2016-04-05 23:18:53 +00001530 Replacements.emplace_back(
1531 DeferredReplacement::createRAUW(CS.getInstruction(), GCResult));
Sanjoy Das49e974b2016-04-05 23:18:35 +00001532 } else {
Sanjoy Das8d89a2b2016-04-05 23:18:53 +00001533 Replacements.emplace_back(
1534 DeferredReplacement::createDelete(CS.getInstruction()));
Sanjoy Das49e974b2016-04-05 23:18:35 +00001535 }
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001536 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00001537
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001538 Result.StatepointToken = Token;
Philip Reames0a3240f2015-02-20 21:34:11 +00001539
Philip Reamesd16a9b12015-02-20 01:06:44 +00001540 // Second, create a gc.relocate for every live variable
Sanjoy Das3c520a12015-10-08 23:18:38 +00001541 const unsigned LiveStartIdx = Statepoint(Token).gcArgsStartIdx();
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001542 CreateGCRelocates(LiveVariables, LiveStartIdx, BasePtrs, Token, Builder);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001543}
1544
Philip Reamesd16a9b12015-02-20 01:06:44 +00001545// Replace an existing gc.statepoint with a new one and a set of gc.relocates
1546// which make the relocations happening at this safepoint explicit.
Philip Reames704e78b2015-04-10 22:34:56 +00001547//
Philip Reamesd16a9b12015-02-20 01:06:44 +00001548// WARNING: Does not do any fixup to adjust users of the original live
1549// values. That's the callers responsibility.
1550static void
Sanjoy Dasa3244872016-06-17 00:45:00 +00001551makeStatepointExplicit(DominatorTree &DT, CallSite CS,
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001552 PartiallyConstructedSafepointRecord &Result,
1553 std::vector<DeferredReplacement> &Replacements) {
Sanjoy Das1ede5362015-10-08 23:18:22 +00001554 const auto &LiveSet = Result.LiveSet;
1555 const auto &PointerToBase = Result.PointerToBase;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001556
1557 // Convert to vector for efficient cross referencing.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001558 SmallVector<Value *, 64> BaseVec, LiveVec;
1559 LiveVec.reserve(LiveSet.size());
1560 BaseVec.reserve(LiveSet.size());
1561 for (Value *L : LiveSet) {
1562 LiveVec.push_back(L);
Philip Reames74ce2e72015-07-21 16:51:17 +00001563 assert(PointerToBase.count(L));
Sanjoy Das1ede5362015-10-08 23:18:22 +00001564 Value *Base = PointerToBase.find(L)->second;
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001565 BaseVec.push_back(Base);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001566 }
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001567 assert(LiveVec.size() == BaseVec.size());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001568
Philip Reamesd16a9b12015-02-20 01:06:44 +00001569 // Do the actual rewriting and delete the old statepoint
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001570 makeStatepointExplicitImpl(CS, BaseVec, LiveVec, Result, Replacements);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001571}
1572
1573// Helper function for the relocationViaAlloca.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001574//
1575// It receives iterator to the statepoint gc relocates and emits a store to the
1576// assigned location (via allocaMap) for the each one of them. It adds the
1577// visited values into the visitedLiveValues set, which we will later use them
1578// for sanity checking.
Philip Reamesd16a9b12015-02-20 01:06:44 +00001579static void
Sanjoy Das5665c992015-05-11 23:47:27 +00001580insertRelocationStores(iterator_range<Value::user_iterator> GCRelocs,
1581 DenseMap<Value *, Value *> &AllocaMap,
1582 DenseSet<Value *> &VisitedLiveValues) {
Sanjoy Das5665c992015-05-11 23:47:27 +00001583 for (User *U : GCRelocs) {
Manuel Jacob83eefa62016-01-05 04:03:00 +00001584 GCRelocateInst *Relocate = dyn_cast<GCRelocateInst>(U);
1585 if (!Relocate)
Philip Reamesd16a9b12015-02-20 01:06:44 +00001586 continue;
1587
Sanjoy Das565f7862016-01-29 16:54:49 +00001588 Value *OriginalValue = Relocate->getDerivedPtr();
Sanjoy Das5665c992015-05-11 23:47:27 +00001589 assert(AllocaMap.count(OriginalValue));
1590 Value *Alloca = AllocaMap[OriginalValue];
Philip Reamesd16a9b12015-02-20 01:06:44 +00001591
1592 // Emit store into the related alloca
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001593 // All gc_relocates are i8 addrspace(1)* typed, and it must be bitcasted to
Sanjoy Das89c54912015-05-11 18:49:34 +00001594 // the correct type according to alloca.
Manuel Jacob83eefa62016-01-05 04:03:00 +00001595 assert(Relocate->getNextNode() &&
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001596 "Should always have one since it's not a terminator");
Manuel Jacob83eefa62016-01-05 04:03:00 +00001597 IRBuilder<> Builder(Relocate->getNextNode());
Sanjoy Das89c54912015-05-11 18:49:34 +00001598 Value *CastedRelocatedValue =
Manuel Jacob83eefa62016-01-05 04:03:00 +00001599 Builder.CreateBitCast(Relocate,
Philip Reamesece70b82015-09-09 23:57:18 +00001600 cast<AllocaInst>(Alloca)->getAllocatedType(),
Manuel Jacob83eefa62016-01-05 04:03:00 +00001601 suffixed_name_or(Relocate, ".casted", ""));
Sanjoy Das89c54912015-05-11 18:49:34 +00001602
Sanjoy Das5665c992015-05-11 23:47:27 +00001603 StoreInst *Store = new StoreInst(CastedRelocatedValue, Alloca);
1604 Store->insertAfter(cast<Instruction>(CastedRelocatedValue));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001605
1606#ifndef NDEBUG
Sanjoy Das5665c992015-05-11 23:47:27 +00001607 VisitedLiveValues.insert(OriginalValue);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001608#endif
1609 }
1610}
1611
Igor Laevskye0317182015-05-19 15:59:05 +00001612// Helper function for the "relocationViaAlloca". Similar to the
1613// "insertRelocationStores" but works for rematerialized values.
Joseph Tremouletadc23762016-02-05 01:42:52 +00001614static void insertRematerializationStores(
1615 const RematerializedValueMapTy &RematerializedValues,
1616 DenseMap<Value *, Value *> &AllocaMap,
1617 DenseSet<Value *> &VisitedLiveValues) {
Igor Laevskye0317182015-05-19 15:59:05 +00001618 for (auto RematerializedValuePair: RematerializedValues) {
1619 Instruction *RematerializedValue = RematerializedValuePair.first;
1620 Value *OriginalValue = RematerializedValuePair.second;
1621
1622 assert(AllocaMap.count(OriginalValue) &&
1623 "Can not find alloca for rematerialized value");
1624 Value *Alloca = AllocaMap[OriginalValue];
1625
1626 StoreInst *Store = new StoreInst(RematerializedValue, Alloca);
1627 Store->insertAfter(RematerializedValue);
1628
1629#ifndef NDEBUG
1630 VisitedLiveValues.insert(OriginalValue);
1631#endif
1632 }
1633}
1634
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001635/// Do all the relocation update via allocas and mem2reg
Philip Reamesd16a9b12015-02-20 01:06:44 +00001636static void relocationViaAlloca(
Igor Laevsky285fe842015-05-19 16:29:43 +00001637 Function &F, DominatorTree &DT, ArrayRef<Value *> Live,
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001638 ArrayRef<PartiallyConstructedSafepointRecord> Records) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001639#ifndef NDEBUG
Philip Reamesa6ebf072015-03-27 05:53:16 +00001640 // record initial number of (static) allocas; we'll check we have the same
1641 // number when we get done.
1642 int InitialAllocaNum = 0;
Benjamin Kramer135f7352016-06-26 12:28:59 +00001643 for (Instruction &I : F.getEntryBlock())
1644 if (isa<AllocaInst>(I))
Philip Reamesa6ebf072015-03-27 05:53:16 +00001645 InitialAllocaNum++;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001646#endif
1647
1648 // TODO-PERF: change data structures, reserve
Igor Laevsky285fe842015-05-19 16:29:43 +00001649 DenseMap<Value *, Value *> AllocaMap;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001650 SmallVector<AllocaInst *, 200> PromotableAllocas;
Igor Laevskye0317182015-05-19 15:59:05 +00001651 // Used later to chack that we have enough allocas to store all values
1652 std::size_t NumRematerializedValues = 0;
Igor Laevsky285fe842015-05-19 16:29:43 +00001653 PromotableAllocas.reserve(Live.size());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001654
Igor Laevskye0317182015-05-19 15:59:05 +00001655 // Emit alloca for "LiveValue" and record it in "allocaMap" and
1656 // "PromotableAllocas"
Matt Arsenault3c1fc762017-04-10 22:27:50 +00001657 const DataLayout &DL = F.getParent()->getDataLayout();
Igor Laevskye0317182015-05-19 15:59:05 +00001658 auto emitAllocaFor = [&](Value *LiveValue) {
Matt Arsenault3c1fc762017-04-10 22:27:50 +00001659 AllocaInst *Alloca = new AllocaInst(LiveValue->getType(),
1660 DL.getAllocaAddrSpace(), "",
Igor Laevskye0317182015-05-19 15:59:05 +00001661 F.getEntryBlock().getFirstNonPHI());
Igor Laevsky285fe842015-05-19 16:29:43 +00001662 AllocaMap[LiveValue] = Alloca;
Igor Laevskye0317182015-05-19 15:59:05 +00001663 PromotableAllocas.push_back(Alloca);
1664 };
1665
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001666 // Emit alloca for each live gc pointer
1667 for (Value *V : Live)
1668 emitAllocaFor(V);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001669
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001670 // Emit allocas for rematerialized values
1671 for (const auto &Info : Records)
Igor Laevsky285fe842015-05-19 16:29:43 +00001672 for (auto RematerializedValuePair : Info.RematerializedValues) {
Igor Laevskye0317182015-05-19 15:59:05 +00001673 Value *OriginalValue = RematerializedValuePair.second;
Igor Laevsky285fe842015-05-19 16:29:43 +00001674 if (AllocaMap.count(OriginalValue) != 0)
Igor Laevskye0317182015-05-19 15:59:05 +00001675 continue;
1676
1677 emitAllocaFor(OriginalValue);
1678 ++NumRematerializedValues;
1679 }
Igor Laevsky285fe842015-05-19 16:29:43 +00001680
Philip Reamesd16a9b12015-02-20 01:06:44 +00001681 // The next two loops are part of the same conceptual operation. We need to
1682 // insert a store to the alloca after the original def and at each
1683 // redefinition. We need to insert a load before each use. These are split
1684 // into distinct loops for performance reasons.
1685
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001686 // Update gc pointer after each statepoint: either store a relocated value or
1687 // null (if no relocated value was found for this gc pointer and it is not a
1688 // gc_result). This must happen before we update the statepoint with load of
1689 // alloca otherwise we lose the link between statepoint and old def.
1690 for (const auto &Info : Records) {
Igor Laevsky285fe842015-05-19 16:29:43 +00001691 Value *Statepoint = Info.StatepointToken;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001692
1693 // This will be used for consistency check
Igor Laevsky285fe842015-05-19 16:29:43 +00001694 DenseSet<Value *> VisitedLiveValues;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001695
1696 // Insert stores for normal statepoint gc relocates
Igor Laevsky285fe842015-05-19 16:29:43 +00001697 insertRelocationStores(Statepoint->users(), AllocaMap, VisitedLiveValues);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001698
1699 // In case if it was invoke statepoint
1700 // we will insert stores for exceptional path gc relocates.
Philip Reames0a3240f2015-02-20 21:34:11 +00001701 if (isa<InvokeInst>(Statepoint)) {
Igor Laevsky285fe842015-05-19 16:29:43 +00001702 insertRelocationStores(Info.UnwindToken->users(), AllocaMap,
1703 VisitedLiveValues);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001704 }
1705
Igor Laevskye0317182015-05-19 15:59:05 +00001706 // Do similar thing with rematerialized values
Igor Laevsky285fe842015-05-19 16:29:43 +00001707 insertRematerializationStores(Info.RematerializedValues, AllocaMap,
1708 VisitedLiveValues);
Igor Laevskye0317182015-05-19 15:59:05 +00001709
Philip Reamese73300b2015-04-13 16:41:32 +00001710 if (ClobberNonLive) {
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001711 // As a debugging aid, pretend that an unrelocated pointer becomes null at
Philip Reamese73300b2015-04-13 16:41:32 +00001712 // the gc.statepoint. This will turn some subtle GC problems into
1713 // slightly easier to debug SEGVs. Note that on large IR files with
1714 // lots of gc.statepoints this is extremely costly both memory and time
1715 // wise.
1716 SmallVector<AllocaInst *, 64> ToClobber;
Igor Laevsky285fe842015-05-19 16:29:43 +00001717 for (auto Pair : AllocaMap) {
Philip Reamese73300b2015-04-13 16:41:32 +00001718 Value *Def = Pair.first;
1719 AllocaInst *Alloca = cast<AllocaInst>(Pair.second);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001720
Philip Reamese73300b2015-04-13 16:41:32 +00001721 // This value was relocated
Igor Laevsky285fe842015-05-19 16:29:43 +00001722 if (VisitedLiveValues.count(Def)) {
Philip Reamese73300b2015-04-13 16:41:32 +00001723 continue;
1724 }
1725 ToClobber.push_back(Alloca);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001726 }
Philip Reamesfa2fcf172015-02-20 19:51:56 +00001727
Philip Reamese73300b2015-04-13 16:41:32 +00001728 auto InsertClobbersAt = [&](Instruction *IP) {
1729 for (auto *AI : ToClobber) {
Eduard Burtescu90c44492016-01-18 00:10:01 +00001730 auto PT = cast<PointerType>(AI->getAllocatedType());
Philip Reamese73300b2015-04-13 16:41:32 +00001731 Constant *CPN = ConstantPointerNull::get(PT);
Igor Laevsky285fe842015-05-19 16:29:43 +00001732 StoreInst *Store = new StoreInst(CPN, AI);
1733 Store->insertBefore(IP);
Philip Reamese73300b2015-04-13 16:41:32 +00001734 }
1735 };
1736
1737 // Insert the clobbering stores. These may get intermixed with the
1738 // gc.results and gc.relocates, but that's fine.
1739 if (auto II = dyn_cast<InvokeInst>(Statepoint)) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001740 InsertClobbersAt(&*II->getNormalDest()->getFirstInsertionPt());
1741 InsertClobbersAt(&*II->getUnwindDest()->getFirstInsertionPt());
Philip Reamese73300b2015-04-13 16:41:32 +00001742 } else {
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001743 InsertClobbersAt(cast<Instruction>(Statepoint)->getNextNode());
Philip Reamesfa2fcf172015-02-20 19:51:56 +00001744 }
David Blaikie82ad7872015-02-20 23:44:24 +00001745 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00001746 }
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001747
1748 // Update use with load allocas and add store for gc_relocated.
Igor Laevsky285fe842015-05-19 16:29:43 +00001749 for (auto Pair : AllocaMap) {
1750 Value *Def = Pair.first;
1751 Value *Alloca = Pair.second;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001752
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001753 // We pre-record the uses of allocas so that we dont have to worry about
1754 // later update that changes the user information..
1755
Igor Laevsky285fe842015-05-19 16:29:43 +00001756 SmallVector<Instruction *, 20> Uses;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001757 // PERF: trade a linear scan for repeated reallocation
Igor Laevsky285fe842015-05-19 16:29:43 +00001758 Uses.reserve(std::distance(Def->user_begin(), Def->user_end()));
1759 for (User *U : Def->users()) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001760 if (!isa<ConstantExpr>(U)) {
1761 // If the def has a ConstantExpr use, then the def is either a
1762 // ConstantExpr use itself or null. In either case
1763 // (recursively in the first, directly in the second), the oop
1764 // it is ultimately dependent on is null and this particular
1765 // use does not need to be fixed up.
Igor Laevsky285fe842015-05-19 16:29:43 +00001766 Uses.push_back(cast<Instruction>(U));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001767 }
1768 }
1769
Igor Laevsky285fe842015-05-19 16:29:43 +00001770 std::sort(Uses.begin(), Uses.end());
1771 auto Last = std::unique(Uses.begin(), Uses.end());
1772 Uses.erase(Last, Uses.end());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001773
Igor Laevsky285fe842015-05-19 16:29:43 +00001774 for (Instruction *Use : Uses) {
1775 if (isa<PHINode>(Use)) {
1776 PHINode *Phi = cast<PHINode>(Use);
1777 for (unsigned i = 0; i < Phi->getNumIncomingValues(); i++) {
1778 if (Def == Phi->getIncomingValue(i)) {
1779 LoadInst *Load = new LoadInst(
1780 Alloca, "", Phi->getIncomingBlock(i)->getTerminator());
1781 Phi->setIncomingValue(i, Load);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001782 }
1783 }
1784 } else {
Igor Laevsky285fe842015-05-19 16:29:43 +00001785 LoadInst *Load = new LoadInst(Alloca, "", Use);
1786 Use->replaceUsesOfWith(Def, Load);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001787 }
1788 }
1789
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001790 // Emit store for the initial gc value. Store must be inserted after load,
1791 // otherwise store will be in alloca's use list and an extra load will be
1792 // inserted before it.
Igor Laevsky285fe842015-05-19 16:29:43 +00001793 StoreInst *Store = new StoreInst(Def, Alloca);
1794 if (Instruction *Inst = dyn_cast<Instruction>(Def)) {
1795 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(Inst)) {
Philip Reames6da37852015-03-04 00:13:52 +00001796 // InvokeInst is a TerminatorInst so the store need to be inserted
1797 // into its normal destination block.
Igor Laevsky285fe842015-05-19 16:29:43 +00001798 BasicBlock *NormalDest = Invoke->getNormalDest();
1799 Store->insertBefore(NormalDest->getFirstNonPHI());
Philip Reames6da37852015-03-04 00:13:52 +00001800 } else {
Igor Laevsky285fe842015-05-19 16:29:43 +00001801 assert(!Inst->isTerminator() &&
Philip Reames6da37852015-03-04 00:13:52 +00001802 "The only TerminatorInst that can produce a value is "
1803 "InvokeInst which is handled above.");
Igor Laevsky285fe842015-05-19 16:29:43 +00001804 Store->insertAfter(Inst);
Philip Reames6da37852015-03-04 00:13:52 +00001805 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00001806 } else {
Igor Laevsky285fe842015-05-19 16:29:43 +00001807 assert(isa<Argument>(Def));
1808 Store->insertAfter(cast<Instruction>(Alloca));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001809 }
1810 }
1811
Igor Laevsky285fe842015-05-19 16:29:43 +00001812 assert(PromotableAllocas.size() == Live.size() + NumRematerializedValues &&
Philip Reamesd16a9b12015-02-20 01:06:44 +00001813 "we must have the same allocas with lives");
1814 if (!PromotableAllocas.empty()) {
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001815 // Apply mem2reg to promote alloca to SSA
Philip Reamesd16a9b12015-02-20 01:06:44 +00001816 PromoteMemToReg(PromotableAllocas, DT);
1817 }
1818
1819#ifndef NDEBUG
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001820 for (auto &I : F.getEntryBlock())
1821 if (isa<AllocaInst>(I))
Philip Reamesa6ebf072015-03-27 05:53:16 +00001822 InitialAllocaNum--;
1823 assert(InitialAllocaNum == 0 && "We must not introduce any extra allocas");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001824#endif
1825}
1826
1827/// Implement a unique function which doesn't require we sort the input
1828/// vector. Doing so has the effect of changing the output of a couple of
1829/// tests in ways which make them less useful in testing fused safepoints.
Philip Reamesd2b66462015-02-20 22:39:41 +00001830template <typename T> static void unique_unsorted(SmallVectorImpl<T> &Vec) {
Benjamin Kramer258ea0d2015-06-13 19:50:38 +00001831 SmallSet<T, 8> Seen;
David Majnemerc7004902016-08-12 04:32:37 +00001832 Vec.erase(remove_if(Vec, [&](const T &V) { return !Seen.insert(V).second; }),
1833 Vec.end());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001834}
1835
Philip Reamesd16a9b12015-02-20 01:06:44 +00001836/// Insert holders so that each Value is obviously live through the entire
Philip Reamesf209a152015-04-13 20:00:30 +00001837/// lifetime of the call.
Philip Reamesd16a9b12015-02-20 01:06:44 +00001838static void insertUseHolderAfter(CallSite &CS, const ArrayRef<Value *> Values,
Philip Reamesf209a152015-04-13 20:00:30 +00001839 SmallVectorImpl<CallInst *> &Holders) {
Philip Reames21142752015-04-13 19:07:47 +00001840 if (Values.empty())
1841 // No values to hold live, might as well not insert the empty holder
1842 return;
1843
Sanjay Patelaf674fb2015-12-14 17:24:23 +00001844 Module *M = CS.getInstruction()->getModule();
Philip Reamesf209a152015-04-13 20:00:30 +00001845 // Use a dummy vararg function to actually hold the values live
1846 Function *Func = cast<Function>(M->getOrInsertFunction(
1847 "__tmp_use", FunctionType::get(Type::getVoidTy(M->getContext()), true)));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001848 if (CS.isCall()) {
1849 // For call safepoints insert dummy calls right after safepoint
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001850 Holders.push_back(CallInst::Create(Func, Values, "",
1851 &*++CS.getInstruction()->getIterator()));
Philip Reamesf209a152015-04-13 20:00:30 +00001852 return;
1853 }
1854 // For invoke safepooints insert dummy calls both in normal and
1855 // exceptional destination blocks
1856 auto *II = cast<InvokeInst>(CS.getInstruction());
1857 Holders.push_back(CallInst::Create(
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001858 Func, Values, "", &*II->getNormalDest()->getFirstInsertionPt()));
Philip Reamesf209a152015-04-13 20:00:30 +00001859 Holders.push_back(CallInst::Create(
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001860 Func, Values, "", &*II->getUnwindDest()->getFirstInsertionPt()));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001861}
1862
1863static void findLiveReferences(
Justin Bogner843fb202015-12-15 19:40:57 +00001864 Function &F, DominatorTree &DT, ArrayRef<CallSite> toUpdate,
Philip Reamesd2b66462015-02-20 22:39:41 +00001865 MutableArrayRef<struct PartiallyConstructedSafepointRecord> records) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00001866 GCPtrLivenessData OriginalLivenessData;
1867 computeLiveInValues(DT, F, OriginalLivenessData);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001868 for (size_t i = 0; i < records.size(); i++) {
1869 struct PartiallyConstructedSafepointRecord &info = records[i];
Sanjoy Dasa3244872016-06-17 00:45:00 +00001870 analyzeParsePointLiveness(DT, OriginalLivenessData, toUpdate[i], info);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001871 }
1872}
1873
Igor Laevskye0317182015-05-19 15:59:05 +00001874// Helper function for the "rematerializeLiveValues". It walks use chain
Anna Thomas8cd7de12016-09-20 21:36:02 +00001875// starting from the "CurrentValue" until it reaches the root of the chain, i.e.
1876// the base or a value it cannot process. Only "simple" values are processed
1877// (currently it is GEP's and casts). The returned root is examined by the
1878// callers of findRematerializableChainToBasePointer. Fills "ChainToBase" array
1879// with all visited values.
1880static Value* findRematerializableChainToBasePointer(
Igor Laevskye0317182015-05-19 15:59:05 +00001881 SmallVectorImpl<Instruction*> &ChainToBase,
Anna Thomas8cd7de12016-09-20 21:36:02 +00001882 Value *CurrentValue) {
Igor Laevskye0317182015-05-19 15:59:05 +00001883 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurrentValue)) {
1884 ChainToBase.push_back(GEP);
1885 return findRematerializableChainToBasePointer(ChainToBase,
Anna Thomas8cd7de12016-09-20 21:36:02 +00001886 GEP->getPointerOperand());
Igor Laevskye0317182015-05-19 15:59:05 +00001887 }
1888
1889 if (CastInst *CI = dyn_cast<CastInst>(CurrentValue)) {
Igor Laevskye0317182015-05-19 15:59:05 +00001890 if (!CI->isNoopCast(CI->getModule()->getDataLayout()))
Anna Thomas8cd7de12016-09-20 21:36:02 +00001891 return CI;
Igor Laevskye0317182015-05-19 15:59:05 +00001892
1893 ChainToBase.push_back(CI);
Manuel Jacob9db5b932015-12-28 20:14:05 +00001894 return findRematerializableChainToBasePointer(ChainToBase,
Anna Thomas8cd7de12016-09-20 21:36:02 +00001895 CI->getOperand(0));
Igor Laevskye0317182015-05-19 15:59:05 +00001896 }
1897
Anna Thomas8cd7de12016-09-20 21:36:02 +00001898 // We have reached the root of the chain, which is either equal to the base or
1899 // is the first unsupported value along the use chain.
1900 return CurrentValue;
Igor Laevskye0317182015-05-19 15:59:05 +00001901}
1902
1903// Helper function for the "rematerializeLiveValues". Compute cost of the use
1904// chain we are going to rematerialize.
1905static unsigned
1906chainToBasePointerCost(SmallVectorImpl<Instruction*> &Chain,
1907 TargetTransformInfo &TTI) {
1908 unsigned Cost = 0;
1909
1910 for (Instruction *Instr : Chain) {
1911 if (CastInst *CI = dyn_cast<CastInst>(Instr)) {
1912 assert(CI->isNoopCast(CI->getModule()->getDataLayout()) &&
1913 "non noop cast is found during rematerialization");
1914
1915 Type *SrcTy = CI->getOperand(0)->getType();
Jonas Paulssonfccc7d62017-04-12 11:49:08 +00001916 Cost += TTI.getCastInstrCost(CI->getOpcode(), CI->getType(), SrcTy, CI);
Igor Laevskye0317182015-05-19 15:59:05 +00001917
1918 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Instr)) {
1919 // Cost of the address calculation
Eduard Burtescu19eb0312016-01-19 17:28:00 +00001920 Type *ValTy = GEP->getSourceElementType();
Igor Laevskye0317182015-05-19 15:59:05 +00001921 Cost += TTI.getAddressComputationCost(ValTy);
1922
1923 // And cost of the GEP itself
1924 // TODO: Use TTI->getGEPCost here (it exists, but appears to be not
1925 // allowed for the external usage)
1926 if (!GEP->hasAllConstantIndices())
1927 Cost += 2;
1928
1929 } else {
1930 llvm_unreachable("unsupported instruciton type during rematerialization");
1931 }
1932 }
1933
1934 return Cost;
1935}
1936
Anna Thomas8cd7de12016-09-20 21:36:02 +00001937static bool AreEquivalentPhiNodes(PHINode &OrigRootPhi, PHINode &AlternateRootPhi) {
Anna Thomas8cd7de12016-09-20 21:36:02 +00001938 unsigned PhiNum = OrigRootPhi.getNumIncomingValues();
1939 if (PhiNum != AlternateRootPhi.getNumIncomingValues() ||
1940 OrigRootPhi.getParent() != AlternateRootPhi.getParent())
1941 return false;
1942 // Map of incoming values and their corresponding basic blocks of
1943 // OrigRootPhi.
1944 SmallDenseMap<Value *, BasicBlock *, 8> CurrentIncomingValues;
1945 for (unsigned i = 0; i < PhiNum; i++)
1946 CurrentIncomingValues[OrigRootPhi.getIncomingValue(i)] =
1947 OrigRootPhi.getIncomingBlock(i);
1948
1949 // Both current and base PHIs should have same incoming values and
1950 // the same basic blocks corresponding to the incoming values.
1951 for (unsigned i = 0; i < PhiNum; i++) {
1952 auto CIVI =
1953 CurrentIncomingValues.find(AlternateRootPhi.getIncomingValue(i));
1954 if (CIVI == CurrentIncomingValues.end())
1955 return false;
1956 BasicBlock *CurrentIncomingBB = CIVI->second;
1957 if (CurrentIncomingBB != AlternateRootPhi.getIncomingBlock(i))
1958 return false;
1959 }
1960 return true;
Anna Thomas8cd7de12016-09-20 21:36:02 +00001961}
1962
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001963// From the statepoint live set pick values that are cheaper to recompute then
1964// to relocate. Remove this values from the live set, rematerialize them after
Igor Laevskye0317182015-05-19 15:59:05 +00001965// statepoint and record them in "Info" structure. Note that similar to
1966// relocated values we don't do any user adjustments here.
1967static void rematerializeLiveValues(CallSite CS,
1968 PartiallyConstructedSafepointRecord &Info,
1969 TargetTransformInfo &TTI) {
Aaron Ballmanff7d4fa2015-05-20 14:53:50 +00001970 const unsigned int ChainLengthThreshold = 10;
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +00001971
Igor Laevskye0317182015-05-19 15:59:05 +00001972 // Record values we are going to delete from this statepoint live set.
1973 // We can not di this in following loop due to iterator invalidation.
1974 SmallVector<Value *, 32> LiveValuesToBeDeleted;
1975
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001976 for (Value *LiveValue: Info.LiveSet) {
Igor Laevskye0317182015-05-19 15:59:05 +00001977 // For each live pointer find it's defining chain
1978 SmallVector<Instruction *, 3> ChainToBase;
Philip Reames74ce2e72015-07-21 16:51:17 +00001979 assert(Info.PointerToBase.count(LiveValue));
Anna Thomas8cd7de12016-09-20 21:36:02 +00001980 Value *RootOfChain =
Igor Laevskye0317182015-05-19 15:59:05 +00001981 findRematerializableChainToBasePointer(ChainToBase,
Anna Thomas8cd7de12016-09-20 21:36:02 +00001982 LiveValue);
1983
Igor Laevskye0317182015-05-19 15:59:05 +00001984 // Nothing to do, or chain is too long
Anna Thomas8cd7de12016-09-20 21:36:02 +00001985 if ( ChainToBase.size() == 0 ||
Igor Laevskye0317182015-05-19 15:59:05 +00001986 ChainToBase.size() > ChainLengthThreshold)
1987 continue;
1988
Anna Thomas8cd7de12016-09-20 21:36:02 +00001989 // Handle the scenario where the RootOfChain is not equal to the
1990 // Base Value, but they are essentially the same phi values.
1991 if (RootOfChain != Info.PointerToBase[LiveValue]) {
1992 PHINode *OrigRootPhi = dyn_cast<PHINode>(RootOfChain);
1993 PHINode *AlternateRootPhi = dyn_cast<PHINode>(Info.PointerToBase[LiveValue]);
1994 if (!OrigRootPhi || !AlternateRootPhi)
1995 continue;
1996 // PHI nodes that have the same incoming values, and belonging to the same
1997 // basic blocks are essentially the same SSA value. When the original phi
1998 // has incoming values with different base pointers, the original phi is
1999 // marked as conflict, and an additional `AlternateRootPhi` with the same
2000 // incoming values get generated by the findBasePointer function. We need
2001 // to identify the newly generated AlternateRootPhi (.base version of phi)
2002 // and RootOfChain (the original phi node itself) are the same, so that we
2003 // can rematerialize the gep and casts. This is a workaround for the
Hiroshi Inoueef1c2ba2017-07-01 07:12:15 +00002004 // deficiency in the findBasePointer algorithm.
Anna Thomas8cd7de12016-09-20 21:36:02 +00002005 if (!AreEquivalentPhiNodes(*OrigRootPhi, *AlternateRootPhi))
2006 continue;
2007 // Now that the phi nodes are proved to be the same, assert that
2008 // findBasePointer's newly generated AlternateRootPhi is present in the
2009 // liveset of the call.
2010 assert(Info.LiveSet.count(AlternateRootPhi));
2011 }
Igor Laevskye0317182015-05-19 15:59:05 +00002012 // Compute cost of this chain
2013 unsigned Cost = chainToBasePointerCost(ChainToBase, TTI);
2014 // TODO: We can also account for cases when we will be able to remove some
2015 // of the rematerialized values by later optimization passes. I.e if
2016 // we rematerialized several intersecting chains. Or if original values
2017 // don't have any uses besides this statepoint.
2018
2019 // For invokes we need to rematerialize each chain twice - for normal and
2020 // for unwind basic blocks. Model this by multiplying cost by two.
2021 if (CS.isInvoke()) {
2022 Cost *= 2;
2023 }
2024 // If it's too expensive - skip it
2025 if (Cost >= RematerializationThreshold)
2026 continue;
2027
2028 // Remove value from the live set
2029 LiveValuesToBeDeleted.push_back(LiveValue);
2030
2031 // Clone instructions and record them inside "Info" structure
2032
2033 // Walk backwards to visit top-most instructions first
2034 std::reverse(ChainToBase.begin(), ChainToBase.end());
2035
2036 // Utility function which clones all instructions from "ChainToBase"
2037 // and inserts them before "InsertBefore". Returns rematerialized value
2038 // which should be used after statepoint.
Anna Thomas82c37172016-09-22 13:13:06 +00002039 auto rematerializeChain = [&ChainToBase](
2040 Instruction *InsertBefore, Value *RootOfChain, Value *AlternateLiveBase) {
Igor Laevskye0317182015-05-19 15:59:05 +00002041 Instruction *LastClonedValue = nullptr;
2042 Instruction *LastValue = nullptr;
2043 for (Instruction *Instr: ChainToBase) {
Hiroshi Inouebb703e82017-07-02 03:24:54 +00002044 // Only GEP's and casts are supported as we need to be careful to not
Igor Laevskye0317182015-05-19 15:59:05 +00002045 // introduce any new uses of pointers not in the liveset.
2046 // Note that it's fine to introduce new uses of pointers which were
2047 // otherwise not used after this statepoint.
2048 assert(isa<GetElementPtrInst>(Instr) || isa<CastInst>(Instr));
2049
2050 Instruction *ClonedValue = Instr->clone();
2051 ClonedValue->insertBefore(InsertBefore);
2052 ClonedValue->setName(Instr->getName() + ".remat");
2053
2054 // If it is not first instruction in the chain then it uses previously
2055 // cloned value. We should update it to use cloned value.
2056 if (LastClonedValue) {
2057 assert(LastValue);
2058 ClonedValue->replaceUsesOfWith(LastValue, LastClonedValue);
2059#ifndef NDEBUG
Igor Laevskyd83f6972015-05-21 13:02:14 +00002060 for (auto OpValue : ClonedValue->operand_values()) {
Anna Thomas82c37172016-09-22 13:13:06 +00002061 // Assert that cloned instruction does not use any instructions from
2062 // this chain other than LastClonedValue
David Majnemer0d955d02016-08-11 22:21:41 +00002063 assert(!is_contained(ChainToBase, OpValue) &&
Igor Laevskyd83f6972015-05-21 13:02:14 +00002064 "incorrect use in rematerialization chain");
Anna Thomas82c37172016-09-22 13:13:06 +00002065 // Assert that the cloned instruction does not use the RootOfChain
2066 // or the AlternateLiveBase.
2067 assert(OpValue != RootOfChain && OpValue != AlternateLiveBase);
Igor Laevskye0317182015-05-19 15:59:05 +00002068 }
2069#endif
Anna Thomas82c37172016-09-22 13:13:06 +00002070 } else {
2071 // For the first instruction, replace the use of unrelocated base i.e.
2072 // RootOfChain/OrigRootPhi, with the corresponding PHI present in the
2073 // live set. They have been proved to be the same PHI nodes. Note
2074 // that the *only* use of the RootOfChain in the ChainToBase list is
2075 // the first Value in the list.
2076 if (RootOfChain != AlternateLiveBase)
2077 ClonedValue->replaceUsesOfWith(RootOfChain, AlternateLiveBase);
Igor Laevskye0317182015-05-19 15:59:05 +00002078 }
2079
2080 LastClonedValue = ClonedValue;
2081 LastValue = Instr;
2082 }
2083 assert(LastClonedValue);
2084 return LastClonedValue;
2085 };
2086
2087 // Different cases for calls and invokes. For invokes we need to clone
2088 // instructions both on normal and unwind path.
2089 if (CS.isCall()) {
2090 Instruction *InsertBefore = CS.getInstruction()->getNextNode();
2091 assert(InsertBefore);
Anna Thomas82c37172016-09-22 13:13:06 +00002092 Instruction *RematerializedValue = rematerializeChain(
2093 InsertBefore, RootOfChain, Info.PointerToBase[LiveValue]);
Igor Laevskye0317182015-05-19 15:59:05 +00002094 Info.RematerializedValues[RematerializedValue] = LiveValue;
2095 } else {
2096 InvokeInst *Invoke = cast<InvokeInst>(CS.getInstruction());
2097
2098 Instruction *NormalInsertBefore =
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00002099 &*Invoke->getNormalDest()->getFirstInsertionPt();
Igor Laevskye0317182015-05-19 15:59:05 +00002100 Instruction *UnwindInsertBefore =
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00002101 &*Invoke->getUnwindDest()->getFirstInsertionPt();
Igor Laevskye0317182015-05-19 15:59:05 +00002102
Anna Thomas82c37172016-09-22 13:13:06 +00002103 Instruction *NormalRematerializedValue = rematerializeChain(
2104 NormalInsertBefore, RootOfChain, Info.PointerToBase[LiveValue]);
2105 Instruction *UnwindRematerializedValue = rematerializeChain(
2106 UnwindInsertBefore, RootOfChain, Info.PointerToBase[LiveValue]);
Igor Laevskye0317182015-05-19 15:59:05 +00002107
2108 Info.RematerializedValues[NormalRematerializedValue] = LiveValue;
2109 Info.RematerializedValues[UnwindRematerializedValue] = LiveValue;
2110 }
2111 }
2112
2113 // Remove rematerializaed values from the live set
2114 for (auto LiveValue: LiveValuesToBeDeleted) {
Igor Laevskyfb1811d2016-05-04 14:55:36 +00002115 Info.LiveSet.remove(LiveValue);
Igor Laevskye0317182015-05-19 15:59:05 +00002116 }
2117}
2118
Justin Bogner843fb202015-12-15 19:40:57 +00002119static bool insertParsePoints(Function &F, DominatorTree &DT,
2120 TargetTransformInfo &TTI,
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002121 SmallVectorImpl<CallSite> &ToUpdate) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00002122#ifndef NDEBUG
2123 // sanity check the input
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002124 std::set<CallSite> Uniqued;
2125 Uniqued.insert(ToUpdate.begin(), ToUpdate.end());
2126 assert(Uniqued.size() == ToUpdate.size() && "no duplicates please!");
Philip Reamesd16a9b12015-02-20 01:06:44 +00002127
Sanjoy Dasbcf27522016-01-29 01:03:20 +00002128 for (CallSite CS : ToUpdate)
2129 assert(CS.getInstruction()->getFunction() == &F);
Philip Reamesd16a9b12015-02-20 01:06:44 +00002130#endif
2131
Philip Reames69e51ca2015-04-13 18:07:21 +00002132 // When inserting gc.relocates for invokes, we need to be able to insert at
2133 // the top of the successor blocks. See the comment on
2134 // normalForInvokeSafepoint on exactly what is needed. Note that this step
Philip Reamesf209a152015-04-13 20:00:30 +00002135 // may restructure the CFG.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002136 for (CallSite CS : ToUpdate) {
Philip Reamesf209a152015-04-13 20:00:30 +00002137 if (!CS.isInvoke())
2138 continue;
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002139 auto *II = cast<InvokeInst>(CS.getInstruction());
2140 normalizeForInvokeSafepoint(II->getNormalDest(), II->getParent(), DT);
2141 normalizeForInvokeSafepoint(II->getUnwindDest(), II->getParent(), DT);
Philip Reamesf209a152015-04-13 20:00:30 +00002142 }
Philip Reames69e51ca2015-04-13 18:07:21 +00002143
Philip Reamesd16a9b12015-02-20 01:06:44 +00002144 // A list of dummy calls added to the IR to keep various values obviously
2145 // live in the IR. We'll remove all of these when done.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002146 SmallVector<CallInst *, 64> Holders;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002147
Philip Reamesb70cecd2017-06-02 23:03:26 +00002148 // Insert a dummy call with all of the deopt operands we'll need for the
2149 // actual safepoint insertion as arguments. This ensures reference operands
2150 // in the deopt argument list are considered live through the safepoint (and
Philip Reamesd16a9b12015-02-20 01:06:44 +00002151 // thus makes sure they get relocated.)
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002152 for (CallSite CS : ToUpdate) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00002153 SmallVector<Value *, 64> DeoptValues;
Sanjoy Das25ec1a32015-10-16 02:41:00 +00002154
Sanjoy Das40992972016-01-29 01:03:17 +00002155 for (Value *Arg : GetDeoptBundleOperands(CS)) {
Philip Reames8531d8c2015-04-10 21:48:25 +00002156 assert(!isUnhandledGCPointerType(Arg->getType()) &&
2157 "support for FCA unimplemented");
2158 if (isHandledGCPointerType(Arg->getType()))
Philip Reamesd16a9b12015-02-20 01:06:44 +00002159 DeoptValues.push_back(Arg);
2160 }
Sanjoy Das25ec1a32015-10-16 02:41:00 +00002161
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002162 insertUseHolderAfter(CS, DeoptValues, Holders);
Philip Reamesd16a9b12015-02-20 01:06:44 +00002163 }
2164
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002165 SmallVector<PartiallyConstructedSafepointRecord, 64> Records(ToUpdate.size());
Philip Reamesd16a9b12015-02-20 01:06:44 +00002166
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002167 // A) Identify all gc pointers which are statically live at the given call
Philip Reamesd16a9b12015-02-20 01:06:44 +00002168 // site.
Justin Bogner843fb202015-12-15 19:40:57 +00002169 findLiveReferences(F, DT, ToUpdate, Records);
Philip Reamesd16a9b12015-02-20 01:06:44 +00002170
2171 // B) Find the base pointers for each live pointer
2172 /* scope for caching */ {
2173 // Cache the 'defining value' relation used in the computation and
2174 // insertion of base phis and selects. This ensures that we don't insert
2175 // large numbers of duplicate base_phis.
2176 DefiningValueMapTy DVCache;
2177
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002178 for (size_t i = 0; i < Records.size(); i++) {
2179 PartiallyConstructedSafepointRecord &info = Records[i];
2180 findBasePointers(DT, DVCache, ToUpdate[i], info);
Philip Reamesd16a9b12015-02-20 01:06:44 +00002181 }
2182 } // end of cache scope
2183
2184 // The base phi insertion logic (for any safepoint) may have inserted new
2185 // instructions which are now live at some safepoint. The simplest such
2186 // example is:
2187 // loop:
2188 // phi a <-- will be a new base_phi here
2189 // safepoint 1 <-- that needs to be live here
2190 // gep a + 1
2191 // safepoint 2
2192 // br loop
Philip Reamesd16a9b12015-02-20 01:06:44 +00002193 // We insert some dummy calls after each safepoint to definitely hold live
2194 // the base pointers which were identified for that safepoint. We'll then
2195 // ask liveness for _every_ base inserted to see what is now live. Then we
2196 // remove the dummy calls.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002197 Holders.reserve(Holders.size() + Records.size());
2198 for (size_t i = 0; i < Records.size(); i++) {
2199 PartiallyConstructedSafepointRecord &Info = Records[i];
Philip Reamesd16a9b12015-02-20 01:06:44 +00002200
2201 SmallVector<Value *, 128> Bases;
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002202 for (auto Pair : Info.PointerToBase)
Philip Reamesd16a9b12015-02-20 01:06:44 +00002203 Bases.push_back(Pair.second);
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002204
2205 insertUseHolderAfter(ToUpdate[i], Bases, Holders);
Philip Reamesd16a9b12015-02-20 01:06:44 +00002206 }
2207
Philip Reamesdf1ef082015-04-10 22:53:14 +00002208 // By selecting base pointers, we've effectively inserted new uses. Thus, we
2209 // need to rerun liveness. We may *also* have inserted new defs, but that's
2210 // not the key issue.
Justin Bogner843fb202015-12-15 19:40:57 +00002211 recomputeLiveInValues(F, DT, ToUpdate, Records);
Philip Reamesd16a9b12015-02-20 01:06:44 +00002212
Philip Reamesd16a9b12015-02-20 01:06:44 +00002213 if (PrintBasePointers) {
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002214 for (auto &Info : Records) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00002215 errs() << "Base Pairs: (w/Relocation)\n";
Manuel Jacoba4efd8a2015-12-23 00:19:45 +00002216 for (auto Pair : Info.PointerToBase) {
2217 errs() << " derived ";
2218 Pair.first->printAsOperand(errs(), false);
2219 errs() << " base ";
2220 Pair.second->printAsOperand(errs(), false);
2221 errs() << "\n";
2222 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00002223 }
2224 }
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002225
Manuel Jacob990dfa62015-12-22 16:50:44 +00002226 // It is possible that non-constant live variables have a constant base. For
2227 // example, a GEP with a variable offset from a global. In this case we can
2228 // remove it from the liveset. We already don't add constants to the liveset
2229 // because we assume they won't move at runtime and the GC doesn't need to be
2230 // informed about them. The same reasoning applies if the base is constant.
2231 // Note that the relocation placement code relies on this filtering for
2232 // correctness as it expects the base to be in the liveset, which isn't true
2233 // if the base is constant.
2234 for (auto &Info : Records)
2235 for (auto &BasePair : Info.PointerToBase)
2236 if (isa<Constant>(BasePair.second))
Igor Laevskyfb1811d2016-05-04 14:55:36 +00002237 Info.LiveSet.remove(BasePair.first);
Manuel Jacob990dfa62015-12-22 16:50:44 +00002238
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002239 for (CallInst *CI : Holders)
2240 CI->eraseFromParent();
2241
2242 Holders.clear();
Philip Reamesd16a9b12015-02-20 01:06:44 +00002243
Igor Laevskye0317182015-05-19 15:59:05 +00002244 // In order to reduce live set of statepoint we might choose to rematerialize
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002245 // some values instead of relocating them. This is purely an optimization and
Igor Laevskye0317182015-05-19 15:59:05 +00002246 // does not influence correctness.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002247 for (size_t i = 0; i < Records.size(); i++)
2248 rematerializeLiveValues(ToUpdate[i], Records[i], TTI);
Igor Laevskye0317182015-05-19 15:59:05 +00002249
Sanjoy Das25ec1a32015-10-16 02:41:00 +00002250 // We need this to safely RAUW and delete call or invoke return values that
2251 // may themselves be live over a statepoint. For details, please see usage in
2252 // makeStatepointExplicitImpl.
2253 std::vector<DeferredReplacement> Replacements;
2254
Philip Reamesd16a9b12015-02-20 01:06:44 +00002255 // Now run through and replace the existing statepoints with new ones with
2256 // the live variables listed. We do not yet update uses of the values being
2257 // relocated. We have references to live variables that need to
2258 // survive to the last iteration of this loop. (By construction, the
2259 // previous statepoint can not be a live variable, thus we can and remove
2260 // the old statepoint calls as we go.)
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002261 for (size_t i = 0; i < Records.size(); i++)
Sanjoy Das25ec1a32015-10-16 02:41:00 +00002262 makeStatepointExplicit(DT, ToUpdate[i], Records[i], Replacements);
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002263
2264 ToUpdate.clear(); // prevent accident use of invalid CallSites
Philip Reamesd16a9b12015-02-20 01:06:44 +00002265
Sanjoy Das25ec1a32015-10-16 02:41:00 +00002266 for (auto &PR : Replacements)
2267 PR.doReplacement();
2268
2269 Replacements.clear();
2270
2271 for (auto &Info : Records) {
2272 // These live sets may contain state Value pointers, since we replaced calls
2273 // with operand bundles with calls wrapped in gc.statepoint, and some of
2274 // those calls may have been def'ing live gc pointers. Clear these out to
2275 // avoid accidentally using them.
2276 //
2277 // TODO: We should create a separate data structure that does not contain
2278 // these live sets, and migrate to using that data structure from this point
2279 // onward.
2280 Info.LiveSet.clear();
2281 Info.PointerToBase.clear();
2282 }
2283
Philip Reamesd16a9b12015-02-20 01:06:44 +00002284 // Do all the fixups of the original live variables to their relocated selves
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002285 SmallVector<Value *, 128> Live;
2286 for (size_t i = 0; i < Records.size(); i++) {
2287 PartiallyConstructedSafepointRecord &Info = Records[i];
Sanjoy Das25ec1a32015-10-16 02:41:00 +00002288
Philip Reamesd16a9b12015-02-20 01:06:44 +00002289 // We can't simply save the live set from the original insertion. One of
2290 // the live values might be the result of a call which needs a safepoint.
2291 // That Value* no longer exists and we need to use the new gc_result.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002292 // Thankfully, the live set is embedded in the statepoint (and updated), so
Philip Reamesd16a9b12015-02-20 01:06:44 +00002293 // we just grab that.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002294 Statepoint Statepoint(Info.StatepointToken);
2295 Live.insert(Live.end(), Statepoint.gc_args_begin(),
2296 Statepoint.gc_args_end());
Philip Reames9a2e01d2015-04-13 17:35:55 +00002297#ifndef NDEBUG
2298 // Do some basic sanity checks on our liveness results before performing
2299 // relocation. Relocation can and will turn mistakes in liveness results
2300 // into non-sensical code which is must harder to debug.
2301 // TODO: It would be nice to test consistency as well
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002302 assert(DT.isReachableFromEntry(Info.StatepointToken->getParent()) &&
Philip Reames9a2e01d2015-04-13 17:35:55 +00002303 "statepoint must be reachable or liveness is meaningless");
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002304 for (Value *V : Statepoint.gc_args()) {
Philip Reames9a2e01d2015-04-13 17:35:55 +00002305 if (!isa<Instruction>(V))
2306 // Non-instruction values trivial dominate all possible uses
2307 continue;
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002308 auto *LiveInst = cast<Instruction>(V);
Philip Reames9a2e01d2015-04-13 17:35:55 +00002309 assert(DT.isReachableFromEntry(LiveInst->getParent()) &&
2310 "unreachable values should never be live");
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002311 assert(DT.dominates(LiveInst, Info.StatepointToken) &&
Philip Reames9a2e01d2015-04-13 17:35:55 +00002312 "basic SSA liveness expectation violated by liveness analysis");
2313 }
2314#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +00002315 }
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002316 unique_unsorted(Live);
Philip Reamesd16a9b12015-02-20 01:06:44 +00002317
Nick Lewyckyeb3231e2015-02-20 07:14:02 +00002318#ifndef NDEBUG
Philip Reamesd16a9b12015-02-20 01:06:44 +00002319 // sanity check
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002320 for (auto *Ptr : Live)
Philip Reames5715f572016-01-09 01:31:13 +00002321 assert(isHandledGCPointerType(Ptr->getType()) &&
2322 "must be a gc pointer type");
Nick Lewyckyeb3231e2015-02-20 07:14:02 +00002323#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +00002324
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002325 relocationViaAlloca(F, DT, Live, Records);
2326 return !Records.empty();
Philip Reamesd16a9b12015-02-20 01:06:44 +00002327}
2328
Sanjoy Das353a19e2015-06-02 22:33:37 +00002329// Handles both return values and arguments for Functions and CallSites.
2330template <typename AttrHolder>
Igor Laevskydde00292015-10-23 22:42:44 +00002331static void RemoveNonValidAttrAtIndex(LLVMContext &Ctx, AttrHolder &AH,
2332 unsigned Index) {
Sanjoy Das353a19e2015-06-02 22:33:37 +00002333 AttrBuilder R;
2334 if (AH.getDereferenceableBytes(Index))
2335 R.addAttribute(Attribute::get(Ctx, Attribute::Dereferenceable,
2336 AH.getDereferenceableBytes(Index)));
2337 if (AH.getDereferenceableOrNullBytes(Index))
2338 R.addAttribute(Attribute::get(Ctx, Attribute::DereferenceableOrNull,
2339 AH.getDereferenceableOrNullBytes(Index)));
Reid Klecknera0b45f42017-05-03 18:17:31 +00002340 if (AH.getAttributes().hasAttribute(Index, Attribute::NoAlias))
Igor Laevsky1ef06552015-10-26 19:06:01 +00002341 R.addAttribute(Attribute::NoAlias);
Sanjoy Das353a19e2015-06-02 22:33:37 +00002342
2343 if (!R.empty())
Reid Kleckneree4930b2017-05-02 22:07:37 +00002344 AH.setAttributes(AH.getAttributes().removeAttributes(Ctx, Index, R));
Vasileios Kalintiris9f77f612015-06-03 08:51:30 +00002345}
Sanjoy Das353a19e2015-06-02 22:33:37 +00002346
2347void
Igor Laevskydde00292015-10-23 22:42:44 +00002348RewriteStatepointsForGC::stripNonValidAttributesFromPrototype(Function &F) {
Sanjoy Das353a19e2015-06-02 22:33:37 +00002349 LLVMContext &Ctx = F.getContext();
2350
2351 for (Argument &A : F.args())
2352 if (isa<PointerType>(A.getType()))
Reid Klecknera0b45f42017-05-03 18:17:31 +00002353 RemoveNonValidAttrAtIndex(Ctx, F,
2354 A.getArgNo() + AttributeList::FirstArgIndex);
Sanjoy Das353a19e2015-06-02 22:33:37 +00002355
2356 if (isa<PointerType>(F.getReturnType()))
Reid Klecknerb5180542017-03-21 16:57:19 +00002357 RemoveNonValidAttrAtIndex(Ctx, F, AttributeList::ReturnIndex);
Sanjoy Das353a19e2015-06-02 22:33:37 +00002358}
2359
Anna Thomas4b027e82017-06-12 21:26:53 +00002360void RewriteStatepointsForGC::stripInvalidMetadataFromInstruction(Instruction &I) {
Anna Thomas4b027e82017-06-12 21:26:53 +00002361 if (!isa<LoadInst>(I) && !isa<StoreInst>(I))
2362 return;
2363 // These are the attributes that are still valid on loads and stores after
2364 // RS4GC.
2365 // The metadata implying dereferenceability and noalias are (conservatively)
2366 // dropped. This is because semantically, after RewriteStatepointsForGC runs,
2367 // all calls to gc.statepoint "free" the entire heap. Also, gc.statepoint can
2368 // touch the entire heap including noalias objects. Note: The reasoning is
2369 // same as stripping the dereferenceability and noalias attributes that are
2370 // analogous to the metadata counterparts.
2371 // We also drop the invariant.load metadata on the load because that metadata
2372 // implies the address operand to the load points to memory that is never
2373 // changed once it became dereferenceable. This is no longer true after RS4GC.
2374 // Similar reasoning applies to invariant.group metadata, which applies to
2375 // loads within a group.
2376 unsigned ValidMetadataAfterRS4GC[] = {LLVMContext::MD_tbaa,
2377 LLVMContext::MD_range,
2378 LLVMContext::MD_alias_scope,
2379 LLVMContext::MD_nontemporal,
2380 LLVMContext::MD_nonnull,
2381 LLVMContext::MD_align,
2382 LLVMContext::MD_type};
2383
2384 // Drops all metadata on the instruction other than ValidMetadataAfterRS4GC.
2385 I.dropUnknownNonDebugMetadata(ValidMetadataAfterRS4GC);
Anna Thomas4b027e82017-06-12 21:26:53 +00002386}
2387
2388void RewriteStatepointsForGC::stripNonValidAttributesAndMetadataFromBody(Function &F) {
Sanjoy Das353a19e2015-06-02 22:33:37 +00002389 if (F.empty())
2390 return;
2391
2392 LLVMContext &Ctx = F.getContext();
2393 MDBuilder Builder(Ctx);
2394
Nico Rieck78199512015-08-06 19:10:45 +00002395 for (Instruction &I : instructions(F)) {
Sanjoy Das353a19e2015-06-02 22:33:37 +00002396 if (const MDNode *MD = I.getMetadata(LLVMContext::MD_tbaa)) {
2397 assert(MD->getNumOperands() < 5 && "unrecognized metadata shape!");
2398 bool IsImmutableTBAA =
2399 MD->getNumOperands() == 4 &&
2400 mdconst::extract<ConstantInt>(MD->getOperand(3))->getValue() == 1;
2401
2402 if (!IsImmutableTBAA)
2403 continue; // no work to do, MD_tbaa is already marked mutable
2404
2405 MDNode *Base = cast<MDNode>(MD->getOperand(0));
2406 MDNode *Access = cast<MDNode>(MD->getOperand(1));
2407 uint64_t Offset =
2408 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue();
2409
2410 MDNode *MutableTBAA =
2411 Builder.createTBAAStructTagNode(Base, Access, Offset);
2412 I.setMetadata(LLVMContext::MD_tbaa, MutableTBAA);
2413 }
2414
Anna Thomas4b027e82017-06-12 21:26:53 +00002415 stripInvalidMetadataFromInstruction(I);
2416
Sanjoy Das353a19e2015-06-02 22:33:37 +00002417 if (CallSite CS = CallSite(&I)) {
2418 for (int i = 0, e = CS.arg_size(); i != e; i++)
2419 if (isa<PointerType>(CS.getArgument(i)->getType()))
Reid Klecknera0b45f42017-05-03 18:17:31 +00002420 RemoveNonValidAttrAtIndex(Ctx, CS, i + AttributeList::FirstArgIndex);
Sanjoy Das353a19e2015-06-02 22:33:37 +00002421 if (isa<PointerType>(CS.getType()))
Reid Klecknerb5180542017-03-21 16:57:19 +00002422 RemoveNonValidAttrAtIndex(Ctx, CS, AttributeList::ReturnIndex);
Sanjoy Das353a19e2015-06-02 22:33:37 +00002423 }
2424 }
2425}
2426
Philip Reamesd16a9b12015-02-20 01:06:44 +00002427/// Returns true if this function should be rewritten by this pass. The main
2428/// point of this function is as an extension point for custom logic.
2429static bool shouldRewriteStatepointsIn(Function &F) {
2430 // TODO: This should check the GCStrategy
Philip Reames2ef029c2015-02-20 18:56:14 +00002431 if (F.hasGC()) {
Mehdi Amini599ebf22016-01-08 02:28:20 +00002432 const auto &FunctionGCName = F.getGC();
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +00002433 const StringRef StatepointExampleName("statepoint-example");
2434 const StringRef CoreCLRName("coreclr");
2435 return (StatepointExampleName == FunctionGCName) ||
NAKAMURA Takumi5582a6a2015-05-25 01:43:34 +00002436 (CoreCLRName == FunctionGCName);
2437 } else
Philip Reames2ef029c2015-02-20 18:56:14 +00002438 return false;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002439}
2440
Anna Thomas4b027e82017-06-12 21:26:53 +00002441void RewriteStatepointsForGC::stripNonValidAttributesAndMetadata(Module &M) {
Sanjoy Das353a19e2015-06-02 22:33:37 +00002442#ifndef NDEBUG
Eugene Zelenko75075ef2017-09-01 21:37:29 +00002443 assert(llvm::any_of(M, shouldRewriteStatepointsIn) && "precondition!");
Sanjoy Das353a19e2015-06-02 22:33:37 +00002444#endif
2445
2446 for (Function &F : M)
Igor Laevskydde00292015-10-23 22:42:44 +00002447 stripNonValidAttributesFromPrototype(F);
Sanjoy Das353a19e2015-06-02 22:33:37 +00002448
2449 for (Function &F : M)
Anna Thomas4b027e82017-06-12 21:26:53 +00002450 stripNonValidAttributesAndMetadataFromBody(F);
Sanjoy Das353a19e2015-06-02 22:33:37 +00002451}
2452
Philip Reamesd16a9b12015-02-20 01:06:44 +00002453bool RewriteStatepointsForGC::runOnFunction(Function &F) {
2454 // Nothing to do for declarations.
2455 if (F.isDeclaration() || F.empty())
2456 return false;
2457
2458 // Policy choice says not to rewrite - the most common reason is that we're
2459 // compiling code without a GCStrategy.
2460 if (!shouldRewriteStatepointsIn(F))
2461 return false;
2462
Sanjoy Dasea45f0e2015-06-02 22:33:34 +00002463 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
Justin Bogner843fb202015-12-15 19:40:57 +00002464 TargetTransformInfo &TTI =
2465 getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
Daniel Neilson2574d7c2017-07-27 16:49:39 +00002466 const TargetLibraryInfo &TLI =
2467 getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Philip Reames704e78b2015-04-10 22:34:56 +00002468
Daniel Neilson2574d7c2017-07-27 16:49:39 +00002469 auto NeedsRewrite = [&TLI](Instruction &I) {
Sanjoy Das40992972016-01-29 01:03:17 +00002470 if (ImmutableCallSite CS = ImmutableCallSite(&I))
Daniel Neilson2574d7c2017-07-27 16:49:39 +00002471 return !callsGCLeafFunction(CS, TLI) && !isStatepoint(CS);
Sanjoy Das40992972016-01-29 01:03:17 +00002472 return false;
Sanjoy Das25ec1a32015-10-16 02:41:00 +00002473 };
2474
Philip Reames85b36a82015-04-10 22:07:04 +00002475 // Gather all the statepoints which need rewritten. Be careful to only
2476 // consider those in reachable code since we need to ask dominance queries
2477 // when rewriting. We'll delete the unreachable ones in a moment.
Philip Reamesd2b66462015-02-20 22:39:41 +00002478 SmallVector<CallSite, 64> ParsePointNeeded;
Philip Reamesf66d7372015-04-10 22:16:58 +00002479 bool HasUnreachableStatepoint = false;
Nico Rieck78199512015-08-06 19:10:45 +00002480 for (Instruction &I : instructions(F)) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00002481 // TODO: only the ones with the flag set!
Sanjoy Das25ec1a32015-10-16 02:41:00 +00002482 if (NeedsRewrite(I)) {
Philip Reames85b36a82015-04-10 22:07:04 +00002483 if (DT.isReachableFromEntry(I.getParent()))
2484 ParsePointNeeded.push_back(CallSite(&I));
2485 else
Philip Reamesf66d7372015-04-10 22:16:58 +00002486 HasUnreachableStatepoint = true;
Philip Reames85b36a82015-04-10 22:07:04 +00002487 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00002488 }
2489
Philip Reames85b36a82015-04-10 22:07:04 +00002490 bool MadeChange = false;
Philip Reames704e78b2015-04-10 22:34:56 +00002491
Philip Reames85b36a82015-04-10 22:07:04 +00002492 // Delete any unreachable statepoints so that we don't have unrewritten
2493 // statepoints surviving this pass. This makes testing easier and the
2494 // resulting IR less confusing to human readers. Rather than be fancy, we
2495 // just reuse a utility function which removes the unreachable blocks.
Philip Reamesf66d7372015-04-10 22:16:58 +00002496 if (HasUnreachableStatepoint)
Philip Reames85b36a82015-04-10 22:07:04 +00002497 MadeChange |= removeUnreachableBlocks(F);
2498
Philip Reamesd16a9b12015-02-20 01:06:44 +00002499 // Return early if no work to do.
2500 if (ParsePointNeeded.empty())
Philip Reames85b36a82015-04-10 22:07:04 +00002501 return MadeChange;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002502
Philip Reames85b36a82015-04-10 22:07:04 +00002503 // As a prepass, go ahead and aggressively destroy single entry phi nodes.
2504 // These are created by LCSSA. They have the effect of increasing the size
2505 // of liveness sets for no good reason. It may be harder to do this post
2506 // insertion since relocations and base phis can confuse things.
2507 for (BasicBlock &BB : F)
2508 if (BB.getUniquePredecessor()) {
2509 MadeChange = true;
2510 FoldSingleEntryPHINodes(&BB);
2511 }
2512
Philip Reames971dc3a2015-08-12 22:11:45 +00002513 // Before we start introducing relocations, we want to tweak the IR a bit to
2514 // avoid unfortunate code generation effects. The main example is that we
2515 // want to try to make sure the comparison feeding a branch is after any
2516 // safepoints. Otherwise, we end up with a comparison of pre-relocation
2517 // values feeding a branch after relocation. This is semantically correct,
2518 // but results in extra register pressure since both the pre-relocation and
2519 // post-relocation copies must be available in registers. For code without
2520 // relocations this is handled elsewhere, but teaching the scheduler to
2521 // reverse the transform we're about to do would be slightly complex.
2522 // Note: This may extend the live range of the inputs to the icmp and thus
2523 // increase the liveset of any statepoint we move over. This is profitable
2524 // as long as all statepoints are in rare blocks. If we had in-register
2525 // lowering for live values this would be a much safer transform.
2526 auto getConditionInst = [](TerminatorInst *TI) -> Instruction* {
2527 if (auto *BI = dyn_cast<BranchInst>(TI))
2528 if (BI->isConditional())
2529 return dyn_cast<Instruction>(BI->getCondition());
2530 // TODO: Extend this to handle switches
2531 return nullptr;
2532 };
2533 for (BasicBlock &BB : F) {
2534 TerminatorInst *TI = BB.getTerminator();
2535 if (auto *Cond = getConditionInst(TI))
2536 // TODO: Handle more than just ICmps here. We should be able to move
2537 // most instructions without side effects or memory access.
2538 if (isa<ICmpInst>(Cond) && Cond->hasOneUse()) {
2539 MadeChange = true;
2540 Cond->moveBefore(TI);
2541 }
2542 }
2543
Justin Bogner843fb202015-12-15 19:40:57 +00002544 MadeChange |= insertParsePoints(F, DT, TTI, ParsePointNeeded);
Philip Reames85b36a82015-04-10 22:07:04 +00002545 return MadeChange;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002546}
Philip Reamesdf1ef082015-04-10 22:53:14 +00002547
2548// liveness computation via standard dataflow
2549// -------------------------------------------------------------------
2550
2551// TODO: Consider using bitvectors for liveness, the set of potentially
2552// interesting values should be small and easy to pre-compute.
2553
Philip Reamesdf1ef082015-04-10 22:53:14 +00002554/// Compute the live-in set for the location rbegin starting from
2555/// the live-out set of the basic block
Sanjoy Das61c76e32016-06-26 04:55:32 +00002556static void computeLiveInValues(BasicBlock::reverse_iterator Begin,
2557 BasicBlock::reverse_iterator End,
Igor Laevskyfb1811d2016-05-04 14:55:36 +00002558 SetVector<Value *> &LiveTmp) {
Sanjoy Das61c76e32016-06-26 04:55:32 +00002559 for (auto &I : make_range(Begin, End)) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00002560 // KILL/Def - Remove this definition from LiveIn
Sanjoy Das61c76e32016-06-26 04:55:32 +00002561 LiveTmp.remove(&I);
Philip Reamesdf1ef082015-04-10 22:53:14 +00002562
2563 // Don't consider *uses* in PHI nodes, we handle their contribution to
2564 // predecessor blocks when we seed the LiveOut sets
2565 if (isa<PHINode>(I))
2566 continue;
2567
2568 // USE - Add to the LiveIn set for this instruction
Sanjoy Das61c76e32016-06-26 04:55:32 +00002569 for (Value *V : I.operands()) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00002570 assert(!isUnhandledGCPointerType(V->getType()) &&
2571 "support for FCA unimplemented");
Philip Reames63294cb2015-04-26 19:48:03 +00002572 if (isHandledGCPointerType(V->getType()) && !isa<Constant>(V)) {
2573 // The choice to exclude all things constant here is slightly subtle.
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002574 // There are two independent reasons:
Philip Reames63294cb2015-04-26 19:48:03 +00002575 // - We assume that things which are constant (from LLVM's definition)
2576 // do not move at runtime. For example, the address of a global
2577 // variable is fixed, even though it's contents may not be.
2578 // - Second, we can't disallow arbitrary inttoptr constants even
2579 // if the language frontend does. Optimization passes are free to
2580 // locally exploit facts without respect to global reachability. This
2581 // can create sections of code which are dynamically unreachable and
2582 // contain just about anything. (see constants.ll in tests)
Philip Reamesdf1ef082015-04-10 22:53:14 +00002583 LiveTmp.insert(V);
2584 }
2585 }
2586 }
2587}
2588
Igor Laevskyfb1811d2016-05-04 14:55:36 +00002589static void computeLiveOutSeed(BasicBlock *BB, SetVector<Value *> &LiveTmp) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00002590 for (BasicBlock *Succ : successors(BB)) {
Sanjoy Das83186b02016-06-26 04:55:30 +00002591 for (auto &I : *Succ) {
2592 PHINode *PN = dyn_cast<PHINode>(&I);
2593 if (!PN)
2594 break;
2595
2596 Value *V = PN->getIncomingValueForBlock(BB);
Philip Reamesdf1ef082015-04-10 22:53:14 +00002597 assert(!isUnhandledGCPointerType(V->getType()) &&
2598 "support for FCA unimplemented");
Sanjoy Das83186b02016-06-26 04:55:30 +00002599 if (isHandledGCPointerType(V->getType()) && !isa<Constant>(V))
Philip Reamesdf1ef082015-04-10 22:53:14 +00002600 LiveTmp.insert(V);
Philip Reamesdf1ef082015-04-10 22:53:14 +00002601 }
2602 }
2603}
2604
Igor Laevskyfb1811d2016-05-04 14:55:36 +00002605static SetVector<Value *> computeKillSet(BasicBlock *BB) {
2606 SetVector<Value *> KillSet;
Philip Reamesdf1ef082015-04-10 22:53:14 +00002607 for (Instruction &I : *BB)
2608 if (isHandledGCPointerType(I.getType()))
2609 KillSet.insert(&I);
2610 return KillSet;
2611}
2612
Philip Reames9638ff92015-04-11 00:06:47 +00002613#ifndef NDEBUG
Philip Reamesdf1ef082015-04-10 22:53:14 +00002614/// Check that the items in 'Live' dominate 'TI'. This is used as a basic
2615/// sanity check for the liveness computation.
Igor Laevskyfb1811d2016-05-04 14:55:36 +00002616static void checkBasicSSA(DominatorTree &DT, SetVector<Value *> &Live,
Philip Reamesdf1ef082015-04-10 22:53:14 +00002617 TerminatorInst *TI, bool TermOkay = false) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00002618 for (Value *V : Live) {
2619 if (auto *I = dyn_cast<Instruction>(V)) {
2620 // The terminator can be a member of the LiveOut set. LLVM's definition
2621 // of instruction dominance states that V does not dominate itself. As
2622 // such, we need to special case this to allow it.
2623 if (TermOkay && TI == I)
2624 continue;
2625 assert(DT.dominates(I, TI) &&
2626 "basic SSA liveness expectation violated by liveness analysis");
2627 }
2628 }
Philip Reamesdf1ef082015-04-10 22:53:14 +00002629}
2630
2631/// Check that all the liveness sets used during the computation of liveness
2632/// obey basic SSA properties. This is useful for finding cases where we miss
2633/// a def.
2634static void checkBasicSSA(DominatorTree &DT, GCPtrLivenessData &Data,
2635 BasicBlock &BB) {
2636 checkBasicSSA(DT, Data.LiveSet[&BB], BB.getTerminator());
2637 checkBasicSSA(DT, Data.LiveOut[&BB], BB.getTerminator(), true);
2638 checkBasicSSA(DT, Data.LiveIn[&BB], BB.getTerminator());
2639}
Philip Reames9638ff92015-04-11 00:06:47 +00002640#endif
Philip Reamesdf1ef082015-04-10 22:53:14 +00002641
2642static void computeLiveInValues(DominatorTree &DT, Function &F,
2643 GCPtrLivenessData &Data) {
Matthias Braunb30f2f512016-01-30 01:24:31 +00002644 SmallSetVector<BasicBlock *, 32> Worklist;
Philip Reamesdf1ef082015-04-10 22:53:14 +00002645
2646 // Seed the liveness for each individual block
2647 for (BasicBlock &BB : F) {
2648 Data.KillSet[&BB] = computeKillSet(&BB);
2649 Data.LiveSet[&BB].clear();
2650 computeLiveInValues(BB.rbegin(), BB.rend(), Data.LiveSet[&BB]);
2651
2652#ifndef NDEBUG
2653 for (Value *Kill : Data.KillSet[&BB])
2654 assert(!Data.LiveSet[&BB].count(Kill) && "live set contains kill");
2655#endif
2656
Igor Laevskyfb1811d2016-05-04 14:55:36 +00002657 Data.LiveOut[&BB] = SetVector<Value *>();
Philip Reamesdf1ef082015-04-10 22:53:14 +00002658 computeLiveOutSeed(&BB, Data.LiveOut[&BB]);
2659 Data.LiveIn[&BB] = Data.LiveSet[&BB];
Igor Laevskyfb1811d2016-05-04 14:55:36 +00002660 Data.LiveIn[&BB].set_union(Data.LiveOut[&BB]);
2661 Data.LiveIn[&BB].set_subtract(Data.KillSet[&BB]);
Philip Reamesdf1ef082015-04-10 22:53:14 +00002662 if (!Data.LiveIn[&BB].empty())
Sanjoy Dasb2df57a2016-06-26 04:55:26 +00002663 Worklist.insert(pred_begin(&BB), pred_end(&BB));
Philip Reamesdf1ef082015-04-10 22:53:14 +00002664 }
2665
2666 // Propagate that liveness until stable
2667 while (!Worklist.empty()) {
Sanjoy Dasb2df57a2016-06-26 04:55:26 +00002668 BasicBlock *BB = Worklist.pop_back_val();
Philip Reamesdf1ef082015-04-10 22:53:14 +00002669
Sanjoy Dasb2df57a2016-06-26 04:55:26 +00002670 // Compute our new liveout set, then exit early if it hasn't changed despite
2671 // the contribution of our successor.
Igor Laevskyfb1811d2016-05-04 14:55:36 +00002672 SetVector<Value *> LiveOut = Data.LiveOut[BB];
Philip Reamesdf1ef082015-04-10 22:53:14 +00002673 const auto OldLiveOutSize = LiveOut.size();
2674 for (BasicBlock *Succ : successors(BB)) {
2675 assert(Data.LiveIn.count(Succ));
Igor Laevskyfb1811d2016-05-04 14:55:36 +00002676 LiveOut.set_union(Data.LiveIn[Succ]);
Philip Reamesdf1ef082015-04-10 22:53:14 +00002677 }
2678 // assert OutLiveOut is a subset of LiveOut
2679 if (OldLiveOutSize == LiveOut.size()) {
2680 // If the sets are the same size, then we didn't actually add anything
Sanjoy Dasb2df57a2016-06-26 04:55:26 +00002681 // when unioning our successors LiveIn. Thus, the LiveIn of this block
Philip Reamesdf1ef082015-04-10 22:53:14 +00002682 // hasn't changed.
2683 continue;
2684 }
2685 Data.LiveOut[BB] = LiveOut;
2686
2687 // Apply the effects of this basic block
Igor Laevskyfb1811d2016-05-04 14:55:36 +00002688 SetVector<Value *> LiveTmp = LiveOut;
2689 LiveTmp.set_union(Data.LiveSet[BB]);
2690 LiveTmp.set_subtract(Data.KillSet[BB]);
Philip Reamesdf1ef082015-04-10 22:53:14 +00002691
2692 assert(Data.LiveIn.count(BB));
Igor Laevskyfb1811d2016-05-04 14:55:36 +00002693 const SetVector<Value *> &OldLiveIn = Data.LiveIn[BB];
Philip Reamesdf1ef082015-04-10 22:53:14 +00002694 // assert: OldLiveIn is a subset of LiveTmp
2695 if (OldLiveIn.size() != LiveTmp.size()) {
2696 Data.LiveIn[BB] = LiveTmp;
Sanjoy Dasb2df57a2016-06-26 04:55:26 +00002697 Worklist.insert(pred_begin(BB), pred_end(BB));
Philip Reamesdf1ef082015-04-10 22:53:14 +00002698 }
Sanjoy Dasb2df57a2016-06-26 04:55:26 +00002699 } // while (!Worklist.empty())
Philip Reamesdf1ef082015-04-10 22:53:14 +00002700
2701#ifndef NDEBUG
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002702 // Sanity check our output against SSA properties. This helps catch any
Philip Reamesdf1ef082015-04-10 22:53:14 +00002703 // missing kills during the above iteration.
Sanjoy Dasb2df57a2016-06-26 04:55:26 +00002704 for (BasicBlock &BB : F)
Philip Reamesdf1ef082015-04-10 22:53:14 +00002705 checkBasicSSA(DT, Data, BB);
Philip Reamesdf1ef082015-04-10 22:53:14 +00002706#endif
2707}
2708
2709static void findLiveSetAtInst(Instruction *Inst, GCPtrLivenessData &Data,
2710 StatepointLiveSetTy &Out) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00002711 BasicBlock *BB = Inst->getParent();
2712
2713 // Note: The copy is intentional and required
2714 assert(Data.LiveOut.count(BB));
Igor Laevskyfb1811d2016-05-04 14:55:36 +00002715 SetVector<Value *> LiveOut = Data.LiveOut[BB];
Philip Reamesdf1ef082015-04-10 22:53:14 +00002716
2717 // We want to handle the statepoint itself oddly. It's
2718 // call result is not live (normal), nor are it's arguments
2719 // (unless they're used again later). This adjustment is
2720 // specifically what we need to relocate
Duncan P. N. Exon Smith5c001c32016-08-30 00:13:12 +00002721 computeLiveInValues(BB->rbegin(), ++Inst->getIterator().getReverse(),
2722 LiveOut);
Igor Laevskyfb1811d2016-05-04 14:55:36 +00002723 LiveOut.remove(Inst);
Philip Reamesdf1ef082015-04-10 22:53:14 +00002724 Out.insert(LiveOut.begin(), LiveOut.end());
2725}
2726
2727static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData,
Sanjoy Dasa3244872016-06-17 00:45:00 +00002728 CallSite CS,
Philip Reamesdf1ef082015-04-10 22:53:14 +00002729 PartiallyConstructedSafepointRecord &Info) {
2730 Instruction *Inst = CS.getInstruction();
2731 StatepointLiveSetTy Updated;
2732 findLiveSetAtInst(Inst, RevisedLivenessData, Updated);
2733
2734#ifndef NDEBUG
2735 DenseSet<Value *> Bases;
Sanjoy Das255532f2016-06-26 04:55:23 +00002736 for (auto KVPair : Info.PointerToBase)
Philip Reamesdf1ef082015-04-10 22:53:14 +00002737 Bases.insert(KVPair.second);
Philip Reamesdf1ef082015-04-10 22:53:14 +00002738#endif
Sanjoy Das255532f2016-06-26 04:55:23 +00002739
Philip Reamesdf1ef082015-04-10 22:53:14 +00002740 // We may have base pointers which are now live that weren't before. We need
2741 // to update the PointerToBase structure to reflect this.
2742 for (auto V : Updated)
Sanjoy Das255532f2016-06-26 04:55:23 +00002743 if (Info.PointerToBase.insert({V, V}).second) {
2744 assert(Bases.count(V) && "Can't find base for unexpected live value!");
Philip Reamesdf1ef082015-04-10 22:53:14 +00002745 continue;
2746 }
2747
2748#ifndef NDEBUG
Sanjoy Das255532f2016-06-26 04:55:23 +00002749 for (auto V : Updated)
Philip Reamesdf1ef082015-04-10 22:53:14 +00002750 assert(Info.PointerToBase.count(V) &&
Sanjoy Das255532f2016-06-26 04:55:23 +00002751 "Must be able to find base for live value!");
Philip Reamesdf1ef082015-04-10 22:53:14 +00002752#endif
2753
2754 // Remove any stale base mappings - this can happen since our liveness is
Sanjoy Das255532f2016-06-26 04:55:23 +00002755 // more precise then the one inherent in the base pointer analysis.
Philip Reamesdf1ef082015-04-10 22:53:14 +00002756 DenseSet<Value *> ToErase;
2757 for (auto KVPair : Info.PointerToBase)
2758 if (!Updated.count(KVPair.first))
2759 ToErase.insert(KVPair.first);
Sanjoy Das255532f2016-06-26 04:55:23 +00002760
2761 for (auto *V : ToErase)
Philip Reamesdf1ef082015-04-10 22:53:14 +00002762 Info.PointerToBase.erase(V);
2763
2764#ifndef NDEBUG
2765 for (auto KVPair : Info.PointerToBase)
2766 assert(Updated.count(KVPair.first) && "record for non-live value");
2767#endif
2768
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002769 Info.LiveSet = Updated;
Philip Reamesdf1ef082015-04-10 22:53:14 +00002770}