blob: 4b8ddb7cc24f0484c4fcb99c20f2e717cb2bc4b0 [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
Philip Reames8fe7f132015-06-26 22:47:37 +0000424 // A PHI or Select is a base defining value. The outer findBasePointer
425 // algorithm is responsible for constructing a base value for this BDV.
426 assert((isa<SelectInst>(I) || isa<PHINode>(I)) &&
427 "unknown vector instruction - no base found for vector element");
Philip Reamesf5b8e472015-09-03 21:34:30 +0000428 return BaseDefiningValueResult(I, false);
Philip Reames8531d8c2015-04-10 21:48:25 +0000429}
430
Philip Reamesd16a9b12015-02-20 01:06:44 +0000431/// Helper function for findBasePointer - Will return a value which either a)
Philip Reames9ac4e382015-08-12 21:00:20 +0000432/// defines the base pointer for the input, b) blocks the simple search
433/// (i.e. a PHI or Select of two derived pointers), or c) involves a change
434/// from pointer to vector type or back.
Philip Reamesf5b8e472015-09-03 21:34:30 +0000435static BaseDefiningValueResult findBaseDefiningValue(Value *I) {
Manuel Jacob0593cfd2016-01-09 03:08:49 +0000436 assert(I->getType()->isPtrOrPtrVectorTy() &&
437 "Illegal to ask for the base pointer of a non-pointer type");
438
Philip Reames8fe7f132015-06-26 22:47:37 +0000439 if (I->getType()->isVectorTy())
Philip Reamesf5b8e472015-09-03 21:34:30 +0000440 return findBaseDefiningValueOfVector(I);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000441
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000442 if (isa<Argument>(I))
Philip Reamesd16a9b12015-02-20 01:06:44 +0000443 // An incoming argument to the function is a base pointer
444 // We should have never reached here if this argument isn't an gc value
Philip Reamesf5b8e472015-09-03 21:34:30 +0000445 return BaseDefiningValueResult(I, true);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000446
Igor Laevskydf9db452016-05-27 13:13:59 +0000447 if (isa<Constant>(I)) {
Manuel Jacob75cbfdc2016-01-05 04:06:21 +0000448 // We assume that objects with a constant base (e.g. a global) can't move
449 // and don't need to be reported to the collector because they are always
Igor Laevskydf9db452016-05-27 13:13:59 +0000450 // live. Besides global references, all kinds of constants (e.g. undef,
451 // constant expressions, null pointers) can be introduced by the inliner or
452 // the optimizer, especially on dynamically dead paths.
453 // Here we treat all of them as having single null base. By doing this we
454 // trying to avoid problems reporting various conflicts in a form of
455 // "phi (const1, const2)" or "phi (const, regular gc ptr)".
456 // See constant.ll file for relevant test cases.
457
458 return BaseDefiningValueResult(
459 ConstantPointerNull::get(cast<PointerType>(I->getType())), true);
460 }
Philip Reamesd16a9b12015-02-20 01:06:44 +0000461
Philip Reamesd16a9b12015-02-20 01:06:44 +0000462 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000463 Value *Def = CI->stripPointerCasts();
Manuel Jacob8050a492015-12-21 01:26:46 +0000464 // If stripping pointer casts changes the address space there is an
465 // addrspacecast in between.
466 assert(cast<PointerType>(Def->getType())->getAddressSpace() ==
467 cast<PointerType>(CI->getType())->getAddressSpace() &&
468 "unsupported addrspacecast");
David Blaikie82ad7872015-02-20 23:44:24 +0000469 // If we find a cast instruction here, it means we've found a cast which is
470 // not simply a pointer cast (i.e. an inttoptr). We don't know how to
471 // handle int->ptr conversion.
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000472 assert(!isa<CastInst>(Def) && "shouldn't find another cast here");
473 return findBaseDefiningValue(Def);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000474 }
475
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000476 if (isa<LoadInst>(I))
Philip Reamesf5b8e472015-09-03 21:34:30 +0000477 // The value loaded is an gc base itself
478 return BaseDefiningValueResult(I, true);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000479
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000480 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I))
481 // The base of this GEP is the base
482 return findBaseDefiningValue(GEP->getPointerOperand());
Philip Reamesd16a9b12015-02-20 01:06:44 +0000483
484 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
485 switch (II->getIntrinsicID()) {
486 default:
487 // fall through to general call handling
488 break;
489 case Intrinsic::experimental_gc_statepoint:
Manuel Jacob4e4f60d2015-12-22 18:44:45 +0000490 llvm_unreachable("statepoints don't produce pointers");
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000491 case Intrinsic::experimental_gc_relocate:
Philip Reamesd16a9b12015-02-20 01:06:44 +0000492 // Rerunning safepoint insertion after safepoints are already
493 // inserted is not supported. It could probably be made to work,
494 // but why are you doing this? There's no good reason.
495 llvm_unreachable("repeat safepoint insertion is not supported");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000496 case Intrinsic::gcroot:
497 // Currently, this mechanism hasn't been extended to work with gcroot.
498 // There's no reason it couldn't be, but I haven't thought about the
499 // implications much.
500 llvm_unreachable(
501 "interaction with the gcroot mechanism is not supported");
502 }
503 }
504 // We assume that functions in the source language only return base
505 // pointers. This should probably be generalized via attributes to support
506 // both source language and internal functions.
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000507 if (isa<CallInst>(I) || isa<InvokeInst>(I))
Philip Reamesf5b8e472015-09-03 21:34:30 +0000508 return BaseDefiningValueResult(I, true);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000509
Anna Thomas488c0572016-10-06 13:24:20 +0000510 // TODO: I have absolutely no idea how to implement this part yet. It's not
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000511 // necessarily hard, I just haven't really looked at it yet.
Philip Reamesd16a9b12015-02-20 01:06:44 +0000512 assert(!isa<LandingPadInst>(I) && "Landing Pad is unimplemented");
513
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000514 if (isa<AtomicCmpXchgInst>(I))
Philip Reamesd16a9b12015-02-20 01:06:44 +0000515 // A CAS is effectively a atomic store and load combined under a
516 // predicate. From the perspective of base pointers, we just treat it
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000517 // like a load.
Philip Reamesf5b8e472015-09-03 21:34:30 +0000518 return BaseDefiningValueResult(I, true);
Philip Reames704e78b2015-04-10 22:34:56 +0000519
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000520 assert(!isa<AtomicRMWInst>(I) && "Xchg handled above, all others are "
Philip Reames704e78b2015-04-10 22:34:56 +0000521 "binary ops which don't apply to pointers");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000522
523 // The aggregate ops. Aggregates can either be in the heap or on the
524 // stack, but in either case, this is simply a field load. As a result,
525 // this is a defining definition of the base just like a load is.
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000526 if (isa<ExtractValueInst>(I))
Philip Reamesf5b8e472015-09-03 21:34:30 +0000527 return BaseDefiningValueResult(I, true);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000528
529 // We should never see an insert vector since that would require we be
530 // tracing back a struct value not a pointer value.
531 assert(!isa<InsertValueInst>(I) &&
532 "Base pointer for a struct is meaningless");
533
Philip Reames9ac4e382015-08-12 21:00:20 +0000534 // An extractelement produces a base result exactly when it's input does.
535 // We may need to insert a parallel instruction to extract the appropriate
536 // element out of the base vector corresponding to the input. Given this,
537 // it's analogous to the phi and select case even though it's not a merge.
Philip Reames66287132015-09-09 23:40:12 +0000538 if (isa<ExtractElementInst>(I))
539 // Note: There a lot of obvious peephole cases here. This are deliberately
540 // handled after the main base pointer inference algorithm to make writing
541 // test cases to exercise that code easier.
542 return BaseDefiningValueResult(I, false);
Philip Reames9ac4e382015-08-12 21:00:20 +0000543
Philip Reamesd16a9b12015-02-20 01:06:44 +0000544 // The last two cases here don't return a base pointer. Instead, they
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000545 // return a value which dynamically selects from among several base
Philip Reamesd16a9b12015-02-20 01:06:44 +0000546 // derived pointers (each with it's own base potentially). It's the job of
547 // the caller to resolve these.
Philip Reames704e78b2015-04-10 22:34:56 +0000548 assert((isa<SelectInst>(I) || isa<PHINode>(I)) &&
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000549 "missing instruction case in findBaseDefiningValing");
Philip Reamesf5b8e472015-09-03 21:34:30 +0000550 return BaseDefiningValueResult(I, false);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000551}
552
553/// Returns the base defining value for this value.
Philip Reames18d0feb2015-03-27 05:39:32 +0000554static Value *findBaseDefiningValueCached(Value *I, DefiningValueMapTy &Cache) {
555 Value *&Cached = Cache[I];
Benjamin Kramer6f665452015-02-20 14:00:58 +0000556 if (!Cached) {
Philip Reamesf5b8e472015-09-03 21:34:30 +0000557 Cached = findBaseDefiningValue(I).BDV;
Philip Reames2a892a62015-07-23 22:25:26 +0000558 DEBUG(dbgs() << "fBDV-cached: " << I->getName() << " -> "
559 << Cached->getName() << "\n");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000560 }
Philip Reames18d0feb2015-03-27 05:39:32 +0000561 assert(Cache[I] != nullptr);
Benjamin Kramer6f665452015-02-20 14:00:58 +0000562 return Cached;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000563}
564
565/// Return a base pointer for this value if known. Otherwise, return it's
566/// base defining value.
Philip Reames18d0feb2015-03-27 05:39:32 +0000567static Value *findBaseOrBDV(Value *I, DefiningValueMapTy &Cache) {
568 Value *Def = findBaseDefiningValueCached(I, Cache);
569 auto Found = Cache.find(Def);
570 if (Found != Cache.end()) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000571 // Either a base-of relation, or a self reference. Caller must check.
Benjamin Kramer6f665452015-02-20 14:00:58 +0000572 return Found->second;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000573 }
574 // Only a BDV available
Philip Reames18d0feb2015-03-27 05:39:32 +0000575 return Def;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000576}
577
578/// Given the result of a call to findBaseDefiningValue, or findBaseOrBDV,
579/// is it known to be a base pointer? Or do we need to continue searching.
Philip Reames18d0feb2015-03-27 05:39:32 +0000580static bool isKnownBaseResult(Value *V) {
Philip Reames66287132015-09-09 23:40:12 +0000581 if (!isa<PHINode>(V) && !isa<SelectInst>(V) &&
582 !isa<ExtractElementInst>(V) && !isa<InsertElementInst>(V) &&
583 !isa<ShuffleVectorInst>(V)) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000584 // no recursion possible
585 return true;
586 }
Philip Reames18d0feb2015-03-27 05:39:32 +0000587 if (isa<Instruction>(V) &&
588 cast<Instruction>(V)->getMetadata("is_base_value")) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000589 // This is a previously inserted base phi or select. We know
590 // that this is a base value.
591 return true;
592 }
593
594 // We need to keep searching
595 return false;
596}
597
Philip Reamesd16a9b12015-02-20 01:06:44 +0000598namespace {
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000599
Philip Reames9b141ed2015-07-23 22:49:14 +0000600/// Models the state of a single base defining value in the findBasePointer
601/// algorithm for determining where a new instruction is needed to propagate
602/// the base of this BDV.
603class BDVState {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000604public:
605 enum Status { Unknown, Base, Conflict };
606
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000607 BDVState() : BaseValue(nullptr) {}
Philip Reamesd16a9b12015-02-20 01:06:44 +0000608
Sanjoy Das7dda0ed2016-06-26 04:55:35 +0000609 explicit BDVState(Status Status, Value *BaseValue = nullptr)
610 : Status(Status), BaseValue(BaseValue) {
611 assert(Status != Base || BaseValue);
612 }
613
614 explicit BDVState(Value *BaseValue) : Status(Base), BaseValue(BaseValue) {}
615
616 Status getStatus() const { return Status; }
617 Value *getBaseValue() const { return BaseValue; }
Philip Reamesd16a9b12015-02-20 01:06:44 +0000618
619 bool isBase() const { return getStatus() == Base; }
620 bool isUnknown() const { return getStatus() == Unknown; }
621 bool isConflict() const { return getStatus() == Conflict; }
622
Sanjoy Das7dda0ed2016-06-26 04:55:35 +0000623 bool operator==(const BDVState &Other) const {
624 return BaseValue == Other.BaseValue && Status == Other.Status;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000625 }
626
Philip Reames9b141ed2015-07-23 22:49:14 +0000627 bool operator!=(const BDVState &other) const { return !(*this == other); }
Philip Reamesd16a9b12015-02-20 01:06:44 +0000628
Philip Reames2a892a62015-07-23 22:25:26 +0000629 LLVM_DUMP_METHOD
Sanjoy Das7dda0ed2016-06-26 04:55:35 +0000630 void dump() const {
631 print(dbgs());
632 dbgs() << '\n';
633 }
634
Philip Reames2a892a62015-07-23 22:25:26 +0000635 void print(raw_ostream &OS) const {
Sanjoy Das7dda0ed2016-06-26 04:55:35 +0000636 switch (getStatus()) {
Philip Reamesdab35f32015-09-02 21:11:44 +0000637 case Unknown:
638 OS << "U";
639 break;
640 case Base:
641 OS << "B";
642 break;
643 case Conflict:
644 OS << "C";
645 break;
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000646 }
Sanjoy Das7dda0ed2016-06-26 04:55:35 +0000647 OS << " (" << getBaseValue() << " - "
648 << (getBaseValue() ? getBaseValue()->getName() : "nullptr") << "): ";
Philip Reamesd16a9b12015-02-20 01:06:44 +0000649 }
650
651private:
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000652 Status Status = Unknown;
Sanjoy Das7dda0ed2016-06-26 04:55:35 +0000653 AssertingVH<Value> BaseValue; // Non-null only if Status == Base.
Philip Reamesd16a9b12015-02-20 01:06:44 +0000654};
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000655
656} // end anonymous namespace
Philip Reamesd16a9b12015-02-20 01:06:44 +0000657
Philip Reames6906e922015-09-02 21:57:17 +0000658#ifndef NDEBUG
Philip Reamesb3967cd2015-09-02 22:30:53 +0000659static raw_ostream &operator<<(raw_ostream &OS, const BDVState &State) {
Philip Reames2a892a62015-07-23 22:25:26 +0000660 State.print(OS);
661 return OS;
662}
Philip Reames6906e922015-09-02 21:57:17 +0000663#endif
Philip Reames2a892a62015-07-23 22:25:26 +0000664
Sanjoy Das6cf88092016-06-26 04:55:13 +0000665static BDVState meetBDVStateImpl(const BDVState &LHS, const BDVState &RHS) {
666 switch (LHS.getStatus()) {
Sanjoy Dasbd43d0e2016-06-26 04:55:10 +0000667 case BDVState::Unknown:
Sanjoy Das6cf88092016-06-26 04:55:13 +0000668 return RHS;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000669
Sanjoy Dasbd43d0e2016-06-26 04:55:10 +0000670 case BDVState::Base:
Sanjoy Das7dda0ed2016-06-26 04:55:35 +0000671 assert(LHS.getBaseValue() && "can't be null");
Sanjoy Das6cf88092016-06-26 04:55:13 +0000672 if (RHS.isUnknown())
673 return LHS;
Sanjoy Dasbd43d0e2016-06-26 04:55:10 +0000674
Sanjoy Das6cf88092016-06-26 04:55:13 +0000675 if (RHS.isBase()) {
Sanjoy Das7dda0ed2016-06-26 04:55:35 +0000676 if (LHS.getBaseValue() == RHS.getBaseValue()) {
Sanjoy Das6cf88092016-06-26 04:55:13 +0000677 assert(LHS == RHS && "equality broken!");
678 return LHS;
Sanjoy Dasbd43d0e2016-06-26 04:55:10 +0000679 }
680 return BDVState(BDVState::Conflict);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000681 }
Sanjoy Das6cf88092016-06-26 04:55:13 +0000682 assert(RHS.isConflict() && "only three states!");
Sanjoy Dasbd43d0e2016-06-26 04:55:10 +0000683 return BDVState(BDVState::Conflict);
684
685 case BDVState::Conflict:
Sanjoy Das6cf88092016-06-26 04:55:13 +0000686 return LHS;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000687 }
Sanjoy Dasbd43d0e2016-06-26 04:55:10 +0000688 llvm_unreachable("only three states!");
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000689}
Philip Reamesb3967cd2015-09-02 22:30:53 +0000690
Sanjoy Dasbd43d0e2016-06-26 04:55:10 +0000691// Values of type BDVState form a lattice, and this function implements the meet
692// operation.
Benjamin Kramer061f4a52017-01-13 14:39:03 +0000693static BDVState meetBDVState(const BDVState &LHS, const BDVState &RHS) {
Sanjoy Dasbd43d0e2016-06-26 04:55:10 +0000694 BDVState Result = meetBDVStateImpl(LHS, RHS);
695 assert(Result == meetBDVStateImpl(RHS, LHS) &&
696 "Math is wrong: meet does not commute!");
697 return Result;
698}
Philip Reamesb3967cd2015-09-02 22:30:53 +0000699
Sanjoy Das90547f12016-06-26 04:55:05 +0000700/// For a given value or instruction, figure out what base ptr its derived from.
701/// For gc objects, this is simply itself. On success, returns a value which is
702/// the base pointer. (This is reliable and can be used for relocation.) On
703/// failure, returns nullptr.
704static Value *findBasePointer(Value *I, DefiningValueMapTy &Cache) {
705 Value *Def = findBaseOrBDV(I, Cache);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000706
Sanjoy Das90547f12016-06-26 04:55:05 +0000707 if (isKnownBaseResult(Def))
708 return Def;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000709
710 // Here's the rough algorithm:
711 // - For every SSA value, construct a mapping to either an actual base
712 // pointer or a PHI which obscures the base pointer.
713 // - Construct a mapping from PHI to unknown TOP state. Use an
714 // optimistic algorithm to propagate base pointer information. Lattice
715 // looks like:
716 // UNKNOWN
717 // b1 b2 b3 b4
718 // CONFLICT
719 // When algorithm terminates, all PHIs will either have a single concrete
720 // base or be in a conflict state.
721 // - For every conflict, insert a dummy PHI node without arguments. Add
722 // these to the base[Instruction] = BasePtr mapping. For every
723 // non-conflict, add the actual base.
724 // - For every conflict, add arguments for the base[a] of each input
725 // arguments.
726 //
727 // Note: A simpler form of this would be to add the conflict form of all
728 // PHIs without running the optimistic algorithm. This would be
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000729 // analogous to pessimistic data flow and would likely lead to an
Philip Reamesd16a9b12015-02-20 01:06:44 +0000730 // overall worse solution.
731
Philip Reames29e9ae72015-07-24 00:42:55 +0000732#ifndef NDEBUG
Philip Reames88958b22015-07-24 00:02:11 +0000733 auto isExpectedBDVType = [](Value *BDV) {
Philip Reames66287132015-09-09 23:40:12 +0000734 return isa<PHINode>(BDV) || isa<SelectInst>(BDV) ||
Anna Thomas479cbb92016-10-04 13:48:37 +0000735 isa<ExtractElementInst>(BDV) || isa<InsertElementInst>(BDV) ||
736 isa<ShuffleVectorInst>(BDV);
Philip Reames88958b22015-07-24 00:02:11 +0000737 };
Philip Reames29e9ae72015-07-24 00:42:55 +0000738#endif
Philip Reames88958b22015-07-24 00:02:11 +0000739
740 // Once populated, will contain a mapping from each potentially non-base BDV
741 // to a lattice value (described above) which corresponds to that BDV.
Philip Reames15d55632015-09-09 23:26:08 +0000742 // We use the order of insertion (DFS over the def/use graph) to provide a
743 // stable deterministic ordering for visiting DenseMaps (which are unordered)
744 // below. This is important for deterministic compilation.
Philip Reames34d7a742015-09-10 00:22:49 +0000745 MapVector<Value *, BDVState> States;
Philip Reames15d55632015-09-09 23:26:08 +0000746
747 // Recursively fill in all base defining values reachable from the initial
748 // one for which we don't already know a definite base value for
Philip Reames88958b22015-07-24 00:02:11 +0000749 /* scope */ {
Philip Reames88958b22015-07-24 00:02:11 +0000750 SmallVector<Value*, 16> Worklist;
Sanjoy Das90547f12016-06-26 04:55:05 +0000751 Worklist.push_back(Def);
752 States.insert({Def, BDVState()});
Philip Reames88958b22015-07-24 00:02:11 +0000753 while (!Worklist.empty()) {
754 Value *Current = Worklist.pop_back_val();
755 assert(!isKnownBaseResult(Current) && "why did it get added?");
756
757 auto visitIncomingValue = [&](Value *InVal) {
Sanjoy Das90547f12016-06-26 04:55:05 +0000758 Value *Base = findBaseOrBDV(InVal, Cache);
Philip Reames88958b22015-07-24 00:02:11 +0000759 if (isKnownBaseResult(Base))
760 // Known bases won't need new instructions introduced and can be
761 // ignored safely
762 return;
763 assert(isExpectedBDVType(Base) && "the only non-base values "
764 "we see should be base defining values");
Philip Reames34d7a742015-09-10 00:22:49 +0000765 if (States.insert(std::make_pair(Base, BDVState())).second)
Philip Reames88958b22015-07-24 00:02:11 +0000766 Worklist.push_back(Base);
767 };
Sanjoy Das90547f12016-06-26 04:55:05 +0000768 if (PHINode *PN = dyn_cast<PHINode>(Current)) {
769 for (Value *InVal : PN->incoming_values())
Philip Reames88958b22015-07-24 00:02:11 +0000770 visitIncomingValue(InVal);
Sanjoy Das90547f12016-06-26 04:55:05 +0000771 } else if (SelectInst *SI = dyn_cast<SelectInst>(Current)) {
772 visitIncomingValue(SI->getTrueValue());
773 visitIncomingValue(SI->getFalseValue());
Philip Reames9ac4e382015-08-12 21:00:20 +0000774 } else if (auto *EE = dyn_cast<ExtractElementInst>(Current)) {
775 visitIncomingValue(EE->getVectorOperand());
Philip Reames66287132015-09-09 23:40:12 +0000776 } else if (auto *IE = dyn_cast<InsertElementInst>(Current)) {
777 visitIncomingValue(IE->getOperand(0)); // vector operand
778 visitIncomingValue(IE->getOperand(1)); // scalar operand
Anna Thomas479cbb92016-10-04 13:48:37 +0000779 } else if (auto *SV = dyn_cast<ShuffleVectorInst>(Current)) {
780 visitIncomingValue(SV->getOperand(0));
781 visitIncomingValue(SV->getOperand(1));
782 }
783 else {
Sanjoy Das90547f12016-06-26 04:55:05 +0000784 llvm_unreachable("Unimplemented instruction case");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000785 }
786 }
787 }
788
Philip Reamesdab35f32015-09-02 21:11:44 +0000789#ifndef NDEBUG
790 DEBUG(dbgs() << "States after initialization:\n");
Sanjoy Das9d086422016-06-26 05:42:52 +0000791 for (auto Pair : States) {
Philip Reamesdab35f32015-09-02 21:11:44 +0000792 DEBUG(dbgs() << " " << Pair.second << " for " << *Pair.first << "\n");
Sanjoy Das9d086422016-06-26 05:42:52 +0000793 }
Philip Reamesdab35f32015-09-02 21:11:44 +0000794#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +0000795
Philip Reames273e6bb2015-07-23 21:41:27 +0000796 // Return a phi state for a base defining value. We'll generate a new
797 // base state for known bases and expect to find a cached state otherwise.
798 auto getStateForBDV = [&](Value *baseValue) {
799 if (isKnownBaseResult(baseValue))
Philip Reames9b141ed2015-07-23 22:49:14 +0000800 return BDVState(baseValue);
Philip Reames34d7a742015-09-10 00:22:49 +0000801 auto I = States.find(baseValue);
802 assert(I != States.end() && "lookup failed!");
Philip Reames273e6bb2015-07-23 21:41:27 +0000803 return I->second;
804 };
805
Sanjoy Das90547f12016-06-26 04:55:05 +0000806 bool Progress = true;
807 while (Progress) {
Yaron Keren42a7adf2015-02-28 13:11:24 +0000808#ifndef NDEBUG
Sanjoy Das90547f12016-06-26 04:55:05 +0000809 const size_t OldSize = States.size();
Yaron Keren42a7adf2015-02-28 13:11:24 +0000810#endif
Sanjoy Das90547f12016-06-26 04:55:05 +0000811 Progress = false;
Philip Reames15d55632015-09-09 23:26:08 +0000812 // We're only changing values in this loop, thus safe to keep iterators.
813 // Since this is computing a fixed point, the order of visit does not
814 // effect the result. TODO: We could use a worklist here and make this run
815 // much faster.
Philip Reames34d7a742015-09-10 00:22:49 +0000816 for (auto Pair : States) {
Philip Reamesece70b82015-09-09 23:57:18 +0000817 Value *BDV = Pair.first;
818 assert(!isKnownBaseResult(BDV) && "why did it get added?");
Philip Reames273e6bb2015-07-23 21:41:27 +0000819
Philip Reames9b141ed2015-07-23 22:49:14 +0000820 // Given an input value for the current instruction, return a BDVState
Philip Reames273e6bb2015-07-23 21:41:27 +0000821 // instance which represents the BDV of that value.
822 auto getStateForInput = [&](Value *V) mutable {
Sanjoy Das90547f12016-06-26 04:55:05 +0000823 Value *BDV = findBaseOrBDV(V, Cache);
Philip Reames273e6bb2015-07-23 21:41:27 +0000824 return getStateForBDV(BDV);
825 };
826
Sanjoy Dasbd43d0e2016-06-26 04:55:10 +0000827 BDVState NewState;
Sanjoy Das90547f12016-06-26 04:55:05 +0000828 if (SelectInst *SI = dyn_cast<SelectInst>(BDV)) {
Sanjoy Dasbd43d0e2016-06-26 04:55:10 +0000829 NewState = meetBDVState(NewState, getStateForInput(SI->getTrueValue()));
830 NewState =
831 meetBDVState(NewState, getStateForInput(SI->getFalseValue()));
Sanjoy Das90547f12016-06-26 04:55:05 +0000832 } else if (PHINode *PN = dyn_cast<PHINode>(BDV)) {
833 for (Value *Val : PN->incoming_values())
Sanjoy Dasbd43d0e2016-06-26 04:55:10 +0000834 NewState = meetBDVState(NewState, getStateForInput(Val));
Philip Reamesece70b82015-09-09 23:57:18 +0000835 } else if (auto *EE = dyn_cast<ExtractElementInst>(BDV)) {
Philip Reames9ac4e382015-08-12 21:00:20 +0000836 // The 'meet' for an extractelement is slightly trivial, but it's still
837 // useful in that it drives us to conflict if our input is.
Sanjoy Dasbd43d0e2016-06-26 04:55:10 +0000838 NewState =
839 meetBDVState(NewState, getStateForInput(EE->getVectorOperand()));
Anna Thomas479cbb92016-10-04 13:48:37 +0000840 } else if (auto *IE = dyn_cast<InsertElementInst>(BDV)){
Philip Reames66287132015-09-09 23:40:12 +0000841 // Given there's a inherent type mismatch between the operands, will
842 // *always* produce Conflict.
Sanjoy Dasbd43d0e2016-06-26 04:55:10 +0000843 NewState = meetBDVState(NewState, getStateForInput(IE->getOperand(0)));
844 NewState = meetBDVState(NewState, getStateForInput(IE->getOperand(1)));
Anna Thomas479cbb92016-10-04 13:48:37 +0000845 } else {
846 // The only instance this does not return a Conflict is when both the
847 // vector operands are the same vector.
848 auto *SV = cast<ShuffleVectorInst>(BDV);
849 NewState = meetBDVState(NewState, getStateForInput(SV->getOperand(0)));
850 NewState = meetBDVState(NewState, getStateForInput(SV->getOperand(1)));
Philip Reames9ac4e382015-08-12 21:00:20 +0000851 }
852
Sanjoy Das90547f12016-06-26 04:55:05 +0000853 BDVState OldState = States[BDV];
Sanjoy Das90547f12016-06-26 04:55:05 +0000854 if (OldState != NewState) {
855 Progress = true;
856 States[BDV] = NewState;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000857 }
858 }
859
Sanjoy Das90547f12016-06-26 04:55:05 +0000860 assert(OldSize == States.size() &&
Philip Reamesb4e55f32015-09-10 00:32:56 +0000861 "fixed point shouldn't be adding any new nodes to state");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000862 }
863
Philip Reamesdab35f32015-09-02 21:11:44 +0000864#ifndef NDEBUG
865 DEBUG(dbgs() << "States after meet iteration:\n");
Sanjoy Das9d086422016-06-26 05:42:52 +0000866 for (auto Pair : States) {
Philip Reamesdab35f32015-09-02 21:11:44 +0000867 DEBUG(dbgs() << " " << Pair.second << " for " << *Pair.first << "\n");
Sanjoy Das9d086422016-06-26 05:42:52 +0000868 }
Philip Reamesdab35f32015-09-02 21:11:44 +0000869#endif
Sanjoy Das90547f12016-06-26 04:55:05 +0000870
Philip Reamesd16a9b12015-02-20 01:06:44 +0000871 // Insert Phis for all conflicts
Philip Reames2e5bcbe2015-02-28 01:52:09 +0000872 // TODO: adjust naming patterns to avoid this order of iteration dependency
Philip Reames34d7a742015-09-10 00:22:49 +0000873 for (auto Pair : States) {
Philip Reames15d55632015-09-09 23:26:08 +0000874 Instruction *I = cast<Instruction>(Pair.first);
875 BDVState State = Pair.second;
Philip Reames6ff1a1e32015-07-21 19:04:38 +0000876 assert(!isKnownBaseResult(I) && "why did it get added?");
877 assert(!State.isUnknown() && "Optimistic algorithm didn't complete!");
Philip Reames9ac4e382015-08-12 21:00:20 +0000878
879 // extractelement instructions are a bit special in that we may need to
880 // insert an extract even when we know an exact base for the instruction.
881 // The problem is that we need to convert from a vector base to a scalar
882 // base for the particular indice we're interested in.
883 if (State.isBase() && isa<ExtractElementInst>(I) &&
Sanjoy Das7dda0ed2016-06-26 04:55:35 +0000884 isa<VectorType>(State.getBaseValue()->getType())) {
Philip Reames9ac4e382015-08-12 21:00:20 +0000885 auto *EE = cast<ExtractElementInst>(I);
886 // TODO: In many cases, the new instruction is just EE itself. We should
887 // exploit this, but can't do it here since it would break the invariant
888 // about the BDV not being known to be a base.
Sanjoy Das90547f12016-06-26 04:55:05 +0000889 auto *BaseInst = ExtractElementInst::Create(
Sanjoy Das7dda0ed2016-06-26 04:55:35 +0000890 State.getBaseValue(), EE->getIndexOperand(), "base_ee", EE);
Philip Reames9ac4e382015-08-12 21:00:20 +0000891 BaseInst->setMetadata("is_base_value", MDNode::get(I->getContext(), {}));
Philip Reames34d7a742015-09-10 00:22:49 +0000892 States[I] = BDVState(BDVState::Base, BaseInst);
Philip Reames9ac4e382015-08-12 21:00:20 +0000893 }
Philip Reames66287132015-09-09 23:40:12 +0000894
895 // Since we're joining a vector and scalar base, they can never be the
896 // same. As a result, we should always see insert element having reached
897 // the conflict state.
Sanjoy Das90547f12016-06-26 04:55:05 +0000898 assert(!isa<InsertElementInst>(I) || State.isConflict());
899
Philip Reames6ff1a1e32015-07-21 19:04:38 +0000900 if (!State.isConflict())
Philip Reamesf986d682015-02-28 00:54:41 +0000901 continue;
Philip Reames704e78b2015-04-10 22:34:56 +0000902
Philip Reames6ff1a1e32015-07-21 19:04:38 +0000903 /// Create and insert a new instruction which will represent the base of
904 /// the given instruction 'I'.
905 auto MakeBaseInstPlaceholder = [](Instruction *I) -> Instruction* {
906 if (isa<PHINode>(I)) {
907 BasicBlock *BB = I->getParent();
908 int NumPreds = std::distance(pred_begin(BB), pred_end(BB));
909 assert(NumPreds > 0 && "how did we reach here");
Philip Reamesece70b82015-09-09 23:57:18 +0000910 std::string Name = suffixed_name_or(I, ".base", "base_phi");
Philip Reamesfa2c6302015-07-24 19:01:39 +0000911 return PHINode::Create(I->getType(), NumPreds, Name, I);
Sanjoy Das90547f12016-06-26 04:55:05 +0000912 } else if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
Philip Reames9ac4e382015-08-12 21:00:20 +0000913 // The undef will be replaced later
Sanjoy Das90547f12016-06-26 04:55:05 +0000914 UndefValue *Undef = UndefValue::get(SI->getType());
Philip Reamesece70b82015-09-09 23:57:18 +0000915 std::string Name = suffixed_name_or(I, ".base", "base_select");
Sanjoy Das90547f12016-06-26 04:55:05 +0000916 return SelectInst::Create(SI->getCondition(), Undef, Undef, Name, SI);
Philip Reames66287132015-09-09 23:40:12 +0000917 } else if (auto *EE = dyn_cast<ExtractElementInst>(I)) {
Philip Reames9ac4e382015-08-12 21:00:20 +0000918 UndefValue *Undef = UndefValue::get(EE->getVectorOperand()->getType());
Philip Reamesece70b82015-09-09 23:57:18 +0000919 std::string Name = suffixed_name_or(I, ".base", "base_ee");
Philip Reames9ac4e382015-08-12 21:00:20 +0000920 return ExtractElementInst::Create(Undef, EE->getIndexOperand(), Name,
921 EE);
Anna Thomas479cbb92016-10-04 13:48:37 +0000922 } else if (auto *IE = dyn_cast<InsertElementInst>(I)) {
Philip Reames66287132015-09-09 23:40:12 +0000923 UndefValue *VecUndef = UndefValue::get(IE->getOperand(0)->getType());
924 UndefValue *ScalarUndef = UndefValue::get(IE->getOperand(1)->getType());
Philip Reamesece70b82015-09-09 23:57:18 +0000925 std::string Name = suffixed_name_or(I, ".base", "base_ie");
Philip Reames66287132015-09-09 23:40:12 +0000926 return InsertElementInst::Create(VecUndef, ScalarUndef,
927 IE->getOperand(2), Name, IE);
Anna Thomas479cbb92016-10-04 13:48:37 +0000928 } else {
929 auto *SV = cast<ShuffleVectorInst>(I);
930 UndefValue *VecUndef = UndefValue::get(SV->getOperand(0)->getType());
931 std::string Name = suffixed_name_or(I, ".base", "base_sv");
932 return new ShuffleVectorInst(VecUndef, VecUndef, SV->getOperand(2),
933 Name, SV);
Philip Reames6ff1a1e32015-07-21 19:04:38 +0000934 }
Philip Reames6ff1a1e32015-07-21 19:04:38 +0000935 };
936 Instruction *BaseInst = MakeBaseInstPlaceholder(I);
937 // Add metadata marking this as a base value
938 BaseInst->setMetadata("is_base_value", MDNode::get(I->getContext(), {}));
Philip Reames34d7a742015-09-10 00:22:49 +0000939 States[I] = BDVState(BDVState::Conflict, BaseInst);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000940 }
941
Philip Reames3ea15892015-09-03 21:57:40 +0000942 // Returns a instruction which produces the base pointer for a given
943 // instruction. The instruction is assumed to be an input to one of the BDVs
944 // seen in the inference algorithm above. As such, we must either already
945 // know it's base defining value is a base, or have inserted a new
946 // instruction to propagate the base of it's BDV and have entered that newly
947 // introduced instruction into the state table. In either case, we are
948 // assured to be able to determine an instruction which produces it's base
Sanjoy Das90547f12016-06-26 04:55:05 +0000949 // pointer.
Philip Reames3ea15892015-09-03 21:57:40 +0000950 auto getBaseForInput = [&](Value *Input, Instruction *InsertPt) {
Sanjoy Das90547f12016-06-26 04:55:05 +0000951 Value *BDV = findBaseOrBDV(Input, Cache);
Philip Reames3ea15892015-09-03 21:57:40 +0000952 Value *Base = nullptr;
953 if (isKnownBaseResult(BDV)) {
954 Base = BDV;
955 } else {
956 // Either conflict or base.
Philip Reames34d7a742015-09-10 00:22:49 +0000957 assert(States.count(BDV));
Sanjoy Das7dda0ed2016-06-26 04:55:35 +0000958 Base = States[BDV].getBaseValue();
Philip Reames3ea15892015-09-03 21:57:40 +0000959 }
Sanjoy Das90547f12016-06-26 04:55:05 +0000960 assert(Base && "Can't be null");
Philip Reames3ea15892015-09-03 21:57:40 +0000961 // The cast is needed since base traversal may strip away bitcasts
Sanjoy Das90547f12016-06-26 04:55:05 +0000962 if (Base->getType() != Input->getType() && InsertPt)
963 Base = new BitCastInst(Base, Input->getType(), "cast", InsertPt);
Philip Reames3ea15892015-09-03 21:57:40 +0000964 return Base;
965 };
966
Philip Reames15d55632015-09-09 23:26:08 +0000967 // Fixup all the inputs of the new PHIs. Visit order needs to be
968 // deterministic and predictable because we're naming newly created
969 // instructions.
Philip Reames34d7a742015-09-10 00:22:49 +0000970 for (auto Pair : States) {
Philip Reames7540e3a2015-09-10 00:01:53 +0000971 Instruction *BDV = cast<Instruction>(Pair.first);
Philip Reamesc8ded462015-09-10 00:27:50 +0000972 BDVState State = Pair.second;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000973
Philip Reames7540e3a2015-09-10 00:01:53 +0000974 assert(!isKnownBaseResult(BDV) && "why did it get added?");
Philip Reamesc8ded462015-09-10 00:27:50 +0000975 assert(!State.isUnknown() && "Optimistic algorithm didn't complete!");
976 if (!State.isConflict())
Philip Reames28e61ce2015-02-28 01:57:44 +0000977 continue;
Philip Reames704e78b2015-04-10 22:34:56 +0000978
Sanjoy Das7dda0ed2016-06-26 04:55:35 +0000979 if (PHINode *BasePHI = dyn_cast<PHINode>(State.getBaseValue())) {
Sanjoy Das90547f12016-06-26 04:55:05 +0000980 PHINode *PN = cast<PHINode>(BDV);
981 unsigned NumPHIValues = PN->getNumIncomingValues();
Philip Reames28e61ce2015-02-28 01:57:44 +0000982 for (unsigned i = 0; i < NumPHIValues; i++) {
Sanjoy Das90547f12016-06-26 04:55:05 +0000983 Value *InVal = PN->getIncomingValue(i);
984 BasicBlock *InBB = PN->getIncomingBlock(i);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000985
Philip Reames28e61ce2015-02-28 01:57:44 +0000986 // If we've already seen InBB, add the same incoming value
987 // we added for it earlier. The IR verifier requires phi
988 // nodes with multiple entries from the same basic block
989 // to have the same incoming value for each of those
990 // entries. If we don't do this check here and basephi
991 // has a different type than base, we'll end up adding two
992 // bitcasts (and hence two distinct values) as incoming
993 // values for the same basic block.
Philip Reamesd16a9b12015-02-20 01:06:44 +0000994
Sanjoy Das90547f12016-06-26 04:55:05 +0000995 int BlockIndex = BasePHI->getBasicBlockIndex(InBB);
996 if (BlockIndex != -1) {
997 Value *OldBase = BasePHI->getIncomingValue(BlockIndex);
998 BasePHI->addIncoming(OldBase, InBB);
999
Philip Reamesd16a9b12015-02-20 01:06:44 +00001000#ifndef NDEBUG
Philip Reames3ea15892015-09-03 21:57:40 +00001001 Value *Base = getBaseForInput(InVal, nullptr);
Sanjoy Das90547f12016-06-26 04:55:05 +00001002 // In essence this assert states: the only way two values
1003 // incoming from the same basic block may be different is by
1004 // being different bitcasts of the same value. A cleanup
1005 // that remains TODO is changing findBaseOrBDV to return an
1006 // llvm::Value of the correct type (and still remain pure).
1007 // This will remove the need to add bitcasts.
1008 assert(Base->stripPointerCasts() == OldBase->stripPointerCasts() &&
1009 "Sanity -- findBaseOrBDV should be pure!");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001010#endif
Philip Reames28e61ce2015-02-28 01:57:44 +00001011 continue;
1012 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00001013
Philip Reames3ea15892015-09-03 21:57:40 +00001014 // Find the instruction which produces the base for each input. We may
1015 // need to insert a bitcast in the incoming block.
1016 // TODO: Need to split critical edges if insertion is needed
1017 Value *Base = getBaseForInput(InVal, InBB->getTerminator());
Sanjoy Das90547f12016-06-26 04:55:05 +00001018 BasePHI->addIncoming(Base, InBB);
Philip Reames28e61ce2015-02-28 01:57:44 +00001019 }
Sanjoy Das90547f12016-06-26 04:55:05 +00001020 assert(BasePHI->getNumIncomingValues() == NumPHIValues);
Sanjoy Das7dda0ed2016-06-26 04:55:35 +00001021 } else if (SelectInst *BaseSI =
1022 dyn_cast<SelectInst>(State.getBaseValue())) {
Sanjoy Das90547f12016-06-26 04:55:05 +00001023 SelectInst *SI = cast<SelectInst>(BDV);
1024
1025 // Find the instruction which produces the base for each input.
1026 // We may need to insert a bitcast.
1027 BaseSI->setTrueValue(getBaseForInput(SI->getTrueValue(), BaseSI));
1028 BaseSI->setFalseValue(getBaseForInput(SI->getFalseValue(), BaseSI));
Sanjoy Das7dda0ed2016-06-26 04:55:35 +00001029 } else if (auto *BaseEE =
1030 dyn_cast<ExtractElementInst>(State.getBaseValue())) {
Philip Reames7540e3a2015-09-10 00:01:53 +00001031 Value *InVal = cast<ExtractElementInst>(BDV)->getVectorOperand();
Philip Reames3ea15892015-09-03 21:57:40 +00001032 // Find the instruction which produces the base for each input. We may
1033 // need to insert a bitcast.
Sanjoy Das90547f12016-06-26 04:55:05 +00001034 BaseEE->setOperand(0, getBaseForInput(InVal, BaseEE));
Anna Thomas479cbb92016-10-04 13:48:37 +00001035 } else if (auto *BaseIE = dyn_cast<InsertElementInst>(State.getBaseValue())){
Philip Reames7540e3a2015-09-10 00:01:53 +00001036 auto *BdvIE = cast<InsertElementInst>(BDV);
Philip Reames66287132015-09-09 23:40:12 +00001037 auto UpdateOperand = [&](int OperandIdx) {
1038 Value *InVal = BdvIE->getOperand(OperandIdx);
Philip Reames953817b2015-09-10 00:44:10 +00001039 Value *Base = getBaseForInput(InVal, BaseIE);
Philip Reames66287132015-09-09 23:40:12 +00001040 BaseIE->setOperand(OperandIdx, Base);
1041 };
1042 UpdateOperand(0); // vector operand
1043 UpdateOperand(1); // scalar operand
Anna Thomas479cbb92016-10-04 13:48:37 +00001044 } else {
1045 auto *BaseSV = cast<ShuffleVectorInst>(State.getBaseValue());
1046 auto *BdvSV = cast<ShuffleVectorInst>(BDV);
1047 auto UpdateOperand = [&](int OperandIdx) {
1048 Value *InVal = BdvSV->getOperand(OperandIdx);
1049 Value *Base = getBaseForInput(InVal, BaseSV);
1050 BaseSV->setOperand(OperandIdx, Base);
1051 };
1052 UpdateOperand(0); // vector operand
1053 UpdateOperand(1); // vector operand
Philip Reamesd16a9b12015-02-20 01:06:44 +00001054 }
1055 }
1056
1057 // Cache all of our results so we can cheaply reuse them
1058 // NOTE: This is actually two caches: one of the base defining value
1059 // relation and one of the base pointer relation! FIXME
Philip Reames34d7a742015-09-10 00:22:49 +00001060 for (auto Pair : States) {
Philip Reames15d55632015-09-09 23:26:08 +00001061 auto *BDV = Pair.first;
Sanjoy Das7dda0ed2016-06-26 04:55:35 +00001062 Value *Base = Pair.second.getBaseValue();
Sanjoy Das90547f12016-06-26 04:55:05 +00001063 assert(BDV && Base);
Philip Reames79fa9b72016-02-22 20:45:56 +00001064 assert(!isKnownBaseResult(BDV) && "why did it get added?");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001065
Philip Reamesdab35f32015-09-02 21:11:44 +00001066 DEBUG(dbgs() << "Updating base value cache"
Eric Christopherd3d9cbf2016-06-23 00:42:00 +00001067 << " for: " << BDV->getName() << " from: "
Sanjoy Das90547f12016-06-26 04:55:05 +00001068 << (Cache.count(BDV) ? Cache[BDV]->getName().str() : "none")
1069 << " to: " << Base->getName() << "\n");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001070
Sanjoy Das90547f12016-06-26 04:55:05 +00001071 if (Cache.count(BDV)) {
1072 assert(isKnownBaseResult(Base) &&
Philip Reames79fa9b72016-02-22 20:45:56 +00001073 "must be something we 'know' is a base pointer");
Sanjoy Das90547f12016-06-26 04:55:05 +00001074 // Once we transition from the BDV relation being store in the Cache to
Philip Reamesd16a9b12015-02-20 01:06:44 +00001075 // the base relation being stored, it must be stable
Sanjoy Das90547f12016-06-26 04:55:05 +00001076 assert((!isKnownBaseResult(Cache[BDV]) || Cache[BDV] == Base) &&
Philip Reamesd16a9b12015-02-20 01:06:44 +00001077 "base relation should be stable");
1078 }
Sanjoy Das90547f12016-06-26 04:55:05 +00001079 Cache[BDV] = Base;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001080 }
Sanjoy Das90547f12016-06-26 04:55:05 +00001081 assert(Cache.count(Def));
1082 return Cache[Def];
Philip Reamesd16a9b12015-02-20 01:06:44 +00001083}
1084
1085// For a set of live pointers (base and/or derived), identify the base
1086// pointer of the object which they are derived from. This routine will
1087// mutate the IR graph as needed to make the 'base' pointer live at the
1088// definition site of 'derived'. This ensures that any use of 'derived' can
1089// also use 'base'. This may involve the insertion of a number of
1090// additional PHI nodes.
1091//
1092// preconditions: live is a set of pointer type Values
1093//
1094// side effects: may insert PHI nodes into the existing CFG, will preserve
1095// CFG, will not remove or mutate any existing nodes
1096//
Philip Reamesf2041322015-02-20 19:26:04 +00001097// post condition: PointerToBase contains one (derived, base) pair for every
Philip Reamesd16a9b12015-02-20 01:06:44 +00001098// pointer in live. Note that derived can be equal to base if the original
1099// pointer was a base pointer.
Philip Reames704e78b2015-04-10 22:34:56 +00001100static void
1101findBasePointers(const StatepointLiveSetTy &live,
Igor Laevskyfb1811d2016-05-04 14:55:36 +00001102 MapVector<Value *, Value *> &PointerToBase,
Philip Reamesba198492015-04-14 00:41:34 +00001103 DominatorTree *DT, DefiningValueMapTy &DVCache) {
Igor Laevskyfb1811d2016-05-04 14:55:36 +00001104 for (Value *ptr : live) {
Philip Reamesba198492015-04-14 00:41:34 +00001105 Value *base = findBasePointer(ptr, DVCache);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001106 assert(base && "failed to find base pointer");
Philip Reamesf2041322015-02-20 19:26:04 +00001107 PointerToBase[ptr] = base;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001108 assert((!isa<Instruction>(base) || !isa<Instruction>(ptr) ||
1109 DT->dominates(cast<Instruction>(base)->getParent(),
1110 cast<Instruction>(ptr)->getParent())) &&
1111 "The base we found better dominate the derived pointer");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001112 }
1113}
1114
1115/// Find the required based pointers (and adjust the live set) for the given
1116/// parse point.
1117static void findBasePointers(DominatorTree &DT, DefiningValueMapTy &DVCache,
Sanjoy Dasa3244872016-06-17 00:45:00 +00001118 CallSite CS,
Philip Reamesd16a9b12015-02-20 01:06:44 +00001119 PartiallyConstructedSafepointRecord &result) {
Igor Laevskyfb1811d2016-05-04 14:55:36 +00001120 MapVector<Value *, Value *> PointerToBase;
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001121 findBasePointers(result.LiveSet, PointerToBase, &DT, DVCache);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001122
1123 if (PrintBasePointers) {
1124 errs() << "Base Pairs (w/o Relocation):\n";
Igor Laevskyfb1811d2016-05-04 14:55:36 +00001125 for (auto &Pair : PointerToBase) {
Manuel Jacoba4efd8a2015-12-23 00:19:45 +00001126 errs() << " derived ";
Igor Laevskyfb1811d2016-05-04 14:55:36 +00001127 Pair.first->printAsOperand(errs(), false);
Manuel Jacoba4efd8a2015-12-23 00:19:45 +00001128 errs() << " base ";
Igor Laevskyfb1811d2016-05-04 14:55:36 +00001129 Pair.second->printAsOperand(errs(), false);
Manuel Jacoba4efd8a2015-12-23 00:19:45 +00001130 errs() << "\n";;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001131 }
1132 }
1133
Philip Reamesf2041322015-02-20 19:26:04 +00001134 result.PointerToBase = PointerToBase;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001135}
1136
Philip Reamesdf1ef082015-04-10 22:53:14 +00001137/// Given an updated version of the dataflow liveness results, update the
1138/// liveset and base pointer maps for the call site CS.
1139static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData,
Sanjoy Dasa3244872016-06-17 00:45:00 +00001140 CallSite CS,
Philip Reamesdf1ef082015-04-10 22:53:14 +00001141 PartiallyConstructedSafepointRecord &result);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001142
Philip Reamesdf1ef082015-04-10 22:53:14 +00001143static void recomputeLiveInValues(
Justin Bogner843fb202015-12-15 19:40:57 +00001144 Function &F, DominatorTree &DT, ArrayRef<CallSite> toUpdate,
Philip Reamesd2b66462015-02-20 22:39:41 +00001145 MutableArrayRef<struct PartiallyConstructedSafepointRecord> records) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00001146 // TODO-PERF: reuse the original liveness, then simply run the dataflow
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001147 // again. The old values are still live and will help it stabilize quickly.
Philip Reamesdf1ef082015-04-10 22:53:14 +00001148 GCPtrLivenessData RevisedLivenessData;
1149 computeLiveInValues(DT, F, RevisedLivenessData);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001150 for (size_t i = 0; i < records.size(); i++) {
1151 struct PartiallyConstructedSafepointRecord &info = records[i];
Sanjoy Dasa3244872016-06-17 00:45:00 +00001152 recomputeLiveInValues(RevisedLivenessData, toUpdate[i], info);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001153 }
1154}
1155
Sanjoy Das7ad67642015-10-20 01:06:24 +00001156// When inserting gc.relocate and gc.result calls, we need to ensure there are
1157// no uses of the original value / return value between the gc.statepoint and
1158// the gc.relocate / gc.result call. One case which can arise is a phi node
1159// starting one of the successor blocks. We also need to be able to insert the
1160// gc.relocates only on the path which goes through the statepoint. We might
1161// need to split an edge to make this possible.
Philip Reamesf209a152015-04-13 20:00:30 +00001162static BasicBlock *
Sanjoy Dasea45f0e2015-06-02 22:33:34 +00001163normalizeForInvokeSafepoint(BasicBlock *BB, BasicBlock *InvokeParent,
1164 DominatorTree &DT) {
Philip Reames69e51ca2015-04-13 18:07:21 +00001165 BasicBlock *Ret = BB;
Sanjoy Dasff3dba72015-10-20 01:06:17 +00001166 if (!BB->getUniquePredecessor())
Chandler Carruth96ada252015-07-22 09:52:54 +00001167 Ret = SplitBlockPredecessors(BB, InvokeParent, "", &DT);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001168
Sanjoy Das7ad67642015-10-20 01:06:24 +00001169 // Now that 'Ret' has unique predecessor we can safely remove all phi nodes
Philip Reames69e51ca2015-04-13 18:07:21 +00001170 // from it
1171 FoldSingleEntryPHINodes(Ret);
Sanjoy Dasff3dba72015-10-20 01:06:17 +00001172 assert(!isa<PHINode>(Ret->begin()) &&
1173 "All PHI nodes should have been removed!");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001174
Sanjoy Das7ad67642015-10-20 01:06:24 +00001175 // At this point, we can safely insert a gc.relocate or gc.result as the first
1176 // instruction in Ret if needed.
Philip Reames69e51ca2015-04-13 18:07:21 +00001177 return Ret;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001178}
1179
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001180// Create new attribute set containing only attributes which can be transferred
Philip Reamesd16a9b12015-02-20 01:06:44 +00001181// from original call to the safepoint.
Reid Kleckner99351962017-04-28 19:22:40 +00001182static AttributeList legalizeCallAttributes(AttributeList AL) {
1183 if (AL.isEmpty())
1184 return AL;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001185
Reid Kleckner99351962017-04-28 19:22:40 +00001186 // Remove the readonly, readnone, and statepoint function attributes.
1187 AttrBuilder FnAttrs = AL.getFnAttributes();
1188 FnAttrs.removeAttribute(Attribute::ReadNone);
1189 FnAttrs.removeAttribute(Attribute::ReadOnly);
1190 for (Attribute A : AL.getFnAttributes()) {
1191 if (isStatepointDirectiveAttr(A))
1192 FnAttrs.remove(A);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001193 }
1194
Reid Kleckner99351962017-04-28 19:22:40 +00001195 // Just skip parameter and return attributes for now
1196 LLVMContext &Ctx = AL.getContext();
1197 return AttributeList::get(Ctx, AttributeList::FunctionIndex,
1198 AttributeSet::get(Ctx, FnAttrs));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001199}
1200
1201/// Helper function to place all gc relocates necessary for the given
1202/// statepoint.
1203/// Inputs:
1204/// liveVariables - list of variables to be relocated.
1205/// liveStart - index of the first live variable.
1206/// basePtrs - base pointers.
1207/// statepointToken - statepoint instruction to which relocates should be
1208/// bound.
1209/// Builder - Llvm IR builder to be used to construct new calls.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001210static void CreateGCRelocates(ArrayRef<Value *> LiveVariables,
Sanjoy Das5665c992015-05-11 23:47:27 +00001211 const int LiveStart,
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001212 ArrayRef<Value *> BasePtrs,
Sanjoy Das5665c992015-05-11 23:47:27 +00001213 Instruction *StatepointToken,
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00001214 IRBuilder<> Builder) {
Philip Reames94babb72015-07-21 17:18:03 +00001215 if (LiveVariables.empty())
1216 return;
Sanjoy Dasb1942f12015-10-20 01:06:28 +00001217
1218 auto FindIndex = [](ArrayRef<Value *> LiveVec, Value *Val) {
Eugene Zelenko75075ef2017-09-01 21:37:29 +00001219 auto ValIt = llvm::find(LiveVec, Val);
Sanjoy Dasb1942f12015-10-20 01:06:28 +00001220 assert(ValIt != LiveVec.end() && "Val not found in LiveVec!");
1221 size_t Index = std::distance(LiveVec.begin(), ValIt);
1222 assert(Index < LiveVec.size() && "Bug in std::find?");
1223 return Index;
1224 };
Philip Reames74ce2e72015-07-21 16:51:17 +00001225 Module *M = StatepointToken->getModule();
Philip Reames5715f572016-01-09 01:31:13 +00001226
1227 // All gc_relocate are generated as i8 addrspace(1)* (or a vector type whose
1228 // element type is i8 addrspace(1)*). We originally generated unique
1229 // declarations for each pointer type, but this proved problematic because
1230 // the intrinsic mangling code is incomplete and fragile. Since we're moving
1231 // towards a single unified pointer type anyways, we can just cast everything
1232 // to an i8* of the right address space. A bitcast is added later to convert
1233 // gc_relocate to the actual value's type.
1234 auto getGCRelocateDecl = [&] (Type *Ty) {
1235 assert(isHandledGCPointerType(Ty));
1236 auto AS = Ty->getScalarType()->getPointerAddressSpace();
1237 Type *NewTy = Type::getInt8PtrTy(M->getContext(), AS);
1238 if (auto *VT = dyn_cast<VectorType>(Ty))
1239 NewTy = VectorType::get(NewTy, VT->getNumElements());
1240 return Intrinsic::getDeclaration(M, Intrinsic::experimental_gc_relocate,
1241 {NewTy});
1242 };
1243
1244 // Lazily populated map from input types to the canonicalized form mentioned
1245 // in the comment above. This should probably be cached somewhere more
1246 // broadly.
1247 DenseMap<Type*, Value*> TypeToDeclMap;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001248
Sanjoy Das5665c992015-05-11 23:47:27 +00001249 for (unsigned i = 0; i < LiveVariables.size(); i++) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001250 // Generate the gc.relocate call and save the result
Sanjoy Das5665c992015-05-11 23:47:27 +00001251 Value *BaseIdx =
Sanjoy Dasb1942f12015-10-20 01:06:28 +00001252 Builder.getInt32(LiveStart + FindIndex(LiveVariables, BasePtrs[i]));
Sanjoy Das3020b1b2015-10-20 01:06:31 +00001253 Value *LiveIdx = Builder.getInt32(LiveStart + i);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001254
Philip Reames5715f572016-01-09 01:31:13 +00001255 Type *Ty = LiveVariables[i]->getType();
1256 if (!TypeToDeclMap.count(Ty))
1257 TypeToDeclMap[Ty] = getGCRelocateDecl(Ty);
1258 Value *GCRelocateDecl = TypeToDeclMap[Ty];
1259
Philip Reamesd16a9b12015-02-20 01:06:44 +00001260 // only specify a debug name if we can give a useful one
Philip Reames74ce2e72015-07-21 16:51:17 +00001261 CallInst *Reloc = Builder.CreateCall(
David Blaikieff6409d2015-05-18 22:13:54 +00001262 GCRelocateDecl, {StatepointToken, BaseIdx, LiveIdx},
Philip Reamesece70b82015-09-09 23:57:18 +00001263 suffixed_name_or(LiveVariables[i], ".relocated", ""));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001264 // Trick CodeGen into thinking there are lots of free registers at this
1265 // fake call.
Philip Reames74ce2e72015-07-21 16:51:17 +00001266 Reloc->setCallingConv(CallingConv::Cold);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001267 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00001268}
1269
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001270namespace {
1271
1272/// This struct is used to defer RAUWs and `eraseFromParent` s. Using this
1273/// avoids having to worry about keeping around dangling pointers to Values.
1274class DeferredReplacement {
1275 AssertingVH<Instruction> Old;
1276 AssertingVH<Instruction> New;
Sanjoy Das49e974b2016-04-05 23:18:35 +00001277 bool IsDeoptimize = false;
1278
Eugene Zelenko75075ef2017-09-01 21:37:29 +00001279 DeferredReplacement() = default;
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001280
1281public:
Sanjoy Das8d89a2b2016-04-05 23:18:53 +00001282 static DeferredReplacement createRAUW(Instruction *Old, Instruction *New) {
1283 assert(Old != New && Old && New &&
1284 "Cannot RAUW equal values or to / from null!");
1285
1286 DeferredReplacement D;
1287 D.Old = Old;
1288 D.New = New;
1289 return D;
1290 }
1291
1292 static DeferredReplacement createDelete(Instruction *ToErase) {
1293 DeferredReplacement D;
1294 D.Old = ToErase;
1295 return D;
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001296 }
1297
Sanjoy Das49e974b2016-04-05 23:18:35 +00001298 static DeferredReplacement createDeoptimizeReplacement(Instruction *Old) {
1299#ifndef NDEBUG
1300 auto *F = cast<CallInst>(Old)->getCalledFunction();
1301 assert(F && F->getIntrinsicID() == Intrinsic::experimental_deoptimize &&
1302 "Only way to construct a deoptimize deferred replacement");
1303#endif
1304 DeferredReplacement D;
1305 D.Old = Old;
1306 D.IsDeoptimize = true;
1307 return D;
1308 }
1309
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001310 /// Does the task represented by this instance.
1311 void doReplacement() {
1312 Instruction *OldI = Old;
1313 Instruction *NewI = New;
1314
1315 assert(OldI != NewI && "Disallowed at construction?!");
Richard Trieuf35d4b02016-04-06 04:22:00 +00001316 assert((!IsDeoptimize || !New) &&
1317 "Deoptimize instrinsics are not replaced!");
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001318
1319 Old = nullptr;
1320 New = nullptr;
1321
1322 if (NewI)
1323 OldI->replaceAllUsesWith(NewI);
Sanjoy Das49e974b2016-04-05 23:18:35 +00001324
1325 if (IsDeoptimize) {
1326 // Note: we've inserted instructions, so the call to llvm.deoptimize may
1327 // not necessarilly be followed by the matching return.
1328 auto *RI = cast<ReturnInst>(OldI->getParent()->getTerminator());
1329 new UnreachableInst(RI->getContext(), RI);
1330 RI->eraseFromParent();
1331 }
1332
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001333 OldI->eraseFromParent();
1334 }
1335};
Eugene Zelenko75075ef2017-09-01 21:37:29 +00001336
1337} // end anonymous namespace
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001338
Philip Reames2b1084a2016-08-31 15:12:17 +00001339static StringRef getDeoptLowering(CallSite CS) {
1340 const char *DeoptLowering = "deopt-lowering";
1341 if (CS.hasFnAttr(DeoptLowering)) {
1342 // FIXME: CallSite has a *really* confusing interface around attributes
Reid Klecknerb5180542017-03-21 16:57:19 +00001343 // with values.
1344 const AttributeList &CSAS = CS.getAttributes();
1345 if (CSAS.hasAttribute(AttributeList::FunctionIndex, DeoptLowering))
1346 return CSAS.getAttribute(AttributeList::FunctionIndex, DeoptLowering)
1347 .getValueAsString();
Philip Reames2b1084a2016-08-31 15:12:17 +00001348 Function *F = CS.getCalledFunction();
1349 assert(F && F->hasFnAttribute(DeoptLowering));
1350 return F->getFnAttribute(DeoptLowering).getValueAsString();
1351 }
1352 return "live-through";
1353}
1354
Philip Reamesd16a9b12015-02-20 01:06:44 +00001355static void
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001356makeStatepointExplicitImpl(const CallSite CS, /* to replace */
1357 const SmallVectorImpl<Value *> &BasePtrs,
1358 const SmallVectorImpl<Value *> &LiveVariables,
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001359 PartiallyConstructedSafepointRecord &Result,
1360 std::vector<DeferredReplacement> &Replacements) {
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001361 assert(BasePtrs.size() == LiveVariables.size());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001362
Philip Reamesd16a9b12015-02-20 01:06:44 +00001363 // Then go ahead and use the builder do actually do the inserts. We insert
1364 // immediately before the previous instruction under the assumption that all
1365 // arguments will be available here. We can't insert afterwards since we may
1366 // be replacing a terminator.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001367 Instruction *InsertBefore = CS.getInstruction();
1368 IRBuilder<> Builder(InsertBefore);
1369
Sanjoy Das3c520a12015-10-08 23:18:38 +00001370 ArrayRef<Value *> GCArgs(LiveVariables);
Sanjoy Dasc9058ca2016-03-17 18:42:17 +00001371 uint64_t StatepointID = StatepointDirectives::DefaultStatepointID;
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001372 uint32_t NumPatchBytes = 0;
1373 uint32_t Flags = uint32_t(StatepointFlags::None);
Sanjoy Das3c520a12015-10-08 23:18:38 +00001374
Sanjoy Dasbcf27522016-01-29 01:03:20 +00001375 ArrayRef<Use> CallArgs(CS.arg_begin(), CS.arg_end());
1376 ArrayRef<Use> DeoptArgs = GetDeoptBundleOperands(CS);
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001377 ArrayRef<Use> TransitionArgs;
Sanjoy Das40992972016-01-29 01:03:17 +00001378 if (auto TransitionBundle =
1379 CS.getOperandBundle(LLVMContext::OB_gc_transition)) {
1380 Flags |= uint32_t(StatepointFlags::GCTransition);
1381 TransitionArgs = TransitionBundle->Inputs;
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001382 }
Sanjoy Das99abb272016-04-06 01:33:54 +00001383
1384 // Instead of lowering calls to @llvm.experimental.deoptimize as normal calls
1385 // with a return value, we lower then as never returning calls to
1386 // __llvm_deoptimize that are followed by unreachable to get better codegen.
Sanjoy Das49e974b2016-04-05 23:18:35 +00001387 bool IsDeoptimize = false;
Sanjoy Das40992972016-01-29 01:03:17 +00001388
Sanjoy Das31203882016-03-17 01:56:10 +00001389 StatepointDirectives SD =
1390 parseStatepointDirectivesFromAttrs(CS.getAttributes());
1391 if (SD.NumPatchBytes)
1392 NumPatchBytes = *SD.NumPatchBytes;
1393 if (SD.StatepointID)
1394 StatepointID = *SD.StatepointID;
Sanjoy Das40992972016-01-29 01:03:17 +00001395
Philip Reames2b1084a2016-08-31 15:12:17 +00001396 // Pass through the requested lowering if any. The default is live-through.
1397 StringRef DeoptLowering = getDeoptLowering(CS);
1398 if (DeoptLowering.equals("live-in"))
1399 Flags |= uint32_t(StatepointFlags::DeoptLiveIn);
1400 else {
1401 assert(DeoptLowering.equals("live-through") && "Unsupported value!");
1402 }
1403
Sanjoy Das31203882016-03-17 01:56:10 +00001404 Value *CallTarget = CS.getCalledValue();
Sanjoy Dasd4c78332016-03-25 20:12:13 +00001405 if (Function *F = dyn_cast<Function>(CallTarget)) {
1406 if (F->getIntrinsicID() == Intrinsic::experimental_deoptimize) {
Sanjoy Das091fcfa2016-05-06 20:39:33 +00001407 // Calls to llvm.experimental.deoptimize are lowered to calls to the
Sanjoy Dasd4c78332016-03-25 20:12:13 +00001408 // __llvm_deoptimize symbol. We want to resolve this now, since the
1409 // verifier does not allow taking the address of an intrinsic function.
1410
1411 SmallVector<Type *, 8> DomainTy;
1412 for (Value *Arg : CallArgs)
1413 DomainTy.push_back(Arg->getType());
Sanjoy Das49e974b2016-04-05 23:18:35 +00001414 auto *FTy = FunctionType::get(Type::getVoidTy(F->getContext()), DomainTy,
Sanjoy Dasd4c78332016-03-25 20:12:13 +00001415 /* isVarArg = */ false);
1416
1417 // Note: CallTarget can be a bitcast instruction of a symbol if there are
1418 // calls to @llvm.experimental.deoptimize with different argument types in
1419 // the same module. This is fine -- we assume the frontend knew what it
1420 // was doing when generating this kind of IR.
1421 CallTarget =
1422 F->getParent()->getOrInsertFunction("__llvm_deoptimize", FTy);
Sanjoy Das49e974b2016-04-05 23:18:35 +00001423
1424 IsDeoptimize = true;
Sanjoy Dasd4c78332016-03-25 20:12:13 +00001425 }
1426 }
Sanjoy Das40992972016-01-29 01:03:17 +00001427
Philip Reamesd16a9b12015-02-20 01:06:44 +00001428 // Create the statepoint given all the arguments
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001429 Instruction *Token = nullptr;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001430 if (CS.isCall()) {
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001431 CallInst *ToReplace = cast<CallInst>(CS.getInstruction());
Sanjoy Das3c520a12015-10-08 23:18:38 +00001432 CallInst *Call = Builder.CreateGCStatepointCall(
1433 StatepointID, NumPatchBytes, CallTarget, Flags, CallArgs,
1434 TransitionArgs, DeoptArgs, GCArgs, "safepoint_token");
1435
David Majnemerd5648c72016-11-25 22:35:09 +00001436 Call->setTailCallKind(ToReplace->getTailCallKind());
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001437 Call->setCallingConv(ToReplace->getCallingConv());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001438
1439 // Currently we will fail on parameter attributes and on certain
Reid Kleckner99351962017-04-28 19:22:40 +00001440 // function attributes. In case if we can handle this set of attributes -
1441 // set up function attrs directly on statepoint and return attrs later for
1442 // gc_result intrinsic.
1443 Call->setAttributes(legalizeCallAttributes(ToReplace->getAttributes()));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001444
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001445 Token = Call;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001446
1447 // Put the following gc_result and gc_relocate calls immediately after the
1448 // the old call (which we're about to delete)
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001449 assert(ToReplace->getNextNode() && "Not a terminator, must have next!");
1450 Builder.SetInsertPoint(ToReplace->getNextNode());
1451 Builder.SetCurrentDebugLocation(ToReplace->getNextNode()->getDebugLoc());
David Blaikie82ad7872015-02-20 23:44:24 +00001452 } else {
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001453 InvokeInst *ToReplace = cast<InvokeInst>(CS.getInstruction());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001454
1455 // Insert the new invoke into the old block. We'll remove the old one in a
1456 // moment at which point this will become the new terminator for the
1457 // original block.
Sanjoy Das3c520a12015-10-08 23:18:38 +00001458 InvokeInst *Invoke = Builder.CreateGCStatepointInvoke(
1459 StatepointID, NumPatchBytes, CallTarget, ToReplace->getNormalDest(),
1460 ToReplace->getUnwindDest(), Flags, CallArgs, TransitionArgs, DeoptArgs,
1461 GCArgs, "statepoint_token");
1462
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001463 Invoke->setCallingConv(ToReplace->getCallingConv());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001464
1465 // Currently we will fail on parameter attributes and on certain
Reid Kleckner99351962017-04-28 19:22:40 +00001466 // function attributes. In case if we can handle this set of attributes -
1467 // set up function attrs directly on statepoint and return attrs later for
1468 // gc_result intrinsic.
1469 Invoke->setAttributes(legalizeCallAttributes(ToReplace->getAttributes()));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001470
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001471 Token = Invoke;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001472
1473 // Generate gc relocates in exceptional path
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001474 BasicBlock *UnwindBlock = ToReplace->getUnwindDest();
1475 assert(!isa<PHINode>(UnwindBlock->begin()) &&
1476 UnwindBlock->getUniquePredecessor() &&
Philip Reames69e51ca2015-04-13 18:07:21 +00001477 "can't safely insert in this block!");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001478
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001479 Builder.SetInsertPoint(&*UnwindBlock->getFirstInsertionPt());
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001480 Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001481
Chen Lid71999e2015-12-26 07:54:32 +00001482 // Attach exceptional gc relocates to the landingpad.
1483 Instruction *ExceptionalToken = UnwindBlock->getLandingPadInst();
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001484 Result.UnwindToken = ExceptionalToken;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001485
Sanjoy Das3c520a12015-10-08 23:18:38 +00001486 const unsigned LiveStartIdx = Statepoint(Token).gcArgsStartIdx();
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001487 CreateGCRelocates(LiveVariables, LiveStartIdx, BasePtrs, ExceptionalToken,
1488 Builder);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001489
1490 // Generate gc relocates and returns for normal block
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001491 BasicBlock *NormalDest = ToReplace->getNormalDest();
1492 assert(!isa<PHINode>(NormalDest->begin()) &&
1493 NormalDest->getUniquePredecessor() &&
Philip Reames69e51ca2015-04-13 18:07:21 +00001494 "can't safely insert in this block!");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001495
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001496 Builder.SetInsertPoint(&*NormalDest->getFirstInsertionPt());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001497
1498 // gc relocates will be generated later as if it were regular call
1499 // statepoint
Philip Reamesd16a9b12015-02-20 01:06:44 +00001500 }
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001501 assert(Token && "Should be set in one of the above branches!");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001502
Sanjoy Das49e974b2016-04-05 23:18:35 +00001503 if (IsDeoptimize) {
1504 // If we're wrapping an @llvm.experimental.deoptimize in a statepoint, we
1505 // transform the tail-call like structure to a call to a void function
1506 // followed by unreachable to get better codegen.
1507 Replacements.push_back(
1508 DeferredReplacement::createDeoptimizeReplacement(CS.getInstruction()));
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001509 } else {
Sanjoy Das49e974b2016-04-05 23:18:35 +00001510 Token->setName("statepoint_token");
1511 if (!CS.getType()->isVoidTy() && !CS.getInstruction()->use_empty()) {
1512 StringRef Name =
1513 CS.getInstruction()->hasName() ? CS.getInstruction()->getName() : "";
1514 CallInst *GCResult = Builder.CreateGCResult(Token, CS.getType(), Name);
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00001515 GCResult->setAttributes(
1516 AttributeList::get(GCResult->getContext(), AttributeList::ReturnIndex,
1517 CS.getAttributes().getRetAttributes()));
Sanjoy Das49e974b2016-04-05 23:18:35 +00001518
1519 // We cannot RAUW or delete CS.getInstruction() because it could be in the
1520 // live set of some other safepoint, in which case that safepoint's
1521 // PartiallyConstructedSafepointRecord will hold a raw pointer to this
1522 // llvm::Instruction. Instead, we defer the replacement and deletion to
1523 // after the live sets have been made explicit in the IR, and we no longer
1524 // have raw pointers to worry about.
Sanjoy Das8d89a2b2016-04-05 23:18:53 +00001525 Replacements.emplace_back(
1526 DeferredReplacement::createRAUW(CS.getInstruction(), GCResult));
Sanjoy Das49e974b2016-04-05 23:18:35 +00001527 } else {
Sanjoy Das8d89a2b2016-04-05 23:18:53 +00001528 Replacements.emplace_back(
1529 DeferredReplacement::createDelete(CS.getInstruction()));
Sanjoy Das49e974b2016-04-05 23:18:35 +00001530 }
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001531 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00001532
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001533 Result.StatepointToken = Token;
Philip Reames0a3240f2015-02-20 21:34:11 +00001534
Philip Reamesd16a9b12015-02-20 01:06:44 +00001535 // Second, create a gc.relocate for every live variable
Sanjoy Das3c520a12015-10-08 23:18:38 +00001536 const unsigned LiveStartIdx = Statepoint(Token).gcArgsStartIdx();
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001537 CreateGCRelocates(LiveVariables, LiveStartIdx, BasePtrs, Token, Builder);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001538}
1539
Philip Reamesd16a9b12015-02-20 01:06:44 +00001540// Replace an existing gc.statepoint with a new one and a set of gc.relocates
1541// which make the relocations happening at this safepoint explicit.
Philip Reames704e78b2015-04-10 22:34:56 +00001542//
Philip Reamesd16a9b12015-02-20 01:06:44 +00001543// WARNING: Does not do any fixup to adjust users of the original live
1544// values. That's the callers responsibility.
1545static void
Sanjoy Dasa3244872016-06-17 00:45:00 +00001546makeStatepointExplicit(DominatorTree &DT, CallSite CS,
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001547 PartiallyConstructedSafepointRecord &Result,
1548 std::vector<DeferredReplacement> &Replacements) {
Sanjoy Das1ede5362015-10-08 23:18:22 +00001549 const auto &LiveSet = Result.LiveSet;
1550 const auto &PointerToBase = Result.PointerToBase;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001551
1552 // Convert to vector for efficient cross referencing.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001553 SmallVector<Value *, 64> BaseVec, LiveVec;
1554 LiveVec.reserve(LiveSet.size());
1555 BaseVec.reserve(LiveSet.size());
1556 for (Value *L : LiveSet) {
1557 LiveVec.push_back(L);
Philip Reames74ce2e72015-07-21 16:51:17 +00001558 assert(PointerToBase.count(L));
Sanjoy Das1ede5362015-10-08 23:18:22 +00001559 Value *Base = PointerToBase.find(L)->second;
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001560 BaseVec.push_back(Base);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001561 }
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001562 assert(LiveVec.size() == BaseVec.size());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001563
Philip Reamesd16a9b12015-02-20 01:06:44 +00001564 // Do the actual rewriting and delete the old statepoint
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001565 makeStatepointExplicitImpl(CS, BaseVec, LiveVec, Result, Replacements);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001566}
1567
1568// Helper function for the relocationViaAlloca.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001569//
1570// It receives iterator to the statepoint gc relocates and emits a store to the
1571// assigned location (via allocaMap) for the each one of them. It adds the
1572// visited values into the visitedLiveValues set, which we will later use them
1573// for sanity checking.
Philip Reamesd16a9b12015-02-20 01:06:44 +00001574static void
Sanjoy Das5665c992015-05-11 23:47:27 +00001575insertRelocationStores(iterator_range<Value::user_iterator> GCRelocs,
1576 DenseMap<Value *, Value *> &AllocaMap,
1577 DenseSet<Value *> &VisitedLiveValues) {
Sanjoy Das5665c992015-05-11 23:47:27 +00001578 for (User *U : GCRelocs) {
Manuel Jacob83eefa62016-01-05 04:03:00 +00001579 GCRelocateInst *Relocate = dyn_cast<GCRelocateInst>(U);
1580 if (!Relocate)
Philip Reamesd16a9b12015-02-20 01:06:44 +00001581 continue;
1582
Sanjoy Das565f7862016-01-29 16:54:49 +00001583 Value *OriginalValue = Relocate->getDerivedPtr();
Sanjoy Das5665c992015-05-11 23:47:27 +00001584 assert(AllocaMap.count(OriginalValue));
1585 Value *Alloca = AllocaMap[OriginalValue];
Philip Reamesd16a9b12015-02-20 01:06:44 +00001586
1587 // Emit store into the related alloca
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001588 // All gc_relocates are i8 addrspace(1)* typed, and it must be bitcasted to
Sanjoy Das89c54912015-05-11 18:49:34 +00001589 // the correct type according to alloca.
Manuel Jacob83eefa62016-01-05 04:03:00 +00001590 assert(Relocate->getNextNode() &&
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001591 "Should always have one since it's not a terminator");
Manuel Jacob83eefa62016-01-05 04:03:00 +00001592 IRBuilder<> Builder(Relocate->getNextNode());
Sanjoy Das89c54912015-05-11 18:49:34 +00001593 Value *CastedRelocatedValue =
Manuel Jacob83eefa62016-01-05 04:03:00 +00001594 Builder.CreateBitCast(Relocate,
Philip Reamesece70b82015-09-09 23:57:18 +00001595 cast<AllocaInst>(Alloca)->getAllocatedType(),
Manuel Jacob83eefa62016-01-05 04:03:00 +00001596 suffixed_name_or(Relocate, ".casted", ""));
Sanjoy Das89c54912015-05-11 18:49:34 +00001597
Sanjoy Das5665c992015-05-11 23:47:27 +00001598 StoreInst *Store = new StoreInst(CastedRelocatedValue, Alloca);
1599 Store->insertAfter(cast<Instruction>(CastedRelocatedValue));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001600
1601#ifndef NDEBUG
Sanjoy Das5665c992015-05-11 23:47:27 +00001602 VisitedLiveValues.insert(OriginalValue);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001603#endif
1604 }
1605}
1606
Igor Laevskye0317182015-05-19 15:59:05 +00001607// Helper function for the "relocationViaAlloca". Similar to the
1608// "insertRelocationStores" but works for rematerialized values.
Joseph Tremouletadc23762016-02-05 01:42:52 +00001609static void insertRematerializationStores(
1610 const RematerializedValueMapTy &RematerializedValues,
1611 DenseMap<Value *, Value *> &AllocaMap,
1612 DenseSet<Value *> &VisitedLiveValues) {
Igor Laevskye0317182015-05-19 15:59:05 +00001613 for (auto RematerializedValuePair: RematerializedValues) {
1614 Instruction *RematerializedValue = RematerializedValuePair.first;
1615 Value *OriginalValue = RematerializedValuePair.second;
1616
1617 assert(AllocaMap.count(OriginalValue) &&
1618 "Can not find alloca for rematerialized value");
1619 Value *Alloca = AllocaMap[OriginalValue];
1620
1621 StoreInst *Store = new StoreInst(RematerializedValue, Alloca);
1622 Store->insertAfter(RematerializedValue);
1623
1624#ifndef NDEBUG
1625 VisitedLiveValues.insert(OriginalValue);
1626#endif
1627 }
1628}
1629
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001630/// Do all the relocation update via allocas and mem2reg
Philip Reamesd16a9b12015-02-20 01:06:44 +00001631static void relocationViaAlloca(
Igor Laevsky285fe842015-05-19 16:29:43 +00001632 Function &F, DominatorTree &DT, ArrayRef<Value *> Live,
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001633 ArrayRef<PartiallyConstructedSafepointRecord> Records) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001634#ifndef NDEBUG
Philip Reamesa6ebf072015-03-27 05:53:16 +00001635 // record initial number of (static) allocas; we'll check we have the same
1636 // number when we get done.
1637 int InitialAllocaNum = 0;
Benjamin Kramer135f7352016-06-26 12:28:59 +00001638 for (Instruction &I : F.getEntryBlock())
1639 if (isa<AllocaInst>(I))
Philip Reamesa6ebf072015-03-27 05:53:16 +00001640 InitialAllocaNum++;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001641#endif
1642
1643 // TODO-PERF: change data structures, reserve
Igor Laevsky285fe842015-05-19 16:29:43 +00001644 DenseMap<Value *, Value *> AllocaMap;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001645 SmallVector<AllocaInst *, 200> PromotableAllocas;
Igor Laevskye0317182015-05-19 15:59:05 +00001646 // Used later to chack that we have enough allocas to store all values
1647 std::size_t NumRematerializedValues = 0;
Igor Laevsky285fe842015-05-19 16:29:43 +00001648 PromotableAllocas.reserve(Live.size());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001649
Igor Laevskye0317182015-05-19 15:59:05 +00001650 // Emit alloca for "LiveValue" and record it in "allocaMap" and
1651 // "PromotableAllocas"
Matt Arsenault3c1fc762017-04-10 22:27:50 +00001652 const DataLayout &DL = F.getParent()->getDataLayout();
Igor Laevskye0317182015-05-19 15:59:05 +00001653 auto emitAllocaFor = [&](Value *LiveValue) {
Matt Arsenault3c1fc762017-04-10 22:27:50 +00001654 AllocaInst *Alloca = new AllocaInst(LiveValue->getType(),
1655 DL.getAllocaAddrSpace(), "",
Igor Laevskye0317182015-05-19 15:59:05 +00001656 F.getEntryBlock().getFirstNonPHI());
Igor Laevsky285fe842015-05-19 16:29:43 +00001657 AllocaMap[LiveValue] = Alloca;
Igor Laevskye0317182015-05-19 15:59:05 +00001658 PromotableAllocas.push_back(Alloca);
1659 };
1660
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001661 // Emit alloca for each live gc pointer
1662 for (Value *V : Live)
1663 emitAllocaFor(V);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001664
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001665 // Emit allocas for rematerialized values
1666 for (const auto &Info : Records)
Igor Laevsky285fe842015-05-19 16:29:43 +00001667 for (auto RematerializedValuePair : Info.RematerializedValues) {
Igor Laevskye0317182015-05-19 15:59:05 +00001668 Value *OriginalValue = RematerializedValuePair.second;
Igor Laevsky285fe842015-05-19 16:29:43 +00001669 if (AllocaMap.count(OriginalValue) != 0)
Igor Laevskye0317182015-05-19 15:59:05 +00001670 continue;
1671
1672 emitAllocaFor(OriginalValue);
1673 ++NumRematerializedValues;
1674 }
Igor Laevsky285fe842015-05-19 16:29:43 +00001675
Philip Reamesd16a9b12015-02-20 01:06:44 +00001676 // The next two loops are part of the same conceptual operation. We need to
1677 // insert a store to the alloca after the original def and at each
1678 // redefinition. We need to insert a load before each use. These are split
1679 // into distinct loops for performance reasons.
1680
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001681 // Update gc pointer after each statepoint: either store a relocated value or
1682 // null (if no relocated value was found for this gc pointer and it is not a
1683 // gc_result). This must happen before we update the statepoint with load of
1684 // alloca otherwise we lose the link between statepoint and old def.
1685 for (const auto &Info : Records) {
Igor Laevsky285fe842015-05-19 16:29:43 +00001686 Value *Statepoint = Info.StatepointToken;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001687
1688 // This will be used for consistency check
Igor Laevsky285fe842015-05-19 16:29:43 +00001689 DenseSet<Value *> VisitedLiveValues;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001690
1691 // Insert stores for normal statepoint gc relocates
Igor Laevsky285fe842015-05-19 16:29:43 +00001692 insertRelocationStores(Statepoint->users(), AllocaMap, VisitedLiveValues);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001693
1694 // In case if it was invoke statepoint
1695 // we will insert stores for exceptional path gc relocates.
Philip Reames0a3240f2015-02-20 21:34:11 +00001696 if (isa<InvokeInst>(Statepoint)) {
Igor Laevsky285fe842015-05-19 16:29:43 +00001697 insertRelocationStores(Info.UnwindToken->users(), AllocaMap,
1698 VisitedLiveValues);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001699 }
1700
Igor Laevskye0317182015-05-19 15:59:05 +00001701 // Do similar thing with rematerialized values
Igor Laevsky285fe842015-05-19 16:29:43 +00001702 insertRematerializationStores(Info.RematerializedValues, AllocaMap,
1703 VisitedLiveValues);
Igor Laevskye0317182015-05-19 15:59:05 +00001704
Philip Reamese73300b2015-04-13 16:41:32 +00001705 if (ClobberNonLive) {
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001706 // As a debugging aid, pretend that an unrelocated pointer becomes null at
Philip Reamese73300b2015-04-13 16:41:32 +00001707 // the gc.statepoint. This will turn some subtle GC problems into
1708 // slightly easier to debug SEGVs. Note that on large IR files with
1709 // lots of gc.statepoints this is extremely costly both memory and time
1710 // wise.
1711 SmallVector<AllocaInst *, 64> ToClobber;
Igor Laevsky285fe842015-05-19 16:29:43 +00001712 for (auto Pair : AllocaMap) {
Philip Reamese73300b2015-04-13 16:41:32 +00001713 Value *Def = Pair.first;
1714 AllocaInst *Alloca = cast<AllocaInst>(Pair.second);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001715
Philip Reamese73300b2015-04-13 16:41:32 +00001716 // This value was relocated
Igor Laevsky285fe842015-05-19 16:29:43 +00001717 if (VisitedLiveValues.count(Def)) {
Philip Reamese73300b2015-04-13 16:41:32 +00001718 continue;
1719 }
1720 ToClobber.push_back(Alloca);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001721 }
Philip Reamesfa2fcf172015-02-20 19:51:56 +00001722
Philip Reamese73300b2015-04-13 16:41:32 +00001723 auto InsertClobbersAt = [&](Instruction *IP) {
1724 for (auto *AI : ToClobber) {
Eduard Burtescu90c44492016-01-18 00:10:01 +00001725 auto PT = cast<PointerType>(AI->getAllocatedType());
Philip Reamese73300b2015-04-13 16:41:32 +00001726 Constant *CPN = ConstantPointerNull::get(PT);
Igor Laevsky285fe842015-05-19 16:29:43 +00001727 StoreInst *Store = new StoreInst(CPN, AI);
1728 Store->insertBefore(IP);
Philip Reamese73300b2015-04-13 16:41:32 +00001729 }
1730 };
1731
1732 // Insert the clobbering stores. These may get intermixed with the
1733 // gc.results and gc.relocates, but that's fine.
1734 if (auto II = dyn_cast<InvokeInst>(Statepoint)) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001735 InsertClobbersAt(&*II->getNormalDest()->getFirstInsertionPt());
1736 InsertClobbersAt(&*II->getUnwindDest()->getFirstInsertionPt());
Philip Reamese73300b2015-04-13 16:41:32 +00001737 } else {
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001738 InsertClobbersAt(cast<Instruction>(Statepoint)->getNextNode());
Philip Reamesfa2fcf172015-02-20 19:51:56 +00001739 }
David Blaikie82ad7872015-02-20 23:44:24 +00001740 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00001741 }
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001742
1743 // Update use with load allocas and add store for gc_relocated.
Igor Laevsky285fe842015-05-19 16:29:43 +00001744 for (auto Pair : AllocaMap) {
1745 Value *Def = Pair.first;
1746 Value *Alloca = Pair.second;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001747
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001748 // We pre-record the uses of allocas so that we dont have to worry about
1749 // later update that changes the user information..
1750
Igor Laevsky285fe842015-05-19 16:29:43 +00001751 SmallVector<Instruction *, 20> Uses;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001752 // PERF: trade a linear scan for repeated reallocation
Igor Laevsky285fe842015-05-19 16:29:43 +00001753 Uses.reserve(std::distance(Def->user_begin(), Def->user_end()));
1754 for (User *U : Def->users()) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001755 if (!isa<ConstantExpr>(U)) {
1756 // If the def has a ConstantExpr use, then the def is either a
1757 // ConstantExpr use itself or null. In either case
1758 // (recursively in the first, directly in the second), the oop
1759 // it is ultimately dependent on is null and this particular
1760 // use does not need to be fixed up.
Igor Laevsky285fe842015-05-19 16:29:43 +00001761 Uses.push_back(cast<Instruction>(U));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001762 }
1763 }
1764
Igor Laevsky285fe842015-05-19 16:29:43 +00001765 std::sort(Uses.begin(), Uses.end());
1766 auto Last = std::unique(Uses.begin(), Uses.end());
1767 Uses.erase(Last, Uses.end());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001768
Igor Laevsky285fe842015-05-19 16:29:43 +00001769 for (Instruction *Use : Uses) {
1770 if (isa<PHINode>(Use)) {
1771 PHINode *Phi = cast<PHINode>(Use);
1772 for (unsigned i = 0; i < Phi->getNumIncomingValues(); i++) {
1773 if (Def == Phi->getIncomingValue(i)) {
1774 LoadInst *Load = new LoadInst(
1775 Alloca, "", Phi->getIncomingBlock(i)->getTerminator());
1776 Phi->setIncomingValue(i, Load);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001777 }
1778 }
1779 } else {
Igor Laevsky285fe842015-05-19 16:29:43 +00001780 LoadInst *Load = new LoadInst(Alloca, "", Use);
1781 Use->replaceUsesOfWith(Def, Load);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001782 }
1783 }
1784
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001785 // Emit store for the initial gc value. Store must be inserted after load,
1786 // otherwise store will be in alloca's use list and an extra load will be
1787 // inserted before it.
Igor Laevsky285fe842015-05-19 16:29:43 +00001788 StoreInst *Store = new StoreInst(Def, Alloca);
1789 if (Instruction *Inst = dyn_cast<Instruction>(Def)) {
1790 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(Inst)) {
Philip Reames6da37852015-03-04 00:13:52 +00001791 // InvokeInst is a TerminatorInst so the store need to be inserted
1792 // into its normal destination block.
Igor Laevsky285fe842015-05-19 16:29:43 +00001793 BasicBlock *NormalDest = Invoke->getNormalDest();
1794 Store->insertBefore(NormalDest->getFirstNonPHI());
Philip Reames6da37852015-03-04 00:13:52 +00001795 } else {
Igor Laevsky285fe842015-05-19 16:29:43 +00001796 assert(!Inst->isTerminator() &&
Philip Reames6da37852015-03-04 00:13:52 +00001797 "The only TerminatorInst that can produce a value is "
1798 "InvokeInst which is handled above.");
Igor Laevsky285fe842015-05-19 16:29:43 +00001799 Store->insertAfter(Inst);
Philip Reames6da37852015-03-04 00:13:52 +00001800 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00001801 } else {
Igor Laevsky285fe842015-05-19 16:29:43 +00001802 assert(isa<Argument>(Def));
1803 Store->insertAfter(cast<Instruction>(Alloca));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001804 }
1805 }
1806
Igor Laevsky285fe842015-05-19 16:29:43 +00001807 assert(PromotableAllocas.size() == Live.size() + NumRematerializedValues &&
Philip Reamesd16a9b12015-02-20 01:06:44 +00001808 "we must have the same allocas with lives");
1809 if (!PromotableAllocas.empty()) {
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001810 // Apply mem2reg to promote alloca to SSA
Philip Reamesd16a9b12015-02-20 01:06:44 +00001811 PromoteMemToReg(PromotableAllocas, DT);
1812 }
1813
1814#ifndef NDEBUG
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001815 for (auto &I : F.getEntryBlock())
1816 if (isa<AllocaInst>(I))
Philip Reamesa6ebf072015-03-27 05:53:16 +00001817 InitialAllocaNum--;
1818 assert(InitialAllocaNum == 0 && "We must not introduce any extra allocas");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001819#endif
1820}
1821
1822/// Implement a unique function which doesn't require we sort the input
1823/// vector. Doing so has the effect of changing the output of a couple of
1824/// tests in ways which make them less useful in testing fused safepoints.
Philip Reamesd2b66462015-02-20 22:39:41 +00001825template <typename T> static void unique_unsorted(SmallVectorImpl<T> &Vec) {
Benjamin Kramer258ea0d2015-06-13 19:50:38 +00001826 SmallSet<T, 8> Seen;
David Majnemerc7004902016-08-12 04:32:37 +00001827 Vec.erase(remove_if(Vec, [&](const T &V) { return !Seen.insert(V).second; }),
1828 Vec.end());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001829}
1830
Philip Reamesd16a9b12015-02-20 01:06:44 +00001831/// Insert holders so that each Value is obviously live through the entire
Philip Reamesf209a152015-04-13 20:00:30 +00001832/// lifetime of the call.
Philip Reamesd16a9b12015-02-20 01:06:44 +00001833static void insertUseHolderAfter(CallSite &CS, const ArrayRef<Value *> Values,
Philip Reamesf209a152015-04-13 20:00:30 +00001834 SmallVectorImpl<CallInst *> &Holders) {
Philip Reames21142752015-04-13 19:07:47 +00001835 if (Values.empty())
1836 // No values to hold live, might as well not insert the empty holder
1837 return;
1838
Sanjay Patelaf674fb2015-12-14 17:24:23 +00001839 Module *M = CS.getInstruction()->getModule();
Philip Reamesf209a152015-04-13 20:00:30 +00001840 // Use a dummy vararg function to actually hold the values live
1841 Function *Func = cast<Function>(M->getOrInsertFunction(
1842 "__tmp_use", FunctionType::get(Type::getVoidTy(M->getContext()), true)));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001843 if (CS.isCall()) {
1844 // For call safepoints insert dummy calls right after safepoint
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001845 Holders.push_back(CallInst::Create(Func, Values, "",
1846 &*++CS.getInstruction()->getIterator()));
Philip Reamesf209a152015-04-13 20:00:30 +00001847 return;
1848 }
1849 // For invoke safepooints insert dummy calls both in normal and
1850 // exceptional destination blocks
1851 auto *II = cast<InvokeInst>(CS.getInstruction());
1852 Holders.push_back(CallInst::Create(
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001853 Func, Values, "", &*II->getNormalDest()->getFirstInsertionPt()));
Philip Reamesf209a152015-04-13 20:00:30 +00001854 Holders.push_back(CallInst::Create(
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001855 Func, Values, "", &*II->getUnwindDest()->getFirstInsertionPt()));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001856}
1857
1858static void findLiveReferences(
Justin Bogner843fb202015-12-15 19:40:57 +00001859 Function &F, DominatorTree &DT, ArrayRef<CallSite> toUpdate,
Philip Reamesd2b66462015-02-20 22:39:41 +00001860 MutableArrayRef<struct PartiallyConstructedSafepointRecord> records) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00001861 GCPtrLivenessData OriginalLivenessData;
1862 computeLiveInValues(DT, F, OriginalLivenessData);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001863 for (size_t i = 0; i < records.size(); i++) {
1864 struct PartiallyConstructedSafepointRecord &info = records[i];
Sanjoy Dasa3244872016-06-17 00:45:00 +00001865 analyzeParsePointLiveness(DT, OriginalLivenessData, toUpdate[i], info);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001866 }
1867}
1868
Igor Laevskye0317182015-05-19 15:59:05 +00001869// Helper function for the "rematerializeLiveValues". It walks use chain
Anna Thomas8cd7de12016-09-20 21:36:02 +00001870// starting from the "CurrentValue" until it reaches the root of the chain, i.e.
1871// the base or a value it cannot process. Only "simple" values are processed
1872// (currently it is GEP's and casts). The returned root is examined by the
1873// callers of findRematerializableChainToBasePointer. Fills "ChainToBase" array
1874// with all visited values.
1875static Value* findRematerializableChainToBasePointer(
Igor Laevskye0317182015-05-19 15:59:05 +00001876 SmallVectorImpl<Instruction*> &ChainToBase,
Anna Thomas8cd7de12016-09-20 21:36:02 +00001877 Value *CurrentValue) {
Igor Laevskye0317182015-05-19 15:59:05 +00001878 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurrentValue)) {
1879 ChainToBase.push_back(GEP);
1880 return findRematerializableChainToBasePointer(ChainToBase,
Anna Thomas8cd7de12016-09-20 21:36:02 +00001881 GEP->getPointerOperand());
Igor Laevskye0317182015-05-19 15:59:05 +00001882 }
1883
1884 if (CastInst *CI = dyn_cast<CastInst>(CurrentValue)) {
Igor Laevskye0317182015-05-19 15:59:05 +00001885 if (!CI->isNoopCast(CI->getModule()->getDataLayout()))
Anna Thomas8cd7de12016-09-20 21:36:02 +00001886 return CI;
Igor Laevskye0317182015-05-19 15:59:05 +00001887
1888 ChainToBase.push_back(CI);
Manuel Jacob9db5b932015-12-28 20:14:05 +00001889 return findRematerializableChainToBasePointer(ChainToBase,
Anna Thomas8cd7de12016-09-20 21:36:02 +00001890 CI->getOperand(0));
Igor Laevskye0317182015-05-19 15:59:05 +00001891 }
1892
Anna Thomas8cd7de12016-09-20 21:36:02 +00001893 // We have reached the root of the chain, which is either equal to the base or
1894 // is the first unsupported value along the use chain.
1895 return CurrentValue;
Igor Laevskye0317182015-05-19 15:59:05 +00001896}
1897
1898// Helper function for the "rematerializeLiveValues". Compute cost of the use
1899// chain we are going to rematerialize.
1900static unsigned
1901chainToBasePointerCost(SmallVectorImpl<Instruction*> &Chain,
1902 TargetTransformInfo &TTI) {
1903 unsigned Cost = 0;
1904
1905 for (Instruction *Instr : Chain) {
1906 if (CastInst *CI = dyn_cast<CastInst>(Instr)) {
1907 assert(CI->isNoopCast(CI->getModule()->getDataLayout()) &&
1908 "non noop cast is found during rematerialization");
1909
1910 Type *SrcTy = CI->getOperand(0)->getType();
Jonas Paulssonfccc7d62017-04-12 11:49:08 +00001911 Cost += TTI.getCastInstrCost(CI->getOpcode(), CI->getType(), SrcTy, CI);
Igor Laevskye0317182015-05-19 15:59:05 +00001912
1913 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Instr)) {
1914 // Cost of the address calculation
Eduard Burtescu19eb0312016-01-19 17:28:00 +00001915 Type *ValTy = GEP->getSourceElementType();
Igor Laevskye0317182015-05-19 15:59:05 +00001916 Cost += TTI.getAddressComputationCost(ValTy);
1917
1918 // And cost of the GEP itself
1919 // TODO: Use TTI->getGEPCost here (it exists, but appears to be not
1920 // allowed for the external usage)
1921 if (!GEP->hasAllConstantIndices())
1922 Cost += 2;
1923
1924 } else {
1925 llvm_unreachable("unsupported instruciton type during rematerialization");
1926 }
1927 }
1928
1929 return Cost;
1930}
1931
Anna Thomas8cd7de12016-09-20 21:36:02 +00001932static bool AreEquivalentPhiNodes(PHINode &OrigRootPhi, PHINode &AlternateRootPhi) {
Anna Thomas8cd7de12016-09-20 21:36:02 +00001933 unsigned PhiNum = OrigRootPhi.getNumIncomingValues();
1934 if (PhiNum != AlternateRootPhi.getNumIncomingValues() ||
1935 OrigRootPhi.getParent() != AlternateRootPhi.getParent())
1936 return false;
1937 // Map of incoming values and their corresponding basic blocks of
1938 // OrigRootPhi.
1939 SmallDenseMap<Value *, BasicBlock *, 8> CurrentIncomingValues;
1940 for (unsigned i = 0; i < PhiNum; i++)
1941 CurrentIncomingValues[OrigRootPhi.getIncomingValue(i)] =
1942 OrigRootPhi.getIncomingBlock(i);
1943
1944 // Both current and base PHIs should have same incoming values and
1945 // the same basic blocks corresponding to the incoming values.
1946 for (unsigned i = 0; i < PhiNum; i++) {
1947 auto CIVI =
1948 CurrentIncomingValues.find(AlternateRootPhi.getIncomingValue(i));
1949 if (CIVI == CurrentIncomingValues.end())
1950 return false;
1951 BasicBlock *CurrentIncomingBB = CIVI->second;
1952 if (CurrentIncomingBB != AlternateRootPhi.getIncomingBlock(i))
1953 return false;
1954 }
1955 return true;
Anna Thomas8cd7de12016-09-20 21:36:02 +00001956}
1957
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001958// From the statepoint live set pick values that are cheaper to recompute then
1959// to relocate. Remove this values from the live set, rematerialize them after
Igor Laevskye0317182015-05-19 15:59:05 +00001960// statepoint and record them in "Info" structure. Note that similar to
1961// relocated values we don't do any user adjustments here.
1962static void rematerializeLiveValues(CallSite CS,
1963 PartiallyConstructedSafepointRecord &Info,
1964 TargetTransformInfo &TTI) {
Aaron Ballmanff7d4fa2015-05-20 14:53:50 +00001965 const unsigned int ChainLengthThreshold = 10;
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +00001966
Igor Laevskye0317182015-05-19 15:59:05 +00001967 // Record values we are going to delete from this statepoint live set.
1968 // We can not di this in following loop due to iterator invalidation.
1969 SmallVector<Value *, 32> LiveValuesToBeDeleted;
1970
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001971 for (Value *LiveValue: Info.LiveSet) {
Igor Laevskye0317182015-05-19 15:59:05 +00001972 // For each live pointer find it's defining chain
1973 SmallVector<Instruction *, 3> ChainToBase;
Philip Reames74ce2e72015-07-21 16:51:17 +00001974 assert(Info.PointerToBase.count(LiveValue));
Anna Thomas8cd7de12016-09-20 21:36:02 +00001975 Value *RootOfChain =
Igor Laevskye0317182015-05-19 15:59:05 +00001976 findRematerializableChainToBasePointer(ChainToBase,
Anna Thomas8cd7de12016-09-20 21:36:02 +00001977 LiveValue);
1978
Igor Laevskye0317182015-05-19 15:59:05 +00001979 // Nothing to do, or chain is too long
Anna Thomas8cd7de12016-09-20 21:36:02 +00001980 if ( ChainToBase.size() == 0 ||
Igor Laevskye0317182015-05-19 15:59:05 +00001981 ChainToBase.size() > ChainLengthThreshold)
1982 continue;
1983
Anna Thomas8cd7de12016-09-20 21:36:02 +00001984 // Handle the scenario where the RootOfChain is not equal to the
1985 // Base Value, but they are essentially the same phi values.
1986 if (RootOfChain != Info.PointerToBase[LiveValue]) {
1987 PHINode *OrigRootPhi = dyn_cast<PHINode>(RootOfChain);
1988 PHINode *AlternateRootPhi = dyn_cast<PHINode>(Info.PointerToBase[LiveValue]);
1989 if (!OrigRootPhi || !AlternateRootPhi)
1990 continue;
1991 // PHI nodes that have the same incoming values, and belonging to the same
1992 // basic blocks are essentially the same SSA value. When the original phi
1993 // has incoming values with different base pointers, the original phi is
1994 // marked as conflict, and an additional `AlternateRootPhi` with the same
1995 // incoming values get generated by the findBasePointer function. We need
1996 // to identify the newly generated AlternateRootPhi (.base version of phi)
1997 // and RootOfChain (the original phi node itself) are the same, so that we
1998 // can rematerialize the gep and casts. This is a workaround for the
Hiroshi Inoueef1c2ba2017-07-01 07:12:15 +00001999 // deficiency in the findBasePointer algorithm.
Anna Thomas8cd7de12016-09-20 21:36:02 +00002000 if (!AreEquivalentPhiNodes(*OrigRootPhi, *AlternateRootPhi))
2001 continue;
2002 // Now that the phi nodes are proved to be the same, assert that
2003 // findBasePointer's newly generated AlternateRootPhi is present in the
2004 // liveset of the call.
2005 assert(Info.LiveSet.count(AlternateRootPhi));
2006 }
Igor Laevskye0317182015-05-19 15:59:05 +00002007 // Compute cost of this chain
2008 unsigned Cost = chainToBasePointerCost(ChainToBase, TTI);
2009 // TODO: We can also account for cases when we will be able to remove some
2010 // of the rematerialized values by later optimization passes. I.e if
2011 // we rematerialized several intersecting chains. Or if original values
2012 // don't have any uses besides this statepoint.
2013
2014 // For invokes we need to rematerialize each chain twice - for normal and
2015 // for unwind basic blocks. Model this by multiplying cost by two.
2016 if (CS.isInvoke()) {
2017 Cost *= 2;
2018 }
2019 // If it's too expensive - skip it
2020 if (Cost >= RematerializationThreshold)
2021 continue;
2022
2023 // Remove value from the live set
2024 LiveValuesToBeDeleted.push_back(LiveValue);
2025
2026 // Clone instructions and record them inside "Info" structure
2027
2028 // Walk backwards to visit top-most instructions first
2029 std::reverse(ChainToBase.begin(), ChainToBase.end());
2030
2031 // Utility function which clones all instructions from "ChainToBase"
2032 // and inserts them before "InsertBefore". Returns rematerialized value
2033 // which should be used after statepoint.
Anna Thomas82c37172016-09-22 13:13:06 +00002034 auto rematerializeChain = [&ChainToBase](
2035 Instruction *InsertBefore, Value *RootOfChain, Value *AlternateLiveBase) {
Igor Laevskye0317182015-05-19 15:59:05 +00002036 Instruction *LastClonedValue = nullptr;
2037 Instruction *LastValue = nullptr;
2038 for (Instruction *Instr: ChainToBase) {
Hiroshi Inouebb703e82017-07-02 03:24:54 +00002039 // Only GEP's and casts are supported as we need to be careful to not
Igor Laevskye0317182015-05-19 15:59:05 +00002040 // introduce any new uses of pointers not in the liveset.
2041 // Note that it's fine to introduce new uses of pointers which were
2042 // otherwise not used after this statepoint.
2043 assert(isa<GetElementPtrInst>(Instr) || isa<CastInst>(Instr));
2044
2045 Instruction *ClonedValue = Instr->clone();
2046 ClonedValue->insertBefore(InsertBefore);
2047 ClonedValue->setName(Instr->getName() + ".remat");
2048
2049 // If it is not first instruction in the chain then it uses previously
2050 // cloned value. We should update it to use cloned value.
2051 if (LastClonedValue) {
2052 assert(LastValue);
2053 ClonedValue->replaceUsesOfWith(LastValue, LastClonedValue);
2054#ifndef NDEBUG
Igor Laevskyd83f6972015-05-21 13:02:14 +00002055 for (auto OpValue : ClonedValue->operand_values()) {
Anna Thomas82c37172016-09-22 13:13:06 +00002056 // Assert that cloned instruction does not use any instructions from
2057 // this chain other than LastClonedValue
David Majnemer0d955d02016-08-11 22:21:41 +00002058 assert(!is_contained(ChainToBase, OpValue) &&
Igor Laevskyd83f6972015-05-21 13:02:14 +00002059 "incorrect use in rematerialization chain");
Anna Thomas82c37172016-09-22 13:13:06 +00002060 // Assert that the cloned instruction does not use the RootOfChain
2061 // or the AlternateLiveBase.
2062 assert(OpValue != RootOfChain && OpValue != AlternateLiveBase);
Igor Laevskye0317182015-05-19 15:59:05 +00002063 }
2064#endif
Anna Thomas82c37172016-09-22 13:13:06 +00002065 } else {
2066 // For the first instruction, replace the use of unrelocated base i.e.
2067 // RootOfChain/OrigRootPhi, with the corresponding PHI present in the
2068 // live set. They have been proved to be the same PHI nodes. Note
2069 // that the *only* use of the RootOfChain in the ChainToBase list is
2070 // the first Value in the list.
2071 if (RootOfChain != AlternateLiveBase)
2072 ClonedValue->replaceUsesOfWith(RootOfChain, AlternateLiveBase);
Igor Laevskye0317182015-05-19 15:59:05 +00002073 }
2074
2075 LastClonedValue = ClonedValue;
2076 LastValue = Instr;
2077 }
2078 assert(LastClonedValue);
2079 return LastClonedValue;
2080 };
2081
2082 // Different cases for calls and invokes. For invokes we need to clone
2083 // instructions both on normal and unwind path.
2084 if (CS.isCall()) {
2085 Instruction *InsertBefore = CS.getInstruction()->getNextNode();
2086 assert(InsertBefore);
Anna Thomas82c37172016-09-22 13:13:06 +00002087 Instruction *RematerializedValue = rematerializeChain(
2088 InsertBefore, RootOfChain, Info.PointerToBase[LiveValue]);
Igor Laevskye0317182015-05-19 15:59:05 +00002089 Info.RematerializedValues[RematerializedValue] = LiveValue;
2090 } else {
2091 InvokeInst *Invoke = cast<InvokeInst>(CS.getInstruction());
2092
2093 Instruction *NormalInsertBefore =
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00002094 &*Invoke->getNormalDest()->getFirstInsertionPt();
Igor Laevskye0317182015-05-19 15:59:05 +00002095 Instruction *UnwindInsertBefore =
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00002096 &*Invoke->getUnwindDest()->getFirstInsertionPt();
Igor Laevskye0317182015-05-19 15:59:05 +00002097
Anna Thomas82c37172016-09-22 13:13:06 +00002098 Instruction *NormalRematerializedValue = rematerializeChain(
2099 NormalInsertBefore, RootOfChain, Info.PointerToBase[LiveValue]);
2100 Instruction *UnwindRematerializedValue = rematerializeChain(
2101 UnwindInsertBefore, RootOfChain, Info.PointerToBase[LiveValue]);
Igor Laevskye0317182015-05-19 15:59:05 +00002102
2103 Info.RematerializedValues[NormalRematerializedValue] = LiveValue;
2104 Info.RematerializedValues[UnwindRematerializedValue] = LiveValue;
2105 }
2106 }
2107
2108 // Remove rematerializaed values from the live set
2109 for (auto LiveValue: LiveValuesToBeDeleted) {
Igor Laevskyfb1811d2016-05-04 14:55:36 +00002110 Info.LiveSet.remove(LiveValue);
Igor Laevskye0317182015-05-19 15:59:05 +00002111 }
2112}
2113
Justin Bogner843fb202015-12-15 19:40:57 +00002114static bool insertParsePoints(Function &F, DominatorTree &DT,
2115 TargetTransformInfo &TTI,
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002116 SmallVectorImpl<CallSite> &ToUpdate) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00002117#ifndef NDEBUG
2118 // sanity check the input
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002119 std::set<CallSite> Uniqued;
2120 Uniqued.insert(ToUpdate.begin(), ToUpdate.end());
2121 assert(Uniqued.size() == ToUpdate.size() && "no duplicates please!");
Philip Reamesd16a9b12015-02-20 01:06:44 +00002122
Sanjoy Dasbcf27522016-01-29 01:03:20 +00002123 for (CallSite CS : ToUpdate)
2124 assert(CS.getInstruction()->getFunction() == &F);
Philip Reamesd16a9b12015-02-20 01:06:44 +00002125#endif
2126
Philip Reames69e51ca2015-04-13 18:07:21 +00002127 // When inserting gc.relocates for invokes, we need to be able to insert at
2128 // the top of the successor blocks. See the comment on
2129 // normalForInvokeSafepoint on exactly what is needed. Note that this step
Philip Reamesf209a152015-04-13 20:00:30 +00002130 // may restructure the CFG.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002131 for (CallSite CS : ToUpdate) {
Philip Reamesf209a152015-04-13 20:00:30 +00002132 if (!CS.isInvoke())
2133 continue;
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002134 auto *II = cast<InvokeInst>(CS.getInstruction());
2135 normalizeForInvokeSafepoint(II->getNormalDest(), II->getParent(), DT);
2136 normalizeForInvokeSafepoint(II->getUnwindDest(), II->getParent(), DT);
Philip Reamesf209a152015-04-13 20:00:30 +00002137 }
Philip Reames69e51ca2015-04-13 18:07:21 +00002138
Philip Reamesd16a9b12015-02-20 01:06:44 +00002139 // A list of dummy calls added to the IR to keep various values obviously
2140 // live in the IR. We'll remove all of these when done.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002141 SmallVector<CallInst *, 64> Holders;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002142
Philip Reamesb70cecd2017-06-02 23:03:26 +00002143 // Insert a dummy call with all of the deopt operands we'll need for the
2144 // actual safepoint insertion as arguments. This ensures reference operands
2145 // in the deopt argument list are considered live through the safepoint (and
Philip Reamesd16a9b12015-02-20 01:06:44 +00002146 // thus makes sure they get relocated.)
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002147 for (CallSite CS : ToUpdate) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00002148 SmallVector<Value *, 64> DeoptValues;
Sanjoy Das25ec1a32015-10-16 02:41:00 +00002149
Sanjoy Das40992972016-01-29 01:03:17 +00002150 for (Value *Arg : GetDeoptBundleOperands(CS)) {
Philip Reames8531d8c2015-04-10 21:48:25 +00002151 assert(!isUnhandledGCPointerType(Arg->getType()) &&
2152 "support for FCA unimplemented");
2153 if (isHandledGCPointerType(Arg->getType()))
Philip Reamesd16a9b12015-02-20 01:06:44 +00002154 DeoptValues.push_back(Arg);
2155 }
Sanjoy Das25ec1a32015-10-16 02:41:00 +00002156
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002157 insertUseHolderAfter(CS, DeoptValues, Holders);
Philip Reamesd16a9b12015-02-20 01:06:44 +00002158 }
2159
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002160 SmallVector<PartiallyConstructedSafepointRecord, 64> Records(ToUpdate.size());
Philip Reamesd16a9b12015-02-20 01:06:44 +00002161
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002162 // A) Identify all gc pointers which are statically live at the given call
Philip Reamesd16a9b12015-02-20 01:06:44 +00002163 // site.
Justin Bogner843fb202015-12-15 19:40:57 +00002164 findLiveReferences(F, DT, ToUpdate, Records);
Philip Reamesd16a9b12015-02-20 01:06:44 +00002165
2166 // B) Find the base pointers for each live pointer
2167 /* scope for caching */ {
2168 // Cache the 'defining value' relation used in the computation and
2169 // insertion of base phis and selects. This ensures that we don't insert
2170 // large numbers of duplicate base_phis.
2171 DefiningValueMapTy DVCache;
2172
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002173 for (size_t i = 0; i < Records.size(); i++) {
2174 PartiallyConstructedSafepointRecord &info = Records[i];
2175 findBasePointers(DT, DVCache, ToUpdate[i], info);
Philip Reamesd16a9b12015-02-20 01:06:44 +00002176 }
2177 } // end of cache scope
2178
2179 // The base phi insertion logic (for any safepoint) may have inserted new
2180 // instructions which are now live at some safepoint. The simplest such
2181 // example is:
2182 // loop:
2183 // phi a <-- will be a new base_phi here
2184 // safepoint 1 <-- that needs to be live here
2185 // gep a + 1
2186 // safepoint 2
2187 // br loop
Philip Reamesd16a9b12015-02-20 01:06:44 +00002188 // We insert some dummy calls after each safepoint to definitely hold live
2189 // the base pointers which were identified for that safepoint. We'll then
2190 // ask liveness for _every_ base inserted to see what is now live. Then we
2191 // remove the dummy calls.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002192 Holders.reserve(Holders.size() + Records.size());
2193 for (size_t i = 0; i < Records.size(); i++) {
2194 PartiallyConstructedSafepointRecord &Info = Records[i];
Philip Reamesd16a9b12015-02-20 01:06:44 +00002195
2196 SmallVector<Value *, 128> Bases;
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002197 for (auto Pair : Info.PointerToBase)
Philip Reamesd16a9b12015-02-20 01:06:44 +00002198 Bases.push_back(Pair.second);
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002199
2200 insertUseHolderAfter(ToUpdate[i], Bases, Holders);
Philip Reamesd16a9b12015-02-20 01:06:44 +00002201 }
2202
Philip Reamesdf1ef082015-04-10 22:53:14 +00002203 // By selecting base pointers, we've effectively inserted new uses. Thus, we
2204 // need to rerun liveness. We may *also* have inserted new defs, but that's
2205 // not the key issue.
Justin Bogner843fb202015-12-15 19:40:57 +00002206 recomputeLiveInValues(F, DT, ToUpdate, Records);
Philip Reamesd16a9b12015-02-20 01:06:44 +00002207
Philip Reamesd16a9b12015-02-20 01:06:44 +00002208 if (PrintBasePointers) {
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002209 for (auto &Info : Records) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00002210 errs() << "Base Pairs: (w/Relocation)\n";
Manuel Jacoba4efd8a2015-12-23 00:19:45 +00002211 for (auto Pair : Info.PointerToBase) {
2212 errs() << " derived ";
2213 Pair.first->printAsOperand(errs(), false);
2214 errs() << " base ";
2215 Pair.second->printAsOperand(errs(), false);
2216 errs() << "\n";
2217 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00002218 }
2219 }
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002220
Manuel Jacob990dfa62015-12-22 16:50:44 +00002221 // It is possible that non-constant live variables have a constant base. For
2222 // example, a GEP with a variable offset from a global. In this case we can
2223 // remove it from the liveset. We already don't add constants to the liveset
2224 // because we assume they won't move at runtime and the GC doesn't need to be
2225 // informed about them. The same reasoning applies if the base is constant.
2226 // Note that the relocation placement code relies on this filtering for
2227 // correctness as it expects the base to be in the liveset, which isn't true
2228 // if the base is constant.
2229 for (auto &Info : Records)
2230 for (auto &BasePair : Info.PointerToBase)
2231 if (isa<Constant>(BasePair.second))
Igor Laevskyfb1811d2016-05-04 14:55:36 +00002232 Info.LiveSet.remove(BasePair.first);
Manuel Jacob990dfa62015-12-22 16:50:44 +00002233
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002234 for (CallInst *CI : Holders)
2235 CI->eraseFromParent();
2236
2237 Holders.clear();
Philip Reamesd16a9b12015-02-20 01:06:44 +00002238
Igor Laevskye0317182015-05-19 15:59:05 +00002239 // In order to reduce live set of statepoint we might choose to rematerialize
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002240 // some values instead of relocating them. This is purely an optimization and
Igor Laevskye0317182015-05-19 15:59:05 +00002241 // does not influence correctness.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002242 for (size_t i = 0; i < Records.size(); i++)
2243 rematerializeLiveValues(ToUpdate[i], Records[i], TTI);
Igor Laevskye0317182015-05-19 15:59:05 +00002244
Sanjoy Das25ec1a32015-10-16 02:41:00 +00002245 // We need this to safely RAUW and delete call or invoke return values that
2246 // may themselves be live over a statepoint. For details, please see usage in
2247 // makeStatepointExplicitImpl.
2248 std::vector<DeferredReplacement> Replacements;
2249
Philip Reamesd16a9b12015-02-20 01:06:44 +00002250 // Now run through and replace the existing statepoints with new ones with
2251 // the live variables listed. We do not yet update uses of the values being
2252 // relocated. We have references to live variables that need to
2253 // survive to the last iteration of this loop. (By construction, the
2254 // previous statepoint can not be a live variable, thus we can and remove
2255 // the old statepoint calls as we go.)
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002256 for (size_t i = 0; i < Records.size(); i++)
Sanjoy Das25ec1a32015-10-16 02:41:00 +00002257 makeStatepointExplicit(DT, ToUpdate[i], Records[i], Replacements);
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002258
2259 ToUpdate.clear(); // prevent accident use of invalid CallSites
Philip Reamesd16a9b12015-02-20 01:06:44 +00002260
Sanjoy Das25ec1a32015-10-16 02:41:00 +00002261 for (auto &PR : Replacements)
2262 PR.doReplacement();
2263
2264 Replacements.clear();
2265
2266 for (auto &Info : Records) {
2267 // These live sets may contain state Value pointers, since we replaced calls
2268 // with operand bundles with calls wrapped in gc.statepoint, and some of
2269 // those calls may have been def'ing live gc pointers. Clear these out to
2270 // avoid accidentally using them.
2271 //
2272 // TODO: We should create a separate data structure that does not contain
2273 // these live sets, and migrate to using that data structure from this point
2274 // onward.
2275 Info.LiveSet.clear();
2276 Info.PointerToBase.clear();
2277 }
2278
Philip Reamesd16a9b12015-02-20 01:06:44 +00002279 // Do all the fixups of the original live variables to their relocated selves
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002280 SmallVector<Value *, 128> Live;
2281 for (size_t i = 0; i < Records.size(); i++) {
2282 PartiallyConstructedSafepointRecord &Info = Records[i];
Sanjoy Das25ec1a32015-10-16 02:41:00 +00002283
Philip Reamesd16a9b12015-02-20 01:06:44 +00002284 // We can't simply save the live set from the original insertion. One of
2285 // the live values might be the result of a call which needs a safepoint.
2286 // That Value* no longer exists and we need to use the new gc_result.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002287 // Thankfully, the live set is embedded in the statepoint (and updated), so
Philip Reamesd16a9b12015-02-20 01:06:44 +00002288 // we just grab that.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002289 Statepoint Statepoint(Info.StatepointToken);
2290 Live.insert(Live.end(), Statepoint.gc_args_begin(),
2291 Statepoint.gc_args_end());
Philip Reames9a2e01d2015-04-13 17:35:55 +00002292#ifndef NDEBUG
2293 // Do some basic sanity checks on our liveness results before performing
2294 // relocation. Relocation can and will turn mistakes in liveness results
2295 // into non-sensical code which is must harder to debug.
2296 // TODO: It would be nice to test consistency as well
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002297 assert(DT.isReachableFromEntry(Info.StatepointToken->getParent()) &&
Philip Reames9a2e01d2015-04-13 17:35:55 +00002298 "statepoint must be reachable or liveness is meaningless");
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002299 for (Value *V : Statepoint.gc_args()) {
Philip Reames9a2e01d2015-04-13 17:35:55 +00002300 if (!isa<Instruction>(V))
2301 // Non-instruction values trivial dominate all possible uses
2302 continue;
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002303 auto *LiveInst = cast<Instruction>(V);
Philip Reames9a2e01d2015-04-13 17:35:55 +00002304 assert(DT.isReachableFromEntry(LiveInst->getParent()) &&
2305 "unreachable values should never be live");
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002306 assert(DT.dominates(LiveInst, Info.StatepointToken) &&
Philip Reames9a2e01d2015-04-13 17:35:55 +00002307 "basic SSA liveness expectation violated by liveness analysis");
2308 }
2309#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +00002310 }
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002311 unique_unsorted(Live);
Philip Reamesd16a9b12015-02-20 01:06:44 +00002312
Nick Lewyckyeb3231e2015-02-20 07:14:02 +00002313#ifndef NDEBUG
Philip Reamesd16a9b12015-02-20 01:06:44 +00002314 // sanity check
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002315 for (auto *Ptr : Live)
Philip Reames5715f572016-01-09 01:31:13 +00002316 assert(isHandledGCPointerType(Ptr->getType()) &&
2317 "must be a gc pointer type");
Nick Lewyckyeb3231e2015-02-20 07:14:02 +00002318#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +00002319
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002320 relocationViaAlloca(F, DT, Live, Records);
2321 return !Records.empty();
Philip Reamesd16a9b12015-02-20 01:06:44 +00002322}
2323
Sanjoy Das353a19e2015-06-02 22:33:37 +00002324// Handles both return values and arguments for Functions and CallSites.
2325template <typename AttrHolder>
Igor Laevskydde00292015-10-23 22:42:44 +00002326static void RemoveNonValidAttrAtIndex(LLVMContext &Ctx, AttrHolder &AH,
2327 unsigned Index) {
Sanjoy Das353a19e2015-06-02 22:33:37 +00002328 AttrBuilder R;
2329 if (AH.getDereferenceableBytes(Index))
2330 R.addAttribute(Attribute::get(Ctx, Attribute::Dereferenceable,
2331 AH.getDereferenceableBytes(Index)));
2332 if (AH.getDereferenceableOrNullBytes(Index))
2333 R.addAttribute(Attribute::get(Ctx, Attribute::DereferenceableOrNull,
2334 AH.getDereferenceableOrNullBytes(Index)));
Reid Klecknera0b45f42017-05-03 18:17:31 +00002335 if (AH.getAttributes().hasAttribute(Index, Attribute::NoAlias))
Igor Laevsky1ef06552015-10-26 19:06:01 +00002336 R.addAttribute(Attribute::NoAlias);
Sanjoy Das353a19e2015-06-02 22:33:37 +00002337
2338 if (!R.empty())
Reid Kleckneree4930b2017-05-02 22:07:37 +00002339 AH.setAttributes(AH.getAttributes().removeAttributes(Ctx, Index, R));
Vasileios Kalintiris9f77f612015-06-03 08:51:30 +00002340}
Sanjoy Das353a19e2015-06-02 22:33:37 +00002341
2342void
Igor Laevskydde00292015-10-23 22:42:44 +00002343RewriteStatepointsForGC::stripNonValidAttributesFromPrototype(Function &F) {
Sanjoy Das353a19e2015-06-02 22:33:37 +00002344 LLVMContext &Ctx = F.getContext();
2345
2346 for (Argument &A : F.args())
2347 if (isa<PointerType>(A.getType()))
Reid Klecknera0b45f42017-05-03 18:17:31 +00002348 RemoveNonValidAttrAtIndex(Ctx, F,
2349 A.getArgNo() + AttributeList::FirstArgIndex);
Sanjoy Das353a19e2015-06-02 22:33:37 +00002350
2351 if (isa<PointerType>(F.getReturnType()))
Reid Klecknerb5180542017-03-21 16:57:19 +00002352 RemoveNonValidAttrAtIndex(Ctx, F, AttributeList::ReturnIndex);
Sanjoy Das353a19e2015-06-02 22:33:37 +00002353}
2354
Anna Thomas4b027e82017-06-12 21:26:53 +00002355void RewriteStatepointsForGC::stripInvalidMetadataFromInstruction(Instruction &I) {
Anna Thomas4b027e82017-06-12 21:26:53 +00002356 if (!isa<LoadInst>(I) && !isa<StoreInst>(I))
2357 return;
2358 // These are the attributes that are still valid on loads and stores after
2359 // RS4GC.
2360 // The metadata implying dereferenceability and noalias are (conservatively)
2361 // dropped. This is because semantically, after RewriteStatepointsForGC runs,
2362 // all calls to gc.statepoint "free" the entire heap. Also, gc.statepoint can
2363 // touch the entire heap including noalias objects. Note: The reasoning is
2364 // same as stripping the dereferenceability and noalias attributes that are
2365 // analogous to the metadata counterparts.
2366 // We also drop the invariant.load metadata on the load because that metadata
2367 // implies the address operand to the load points to memory that is never
2368 // changed once it became dereferenceable. This is no longer true after RS4GC.
2369 // Similar reasoning applies to invariant.group metadata, which applies to
2370 // loads within a group.
2371 unsigned ValidMetadataAfterRS4GC[] = {LLVMContext::MD_tbaa,
2372 LLVMContext::MD_range,
2373 LLVMContext::MD_alias_scope,
2374 LLVMContext::MD_nontemporal,
2375 LLVMContext::MD_nonnull,
2376 LLVMContext::MD_align,
2377 LLVMContext::MD_type};
2378
2379 // Drops all metadata on the instruction other than ValidMetadataAfterRS4GC.
2380 I.dropUnknownNonDebugMetadata(ValidMetadataAfterRS4GC);
Anna Thomas4b027e82017-06-12 21:26:53 +00002381}
2382
2383void RewriteStatepointsForGC::stripNonValidAttributesAndMetadataFromBody(Function &F) {
Sanjoy Das353a19e2015-06-02 22:33:37 +00002384 if (F.empty())
2385 return;
2386
2387 LLVMContext &Ctx = F.getContext();
2388 MDBuilder Builder(Ctx);
2389
Nico Rieck78199512015-08-06 19:10:45 +00002390 for (Instruction &I : instructions(F)) {
Sanjoy Das353a19e2015-06-02 22:33:37 +00002391 if (const MDNode *MD = I.getMetadata(LLVMContext::MD_tbaa)) {
2392 assert(MD->getNumOperands() < 5 && "unrecognized metadata shape!");
2393 bool IsImmutableTBAA =
2394 MD->getNumOperands() == 4 &&
2395 mdconst::extract<ConstantInt>(MD->getOperand(3))->getValue() == 1;
2396
2397 if (!IsImmutableTBAA)
2398 continue; // no work to do, MD_tbaa is already marked mutable
2399
2400 MDNode *Base = cast<MDNode>(MD->getOperand(0));
2401 MDNode *Access = cast<MDNode>(MD->getOperand(1));
2402 uint64_t Offset =
2403 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue();
2404
2405 MDNode *MutableTBAA =
2406 Builder.createTBAAStructTagNode(Base, Access, Offset);
2407 I.setMetadata(LLVMContext::MD_tbaa, MutableTBAA);
2408 }
2409
Anna Thomas4b027e82017-06-12 21:26:53 +00002410 stripInvalidMetadataFromInstruction(I);
2411
Sanjoy Das353a19e2015-06-02 22:33:37 +00002412 if (CallSite CS = CallSite(&I)) {
2413 for (int i = 0, e = CS.arg_size(); i != e; i++)
2414 if (isa<PointerType>(CS.getArgument(i)->getType()))
Reid Klecknera0b45f42017-05-03 18:17:31 +00002415 RemoveNonValidAttrAtIndex(Ctx, CS, i + AttributeList::FirstArgIndex);
Sanjoy Das353a19e2015-06-02 22:33:37 +00002416 if (isa<PointerType>(CS.getType()))
Reid Klecknerb5180542017-03-21 16:57:19 +00002417 RemoveNonValidAttrAtIndex(Ctx, CS, AttributeList::ReturnIndex);
Sanjoy Das353a19e2015-06-02 22:33:37 +00002418 }
2419 }
2420}
2421
Philip Reamesd16a9b12015-02-20 01:06:44 +00002422/// Returns true if this function should be rewritten by this pass. The main
2423/// point of this function is as an extension point for custom logic.
2424static bool shouldRewriteStatepointsIn(Function &F) {
2425 // TODO: This should check the GCStrategy
Philip Reames2ef029c2015-02-20 18:56:14 +00002426 if (F.hasGC()) {
Mehdi Amini599ebf22016-01-08 02:28:20 +00002427 const auto &FunctionGCName = F.getGC();
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +00002428 const StringRef StatepointExampleName("statepoint-example");
2429 const StringRef CoreCLRName("coreclr");
2430 return (StatepointExampleName == FunctionGCName) ||
NAKAMURA Takumi5582a6a2015-05-25 01:43:34 +00002431 (CoreCLRName == FunctionGCName);
2432 } else
Philip Reames2ef029c2015-02-20 18:56:14 +00002433 return false;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002434}
2435
Anna Thomas4b027e82017-06-12 21:26:53 +00002436void RewriteStatepointsForGC::stripNonValidAttributesAndMetadata(Module &M) {
Sanjoy Das353a19e2015-06-02 22:33:37 +00002437#ifndef NDEBUG
Eugene Zelenko75075ef2017-09-01 21:37:29 +00002438 assert(llvm::any_of(M, shouldRewriteStatepointsIn) && "precondition!");
Sanjoy Das353a19e2015-06-02 22:33:37 +00002439#endif
2440
2441 for (Function &F : M)
Igor Laevskydde00292015-10-23 22:42:44 +00002442 stripNonValidAttributesFromPrototype(F);
Sanjoy Das353a19e2015-06-02 22:33:37 +00002443
2444 for (Function &F : M)
Anna Thomas4b027e82017-06-12 21:26:53 +00002445 stripNonValidAttributesAndMetadataFromBody(F);
Sanjoy Das353a19e2015-06-02 22:33:37 +00002446}
2447
Philip Reamesd16a9b12015-02-20 01:06:44 +00002448bool RewriteStatepointsForGC::runOnFunction(Function &F) {
2449 // Nothing to do for declarations.
2450 if (F.isDeclaration() || F.empty())
2451 return false;
2452
2453 // Policy choice says not to rewrite - the most common reason is that we're
2454 // compiling code without a GCStrategy.
2455 if (!shouldRewriteStatepointsIn(F))
2456 return false;
2457
Sanjoy Dasea45f0e2015-06-02 22:33:34 +00002458 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
Justin Bogner843fb202015-12-15 19:40:57 +00002459 TargetTransformInfo &TTI =
2460 getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
Daniel Neilson2574d7c2017-07-27 16:49:39 +00002461 const TargetLibraryInfo &TLI =
2462 getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Philip Reames704e78b2015-04-10 22:34:56 +00002463
Daniel Neilson2574d7c2017-07-27 16:49:39 +00002464 auto NeedsRewrite = [&TLI](Instruction &I) {
Sanjoy Das40992972016-01-29 01:03:17 +00002465 if (ImmutableCallSite CS = ImmutableCallSite(&I))
Daniel Neilson2574d7c2017-07-27 16:49:39 +00002466 return !callsGCLeafFunction(CS, TLI) && !isStatepoint(CS);
Sanjoy Das40992972016-01-29 01:03:17 +00002467 return false;
Sanjoy Das25ec1a32015-10-16 02:41:00 +00002468 };
2469
Philip Reames85b36a82015-04-10 22:07:04 +00002470 // Gather all the statepoints which need rewritten. Be careful to only
2471 // consider those in reachable code since we need to ask dominance queries
2472 // when rewriting. We'll delete the unreachable ones in a moment.
Philip Reamesd2b66462015-02-20 22:39:41 +00002473 SmallVector<CallSite, 64> ParsePointNeeded;
Philip Reamesf66d7372015-04-10 22:16:58 +00002474 bool HasUnreachableStatepoint = false;
Nico Rieck78199512015-08-06 19:10:45 +00002475 for (Instruction &I : instructions(F)) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00002476 // TODO: only the ones with the flag set!
Sanjoy Das25ec1a32015-10-16 02:41:00 +00002477 if (NeedsRewrite(I)) {
Philip Reames85b36a82015-04-10 22:07:04 +00002478 if (DT.isReachableFromEntry(I.getParent()))
2479 ParsePointNeeded.push_back(CallSite(&I));
2480 else
Philip Reamesf66d7372015-04-10 22:16:58 +00002481 HasUnreachableStatepoint = true;
Philip Reames85b36a82015-04-10 22:07:04 +00002482 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00002483 }
2484
Philip Reames85b36a82015-04-10 22:07:04 +00002485 bool MadeChange = false;
Philip Reames704e78b2015-04-10 22:34:56 +00002486
Philip Reames85b36a82015-04-10 22:07:04 +00002487 // Delete any unreachable statepoints so that we don't have unrewritten
2488 // statepoints surviving this pass. This makes testing easier and the
2489 // resulting IR less confusing to human readers. Rather than be fancy, we
2490 // just reuse a utility function which removes the unreachable blocks.
Philip Reamesf66d7372015-04-10 22:16:58 +00002491 if (HasUnreachableStatepoint)
Philip Reames85b36a82015-04-10 22:07:04 +00002492 MadeChange |= removeUnreachableBlocks(F);
2493
Philip Reamesd16a9b12015-02-20 01:06:44 +00002494 // Return early if no work to do.
2495 if (ParsePointNeeded.empty())
Philip Reames85b36a82015-04-10 22:07:04 +00002496 return MadeChange;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002497
Philip Reames85b36a82015-04-10 22:07:04 +00002498 // As a prepass, go ahead and aggressively destroy single entry phi nodes.
2499 // These are created by LCSSA. They have the effect of increasing the size
2500 // of liveness sets for no good reason. It may be harder to do this post
2501 // insertion since relocations and base phis can confuse things.
2502 for (BasicBlock &BB : F)
2503 if (BB.getUniquePredecessor()) {
2504 MadeChange = true;
2505 FoldSingleEntryPHINodes(&BB);
2506 }
2507
Philip Reames971dc3a2015-08-12 22:11:45 +00002508 // Before we start introducing relocations, we want to tweak the IR a bit to
2509 // avoid unfortunate code generation effects. The main example is that we
2510 // want to try to make sure the comparison feeding a branch is after any
2511 // safepoints. Otherwise, we end up with a comparison of pre-relocation
2512 // values feeding a branch after relocation. This is semantically correct,
2513 // but results in extra register pressure since both the pre-relocation and
2514 // post-relocation copies must be available in registers. For code without
2515 // relocations this is handled elsewhere, but teaching the scheduler to
2516 // reverse the transform we're about to do would be slightly complex.
2517 // Note: This may extend the live range of the inputs to the icmp and thus
2518 // increase the liveset of any statepoint we move over. This is profitable
2519 // as long as all statepoints are in rare blocks. If we had in-register
2520 // lowering for live values this would be a much safer transform.
2521 auto getConditionInst = [](TerminatorInst *TI) -> Instruction* {
2522 if (auto *BI = dyn_cast<BranchInst>(TI))
2523 if (BI->isConditional())
2524 return dyn_cast<Instruction>(BI->getCondition());
2525 // TODO: Extend this to handle switches
2526 return nullptr;
2527 };
2528 for (BasicBlock &BB : F) {
2529 TerminatorInst *TI = BB.getTerminator();
2530 if (auto *Cond = getConditionInst(TI))
2531 // TODO: Handle more than just ICmps here. We should be able to move
2532 // most instructions without side effects or memory access.
2533 if (isa<ICmpInst>(Cond) && Cond->hasOneUse()) {
2534 MadeChange = true;
2535 Cond->moveBefore(TI);
2536 }
2537 }
2538
Justin Bogner843fb202015-12-15 19:40:57 +00002539 MadeChange |= insertParsePoints(F, DT, TTI, ParsePointNeeded);
Philip Reames85b36a82015-04-10 22:07:04 +00002540 return MadeChange;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002541}
Philip Reamesdf1ef082015-04-10 22:53:14 +00002542
2543// liveness computation via standard dataflow
2544// -------------------------------------------------------------------
2545
2546// TODO: Consider using bitvectors for liveness, the set of potentially
2547// interesting values should be small and easy to pre-compute.
2548
Philip Reamesdf1ef082015-04-10 22:53:14 +00002549/// Compute the live-in set for the location rbegin starting from
2550/// the live-out set of the basic block
Sanjoy Das61c76e32016-06-26 04:55:32 +00002551static void computeLiveInValues(BasicBlock::reverse_iterator Begin,
2552 BasicBlock::reverse_iterator End,
Igor Laevskyfb1811d2016-05-04 14:55:36 +00002553 SetVector<Value *> &LiveTmp) {
Sanjoy Das61c76e32016-06-26 04:55:32 +00002554 for (auto &I : make_range(Begin, End)) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00002555 // KILL/Def - Remove this definition from LiveIn
Sanjoy Das61c76e32016-06-26 04:55:32 +00002556 LiveTmp.remove(&I);
Philip Reamesdf1ef082015-04-10 22:53:14 +00002557
2558 // Don't consider *uses* in PHI nodes, we handle their contribution to
2559 // predecessor blocks when we seed the LiveOut sets
2560 if (isa<PHINode>(I))
2561 continue;
2562
2563 // USE - Add to the LiveIn set for this instruction
Sanjoy Das61c76e32016-06-26 04:55:32 +00002564 for (Value *V : I.operands()) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00002565 assert(!isUnhandledGCPointerType(V->getType()) &&
2566 "support for FCA unimplemented");
Philip Reames63294cb2015-04-26 19:48:03 +00002567 if (isHandledGCPointerType(V->getType()) && !isa<Constant>(V)) {
2568 // The choice to exclude all things constant here is slightly subtle.
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002569 // There are two independent reasons:
Philip Reames63294cb2015-04-26 19:48:03 +00002570 // - We assume that things which are constant (from LLVM's definition)
2571 // do not move at runtime. For example, the address of a global
2572 // variable is fixed, even though it's contents may not be.
2573 // - Second, we can't disallow arbitrary inttoptr constants even
2574 // if the language frontend does. Optimization passes are free to
2575 // locally exploit facts without respect to global reachability. This
2576 // can create sections of code which are dynamically unreachable and
2577 // contain just about anything. (see constants.ll in tests)
Philip Reamesdf1ef082015-04-10 22:53:14 +00002578 LiveTmp.insert(V);
2579 }
2580 }
2581 }
2582}
2583
Igor Laevskyfb1811d2016-05-04 14:55:36 +00002584static void computeLiveOutSeed(BasicBlock *BB, SetVector<Value *> &LiveTmp) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00002585 for (BasicBlock *Succ : successors(BB)) {
Sanjoy Das83186b02016-06-26 04:55:30 +00002586 for (auto &I : *Succ) {
2587 PHINode *PN = dyn_cast<PHINode>(&I);
2588 if (!PN)
2589 break;
2590
2591 Value *V = PN->getIncomingValueForBlock(BB);
Philip Reamesdf1ef082015-04-10 22:53:14 +00002592 assert(!isUnhandledGCPointerType(V->getType()) &&
2593 "support for FCA unimplemented");
Sanjoy Das83186b02016-06-26 04:55:30 +00002594 if (isHandledGCPointerType(V->getType()) && !isa<Constant>(V))
Philip Reamesdf1ef082015-04-10 22:53:14 +00002595 LiveTmp.insert(V);
Philip Reamesdf1ef082015-04-10 22:53:14 +00002596 }
2597 }
2598}
2599
Igor Laevskyfb1811d2016-05-04 14:55:36 +00002600static SetVector<Value *> computeKillSet(BasicBlock *BB) {
2601 SetVector<Value *> KillSet;
Philip Reamesdf1ef082015-04-10 22:53:14 +00002602 for (Instruction &I : *BB)
2603 if (isHandledGCPointerType(I.getType()))
2604 KillSet.insert(&I);
2605 return KillSet;
2606}
2607
Philip Reames9638ff92015-04-11 00:06:47 +00002608#ifndef NDEBUG
Philip Reamesdf1ef082015-04-10 22:53:14 +00002609/// Check that the items in 'Live' dominate 'TI'. This is used as a basic
2610/// sanity check for the liveness computation.
Igor Laevskyfb1811d2016-05-04 14:55:36 +00002611static void checkBasicSSA(DominatorTree &DT, SetVector<Value *> &Live,
Philip Reamesdf1ef082015-04-10 22:53:14 +00002612 TerminatorInst *TI, bool TermOkay = false) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00002613 for (Value *V : Live) {
2614 if (auto *I = dyn_cast<Instruction>(V)) {
2615 // The terminator can be a member of the LiveOut set. LLVM's definition
2616 // of instruction dominance states that V does not dominate itself. As
2617 // such, we need to special case this to allow it.
2618 if (TermOkay && TI == I)
2619 continue;
2620 assert(DT.dominates(I, TI) &&
2621 "basic SSA liveness expectation violated by liveness analysis");
2622 }
2623 }
Philip Reamesdf1ef082015-04-10 22:53:14 +00002624}
2625
2626/// Check that all the liveness sets used during the computation of liveness
2627/// obey basic SSA properties. This is useful for finding cases where we miss
2628/// a def.
2629static void checkBasicSSA(DominatorTree &DT, GCPtrLivenessData &Data,
2630 BasicBlock &BB) {
2631 checkBasicSSA(DT, Data.LiveSet[&BB], BB.getTerminator());
2632 checkBasicSSA(DT, Data.LiveOut[&BB], BB.getTerminator(), true);
2633 checkBasicSSA(DT, Data.LiveIn[&BB], BB.getTerminator());
2634}
Philip Reames9638ff92015-04-11 00:06:47 +00002635#endif
Philip Reamesdf1ef082015-04-10 22:53:14 +00002636
2637static void computeLiveInValues(DominatorTree &DT, Function &F,
2638 GCPtrLivenessData &Data) {
Matthias Braunb30f2f512016-01-30 01:24:31 +00002639 SmallSetVector<BasicBlock *, 32> Worklist;
Philip Reamesdf1ef082015-04-10 22:53:14 +00002640
2641 // Seed the liveness for each individual block
2642 for (BasicBlock &BB : F) {
2643 Data.KillSet[&BB] = computeKillSet(&BB);
2644 Data.LiveSet[&BB].clear();
2645 computeLiveInValues(BB.rbegin(), BB.rend(), Data.LiveSet[&BB]);
2646
2647#ifndef NDEBUG
2648 for (Value *Kill : Data.KillSet[&BB])
2649 assert(!Data.LiveSet[&BB].count(Kill) && "live set contains kill");
2650#endif
2651
Igor Laevskyfb1811d2016-05-04 14:55:36 +00002652 Data.LiveOut[&BB] = SetVector<Value *>();
Philip Reamesdf1ef082015-04-10 22:53:14 +00002653 computeLiveOutSeed(&BB, Data.LiveOut[&BB]);
2654 Data.LiveIn[&BB] = Data.LiveSet[&BB];
Igor Laevskyfb1811d2016-05-04 14:55:36 +00002655 Data.LiveIn[&BB].set_union(Data.LiveOut[&BB]);
2656 Data.LiveIn[&BB].set_subtract(Data.KillSet[&BB]);
Philip Reamesdf1ef082015-04-10 22:53:14 +00002657 if (!Data.LiveIn[&BB].empty())
Sanjoy Dasb2df57a2016-06-26 04:55:26 +00002658 Worklist.insert(pred_begin(&BB), pred_end(&BB));
Philip Reamesdf1ef082015-04-10 22:53:14 +00002659 }
2660
2661 // Propagate that liveness until stable
2662 while (!Worklist.empty()) {
Sanjoy Dasb2df57a2016-06-26 04:55:26 +00002663 BasicBlock *BB = Worklist.pop_back_val();
Philip Reamesdf1ef082015-04-10 22:53:14 +00002664
Sanjoy Dasb2df57a2016-06-26 04:55:26 +00002665 // Compute our new liveout set, then exit early if it hasn't changed despite
2666 // the contribution of our successor.
Igor Laevskyfb1811d2016-05-04 14:55:36 +00002667 SetVector<Value *> LiveOut = Data.LiveOut[BB];
Philip Reamesdf1ef082015-04-10 22:53:14 +00002668 const auto OldLiveOutSize = LiveOut.size();
2669 for (BasicBlock *Succ : successors(BB)) {
2670 assert(Data.LiveIn.count(Succ));
Igor Laevskyfb1811d2016-05-04 14:55:36 +00002671 LiveOut.set_union(Data.LiveIn[Succ]);
Philip Reamesdf1ef082015-04-10 22:53:14 +00002672 }
2673 // assert OutLiveOut is a subset of LiveOut
2674 if (OldLiveOutSize == LiveOut.size()) {
2675 // If the sets are the same size, then we didn't actually add anything
Sanjoy Dasb2df57a2016-06-26 04:55:26 +00002676 // when unioning our successors LiveIn. Thus, the LiveIn of this block
Philip Reamesdf1ef082015-04-10 22:53:14 +00002677 // hasn't changed.
2678 continue;
2679 }
2680 Data.LiveOut[BB] = LiveOut;
2681
2682 // Apply the effects of this basic block
Igor Laevskyfb1811d2016-05-04 14:55:36 +00002683 SetVector<Value *> LiveTmp = LiveOut;
2684 LiveTmp.set_union(Data.LiveSet[BB]);
2685 LiveTmp.set_subtract(Data.KillSet[BB]);
Philip Reamesdf1ef082015-04-10 22:53:14 +00002686
2687 assert(Data.LiveIn.count(BB));
Igor Laevskyfb1811d2016-05-04 14:55:36 +00002688 const SetVector<Value *> &OldLiveIn = Data.LiveIn[BB];
Philip Reamesdf1ef082015-04-10 22:53:14 +00002689 // assert: OldLiveIn is a subset of LiveTmp
2690 if (OldLiveIn.size() != LiveTmp.size()) {
2691 Data.LiveIn[BB] = LiveTmp;
Sanjoy Dasb2df57a2016-06-26 04:55:26 +00002692 Worklist.insert(pred_begin(BB), pred_end(BB));
Philip Reamesdf1ef082015-04-10 22:53:14 +00002693 }
Sanjoy Dasb2df57a2016-06-26 04:55:26 +00002694 } // while (!Worklist.empty())
Philip Reamesdf1ef082015-04-10 22:53:14 +00002695
2696#ifndef NDEBUG
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002697 // Sanity check our output against SSA properties. This helps catch any
Philip Reamesdf1ef082015-04-10 22:53:14 +00002698 // missing kills during the above iteration.
Sanjoy Dasb2df57a2016-06-26 04:55:26 +00002699 for (BasicBlock &BB : F)
Philip Reamesdf1ef082015-04-10 22:53:14 +00002700 checkBasicSSA(DT, Data, BB);
Philip Reamesdf1ef082015-04-10 22:53:14 +00002701#endif
2702}
2703
2704static void findLiveSetAtInst(Instruction *Inst, GCPtrLivenessData &Data,
2705 StatepointLiveSetTy &Out) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00002706 BasicBlock *BB = Inst->getParent();
2707
2708 // Note: The copy is intentional and required
2709 assert(Data.LiveOut.count(BB));
Igor Laevskyfb1811d2016-05-04 14:55:36 +00002710 SetVector<Value *> LiveOut = Data.LiveOut[BB];
Philip Reamesdf1ef082015-04-10 22:53:14 +00002711
2712 // We want to handle the statepoint itself oddly. It's
2713 // call result is not live (normal), nor are it's arguments
2714 // (unless they're used again later). This adjustment is
2715 // specifically what we need to relocate
Duncan P. N. Exon Smith5c001c32016-08-30 00:13:12 +00002716 computeLiveInValues(BB->rbegin(), ++Inst->getIterator().getReverse(),
2717 LiveOut);
Igor Laevskyfb1811d2016-05-04 14:55:36 +00002718 LiveOut.remove(Inst);
Philip Reamesdf1ef082015-04-10 22:53:14 +00002719 Out.insert(LiveOut.begin(), LiveOut.end());
2720}
2721
2722static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData,
Sanjoy Dasa3244872016-06-17 00:45:00 +00002723 CallSite CS,
Philip Reamesdf1ef082015-04-10 22:53:14 +00002724 PartiallyConstructedSafepointRecord &Info) {
2725 Instruction *Inst = CS.getInstruction();
2726 StatepointLiveSetTy Updated;
2727 findLiveSetAtInst(Inst, RevisedLivenessData, Updated);
2728
2729#ifndef NDEBUG
2730 DenseSet<Value *> Bases;
Sanjoy Das255532f2016-06-26 04:55:23 +00002731 for (auto KVPair : Info.PointerToBase)
Philip Reamesdf1ef082015-04-10 22:53:14 +00002732 Bases.insert(KVPair.second);
Philip Reamesdf1ef082015-04-10 22:53:14 +00002733#endif
Sanjoy Das255532f2016-06-26 04:55:23 +00002734
Philip Reamesdf1ef082015-04-10 22:53:14 +00002735 // We may have base pointers which are now live that weren't before. We need
2736 // to update the PointerToBase structure to reflect this.
2737 for (auto V : Updated)
Sanjoy Das255532f2016-06-26 04:55:23 +00002738 if (Info.PointerToBase.insert({V, V}).second) {
2739 assert(Bases.count(V) && "Can't find base for unexpected live value!");
Philip Reamesdf1ef082015-04-10 22:53:14 +00002740 continue;
2741 }
2742
2743#ifndef NDEBUG
Sanjoy Das255532f2016-06-26 04:55:23 +00002744 for (auto V : Updated)
Philip Reamesdf1ef082015-04-10 22:53:14 +00002745 assert(Info.PointerToBase.count(V) &&
Sanjoy Das255532f2016-06-26 04:55:23 +00002746 "Must be able to find base for live value!");
Philip Reamesdf1ef082015-04-10 22:53:14 +00002747#endif
2748
2749 // Remove any stale base mappings - this can happen since our liveness is
Sanjoy Das255532f2016-06-26 04:55:23 +00002750 // more precise then the one inherent in the base pointer analysis.
Philip Reamesdf1ef082015-04-10 22:53:14 +00002751 DenseSet<Value *> ToErase;
2752 for (auto KVPair : Info.PointerToBase)
2753 if (!Updated.count(KVPair.first))
2754 ToErase.insert(KVPair.first);
Sanjoy Das255532f2016-06-26 04:55:23 +00002755
2756 for (auto *V : ToErase)
Philip Reamesdf1ef082015-04-10 22:53:14 +00002757 Info.PointerToBase.erase(V);
2758
2759#ifndef NDEBUG
2760 for (auto KVPair : Info.PointerToBase)
2761 assert(Updated.count(KVPair.first) && "record for non-live value");
2762#endif
2763
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002764 Info.LiveSet = Updated;
Philip Reamesdf1ef082015-04-10 22:53:14 +00002765}