blob: 47d226f83a42626ca637e45c695edf5e4d6ecf3f [file] [log] [blame]
Philip Reamesd16a9b12015-02-20 01:06:44 +00001//===- RewriteStatepointsForGC.cpp - Make GC relocations explicit ---------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Philip Reamesd16a9b12015-02-20 01:06:44 +00006//
7//===----------------------------------------------------------------------===//
8//
Philip Reamesae800452017-06-02 01:52:06 +00009// Rewrite call/invoke instructions so as to make potential relocations
10// performed by the garbage collector explicit in the IR.
Philip Reamesd16a9b12015-02-20 01:06:44 +000011//
12//===----------------------------------------------------------------------===//
13
Fedor Sergeev4b86d792017-12-15 09:32:11 +000014#include "llvm/Transforms/Scalar/RewriteStatepointsForGC.h"
15
Eugene Zelenko75075ef2017-09-01 21:37:29 +000016#include "llvm/ADT/ArrayRef.h"
17#include "llvm/ADT/DenseMap.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000018#include "llvm/ADT/DenseSet.h"
19#include "llvm/ADT/MapVector.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000020#include "llvm/ADT/None.h"
21#include "llvm/ADT/Optional.h"
22#include "llvm/ADT/STLExtras.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000023#include "llvm/ADT/SetVector.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000024#include "llvm/ADT/SmallSet.h"
25#include "llvm/ADT/SmallVector.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000026#include "llvm/ADT/StringRef.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000027#include "llvm/ADT/iterator_range.h"
Richard Trieu5f436fc2019-02-06 02:52:52 +000028#include "llvm/Analysis/DomTreeUpdater.h"
Daniel Neilson2574d7c2017-07-27 16:49:39 +000029#include "llvm/Analysis/TargetLibraryInfo.h"
Igor Laevskye0317182015-05-19 15:59:05 +000030#include "llvm/Analysis/TargetTransformInfo.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000031#include "llvm/IR/Argument.h"
32#include "llvm/IR/Attributes.h"
Philip Reamesd16a9b12015-02-20 01:06:44 +000033#include "llvm/IR/BasicBlock.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000034#include "llvm/IR/CallingConv.h"
35#include "llvm/IR/Constant.h"
36#include "llvm/IR/Constants.h"
37#include "llvm/IR/DataLayout.h"
38#include "llvm/IR/DerivedTypes.h"
Philip Reamesd16a9b12015-02-20 01:06:44 +000039#include "llvm/IR/Dominators.h"
40#include "llvm/IR/Function.h"
41#include "llvm/IR/IRBuilder.h"
42#include "llvm/IR/InstIterator.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000043#include "llvm/IR/InstrTypes.h"
44#include "llvm/IR/Instruction.h"
Philip Reamesd16a9b12015-02-20 01:06:44 +000045#include "llvm/IR/Instructions.h"
Philip Reamesd16a9b12015-02-20 01:06:44 +000046#include "llvm/IR/IntrinsicInst.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000047#include "llvm/IR/Intrinsics.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000048#include "llvm/IR/LLVMContext.h"
Sanjoy Das353a19e2015-06-02 22:33:37 +000049#include "llvm/IR/MDBuilder.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000050#include "llvm/IR/Metadata.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000051#include "llvm/IR/Module.h"
Philip Reamesd16a9b12015-02-20 01:06:44 +000052#include "llvm/IR/Statepoint.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000053#include "llvm/IR/Type.h"
54#include "llvm/IR/User.h"
Philip Reamesd16a9b12015-02-20 01:06:44 +000055#include "llvm/IR/Value.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000056#include "llvm/IR/ValueHandle.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000057#include "llvm/Pass.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000058#include "llvm/Support/Casting.h"
Philip Reamesd16a9b12015-02-20 01:06:44 +000059#include "llvm/Support/CommandLine.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000060#include "llvm/Support/Compiler.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000061#include "llvm/Support/Debug.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000062#include "llvm/Support/ErrorHandling.h"
63#include "llvm/Support/raw_ostream.h"
Philip Reamesd16a9b12015-02-20 01:06:44 +000064#include "llvm/Transforms/Scalar.h"
65#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chijun Sima21a8b602018-08-03 05:08:17 +000066#include "llvm/Transforms/Utils/Local.h"
Philip Reamesd16a9b12015-02-20 01:06:44 +000067#include "llvm/Transforms/Utils/PromoteMemToReg.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000068#include <algorithm>
69#include <cassert>
70#include <cstddef>
71#include <cstdint>
72#include <iterator>
73#include <set>
74#include <string>
75#include <utility>
76#include <vector>
Philip Reamesd16a9b12015-02-20 01:06:44 +000077
78#define DEBUG_TYPE "rewrite-statepoints-for-gc"
79
80using namespace llvm;
81
Philip Reamesd16a9b12015-02-20 01:06:44 +000082// Print the liveset found at the insert location
83static cl::opt<bool> PrintLiveSet("spp-print-liveset", cl::Hidden,
84 cl::init(false));
Philip Reames704e78b2015-04-10 22:34:56 +000085static cl::opt<bool> PrintLiveSetSize("spp-print-liveset-size", cl::Hidden,
86 cl::init(false));
Eugene Zelenko75075ef2017-09-01 21:37:29 +000087
Philip Reamesd16a9b12015-02-20 01:06:44 +000088// Print out the base pointers for debugging
Philip Reames704e78b2015-04-10 22:34:56 +000089static cl::opt<bool> PrintBasePointers("spp-print-base-pointers", cl::Hidden,
90 cl::init(false));
Philip Reamesd16a9b12015-02-20 01:06:44 +000091
Igor Laevskye0317182015-05-19 15:59:05 +000092// Cost threshold measuring when it is profitable to rematerialize value instead
93// of relocating it
94static cl::opt<unsigned>
95RematerializationThreshold("spp-rematerialization-threshold", cl::Hidden,
96 cl::init(6));
97
Filipe Cabecinhas0da99372016-04-29 15:22:48 +000098#ifdef EXPENSIVE_CHECKS
Philip Reamese73300b2015-04-13 16:41:32 +000099static bool ClobberNonLive = true;
100#else
101static bool ClobberNonLive = false;
102#endif
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000103
Philip Reamese73300b2015-04-13 16:41:32 +0000104static cl::opt<bool, true> ClobberNonLiveOverride("rs4gc-clobber-non-live",
105 cl::location(ClobberNonLive),
106 cl::Hidden);
107
Sanjoy Das25ec1a32015-10-16 02:41:00 +0000108static cl::opt<bool>
109 AllowStatepointWithNoDeoptInfo("rs4gc-allow-statepoint-with-no-deopt-info",
110 cl::Hidden, cl::init(true));
111
Fedor Sergeev4b86d792017-12-15 09:32:11 +0000112/// The IR fed into RewriteStatepointsForGC may have had attributes and
113/// metadata implying dereferenceability that are no longer valid/correct after
114/// RewriteStatepointsForGC has run. This is because semantically, after
115/// RewriteStatepointsForGC runs, all calls to gc.statepoint "free" the entire
116/// heap. stripNonValidData (conservatively) restores
117/// correctness by erasing all attributes in the module that externally imply
118/// dereferenceability. Similar reasoning also applies to the noalias
119/// attributes and metadata. gc.statepoint can touch the entire heap including
120/// noalias objects.
121/// Apart from attributes and metadata, we also remove instructions that imply
122/// constant physical memory: llvm.invariant.start.
123static void stripNonValidData(Module &M);
124
125static bool shouldRewriteStatepointsIn(Function &F);
126
127PreservedAnalyses RewriteStatepointsForGC::run(Module &M,
128 ModuleAnalysisManager &AM) {
129 bool Changed = false;
130 auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
131 for (Function &F : M) {
132 // Nothing to do for declarations.
133 if (F.isDeclaration() || F.empty())
134 continue;
135
136 // Policy choice says not to rewrite - the most common reason is that we're
137 // compiling code without a GCStrategy.
138 if (!shouldRewriteStatepointsIn(F))
139 continue;
140
141 auto &DT = FAM.getResult<DominatorTreeAnalysis>(F);
142 auto &TTI = FAM.getResult<TargetIRAnalysis>(F);
143 auto &TLI = FAM.getResult<TargetLibraryAnalysis>(F);
144 Changed |= runOnFunction(F, DT, TTI, TLI);
145 }
146 if (!Changed)
147 return PreservedAnalyses::all();
148
149 // stripNonValidData asserts that shouldRewriteStatepointsIn
150 // returns true for at least one function in the module. Since at least
151 // one function changed, we know that the precondition is satisfied.
152 stripNonValidData(M);
153
154 PreservedAnalyses PA;
155 PA.preserve<TargetIRAnalysis>();
156 PA.preserve<TargetLibraryAnalysis>();
157 return PA;
158}
159
Benjamin Kramer6f665452015-02-20 14:00:58 +0000160namespace {
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000161
Fedor Sergeev4b86d792017-12-15 09:32:11 +0000162class RewriteStatepointsForGCLegacyPass : public ModulePass {
163 RewriteStatepointsForGC Impl;
164
165public:
Philip Reamesd16a9b12015-02-20 01:06:44 +0000166 static char ID; // Pass identification, replacement for typeid
167
Fedor Sergeev4b86d792017-12-15 09:32:11 +0000168 RewriteStatepointsForGCLegacyPass() : ModulePass(ID), Impl() {
169 initializeRewriteStatepointsForGCLegacyPassPass(
170 *PassRegistry::getPassRegistry());
Philip Reamesd16a9b12015-02-20 01:06:44 +0000171 }
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000172
Sanjoy Dasea45f0e2015-06-02 22:33:34 +0000173 bool runOnModule(Module &M) override {
174 bool Changed = false;
Fedor Sergeev4b86d792017-12-15 09:32:11 +0000175 for (Function &F : M) {
176 // Nothing to do for declarations.
177 if (F.isDeclaration() || F.empty())
178 continue;
Sanjoy Das353a19e2015-06-02 22:33:37 +0000179
Fedor Sergeev4b86d792017-12-15 09:32:11 +0000180 // Policy choice says not to rewrite - the most common reason is that
181 // we're compiling code without a GCStrategy.
182 if (!shouldRewriteStatepointsIn(F))
183 continue;
184
185 TargetTransformInfo &TTI =
186 getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
Teresa Johnson9c27b592019-09-07 03:09:36 +0000187 const TargetLibraryInfo &TLI =
188 getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
Fedor Sergeev4b86d792017-12-15 09:32:11 +0000189 auto &DT = getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
190
191 Changed |= Impl.runOnFunction(F, DT, TTI, TLI);
Sanjoy Das353a19e2015-06-02 22:33:37 +0000192 }
193
Fedor Sergeev4b86d792017-12-15 09:32:11 +0000194 if (!Changed)
195 return false;
196
197 // stripNonValidData asserts that shouldRewriteStatepointsIn
198 // returns true for at least one function in the module. Since at least
199 // one function changed, we know that the precondition is satisfied.
200 stripNonValidData(M);
201 return true;
Sanjoy Dasea45f0e2015-06-02 22:33:34 +0000202 }
Philip Reamesd16a9b12015-02-20 01:06:44 +0000203
204 void getAnalysisUsage(AnalysisUsage &AU) const override {
205 // We add and rewrite a bunch of instructions, but don't really do much
206 // else. We could in theory preserve a lot more analyses here.
207 AU.addRequired<DominatorTreeWrapperPass>();
Igor Laevskye0317182015-05-19 15:59:05 +0000208 AU.addRequired<TargetTransformInfoWrapperPass>();
Daniel Neilson2574d7c2017-07-27 16:49:39 +0000209 AU.addRequired<TargetLibraryInfoWrapperPass>();
Philip Reamesd16a9b12015-02-20 01:06:44 +0000210 }
211};
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000212
213} // end anonymous namespace
Philip Reamesd16a9b12015-02-20 01:06:44 +0000214
Fedor Sergeev4b86d792017-12-15 09:32:11 +0000215char RewriteStatepointsForGCLegacyPass::ID = 0;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000216
Fedor Sergeev4b86d792017-12-15 09:32:11 +0000217ModulePass *llvm::createRewriteStatepointsForGCLegacyPass() {
218 return new RewriteStatepointsForGCLegacyPass();
Philip Reamesd16a9b12015-02-20 01:06:44 +0000219}
220
Fedor Sergeev4b86d792017-12-15 09:32:11 +0000221INITIALIZE_PASS_BEGIN(RewriteStatepointsForGCLegacyPass,
222 "rewrite-statepoints-for-gc",
Philip Reamesd16a9b12015-02-20 01:06:44 +0000223 "Make relocations explicit at statepoints", false, false)
224INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Davide Italiano6f852ee2016-05-16 02:29:53 +0000225INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
Fedor Sergeev4b86d792017-12-15 09:32:11 +0000226INITIALIZE_PASS_END(RewriteStatepointsForGCLegacyPass,
227 "rewrite-statepoints-for-gc",
Philip Reamesd16a9b12015-02-20 01:06:44 +0000228 "Make relocations explicit at statepoints", false, false)
229
230namespace {
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000231
Philip Reamesdf1ef082015-04-10 22:53:14 +0000232struct GCPtrLivenessData {
233 /// Values defined in this block.
Igor Laevskyfb1811d2016-05-04 14:55:36 +0000234 MapVector<BasicBlock *, SetVector<Value *>> KillSet;
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000235
Philip Reamesdf1ef082015-04-10 22:53:14 +0000236 /// Values used in this block (and thus live); does not included values
237 /// killed within this block.
Igor Laevskyfb1811d2016-05-04 14:55:36 +0000238 MapVector<BasicBlock *, SetVector<Value *>> LiveSet;
Philip Reamesdf1ef082015-04-10 22:53:14 +0000239
240 /// Values live into this basic block (i.e. used by any
241 /// instruction in this basic block or ones reachable from here)
Igor Laevskyfb1811d2016-05-04 14:55:36 +0000242 MapVector<BasicBlock *, SetVector<Value *>> LiveIn;
Philip Reamesdf1ef082015-04-10 22:53:14 +0000243
244 /// Values live out of this basic block (i.e. live into
245 /// any successor block)
Igor Laevskyfb1811d2016-05-04 14:55:36 +0000246 MapVector<BasicBlock *, SetVector<Value *>> LiveOut;
Philip Reamesdf1ef082015-04-10 22:53:14 +0000247};
248
Philip Reamesd16a9b12015-02-20 01:06:44 +0000249// The type of the internal cache used inside the findBasePointers family
250// of functions. From the callers perspective, this is an opaque type and
251// should not be inspected.
252//
253// In the actual implementation this caches two relations:
254// - The base relation itself (i.e. this pointer is based on that one)
255// - The base defining value relation (i.e. before base_phi insertion)
256// Generally, after the execution of a full findBasePointer call, only the
257// base relation will remain. Internally, we add a mixture of the two
258// types, then update all the second type to the first type
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000259using DefiningValueMapTy = MapVector<Value *, Value *>;
260using StatepointLiveSetTy = SetVector<Value *>;
261using RematerializedValueMapTy =
262 MapVector<AssertingVH<Instruction>, AssertingVH<Value>>;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000263
Philip Reamesd16a9b12015-02-20 01:06:44 +0000264struct PartiallyConstructedSafepointRecord {
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000265 /// The set of values known to be live across this safepoint
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +0000266 StatepointLiveSetTy LiveSet;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000267
268 /// Mapping from live pointers to a base-defining-value
Igor Laevskyfb1811d2016-05-04 14:55:36 +0000269 MapVector<Value *, Value *> PointerToBase;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000270
Philip Reames0a3240f2015-02-20 21:34:11 +0000271 /// The *new* gc.statepoint instruction itself. This produces the token
272 /// that normal path gc.relocates and the gc.result are tied to.
273 Instruction *StatepointToken;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000274
Philip Reamesf2041322015-02-20 19:26:04 +0000275 /// Instruction to which exceptional gc relocates are attached
276 /// Makes it easier to iterate through them during relocationViaAlloca.
277 Instruction *UnwindToken;
Igor Laevskye0317182015-05-19 15:59:05 +0000278
279 /// Record live values we are rematerialized instead of relocating.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +0000280 /// They are not included into 'LiveSet' field.
Igor Laevskye0317182015-05-19 15:59:05 +0000281 /// Maps rematerialized copy to it's original value.
282 RematerializedValueMapTy RematerializedValues;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000283};
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000284
285} // end anonymous namespace
Philip Reamesd16a9b12015-02-20 01:06:44 +0000286
Chandler Carruth31607342019-02-11 07:42:30 +0000287static ArrayRef<Use> GetDeoptBundleOperands(const CallBase *Call) {
Sanjoy Dasacc43d12016-01-22 19:20:40 +0000288 Optional<OperandBundleUse> DeoptBundle =
Chandler Carruth31607342019-02-11 07:42:30 +0000289 Call->getOperandBundle(LLVMContext::OB_deopt);
Sanjoy Das25ec1a32015-10-16 02:41:00 +0000290
291 if (!DeoptBundle.hasValue()) {
292 assert(AllowStatepointWithNoDeoptInfo &&
293 "Found non-leaf call without deopt info!");
294 return None;
295 }
296
297 return DeoptBundle.getValue().Inputs;
298}
299
Philip Reamesdf1ef082015-04-10 22:53:14 +0000300/// Compute the live-in set for every basic block in the function
301static void computeLiveInValues(DominatorTree &DT, Function &F,
302 GCPtrLivenessData &Data);
303
304/// Given results from the dataflow liveness computation, find the set of live
305/// Values at a particular instruction.
306static void findLiveSetAtInst(Instruction *inst, GCPtrLivenessData &Data,
307 StatepointLiveSetTy &out);
308
Philip Reamesd16a9b12015-02-20 01:06:44 +0000309// TODO: Once we can get to the GCStrategy, this becomes
Philip Reamesee8f0552015-12-23 01:42:15 +0000310// Optional<bool> isGCManagedPointer(const Type *Ty) const override {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000311
Craig Toppere3dcce92015-08-01 22:20:21 +0000312static bool isGCPointerType(Type *T) {
313 if (auto *PT = dyn_cast<PointerType>(T))
Philip Reamesd16a9b12015-02-20 01:06:44 +0000314 // For the sake of this example GC, we arbitrarily pick addrspace(1) as our
315 // GC managed heap. We know that a pointer into this heap needs to be
316 // updated and that no other pointer does.
Sanjoy Das73c7f262016-06-26 04:55:19 +0000317 return PT->getAddressSpace() == 1;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000318 return false;
319}
320
Philip Reames8531d8c2015-04-10 21:48:25 +0000321// Return true if this type is one which a) is a gc pointer or contains a GC
322// pointer and b) is of a type this code expects to encounter as a live value.
323// (The insertion code will assert that a type which matches (a) and not (b)
Philip Reames704e78b2015-04-10 22:34:56 +0000324// is not encountered.)
Philip Reames8531d8c2015-04-10 21:48:25 +0000325static bool isHandledGCPointerType(Type *T) {
326 // We fully support gc pointers
327 if (isGCPointerType(T))
328 return true;
329 // We partially support vectors of gc pointers. The code will assert if it
330 // can't handle something.
331 if (auto VT = dyn_cast<VectorType>(T))
332 if (isGCPointerType(VT->getElementType()))
333 return true;
334 return false;
335}
336
337#ifndef NDEBUG
338/// Returns true if this type contains a gc pointer whether we know how to
339/// handle that type or not.
340static bool containsGCPtrType(Type *Ty) {
Philip Reames704e78b2015-04-10 22:34:56 +0000341 if (isGCPointerType(Ty))
Philip Reames8531d8c2015-04-10 21:48:25 +0000342 return true;
343 if (VectorType *VT = dyn_cast<VectorType>(Ty))
344 return isGCPointerType(VT->getScalarType());
345 if (ArrayType *AT = dyn_cast<ArrayType>(Ty))
346 return containsGCPtrType(AT->getElementType());
347 if (StructType *ST = dyn_cast<StructType>(Ty))
James Y Knight62df5ee2019-01-10 16:07:20 +0000348 return llvm::any_of(ST->elements(), containsGCPtrType);
Philip Reames8531d8c2015-04-10 21:48:25 +0000349 return false;
350}
351
352// Returns true if this is a type which a) is a gc pointer or contains a GC
353// pointer and b) is of a type which the code doesn't expect (i.e. first class
354// aggregates). Used to trip assertions.
355static bool isUnhandledGCPointerType(Type *Ty) {
356 return containsGCPtrType(Ty) && !isHandledGCPointerType(Ty);
357}
358#endif
359
Philip Reamesece70b82015-09-09 23:57:18 +0000360// Return the name of the value suffixed with the provided value, or if the
361// value didn't have a name, the default value specified.
362static std::string suffixed_name_or(Value *V, StringRef Suffix,
363 StringRef DefaultName) {
364 return V->hasName() ? (V->getName() + Suffix).str() : DefaultName.str();
365}
366
Philip Reamesdf1ef082015-04-10 22:53:14 +0000367// Conservatively identifies any definitions which might be live at the
368// given instruction. The analysis is performed immediately before the
369// given instruction. Values defined by that instruction are not considered
370// live. Values used by that instruction are considered live.
Chandler Carruth31607342019-02-11 07:42:30 +0000371static void analyzeParsePointLiveness(
372 DominatorTree &DT, GCPtrLivenessData &OriginalLivenessData, CallBase *Call,
373 PartiallyConstructedSafepointRecord &Result) {
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +0000374 StatepointLiveSetTy LiveSet;
Chandler Carruth31607342019-02-11 07:42:30 +0000375 findLiveSetAtInst(Call, OriginalLivenessData, LiveSet);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000376
377 if (PrintLiveSet) {
Sanjoy Das1e7eeb42016-06-26 04:55:17 +0000378 dbgs() << "Live Variables:\n";
Igor Laevskyfb1811d2016-05-04 14:55:36 +0000379 for (Value *V : LiveSet)
Philip Reamesdab35f32015-09-02 21:11:44 +0000380 dbgs() << " " << V->getName() << " " << *V << "\n";
Philip Reamesd16a9b12015-02-20 01:06:44 +0000381 }
382 if (PrintLiveSetSize) {
Chandler Carruth31607342019-02-11 07:42:30 +0000383 dbgs() << "Safepoint For: " << Call->getCalledValue()->getName() << "\n";
Sanjoy Das1e7eeb42016-06-26 04:55:17 +0000384 dbgs() << "Number live values: " << LiveSet.size() << "\n";
Philip Reamesd16a9b12015-02-20 01:06:44 +0000385 }
Sanjoy Das1e7eeb42016-06-26 04:55:17 +0000386 Result.LiveSet = LiveSet;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000387}
388
Philip Reamesf5b8e472015-09-03 21:34:30 +0000389static bool isKnownBaseResult(Value *V);
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000390
Philip Reamesf5b8e472015-09-03 21:34:30 +0000391namespace {
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000392
Philip Reamesf5b8e472015-09-03 21:34:30 +0000393/// A single base defining value - An immediate base defining value for an
394/// instruction 'Def' is an input to 'Def' whose base is also a base of 'Def'.
395/// For instructions which have multiple pointer [vector] inputs or that
396/// transition between vector and scalar types, there is no immediate base
397/// defining value. The 'base defining value' for 'Def' is the transitive
398/// closure of this relation stopping at the first instruction which has no
399/// immediate base defining value. The b.d.v. might itself be a base pointer,
Fangrui Songf78650a2018-07-30 19:41:25 +0000400/// but it can also be an arbitrary derived pointer.
Philip Reamesf5b8e472015-09-03 21:34:30 +0000401struct BaseDefiningValueResult {
402 /// Contains the value which is the base defining value.
403 Value * const BDV;
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000404
Philip Reamesf5b8e472015-09-03 21:34:30 +0000405 /// True if the base defining value is also known to be an actual base
406 /// pointer.
407 const bool IsKnownBase;
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000408
Philip Reamesf5b8e472015-09-03 21:34:30 +0000409 BaseDefiningValueResult(Value *BDV, bool IsKnownBase)
410 : BDV(BDV), IsKnownBase(IsKnownBase) {
411#ifndef NDEBUG
412 // Check consistency between new and old means of checking whether a BDV is
413 // a base.
414 bool MustBeBase = isKnownBaseResult(BDV);
415 assert(!MustBeBase || MustBeBase == IsKnownBase);
416#endif
417 }
418};
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000419
420} // end anonymous namespace
Philip Reamesf5b8e472015-09-03 21:34:30 +0000421
422static BaseDefiningValueResult findBaseDefiningValue(Value *I);
Philip Reames311f7102015-05-12 22:19:52 +0000423
Philip Reames8fe7f132015-06-26 22:47:37 +0000424/// Return a base defining value for the 'Index' element of the given vector
425/// instruction 'I'. If Index is null, returns a BDV for the entire vector
Fangrui Songf78650a2018-07-30 19:41:25 +0000426/// 'I'. As an optimization, this method will try to determine when the
Philip Reames8fe7f132015-06-26 22:47:37 +0000427/// element is known to already be a base pointer. If this can be established,
428/// the second value in the returned pair will be true. Note that either a
429/// vector or a pointer typed value can be returned. For the former, the
430/// vector returned is a BDV (and possibly a base) of the entire vector 'I'.
431/// If the later, the return pointer is a BDV (or possibly a base) for the
Fangrui Songf78650a2018-07-30 19:41:25 +0000432/// particular element in 'I'.
Philip Reamesf5b8e472015-09-03 21:34:30 +0000433static BaseDefiningValueResult
Philip Reames66287132015-09-09 23:40:12 +0000434findBaseDefiningValueOfVector(Value *I) {
Philip Reames8531d8c2015-04-10 21:48:25 +0000435 // Each case parallels findBaseDefiningValue below, see that code for
436 // detailed motivation.
437
438 if (isa<Argument>(I))
439 // An incoming argument to the function is a base pointer
Philip Reamesf5b8e472015-09-03 21:34:30 +0000440 return BaseDefiningValueResult(I, true);
Philip Reames8531d8c2015-04-10 21:48:25 +0000441
Manuel Jacob734e7332016-01-09 04:02:16 +0000442 if (isa<Constant>(I))
Fangrui Songf78650a2018-07-30 19:41:25 +0000443 // Base of constant vector consists only of constant null pointers.
Igor Laevskydf9db452016-05-27 13:13:59 +0000444 // For reasoning see similar case inside 'findBaseDefiningValue' function.
445 return BaseDefiningValueResult(ConstantAggregateZero::get(I->getType()),
446 true);
Philip Reames8531d8c2015-04-10 21:48:25 +0000447
Philip Reames8531d8c2015-04-10 21:48:25 +0000448 if (isa<LoadInst>(I))
Philip Reamesf5b8e472015-09-03 21:34:30 +0000449 return BaseDefiningValueResult(I, true);
Philip Reamesf5b8e472015-09-03 21:34:30 +0000450
Philip Reames66287132015-09-09 23:40:12 +0000451 if (isa<InsertElementInst>(I))
Philip Reames8fe7f132015-06-26 22:47:37 +0000452 // We don't know whether this vector contains entirely base pointers or
453 // not. To be conservatively correct, we treat it as a BDV and will
454 // duplicate code as needed to construct a parallel vector of bases.
Philip Reames66287132015-09-09 23:40:12 +0000455 return BaseDefiningValueResult(I, false);
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +0000456
Philip Reames8fe7f132015-06-26 22:47:37 +0000457 if (isa<ShuffleVectorInst>(I))
458 // We don't know whether this vector contains entirely base pointers or
459 // not. To be conservatively correct, we treat it as a BDV and will
460 // duplicate code as needed to construct a parallel vector of bases.
461 // TODO: There a number of local optimizations which could be applied here
462 // for particular sufflevector patterns.
Philip Reamesf5b8e472015-09-03 21:34:30 +0000463 return BaseDefiningValueResult(I, false);
Philip Reames8fe7f132015-06-26 22:47:37 +0000464
Sanjoy Dasc4e4dcd2017-03-17 00:55:53 +0000465 // The behavior of getelementptr instructions is the same for vector and
466 // non-vector data types.
467 if (auto *GEP = dyn_cast<GetElementPtrInst>(I))
468 return findBaseDefiningValue(GEP->getPointerOperand());
469
Daniel Neilsonfa14ebd2017-10-13 15:59:13 +0000470 // If the pointer comes through a bitcast of a vector of pointers to
471 // a vector of another type of pointer, then look through the bitcast
472 if (auto *BC = dyn_cast<BitCastInst>(I))
473 return findBaseDefiningValue(BC->getOperand(0));
474
Daniel Neilson594f4432018-01-30 14:43:41 +0000475 // We assume that functions in the source language only return base
476 // pointers. This should probably be generalized via attributes to support
477 // both source language and internal functions.
478 if (isa<CallInst>(I) || isa<InvokeInst>(I))
479 return BaseDefiningValueResult(I, true);
480
Philip Reames8fe7f132015-06-26 22:47:37 +0000481 // A PHI or Select is a base defining value. The outer findBasePointer
482 // algorithm is responsible for constructing a base value for this BDV.
483 assert((isa<SelectInst>(I) || isa<PHINode>(I)) &&
484 "unknown vector instruction - no base found for vector element");
Philip Reamesf5b8e472015-09-03 21:34:30 +0000485 return BaseDefiningValueResult(I, false);
Philip Reames8531d8c2015-04-10 21:48:25 +0000486}
487
Philip Reamesd16a9b12015-02-20 01:06:44 +0000488/// Helper function for findBasePointer - Will return a value which either a)
Philip Reames9ac4e382015-08-12 21:00:20 +0000489/// defines the base pointer for the input, b) blocks the simple search
490/// (i.e. a PHI or Select of two derived pointers), or c) involves a change
491/// from pointer to vector type or back.
Philip Reamesf5b8e472015-09-03 21:34:30 +0000492static BaseDefiningValueResult findBaseDefiningValue(Value *I) {
Manuel Jacob0593cfd2016-01-09 03:08:49 +0000493 assert(I->getType()->isPtrOrPtrVectorTy() &&
494 "Illegal to ask for the base pointer of a non-pointer type");
495
Philip Reames8fe7f132015-06-26 22:47:37 +0000496 if (I->getType()->isVectorTy())
Philip Reamesf5b8e472015-09-03 21:34:30 +0000497 return findBaseDefiningValueOfVector(I);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000498
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000499 if (isa<Argument>(I))
Philip Reamesd16a9b12015-02-20 01:06:44 +0000500 // An incoming argument to the function is a base pointer
501 // We should have never reached here if this argument isn't an gc value
Philip Reamesf5b8e472015-09-03 21:34:30 +0000502 return BaseDefiningValueResult(I, true);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000503
Igor Laevskydf9db452016-05-27 13:13:59 +0000504 if (isa<Constant>(I)) {
Manuel Jacob75cbfdc2016-01-05 04:06:21 +0000505 // We assume that objects with a constant base (e.g. a global) can't move
506 // and don't need to be reported to the collector because they are always
Fangrui Songf78650a2018-07-30 19:41:25 +0000507 // live. Besides global references, all kinds of constants (e.g. undef,
Igor Laevskydf9db452016-05-27 13:13:59 +0000508 // constant expressions, null pointers) can be introduced by the inliner or
509 // the optimizer, especially on dynamically dead paths.
510 // Here we treat all of them as having single null base. By doing this we
Fangrui Songf78650a2018-07-30 19:41:25 +0000511 // trying to avoid problems reporting various conflicts in a form of
Igor Laevskydf9db452016-05-27 13:13:59 +0000512 // "phi (const1, const2)" or "phi (const, regular gc ptr)".
513 // See constant.ll file for relevant test cases.
514
515 return BaseDefiningValueResult(
516 ConstantPointerNull::get(cast<PointerType>(I->getType())), true);
517 }
Philip Reamesd16a9b12015-02-20 01:06:44 +0000518
Philip Reamesd16a9b12015-02-20 01:06:44 +0000519 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000520 Value *Def = CI->stripPointerCasts();
Manuel Jacob8050a492015-12-21 01:26:46 +0000521 // If stripping pointer casts changes the address space there is an
522 // addrspacecast in between.
523 assert(cast<PointerType>(Def->getType())->getAddressSpace() ==
524 cast<PointerType>(CI->getType())->getAddressSpace() &&
525 "unsupported addrspacecast");
David Blaikie82ad7872015-02-20 23:44:24 +0000526 // If we find a cast instruction here, it means we've found a cast which is
527 // not simply a pointer cast (i.e. an inttoptr). We don't know how to
528 // handle int->ptr conversion.
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000529 assert(!isa<CastInst>(Def) && "shouldn't find another cast here");
530 return findBaseDefiningValue(Def);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000531 }
532
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000533 if (isa<LoadInst>(I))
Philip Reamesf5b8e472015-09-03 21:34:30 +0000534 // The value loaded is an gc base itself
535 return BaseDefiningValueResult(I, true);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000536
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000537 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I))
538 // The base of this GEP is the base
539 return findBaseDefiningValue(GEP->getPointerOperand());
Philip Reamesd16a9b12015-02-20 01:06:44 +0000540
541 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
542 switch (II->getIntrinsicID()) {
543 default:
544 // fall through to general call handling
545 break;
546 case Intrinsic::experimental_gc_statepoint:
Manuel Jacob4e4f60d2015-12-22 18:44:45 +0000547 llvm_unreachable("statepoints don't produce pointers");
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000548 case Intrinsic::experimental_gc_relocate:
Philip Reamesd16a9b12015-02-20 01:06:44 +0000549 // Rerunning safepoint insertion after safepoints are already
550 // inserted is not supported. It could probably be made to work,
551 // but why are you doing this? There's no good reason.
552 llvm_unreachable("repeat safepoint insertion is not supported");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000553 case Intrinsic::gcroot:
554 // Currently, this mechanism hasn't been extended to work with gcroot.
555 // There's no reason it couldn't be, but I haven't thought about the
556 // implications much.
557 llvm_unreachable(
558 "interaction with the gcroot mechanism is not supported");
559 }
560 }
561 // We assume that functions in the source language only return base
562 // pointers. This should probably be generalized via attributes to support
563 // both source language and internal functions.
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000564 if (isa<CallInst>(I) || isa<InvokeInst>(I))
Philip Reamesf5b8e472015-09-03 21:34:30 +0000565 return BaseDefiningValueResult(I, true);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000566
Anna Thomas488c0572016-10-06 13:24:20 +0000567 // TODO: I have absolutely no idea how to implement this part yet. It's not
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000568 // necessarily hard, I just haven't really looked at it yet.
Philip Reamesd16a9b12015-02-20 01:06:44 +0000569 assert(!isa<LandingPadInst>(I) && "Landing Pad is unimplemented");
570
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000571 if (isa<AtomicCmpXchgInst>(I))
Philip Reamesd16a9b12015-02-20 01:06:44 +0000572 // A CAS is effectively a atomic store and load combined under a
573 // predicate. From the perspective of base pointers, we just treat it
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000574 // like a load.
Philip Reamesf5b8e472015-09-03 21:34:30 +0000575 return BaseDefiningValueResult(I, true);
Philip Reames704e78b2015-04-10 22:34:56 +0000576
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000577 assert(!isa<AtomicRMWInst>(I) && "Xchg handled above, all others are "
Philip Reames704e78b2015-04-10 22:34:56 +0000578 "binary ops which don't apply to pointers");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000579
580 // The aggregate ops. Aggregates can either be in the heap or on the
581 // stack, but in either case, this is simply a field load. As a result,
582 // this is a defining definition of the base just like a load is.
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000583 if (isa<ExtractValueInst>(I))
Philip Reamesf5b8e472015-09-03 21:34:30 +0000584 return BaseDefiningValueResult(I, true);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000585
586 // We should never see an insert vector since that would require we be
587 // tracing back a struct value not a pointer value.
588 assert(!isa<InsertValueInst>(I) &&
589 "Base pointer for a struct is meaningless");
590
Philip Reames9ac4e382015-08-12 21:00:20 +0000591 // An extractelement produces a base result exactly when it's input does.
592 // We may need to insert a parallel instruction to extract the appropriate
593 // element out of the base vector corresponding to the input. Given this,
594 // it's analogous to the phi and select case even though it's not a merge.
Philip Reames66287132015-09-09 23:40:12 +0000595 if (isa<ExtractElementInst>(I))
596 // Note: There a lot of obvious peephole cases here. This are deliberately
597 // handled after the main base pointer inference algorithm to make writing
598 // test cases to exercise that code easier.
599 return BaseDefiningValueResult(I, false);
Philip Reames9ac4e382015-08-12 21:00:20 +0000600
Philip Reamesd16a9b12015-02-20 01:06:44 +0000601 // The last two cases here don't return a base pointer. Instead, they
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000602 // return a value which dynamically selects from among several base
Philip Reamesd16a9b12015-02-20 01:06:44 +0000603 // derived pointers (each with it's own base potentially). It's the job of
604 // the caller to resolve these.
Philip Reames704e78b2015-04-10 22:34:56 +0000605 assert((isa<SelectInst>(I) || isa<PHINode>(I)) &&
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000606 "missing instruction case in findBaseDefiningValing");
Philip Reamesf5b8e472015-09-03 21:34:30 +0000607 return BaseDefiningValueResult(I, false);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000608}
609
610/// Returns the base defining value for this value.
Philip Reames18d0feb2015-03-27 05:39:32 +0000611static Value *findBaseDefiningValueCached(Value *I, DefiningValueMapTy &Cache) {
612 Value *&Cached = Cache[I];
Benjamin Kramer6f665452015-02-20 14:00:58 +0000613 if (!Cached) {
Philip Reamesf5b8e472015-09-03 21:34:30 +0000614 Cached = findBaseDefiningValue(I).BDV;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000615 LLVM_DEBUG(dbgs() << "fBDV-cached: " << I->getName() << " -> "
616 << Cached->getName() << "\n");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000617 }
Philip Reames18d0feb2015-03-27 05:39:32 +0000618 assert(Cache[I] != nullptr);
Benjamin Kramer6f665452015-02-20 14:00:58 +0000619 return Cached;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000620}
621
622/// Return a base pointer for this value if known. Otherwise, return it's
623/// base defining value.
Philip Reames18d0feb2015-03-27 05:39:32 +0000624static Value *findBaseOrBDV(Value *I, DefiningValueMapTy &Cache) {
625 Value *Def = findBaseDefiningValueCached(I, Cache);
626 auto Found = Cache.find(Def);
627 if (Found != Cache.end()) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000628 // Either a base-of relation, or a self reference. Caller must check.
Benjamin Kramer6f665452015-02-20 14:00:58 +0000629 return Found->second;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000630 }
631 // Only a BDV available
Philip Reames18d0feb2015-03-27 05:39:32 +0000632 return Def;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000633}
634
635/// Given the result of a call to findBaseDefiningValue, or findBaseOrBDV,
636/// is it known to be a base pointer? Or do we need to continue searching.
Philip Reames18d0feb2015-03-27 05:39:32 +0000637static bool isKnownBaseResult(Value *V) {
Philip Reames66287132015-09-09 23:40:12 +0000638 if (!isa<PHINode>(V) && !isa<SelectInst>(V) &&
639 !isa<ExtractElementInst>(V) && !isa<InsertElementInst>(V) &&
640 !isa<ShuffleVectorInst>(V)) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000641 // no recursion possible
642 return true;
643 }
Philip Reames18d0feb2015-03-27 05:39:32 +0000644 if (isa<Instruction>(V) &&
645 cast<Instruction>(V)->getMetadata("is_base_value")) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000646 // This is a previously inserted base phi or select. We know
647 // that this is a base value.
648 return true;
649 }
650
651 // We need to keep searching
652 return false;
653}
654
Philip Reamesd16a9b12015-02-20 01:06:44 +0000655namespace {
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000656
Philip Reames9b141ed2015-07-23 22:49:14 +0000657/// Models the state of a single base defining value in the findBasePointer
658/// algorithm for determining where a new instruction is needed to propagate
659/// the base of this BDV.
660class BDVState {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000661public:
662 enum Status { Unknown, Base, Conflict };
663
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000664 BDVState() : BaseValue(nullptr) {}
Philip Reamesd16a9b12015-02-20 01:06:44 +0000665
Sanjoy Das7dda0ed2016-06-26 04:55:35 +0000666 explicit BDVState(Status Status, Value *BaseValue = nullptr)
667 : Status(Status), BaseValue(BaseValue) {
668 assert(Status != Base || BaseValue);
669 }
670
671 explicit BDVState(Value *BaseValue) : Status(Base), BaseValue(BaseValue) {}
672
673 Status getStatus() const { return Status; }
674 Value *getBaseValue() const { return BaseValue; }
Philip Reamesd16a9b12015-02-20 01:06:44 +0000675
676 bool isBase() const { return getStatus() == Base; }
677 bool isUnknown() const { return getStatus() == Unknown; }
678 bool isConflict() const { return getStatus() == Conflict; }
679
Sanjoy Das7dda0ed2016-06-26 04:55:35 +0000680 bool operator==(const BDVState &Other) const {
681 return BaseValue == Other.BaseValue && Status == Other.Status;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000682 }
683
Philip Reames9b141ed2015-07-23 22:49:14 +0000684 bool operator!=(const BDVState &other) const { return !(*this == other); }
Philip Reamesd16a9b12015-02-20 01:06:44 +0000685
Philip Reames2a892a62015-07-23 22:25:26 +0000686 LLVM_DUMP_METHOD
Sanjoy Das7dda0ed2016-06-26 04:55:35 +0000687 void dump() const {
688 print(dbgs());
689 dbgs() << '\n';
690 }
691
Philip Reames2a892a62015-07-23 22:25:26 +0000692 void print(raw_ostream &OS) const {
Sanjoy Das7dda0ed2016-06-26 04:55:35 +0000693 switch (getStatus()) {
Philip Reamesdab35f32015-09-02 21:11:44 +0000694 case Unknown:
695 OS << "U";
696 break;
697 case Base:
698 OS << "B";
699 break;
700 case Conflict:
701 OS << "C";
702 break;
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000703 }
Sanjoy Das7dda0ed2016-06-26 04:55:35 +0000704 OS << " (" << getBaseValue() << " - "
705 << (getBaseValue() ? getBaseValue()->getName() : "nullptr") << "): ";
Philip Reamesd16a9b12015-02-20 01:06:44 +0000706 }
707
708private:
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000709 Status Status = Unknown;
Sanjoy Das7dda0ed2016-06-26 04:55:35 +0000710 AssertingVH<Value> BaseValue; // Non-null only if Status == Base.
Philip Reamesd16a9b12015-02-20 01:06:44 +0000711};
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000712
713} // end anonymous namespace
Philip Reamesd16a9b12015-02-20 01:06:44 +0000714
Philip Reames6906e922015-09-02 21:57:17 +0000715#ifndef NDEBUG
Philip Reamesb3967cd2015-09-02 22:30:53 +0000716static raw_ostream &operator<<(raw_ostream &OS, const BDVState &State) {
Philip Reames2a892a62015-07-23 22:25:26 +0000717 State.print(OS);
718 return OS;
719}
Philip Reames6906e922015-09-02 21:57:17 +0000720#endif
Philip Reames2a892a62015-07-23 22:25:26 +0000721
Sanjoy Das6cf88092016-06-26 04:55:13 +0000722static BDVState meetBDVStateImpl(const BDVState &LHS, const BDVState &RHS) {
723 switch (LHS.getStatus()) {
Sanjoy Dasbd43d0e2016-06-26 04:55:10 +0000724 case BDVState::Unknown:
Sanjoy Das6cf88092016-06-26 04:55:13 +0000725 return RHS;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000726
Sanjoy Dasbd43d0e2016-06-26 04:55:10 +0000727 case BDVState::Base:
Sanjoy Das7dda0ed2016-06-26 04:55:35 +0000728 assert(LHS.getBaseValue() && "can't be null");
Sanjoy Das6cf88092016-06-26 04:55:13 +0000729 if (RHS.isUnknown())
730 return LHS;
Sanjoy Dasbd43d0e2016-06-26 04:55:10 +0000731
Sanjoy Das6cf88092016-06-26 04:55:13 +0000732 if (RHS.isBase()) {
Sanjoy Das7dda0ed2016-06-26 04:55:35 +0000733 if (LHS.getBaseValue() == RHS.getBaseValue()) {
Sanjoy Das6cf88092016-06-26 04:55:13 +0000734 assert(LHS == RHS && "equality broken!");
735 return LHS;
Sanjoy Dasbd43d0e2016-06-26 04:55:10 +0000736 }
737 return BDVState(BDVState::Conflict);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000738 }
Sanjoy Das6cf88092016-06-26 04:55:13 +0000739 assert(RHS.isConflict() && "only three states!");
Sanjoy Dasbd43d0e2016-06-26 04:55:10 +0000740 return BDVState(BDVState::Conflict);
741
742 case BDVState::Conflict:
Sanjoy Das6cf88092016-06-26 04:55:13 +0000743 return LHS;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000744 }
Sanjoy Dasbd43d0e2016-06-26 04:55:10 +0000745 llvm_unreachable("only three states!");
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000746}
Philip Reamesb3967cd2015-09-02 22:30:53 +0000747
Sanjoy Dasbd43d0e2016-06-26 04:55:10 +0000748// Values of type BDVState form a lattice, and this function implements the meet
749// operation.
Benjamin Kramer061f4a52017-01-13 14:39:03 +0000750static BDVState meetBDVState(const BDVState &LHS, const BDVState &RHS) {
Sanjoy Dasbd43d0e2016-06-26 04:55:10 +0000751 BDVState Result = meetBDVStateImpl(LHS, RHS);
752 assert(Result == meetBDVStateImpl(RHS, LHS) &&
753 "Math is wrong: meet does not commute!");
754 return Result;
755}
Philip Reamesb3967cd2015-09-02 22:30:53 +0000756
Sanjoy Das90547f12016-06-26 04:55:05 +0000757/// For a given value or instruction, figure out what base ptr its derived from.
758/// For gc objects, this is simply itself. On success, returns a value which is
759/// the base pointer. (This is reliable and can be used for relocation.) On
760/// failure, returns nullptr.
761static Value *findBasePointer(Value *I, DefiningValueMapTy &Cache) {
762 Value *Def = findBaseOrBDV(I, Cache);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000763
Sanjoy Das90547f12016-06-26 04:55:05 +0000764 if (isKnownBaseResult(Def))
765 return Def;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000766
767 // Here's the rough algorithm:
768 // - For every SSA value, construct a mapping to either an actual base
769 // pointer or a PHI which obscures the base pointer.
770 // - Construct a mapping from PHI to unknown TOP state. Use an
771 // optimistic algorithm to propagate base pointer information. Lattice
772 // looks like:
773 // UNKNOWN
774 // b1 b2 b3 b4
775 // CONFLICT
776 // When algorithm terminates, all PHIs will either have a single concrete
777 // base or be in a conflict state.
778 // - For every conflict, insert a dummy PHI node without arguments. Add
779 // these to the base[Instruction] = BasePtr mapping. For every
780 // non-conflict, add the actual base.
781 // - For every conflict, add arguments for the base[a] of each input
782 // arguments.
783 //
784 // Note: A simpler form of this would be to add the conflict form of all
785 // PHIs without running the optimistic algorithm. This would be
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000786 // analogous to pessimistic data flow and would likely lead to an
Philip Reamesd16a9b12015-02-20 01:06:44 +0000787 // overall worse solution.
788
Philip Reames29e9ae72015-07-24 00:42:55 +0000789#ifndef NDEBUG
Philip Reames88958b22015-07-24 00:02:11 +0000790 auto isExpectedBDVType = [](Value *BDV) {
Philip Reames66287132015-09-09 23:40:12 +0000791 return isa<PHINode>(BDV) || isa<SelectInst>(BDV) ||
Anna Thomas479cbb92016-10-04 13:48:37 +0000792 isa<ExtractElementInst>(BDV) || isa<InsertElementInst>(BDV) ||
793 isa<ShuffleVectorInst>(BDV);
Philip Reames88958b22015-07-24 00:02:11 +0000794 };
Philip Reames29e9ae72015-07-24 00:42:55 +0000795#endif
Philip Reames88958b22015-07-24 00:02:11 +0000796
797 // Once populated, will contain a mapping from each potentially non-base BDV
798 // to a lattice value (described above) which corresponds to that BDV.
Philip Reames15d55632015-09-09 23:26:08 +0000799 // We use the order of insertion (DFS over the def/use graph) to provide a
800 // stable deterministic ordering for visiting DenseMaps (which are unordered)
801 // below. This is important for deterministic compilation.
Philip Reames34d7a742015-09-10 00:22:49 +0000802 MapVector<Value *, BDVState> States;
Philip Reames15d55632015-09-09 23:26:08 +0000803
804 // Recursively fill in all base defining values reachable from the initial
805 // one for which we don't already know a definite base value for
Philip Reames88958b22015-07-24 00:02:11 +0000806 /* scope */ {
Philip Reames88958b22015-07-24 00:02:11 +0000807 SmallVector<Value*, 16> Worklist;
Sanjoy Das90547f12016-06-26 04:55:05 +0000808 Worklist.push_back(Def);
809 States.insert({Def, BDVState()});
Philip Reames88958b22015-07-24 00:02:11 +0000810 while (!Worklist.empty()) {
811 Value *Current = Worklist.pop_back_val();
812 assert(!isKnownBaseResult(Current) && "why did it get added?");
813
814 auto visitIncomingValue = [&](Value *InVal) {
Sanjoy Das90547f12016-06-26 04:55:05 +0000815 Value *Base = findBaseOrBDV(InVal, Cache);
Philip Reames88958b22015-07-24 00:02:11 +0000816 if (isKnownBaseResult(Base))
817 // Known bases won't need new instructions introduced and can be
818 // ignored safely
819 return;
820 assert(isExpectedBDVType(Base) && "the only non-base values "
821 "we see should be base defining values");
Philip Reames34d7a742015-09-10 00:22:49 +0000822 if (States.insert(std::make_pair(Base, BDVState())).second)
Philip Reames88958b22015-07-24 00:02:11 +0000823 Worklist.push_back(Base);
824 };
Sanjoy Das90547f12016-06-26 04:55:05 +0000825 if (PHINode *PN = dyn_cast<PHINode>(Current)) {
826 for (Value *InVal : PN->incoming_values())
Philip Reames88958b22015-07-24 00:02:11 +0000827 visitIncomingValue(InVal);
Sanjoy Das90547f12016-06-26 04:55:05 +0000828 } else if (SelectInst *SI = dyn_cast<SelectInst>(Current)) {
829 visitIncomingValue(SI->getTrueValue());
830 visitIncomingValue(SI->getFalseValue());
Philip Reames9ac4e382015-08-12 21:00:20 +0000831 } else if (auto *EE = dyn_cast<ExtractElementInst>(Current)) {
832 visitIncomingValue(EE->getVectorOperand());
Philip Reames66287132015-09-09 23:40:12 +0000833 } else if (auto *IE = dyn_cast<InsertElementInst>(Current)) {
834 visitIncomingValue(IE->getOperand(0)); // vector operand
835 visitIncomingValue(IE->getOperand(1)); // scalar operand
Anna Thomas479cbb92016-10-04 13:48:37 +0000836 } else if (auto *SV = dyn_cast<ShuffleVectorInst>(Current)) {
837 visitIncomingValue(SV->getOperand(0));
838 visitIncomingValue(SV->getOperand(1));
839 }
840 else {
Sanjoy Das90547f12016-06-26 04:55:05 +0000841 llvm_unreachable("Unimplemented instruction case");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000842 }
843 }
844 }
845
Philip Reamesdab35f32015-09-02 21:11:44 +0000846#ifndef NDEBUG
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000847 LLVM_DEBUG(dbgs() << "States after initialization:\n");
Sanjoy Das9d086422016-06-26 05:42:52 +0000848 for (auto Pair : States) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000849 LLVM_DEBUG(dbgs() << " " << Pair.second << " for " << *Pair.first << "\n");
Sanjoy Das9d086422016-06-26 05:42:52 +0000850 }
Philip Reamesdab35f32015-09-02 21:11:44 +0000851#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +0000852
Philip Reames273e6bb2015-07-23 21:41:27 +0000853 // Return a phi state for a base defining value. We'll generate a new
854 // base state for known bases and expect to find a cached state otherwise.
855 auto getStateForBDV = [&](Value *baseValue) {
856 if (isKnownBaseResult(baseValue))
Philip Reames9b141ed2015-07-23 22:49:14 +0000857 return BDVState(baseValue);
Philip Reames34d7a742015-09-10 00:22:49 +0000858 auto I = States.find(baseValue);
859 assert(I != States.end() && "lookup failed!");
Philip Reames273e6bb2015-07-23 21:41:27 +0000860 return I->second;
861 };
862
Sanjoy Das90547f12016-06-26 04:55:05 +0000863 bool Progress = true;
864 while (Progress) {
Yaron Keren42a7adf2015-02-28 13:11:24 +0000865#ifndef NDEBUG
Sanjoy Das90547f12016-06-26 04:55:05 +0000866 const size_t OldSize = States.size();
Yaron Keren42a7adf2015-02-28 13:11:24 +0000867#endif
Sanjoy Das90547f12016-06-26 04:55:05 +0000868 Progress = false;
Philip Reames15d55632015-09-09 23:26:08 +0000869 // We're only changing values in this loop, thus safe to keep iterators.
870 // Since this is computing a fixed point, the order of visit does not
871 // effect the result. TODO: We could use a worklist here and make this run
872 // much faster.
Philip Reames34d7a742015-09-10 00:22:49 +0000873 for (auto Pair : States) {
Philip Reamesece70b82015-09-09 23:57:18 +0000874 Value *BDV = Pair.first;
875 assert(!isKnownBaseResult(BDV) && "why did it get added?");
Philip Reames273e6bb2015-07-23 21:41:27 +0000876
Philip Reames9b141ed2015-07-23 22:49:14 +0000877 // Given an input value for the current instruction, return a BDVState
Philip Reames273e6bb2015-07-23 21:41:27 +0000878 // instance which represents the BDV of that value.
879 auto getStateForInput = [&](Value *V) mutable {
Sanjoy Das90547f12016-06-26 04:55:05 +0000880 Value *BDV = findBaseOrBDV(V, Cache);
Philip Reames273e6bb2015-07-23 21:41:27 +0000881 return getStateForBDV(BDV);
882 };
883
Sanjoy Dasbd43d0e2016-06-26 04:55:10 +0000884 BDVState NewState;
Sanjoy Das90547f12016-06-26 04:55:05 +0000885 if (SelectInst *SI = dyn_cast<SelectInst>(BDV)) {
Sanjoy Dasbd43d0e2016-06-26 04:55:10 +0000886 NewState = meetBDVState(NewState, getStateForInput(SI->getTrueValue()));
887 NewState =
888 meetBDVState(NewState, getStateForInput(SI->getFalseValue()));
Sanjoy Das90547f12016-06-26 04:55:05 +0000889 } else if (PHINode *PN = dyn_cast<PHINode>(BDV)) {
890 for (Value *Val : PN->incoming_values())
Sanjoy Dasbd43d0e2016-06-26 04:55:10 +0000891 NewState = meetBDVState(NewState, getStateForInput(Val));
Philip Reamesece70b82015-09-09 23:57:18 +0000892 } else if (auto *EE = dyn_cast<ExtractElementInst>(BDV)) {
Philip Reames9ac4e382015-08-12 21:00:20 +0000893 // The 'meet' for an extractelement is slightly trivial, but it's still
894 // useful in that it drives us to conflict if our input is.
Sanjoy Dasbd43d0e2016-06-26 04:55:10 +0000895 NewState =
896 meetBDVState(NewState, getStateForInput(EE->getVectorOperand()));
Anna Thomas479cbb92016-10-04 13:48:37 +0000897 } else if (auto *IE = dyn_cast<InsertElementInst>(BDV)){
Philip Reames66287132015-09-09 23:40:12 +0000898 // Given there's a inherent type mismatch between the operands, will
899 // *always* produce Conflict.
Sanjoy Dasbd43d0e2016-06-26 04:55:10 +0000900 NewState = meetBDVState(NewState, getStateForInput(IE->getOperand(0)));
901 NewState = meetBDVState(NewState, getStateForInput(IE->getOperand(1)));
Anna Thomas479cbb92016-10-04 13:48:37 +0000902 } else {
903 // The only instance this does not return a Conflict is when both the
904 // vector operands are the same vector.
905 auto *SV = cast<ShuffleVectorInst>(BDV);
906 NewState = meetBDVState(NewState, getStateForInput(SV->getOperand(0)));
907 NewState = meetBDVState(NewState, getStateForInput(SV->getOperand(1)));
Philip Reames9ac4e382015-08-12 21:00:20 +0000908 }
909
Sanjoy Das90547f12016-06-26 04:55:05 +0000910 BDVState OldState = States[BDV];
Sanjoy Das90547f12016-06-26 04:55:05 +0000911 if (OldState != NewState) {
912 Progress = true;
913 States[BDV] = NewState;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000914 }
915 }
916
Sanjoy Das90547f12016-06-26 04:55:05 +0000917 assert(OldSize == States.size() &&
Philip Reamesb4e55f32015-09-10 00:32:56 +0000918 "fixed point shouldn't be adding any new nodes to state");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000919 }
920
Philip Reamesdab35f32015-09-02 21:11:44 +0000921#ifndef NDEBUG
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000922 LLVM_DEBUG(dbgs() << "States after meet iteration:\n");
Sanjoy Das9d086422016-06-26 05:42:52 +0000923 for (auto Pair : States) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000924 LLVM_DEBUG(dbgs() << " " << Pair.second << " for " << *Pair.first << "\n");
Sanjoy Das9d086422016-06-26 05:42:52 +0000925 }
Philip Reamesdab35f32015-09-02 21:11:44 +0000926#endif
Sanjoy Das90547f12016-06-26 04:55:05 +0000927
Philip Reamesd16a9b12015-02-20 01:06:44 +0000928 // Insert Phis for all conflicts
Philip Reames2e5bcbe2015-02-28 01:52:09 +0000929 // TODO: adjust naming patterns to avoid this order of iteration dependency
Philip Reames34d7a742015-09-10 00:22:49 +0000930 for (auto Pair : States) {
Philip Reames15d55632015-09-09 23:26:08 +0000931 Instruction *I = cast<Instruction>(Pair.first);
932 BDVState State = Pair.second;
Philip Reames6ff1a1e32015-07-21 19:04:38 +0000933 assert(!isKnownBaseResult(I) && "why did it get added?");
934 assert(!State.isUnknown() && "Optimistic algorithm didn't complete!");
Philip Reames9ac4e382015-08-12 21:00:20 +0000935
936 // extractelement instructions are a bit special in that we may need to
937 // insert an extract even when we know an exact base for the instruction.
938 // The problem is that we need to convert from a vector base to a scalar
939 // base for the particular indice we're interested in.
940 if (State.isBase() && isa<ExtractElementInst>(I) &&
Sanjoy Das7dda0ed2016-06-26 04:55:35 +0000941 isa<VectorType>(State.getBaseValue()->getType())) {
Philip Reames9ac4e382015-08-12 21:00:20 +0000942 auto *EE = cast<ExtractElementInst>(I);
943 // TODO: In many cases, the new instruction is just EE itself. We should
944 // exploit this, but can't do it here since it would break the invariant
945 // about the BDV not being known to be a base.
Sanjoy Das90547f12016-06-26 04:55:05 +0000946 auto *BaseInst = ExtractElementInst::Create(
Sanjoy Das7dda0ed2016-06-26 04:55:35 +0000947 State.getBaseValue(), EE->getIndexOperand(), "base_ee", EE);
Philip Reames9ac4e382015-08-12 21:00:20 +0000948 BaseInst->setMetadata("is_base_value", MDNode::get(I->getContext(), {}));
Philip Reames34d7a742015-09-10 00:22:49 +0000949 States[I] = BDVState(BDVState::Base, BaseInst);
Philip Reames9ac4e382015-08-12 21:00:20 +0000950 }
Philip Reames66287132015-09-09 23:40:12 +0000951
952 // Since we're joining a vector and scalar base, they can never be the
953 // same. As a result, we should always see insert element having reached
954 // the conflict state.
Sanjoy Das90547f12016-06-26 04:55:05 +0000955 assert(!isa<InsertElementInst>(I) || State.isConflict());
956
Philip Reames6ff1a1e32015-07-21 19:04:38 +0000957 if (!State.isConflict())
Philip Reamesf986d682015-02-28 00:54:41 +0000958 continue;
Philip Reames704e78b2015-04-10 22:34:56 +0000959
Philip Reames6ff1a1e32015-07-21 19:04:38 +0000960 /// Create and insert a new instruction which will represent the base of
961 /// the given instruction 'I'.
962 auto MakeBaseInstPlaceholder = [](Instruction *I) -> Instruction* {
963 if (isa<PHINode>(I)) {
964 BasicBlock *BB = I->getParent();
Vedant Kumare0b5f862018-05-10 23:01:54 +0000965 int NumPreds = pred_size(BB);
Philip Reames6ff1a1e32015-07-21 19:04:38 +0000966 assert(NumPreds > 0 && "how did we reach here");
Philip Reamesece70b82015-09-09 23:57:18 +0000967 std::string Name = suffixed_name_or(I, ".base", "base_phi");
Philip Reamesfa2c6302015-07-24 19:01:39 +0000968 return PHINode::Create(I->getType(), NumPreds, Name, I);
Sanjoy Das90547f12016-06-26 04:55:05 +0000969 } else if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
Philip Reames9ac4e382015-08-12 21:00:20 +0000970 // The undef will be replaced later
Sanjoy Das90547f12016-06-26 04:55:05 +0000971 UndefValue *Undef = UndefValue::get(SI->getType());
Philip Reamesece70b82015-09-09 23:57:18 +0000972 std::string Name = suffixed_name_or(I, ".base", "base_select");
Sanjoy Das90547f12016-06-26 04:55:05 +0000973 return SelectInst::Create(SI->getCondition(), Undef, Undef, Name, SI);
Philip Reames66287132015-09-09 23:40:12 +0000974 } else if (auto *EE = dyn_cast<ExtractElementInst>(I)) {
Philip Reames9ac4e382015-08-12 21:00:20 +0000975 UndefValue *Undef = UndefValue::get(EE->getVectorOperand()->getType());
Philip Reamesece70b82015-09-09 23:57:18 +0000976 std::string Name = suffixed_name_or(I, ".base", "base_ee");
Philip Reames9ac4e382015-08-12 21:00:20 +0000977 return ExtractElementInst::Create(Undef, EE->getIndexOperand(), Name,
978 EE);
Anna Thomas479cbb92016-10-04 13:48:37 +0000979 } else if (auto *IE = dyn_cast<InsertElementInst>(I)) {
Philip Reames66287132015-09-09 23:40:12 +0000980 UndefValue *VecUndef = UndefValue::get(IE->getOperand(0)->getType());
981 UndefValue *ScalarUndef = UndefValue::get(IE->getOperand(1)->getType());
Philip Reamesece70b82015-09-09 23:57:18 +0000982 std::string Name = suffixed_name_or(I, ".base", "base_ie");
Philip Reames66287132015-09-09 23:40:12 +0000983 return InsertElementInst::Create(VecUndef, ScalarUndef,
984 IE->getOperand(2), Name, IE);
Anna Thomas479cbb92016-10-04 13:48:37 +0000985 } else {
986 auto *SV = cast<ShuffleVectorInst>(I);
987 UndefValue *VecUndef = UndefValue::get(SV->getOperand(0)->getType());
988 std::string Name = suffixed_name_or(I, ".base", "base_sv");
989 return new ShuffleVectorInst(VecUndef, VecUndef, SV->getOperand(2),
990 Name, SV);
Philip Reames6ff1a1e32015-07-21 19:04:38 +0000991 }
Philip Reames6ff1a1e32015-07-21 19:04:38 +0000992 };
993 Instruction *BaseInst = MakeBaseInstPlaceholder(I);
994 // Add metadata marking this as a base value
995 BaseInst->setMetadata("is_base_value", MDNode::get(I->getContext(), {}));
Philip Reames34d7a742015-09-10 00:22:49 +0000996 States[I] = BDVState(BDVState::Conflict, BaseInst);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000997 }
998
Philip Reames3ea15892015-09-03 21:57:40 +0000999 // Returns a instruction which produces the base pointer for a given
1000 // instruction. The instruction is assumed to be an input to one of the BDVs
1001 // seen in the inference algorithm above. As such, we must either already
1002 // know it's base defining value is a base, or have inserted a new
1003 // instruction to propagate the base of it's BDV and have entered that newly
1004 // introduced instruction into the state table. In either case, we are
1005 // assured to be able to determine an instruction which produces it's base
Sanjoy Das90547f12016-06-26 04:55:05 +00001006 // pointer.
Philip Reames3ea15892015-09-03 21:57:40 +00001007 auto getBaseForInput = [&](Value *Input, Instruction *InsertPt) {
Sanjoy Das90547f12016-06-26 04:55:05 +00001008 Value *BDV = findBaseOrBDV(Input, Cache);
Philip Reames3ea15892015-09-03 21:57:40 +00001009 Value *Base = nullptr;
1010 if (isKnownBaseResult(BDV)) {
1011 Base = BDV;
1012 } else {
1013 // Either conflict or base.
Philip Reames34d7a742015-09-10 00:22:49 +00001014 assert(States.count(BDV));
Sanjoy Das7dda0ed2016-06-26 04:55:35 +00001015 Base = States[BDV].getBaseValue();
Philip Reames3ea15892015-09-03 21:57:40 +00001016 }
Sanjoy Das90547f12016-06-26 04:55:05 +00001017 assert(Base && "Can't be null");
Philip Reames3ea15892015-09-03 21:57:40 +00001018 // The cast is needed since base traversal may strip away bitcasts
Sanjoy Das90547f12016-06-26 04:55:05 +00001019 if (Base->getType() != Input->getType() && InsertPt)
1020 Base = new BitCastInst(Base, Input->getType(), "cast", InsertPt);
Philip Reames3ea15892015-09-03 21:57:40 +00001021 return Base;
1022 };
1023
Philip Reames15d55632015-09-09 23:26:08 +00001024 // Fixup all the inputs of the new PHIs. Visit order needs to be
1025 // deterministic and predictable because we're naming newly created
1026 // instructions.
Philip Reames34d7a742015-09-10 00:22:49 +00001027 for (auto Pair : States) {
Philip Reames7540e3a2015-09-10 00:01:53 +00001028 Instruction *BDV = cast<Instruction>(Pair.first);
Philip Reamesc8ded462015-09-10 00:27:50 +00001029 BDVState State = Pair.second;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001030
Philip Reames7540e3a2015-09-10 00:01:53 +00001031 assert(!isKnownBaseResult(BDV) && "why did it get added?");
Philip Reamesc8ded462015-09-10 00:27:50 +00001032 assert(!State.isUnknown() && "Optimistic algorithm didn't complete!");
1033 if (!State.isConflict())
Philip Reames28e61ce2015-02-28 01:57:44 +00001034 continue;
Philip Reames704e78b2015-04-10 22:34:56 +00001035
Sanjoy Das7dda0ed2016-06-26 04:55:35 +00001036 if (PHINode *BasePHI = dyn_cast<PHINode>(State.getBaseValue())) {
Sanjoy Das90547f12016-06-26 04:55:05 +00001037 PHINode *PN = cast<PHINode>(BDV);
1038 unsigned NumPHIValues = PN->getNumIncomingValues();
Philip Reames28e61ce2015-02-28 01:57:44 +00001039 for (unsigned i = 0; i < NumPHIValues; i++) {
Sanjoy Das90547f12016-06-26 04:55:05 +00001040 Value *InVal = PN->getIncomingValue(i);
1041 BasicBlock *InBB = PN->getIncomingBlock(i);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001042
Philip Reames28e61ce2015-02-28 01:57:44 +00001043 // If we've already seen InBB, add the same incoming value
1044 // we added for it earlier. The IR verifier requires phi
1045 // nodes with multiple entries from the same basic block
1046 // to have the same incoming value for each of those
1047 // entries. If we don't do this check here and basephi
1048 // has a different type than base, we'll end up adding two
1049 // bitcasts (and hence two distinct values) as incoming
1050 // values for the same basic block.
Philip Reamesd16a9b12015-02-20 01:06:44 +00001051
Sanjoy Das90547f12016-06-26 04:55:05 +00001052 int BlockIndex = BasePHI->getBasicBlockIndex(InBB);
1053 if (BlockIndex != -1) {
1054 Value *OldBase = BasePHI->getIncomingValue(BlockIndex);
1055 BasePHI->addIncoming(OldBase, InBB);
1056
Philip Reamesd16a9b12015-02-20 01:06:44 +00001057#ifndef NDEBUG
Philip Reames3ea15892015-09-03 21:57:40 +00001058 Value *Base = getBaseForInput(InVal, nullptr);
Sanjoy Das90547f12016-06-26 04:55:05 +00001059 // In essence this assert states: the only way two values
1060 // incoming from the same basic block may be different is by
1061 // being different bitcasts of the same value. A cleanup
1062 // that remains TODO is changing findBaseOrBDV to return an
1063 // llvm::Value of the correct type (and still remain pure).
1064 // This will remove the need to add bitcasts.
1065 assert(Base->stripPointerCasts() == OldBase->stripPointerCasts() &&
1066 "Sanity -- findBaseOrBDV should be pure!");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001067#endif
Philip Reames28e61ce2015-02-28 01:57:44 +00001068 continue;
1069 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00001070
Philip Reames3ea15892015-09-03 21:57:40 +00001071 // Find the instruction which produces the base for each input. We may
1072 // need to insert a bitcast in the incoming block.
1073 // TODO: Need to split critical edges if insertion is needed
1074 Value *Base = getBaseForInput(InVal, InBB->getTerminator());
Sanjoy Das90547f12016-06-26 04:55:05 +00001075 BasePHI->addIncoming(Base, InBB);
Philip Reames28e61ce2015-02-28 01:57:44 +00001076 }
Sanjoy Das90547f12016-06-26 04:55:05 +00001077 assert(BasePHI->getNumIncomingValues() == NumPHIValues);
Sanjoy Das7dda0ed2016-06-26 04:55:35 +00001078 } else if (SelectInst *BaseSI =
1079 dyn_cast<SelectInst>(State.getBaseValue())) {
Sanjoy Das90547f12016-06-26 04:55:05 +00001080 SelectInst *SI = cast<SelectInst>(BDV);
1081
1082 // Find the instruction which produces the base for each input.
1083 // We may need to insert a bitcast.
1084 BaseSI->setTrueValue(getBaseForInput(SI->getTrueValue(), BaseSI));
1085 BaseSI->setFalseValue(getBaseForInput(SI->getFalseValue(), BaseSI));
Sanjoy Das7dda0ed2016-06-26 04:55:35 +00001086 } else if (auto *BaseEE =
1087 dyn_cast<ExtractElementInst>(State.getBaseValue())) {
Philip Reames7540e3a2015-09-10 00:01:53 +00001088 Value *InVal = cast<ExtractElementInst>(BDV)->getVectorOperand();
Philip Reames3ea15892015-09-03 21:57:40 +00001089 // Find the instruction which produces the base for each input. We may
1090 // need to insert a bitcast.
Sanjoy Das90547f12016-06-26 04:55:05 +00001091 BaseEE->setOperand(0, getBaseForInput(InVal, BaseEE));
Anna Thomas479cbb92016-10-04 13:48:37 +00001092 } else if (auto *BaseIE = dyn_cast<InsertElementInst>(State.getBaseValue())){
Philip Reames7540e3a2015-09-10 00:01:53 +00001093 auto *BdvIE = cast<InsertElementInst>(BDV);
Philip Reames66287132015-09-09 23:40:12 +00001094 auto UpdateOperand = [&](int OperandIdx) {
1095 Value *InVal = BdvIE->getOperand(OperandIdx);
Philip Reames953817b2015-09-10 00:44:10 +00001096 Value *Base = getBaseForInput(InVal, BaseIE);
Philip Reames66287132015-09-09 23:40:12 +00001097 BaseIE->setOperand(OperandIdx, Base);
1098 };
1099 UpdateOperand(0); // vector operand
1100 UpdateOperand(1); // scalar operand
Anna Thomas479cbb92016-10-04 13:48:37 +00001101 } else {
1102 auto *BaseSV = cast<ShuffleVectorInst>(State.getBaseValue());
1103 auto *BdvSV = cast<ShuffleVectorInst>(BDV);
1104 auto UpdateOperand = [&](int OperandIdx) {
1105 Value *InVal = BdvSV->getOperand(OperandIdx);
1106 Value *Base = getBaseForInput(InVal, BaseSV);
1107 BaseSV->setOperand(OperandIdx, Base);
1108 };
1109 UpdateOperand(0); // vector operand
1110 UpdateOperand(1); // vector operand
Philip Reamesd16a9b12015-02-20 01:06:44 +00001111 }
1112 }
1113
1114 // Cache all of our results so we can cheaply reuse them
1115 // NOTE: This is actually two caches: one of the base defining value
1116 // relation and one of the base pointer relation! FIXME
Philip Reames34d7a742015-09-10 00:22:49 +00001117 for (auto Pair : States) {
Philip Reames15d55632015-09-09 23:26:08 +00001118 auto *BDV = Pair.first;
Sanjoy Das7dda0ed2016-06-26 04:55:35 +00001119 Value *Base = Pair.second.getBaseValue();
Sanjoy Das90547f12016-06-26 04:55:05 +00001120 assert(BDV && Base);
Philip Reames79fa9b72016-02-22 20:45:56 +00001121 assert(!isKnownBaseResult(BDV) && "why did it get added?");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001122
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001123 LLVM_DEBUG(
1124 dbgs() << "Updating base value cache"
1125 << " for: " << BDV->getName() << " from: "
1126 << (Cache.count(BDV) ? Cache[BDV]->getName().str() : "none")
1127 << " to: " << Base->getName() << "\n");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001128
Sanjoy Das90547f12016-06-26 04:55:05 +00001129 if (Cache.count(BDV)) {
1130 assert(isKnownBaseResult(Base) &&
Philip Reames79fa9b72016-02-22 20:45:56 +00001131 "must be something we 'know' is a base pointer");
Sanjoy Das90547f12016-06-26 04:55:05 +00001132 // Once we transition from the BDV relation being store in the Cache to
Philip Reamesd16a9b12015-02-20 01:06:44 +00001133 // the base relation being stored, it must be stable
Sanjoy Das90547f12016-06-26 04:55:05 +00001134 assert((!isKnownBaseResult(Cache[BDV]) || Cache[BDV] == Base) &&
Philip Reamesd16a9b12015-02-20 01:06:44 +00001135 "base relation should be stable");
1136 }
Sanjoy Das90547f12016-06-26 04:55:05 +00001137 Cache[BDV] = Base;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001138 }
Sanjoy Das90547f12016-06-26 04:55:05 +00001139 assert(Cache.count(Def));
1140 return Cache[Def];
Philip Reamesd16a9b12015-02-20 01:06:44 +00001141}
1142
1143// For a set of live pointers (base and/or derived), identify the base
1144// pointer of the object which they are derived from. This routine will
1145// mutate the IR graph as needed to make the 'base' pointer live at the
1146// definition site of 'derived'. This ensures that any use of 'derived' can
1147// also use 'base'. This may involve the insertion of a number of
1148// additional PHI nodes.
1149//
1150// preconditions: live is a set of pointer type Values
1151//
1152// side effects: may insert PHI nodes into the existing CFG, will preserve
1153// CFG, will not remove or mutate any existing nodes
1154//
Philip Reamesf2041322015-02-20 19:26:04 +00001155// post condition: PointerToBase contains one (derived, base) pair for every
Philip Reamesd16a9b12015-02-20 01:06:44 +00001156// pointer in live. Note that derived can be equal to base if the original
1157// pointer was a base pointer.
Philip Reames704e78b2015-04-10 22:34:56 +00001158static void
1159findBasePointers(const StatepointLiveSetTy &live,
Igor Laevskyfb1811d2016-05-04 14:55:36 +00001160 MapVector<Value *, Value *> &PointerToBase,
Philip Reamesba198492015-04-14 00:41:34 +00001161 DominatorTree *DT, DefiningValueMapTy &DVCache) {
Igor Laevskyfb1811d2016-05-04 14:55:36 +00001162 for (Value *ptr : live) {
Philip Reamesba198492015-04-14 00:41:34 +00001163 Value *base = findBasePointer(ptr, DVCache);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001164 assert(base && "failed to find base pointer");
Philip Reamesf2041322015-02-20 19:26:04 +00001165 PointerToBase[ptr] = base;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001166 assert((!isa<Instruction>(base) || !isa<Instruction>(ptr) ||
1167 DT->dominates(cast<Instruction>(base)->getParent(),
1168 cast<Instruction>(ptr)->getParent())) &&
1169 "The base we found better dominate the derived pointer");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001170 }
1171}
1172
1173/// Find the required based pointers (and adjust the live set) for the given
1174/// parse point.
1175static void findBasePointers(DominatorTree &DT, DefiningValueMapTy &DVCache,
Chandler Carruth31607342019-02-11 07:42:30 +00001176 CallBase *Call,
Philip Reamesd16a9b12015-02-20 01:06:44 +00001177 PartiallyConstructedSafepointRecord &result) {
Igor Laevskyfb1811d2016-05-04 14:55:36 +00001178 MapVector<Value *, Value *> PointerToBase;
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001179 findBasePointers(result.LiveSet, PointerToBase, &DT, DVCache);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001180
1181 if (PrintBasePointers) {
1182 errs() << "Base Pairs (w/o Relocation):\n";
Igor Laevskyfb1811d2016-05-04 14:55:36 +00001183 for (auto &Pair : PointerToBase) {
Manuel Jacoba4efd8a2015-12-23 00:19:45 +00001184 errs() << " derived ";
Igor Laevskyfb1811d2016-05-04 14:55:36 +00001185 Pair.first->printAsOperand(errs(), false);
Manuel Jacoba4efd8a2015-12-23 00:19:45 +00001186 errs() << " base ";
Igor Laevskyfb1811d2016-05-04 14:55:36 +00001187 Pair.second->printAsOperand(errs(), false);
Manuel Jacoba4efd8a2015-12-23 00:19:45 +00001188 errs() << "\n";;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001189 }
1190 }
1191
Philip Reamesf2041322015-02-20 19:26:04 +00001192 result.PointerToBase = PointerToBase;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001193}
1194
Philip Reamesdf1ef082015-04-10 22:53:14 +00001195/// Given an updated version of the dataflow liveness results, update the
1196/// liveset and base pointer maps for the call site CS.
1197static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData,
Chandler Carruth31607342019-02-11 07:42:30 +00001198 CallBase *Call,
Philip Reamesdf1ef082015-04-10 22:53:14 +00001199 PartiallyConstructedSafepointRecord &result);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001200
Philip Reamesdf1ef082015-04-10 22:53:14 +00001201static void recomputeLiveInValues(
Chandler Carruth31607342019-02-11 07:42:30 +00001202 Function &F, DominatorTree &DT, ArrayRef<CallBase *> toUpdate,
Philip Reamesd2b66462015-02-20 22:39:41 +00001203 MutableArrayRef<struct PartiallyConstructedSafepointRecord> records) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00001204 // TODO-PERF: reuse the original liveness, then simply run the dataflow
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001205 // again. The old values are still live and will help it stabilize quickly.
Philip Reamesdf1ef082015-04-10 22:53:14 +00001206 GCPtrLivenessData RevisedLivenessData;
1207 computeLiveInValues(DT, F, RevisedLivenessData);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001208 for (size_t i = 0; i < records.size(); i++) {
1209 struct PartiallyConstructedSafepointRecord &info = records[i];
Sanjoy Dasa3244872016-06-17 00:45:00 +00001210 recomputeLiveInValues(RevisedLivenessData, toUpdate[i], info);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001211 }
1212}
1213
Sanjoy Das7ad67642015-10-20 01:06:24 +00001214// When inserting gc.relocate and gc.result calls, we need to ensure there are
1215// no uses of the original value / return value between the gc.statepoint and
1216// the gc.relocate / gc.result call. One case which can arise is a phi node
1217// starting one of the successor blocks. We also need to be able to insert the
1218// gc.relocates only on the path which goes through the statepoint. We might
1219// need to split an edge to make this possible.
Philip Reamesf209a152015-04-13 20:00:30 +00001220static BasicBlock *
Sanjoy Dasea45f0e2015-06-02 22:33:34 +00001221normalizeForInvokeSafepoint(BasicBlock *BB, BasicBlock *InvokeParent,
1222 DominatorTree &DT) {
Philip Reames69e51ca2015-04-13 18:07:21 +00001223 BasicBlock *Ret = BB;
Sanjoy Dasff3dba72015-10-20 01:06:17 +00001224 if (!BB->getUniquePredecessor())
Chandler Carruth96ada252015-07-22 09:52:54 +00001225 Ret = SplitBlockPredecessors(BB, InvokeParent, "", &DT);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001226
Sanjoy Das7ad67642015-10-20 01:06:24 +00001227 // Now that 'Ret' has unique predecessor we can safely remove all phi nodes
Philip Reames69e51ca2015-04-13 18:07:21 +00001228 // from it
1229 FoldSingleEntryPHINodes(Ret);
Sanjoy Dasff3dba72015-10-20 01:06:17 +00001230 assert(!isa<PHINode>(Ret->begin()) &&
1231 "All PHI nodes should have been removed!");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001232
Sanjoy Das7ad67642015-10-20 01:06:24 +00001233 // At this point, we can safely insert a gc.relocate or gc.result as the first
1234 // instruction in Ret if needed.
Philip Reames69e51ca2015-04-13 18:07:21 +00001235 return Ret;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001236}
1237
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001238// Create new attribute set containing only attributes which can be transferred
Philip Reamesd16a9b12015-02-20 01:06:44 +00001239// from original call to the safepoint.
Reid Kleckner99351962017-04-28 19:22:40 +00001240static AttributeList legalizeCallAttributes(AttributeList AL) {
1241 if (AL.isEmpty())
1242 return AL;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001243
Reid Kleckner99351962017-04-28 19:22:40 +00001244 // Remove the readonly, readnone, and statepoint function attributes.
1245 AttrBuilder FnAttrs = AL.getFnAttributes();
1246 FnAttrs.removeAttribute(Attribute::ReadNone);
1247 FnAttrs.removeAttribute(Attribute::ReadOnly);
1248 for (Attribute A : AL.getFnAttributes()) {
1249 if (isStatepointDirectiveAttr(A))
1250 FnAttrs.remove(A);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001251 }
1252
Reid Kleckner99351962017-04-28 19:22:40 +00001253 // Just skip parameter and return attributes for now
1254 LLVMContext &Ctx = AL.getContext();
1255 return AttributeList::get(Ctx, AttributeList::FunctionIndex,
1256 AttributeSet::get(Ctx, FnAttrs));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001257}
1258
1259/// Helper function to place all gc relocates necessary for the given
1260/// statepoint.
1261/// Inputs:
1262/// liveVariables - list of variables to be relocated.
1263/// liveStart - index of the first live variable.
1264/// basePtrs - base pointers.
1265/// statepointToken - statepoint instruction to which relocates should be
1266/// bound.
1267/// Builder - Llvm IR builder to be used to construct new calls.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001268static void CreateGCRelocates(ArrayRef<Value *> LiveVariables,
Sanjoy Das5665c992015-05-11 23:47:27 +00001269 const int LiveStart,
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001270 ArrayRef<Value *> BasePtrs,
Sanjoy Das5665c992015-05-11 23:47:27 +00001271 Instruction *StatepointToken,
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00001272 IRBuilder<> Builder) {
Philip Reames94babb72015-07-21 17:18:03 +00001273 if (LiveVariables.empty())
1274 return;
Sanjoy Dasb1942f12015-10-20 01:06:28 +00001275
1276 auto FindIndex = [](ArrayRef<Value *> LiveVec, Value *Val) {
Eugene Zelenko75075ef2017-09-01 21:37:29 +00001277 auto ValIt = llvm::find(LiveVec, Val);
Sanjoy Dasb1942f12015-10-20 01:06:28 +00001278 assert(ValIt != LiveVec.end() && "Val not found in LiveVec!");
1279 size_t Index = std::distance(LiveVec.begin(), ValIt);
1280 assert(Index < LiveVec.size() && "Bug in std::find?");
1281 return Index;
1282 };
Philip Reames74ce2e72015-07-21 16:51:17 +00001283 Module *M = StatepointToken->getModule();
Fangrui Songf78650a2018-07-30 19:41:25 +00001284
Philip Reames5715f572016-01-09 01:31:13 +00001285 // All gc_relocate are generated as i8 addrspace(1)* (or a vector type whose
1286 // element type is i8 addrspace(1)*). We originally generated unique
1287 // declarations for each pointer type, but this proved problematic because
1288 // the intrinsic mangling code is incomplete and fragile. Since we're moving
1289 // towards a single unified pointer type anyways, we can just cast everything
1290 // to an i8* of the right address space. A bitcast is added later to convert
Fangrui Songf78650a2018-07-30 19:41:25 +00001291 // gc_relocate to the actual value's type.
Philip Reames5715f572016-01-09 01:31:13 +00001292 auto getGCRelocateDecl = [&] (Type *Ty) {
1293 assert(isHandledGCPointerType(Ty));
1294 auto AS = Ty->getScalarType()->getPointerAddressSpace();
1295 Type *NewTy = Type::getInt8PtrTy(M->getContext(), AS);
1296 if (auto *VT = dyn_cast<VectorType>(Ty))
1297 NewTy = VectorType::get(NewTy, VT->getNumElements());
1298 return Intrinsic::getDeclaration(M, Intrinsic::experimental_gc_relocate,
1299 {NewTy});
1300 };
1301
1302 // Lazily populated map from input types to the canonicalized form mentioned
1303 // in the comment above. This should probably be cached somewhere more
1304 // broadly.
James Y Knight7976eb52019-02-01 20:43:25 +00001305 DenseMap<Type *, Function *> TypeToDeclMap;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001306
Sanjoy Das5665c992015-05-11 23:47:27 +00001307 for (unsigned i = 0; i < LiveVariables.size(); i++) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001308 // Generate the gc.relocate call and save the result
Sanjoy Das5665c992015-05-11 23:47:27 +00001309 Value *BaseIdx =
Sanjoy Dasb1942f12015-10-20 01:06:28 +00001310 Builder.getInt32(LiveStart + FindIndex(LiveVariables, BasePtrs[i]));
Sanjoy Das3020b1b2015-10-20 01:06:31 +00001311 Value *LiveIdx = Builder.getInt32(LiveStart + i);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001312
Philip Reames5715f572016-01-09 01:31:13 +00001313 Type *Ty = LiveVariables[i]->getType();
1314 if (!TypeToDeclMap.count(Ty))
1315 TypeToDeclMap[Ty] = getGCRelocateDecl(Ty);
James Y Knight7976eb52019-02-01 20:43:25 +00001316 Function *GCRelocateDecl = TypeToDeclMap[Ty];
Philip Reames5715f572016-01-09 01:31:13 +00001317
Philip Reamesd16a9b12015-02-20 01:06:44 +00001318 // only specify a debug name if we can give a useful one
Philip Reames74ce2e72015-07-21 16:51:17 +00001319 CallInst *Reloc = Builder.CreateCall(
David Blaikieff6409d2015-05-18 22:13:54 +00001320 GCRelocateDecl, {StatepointToken, BaseIdx, LiveIdx},
Philip Reamesece70b82015-09-09 23:57:18 +00001321 suffixed_name_or(LiveVariables[i], ".relocated", ""));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001322 // Trick CodeGen into thinking there are lots of free registers at this
1323 // fake call.
Philip Reames74ce2e72015-07-21 16:51:17 +00001324 Reloc->setCallingConv(CallingConv::Cold);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001325 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00001326}
1327
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001328namespace {
1329
1330/// This struct is used to defer RAUWs and `eraseFromParent` s. Using this
1331/// avoids having to worry about keeping around dangling pointers to Values.
1332class DeferredReplacement {
1333 AssertingVH<Instruction> Old;
1334 AssertingVH<Instruction> New;
Sanjoy Das49e974b2016-04-05 23:18:35 +00001335 bool IsDeoptimize = false;
1336
Eugene Zelenko75075ef2017-09-01 21:37:29 +00001337 DeferredReplacement() = default;
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001338
1339public:
Sanjoy Das8d89a2b2016-04-05 23:18:53 +00001340 static DeferredReplacement createRAUW(Instruction *Old, Instruction *New) {
1341 assert(Old != New && Old && New &&
1342 "Cannot RAUW equal values or to / from null!");
1343
1344 DeferredReplacement D;
1345 D.Old = Old;
1346 D.New = New;
1347 return D;
1348 }
1349
1350 static DeferredReplacement createDelete(Instruction *ToErase) {
1351 DeferredReplacement D;
1352 D.Old = ToErase;
1353 return D;
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001354 }
1355
Sanjoy Das49e974b2016-04-05 23:18:35 +00001356 static DeferredReplacement createDeoptimizeReplacement(Instruction *Old) {
1357#ifndef NDEBUG
1358 auto *F = cast<CallInst>(Old)->getCalledFunction();
1359 assert(F && F->getIntrinsicID() == Intrinsic::experimental_deoptimize &&
1360 "Only way to construct a deoptimize deferred replacement");
1361#endif
1362 DeferredReplacement D;
1363 D.Old = Old;
1364 D.IsDeoptimize = true;
1365 return D;
1366 }
1367
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001368 /// Does the task represented by this instance.
1369 void doReplacement() {
1370 Instruction *OldI = Old;
1371 Instruction *NewI = New;
1372
1373 assert(OldI != NewI && "Disallowed at construction?!");
Richard Trieuf35d4b02016-04-06 04:22:00 +00001374 assert((!IsDeoptimize || !New) &&
Hiroshi Inouef2096492018-06-14 05:41:49 +00001375 "Deoptimize intrinsics are not replaced!");
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001376
1377 Old = nullptr;
1378 New = nullptr;
1379
1380 if (NewI)
1381 OldI->replaceAllUsesWith(NewI);
Sanjoy Das49e974b2016-04-05 23:18:35 +00001382
1383 if (IsDeoptimize) {
1384 // Note: we've inserted instructions, so the call to llvm.deoptimize may
Hiroshi Inouef2096492018-06-14 05:41:49 +00001385 // not necessarily be followed by the matching return.
Sanjoy Das49e974b2016-04-05 23:18:35 +00001386 auto *RI = cast<ReturnInst>(OldI->getParent()->getTerminator());
1387 new UnreachableInst(RI->getContext(), RI);
1388 RI->eraseFromParent();
1389 }
1390
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001391 OldI->eraseFromParent();
1392 }
1393};
Eugene Zelenko75075ef2017-09-01 21:37:29 +00001394
1395} // end anonymous namespace
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001396
Chandler Carruth31607342019-02-11 07:42:30 +00001397static StringRef getDeoptLowering(CallBase *Call) {
Philip Reames2b1084a2016-08-31 15:12:17 +00001398 const char *DeoptLowering = "deopt-lowering";
Chandler Carruth31607342019-02-11 07:42:30 +00001399 if (Call->hasFnAttr(DeoptLowering)) {
1400 // FIXME: Calls have a *really* confusing interface around attributes
Reid Klecknerb5180542017-03-21 16:57:19 +00001401 // with values.
Chandler Carruth31607342019-02-11 07:42:30 +00001402 const AttributeList &CSAS = Call->getAttributes();
Reid Klecknerb5180542017-03-21 16:57:19 +00001403 if (CSAS.hasAttribute(AttributeList::FunctionIndex, DeoptLowering))
1404 return CSAS.getAttribute(AttributeList::FunctionIndex, DeoptLowering)
1405 .getValueAsString();
Chandler Carruth31607342019-02-11 07:42:30 +00001406 Function *F = Call->getCalledFunction();
Philip Reames2b1084a2016-08-31 15:12:17 +00001407 assert(F && F->hasFnAttribute(DeoptLowering));
1408 return F->getFnAttribute(DeoptLowering).getValueAsString();
1409 }
1410 return "live-through";
1411}
Fangrui Songf78650a2018-07-30 19:41:25 +00001412
Philip Reamesd16a9b12015-02-20 01:06:44 +00001413static void
Chandler Carruth31607342019-02-11 07:42:30 +00001414makeStatepointExplicitImpl(CallBase *Call, /* to replace */
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001415 const SmallVectorImpl<Value *> &BasePtrs,
1416 const SmallVectorImpl<Value *> &LiveVariables,
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001417 PartiallyConstructedSafepointRecord &Result,
1418 std::vector<DeferredReplacement> &Replacements) {
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001419 assert(BasePtrs.size() == LiveVariables.size());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001420
Philip Reamesd16a9b12015-02-20 01:06:44 +00001421 // Then go ahead and use the builder do actually do the inserts. We insert
1422 // immediately before the previous instruction under the assumption that all
1423 // arguments will be available here. We can't insert afterwards since we may
1424 // be replacing a terminator.
Chandler Carruth31607342019-02-11 07:42:30 +00001425 IRBuilder<> Builder(Call);
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001426
Sanjoy Das3c520a12015-10-08 23:18:38 +00001427 ArrayRef<Value *> GCArgs(LiveVariables);
Sanjoy Dasc9058ca2016-03-17 18:42:17 +00001428 uint64_t StatepointID = StatepointDirectives::DefaultStatepointID;
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001429 uint32_t NumPatchBytes = 0;
1430 uint32_t Flags = uint32_t(StatepointFlags::None);
Sanjoy Das3c520a12015-10-08 23:18:38 +00001431
Chandler Carruth31607342019-02-11 07:42:30 +00001432 ArrayRef<Use> CallArgs(Call->arg_begin(), Call->arg_end());
1433 ArrayRef<Use> DeoptArgs = GetDeoptBundleOperands(Call);
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001434 ArrayRef<Use> TransitionArgs;
Sanjoy Das40992972016-01-29 01:03:17 +00001435 if (auto TransitionBundle =
Chandler Carruth31607342019-02-11 07:42:30 +00001436 Call->getOperandBundle(LLVMContext::OB_gc_transition)) {
Sanjoy Das40992972016-01-29 01:03:17 +00001437 Flags |= uint32_t(StatepointFlags::GCTransition);
1438 TransitionArgs = TransitionBundle->Inputs;
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001439 }
Sanjoy Das99abb272016-04-06 01:33:54 +00001440
1441 // Instead of lowering calls to @llvm.experimental.deoptimize as normal calls
1442 // with a return value, we lower then as never returning calls to
1443 // __llvm_deoptimize that are followed by unreachable to get better codegen.
Sanjoy Das49e974b2016-04-05 23:18:35 +00001444 bool IsDeoptimize = false;
Sanjoy Das40992972016-01-29 01:03:17 +00001445
Sanjoy Das31203882016-03-17 01:56:10 +00001446 StatepointDirectives SD =
Chandler Carruth31607342019-02-11 07:42:30 +00001447 parseStatepointDirectivesFromAttrs(Call->getAttributes());
Sanjoy Das31203882016-03-17 01:56:10 +00001448 if (SD.NumPatchBytes)
1449 NumPatchBytes = *SD.NumPatchBytes;
1450 if (SD.StatepointID)
1451 StatepointID = *SD.StatepointID;
Sanjoy Das40992972016-01-29 01:03:17 +00001452
Philip Reames2b1084a2016-08-31 15:12:17 +00001453 // Pass through the requested lowering if any. The default is live-through.
Chandler Carruth31607342019-02-11 07:42:30 +00001454 StringRef DeoptLowering = getDeoptLowering(Call);
Philip Reames2b1084a2016-08-31 15:12:17 +00001455 if (DeoptLowering.equals("live-in"))
1456 Flags |= uint32_t(StatepointFlags::DeoptLiveIn);
1457 else {
1458 assert(DeoptLowering.equals("live-through") && "Unsupported value!");
1459 }
1460
Chandler Carruth31607342019-02-11 07:42:30 +00001461 Value *CallTarget = Call->getCalledValue();
Sanjoy Dasd4c78332016-03-25 20:12:13 +00001462 if (Function *F = dyn_cast<Function>(CallTarget)) {
1463 if (F->getIntrinsicID() == Intrinsic::experimental_deoptimize) {
Sanjoy Das091fcfa2016-05-06 20:39:33 +00001464 // Calls to llvm.experimental.deoptimize are lowered to calls to the
Sanjoy Dasd4c78332016-03-25 20:12:13 +00001465 // __llvm_deoptimize symbol. We want to resolve this now, since the
1466 // verifier does not allow taking the address of an intrinsic function.
1467
1468 SmallVector<Type *, 8> DomainTy;
1469 for (Value *Arg : CallArgs)
1470 DomainTy.push_back(Arg->getType());
Sanjoy Das49e974b2016-04-05 23:18:35 +00001471 auto *FTy = FunctionType::get(Type::getVoidTy(F->getContext()), DomainTy,
Sanjoy Dasd4c78332016-03-25 20:12:13 +00001472 /* isVarArg = */ false);
1473
1474 // Note: CallTarget can be a bitcast instruction of a symbol if there are
1475 // calls to @llvm.experimental.deoptimize with different argument types in
1476 // the same module. This is fine -- we assume the frontend knew what it
1477 // was doing when generating this kind of IR.
James Y Knight13680222019-02-01 02:28:03 +00001478 CallTarget = F->getParent()
1479 ->getOrInsertFunction("__llvm_deoptimize", FTy)
1480 .getCallee();
Sanjoy Das49e974b2016-04-05 23:18:35 +00001481
1482 IsDeoptimize = true;
Sanjoy Dasd4c78332016-03-25 20:12:13 +00001483 }
1484 }
Sanjoy Das40992972016-01-29 01:03:17 +00001485
Philip Reamesd16a9b12015-02-20 01:06:44 +00001486 // Create the statepoint given all the arguments
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001487 Instruction *Token = nullptr;
Chandler Carruth31607342019-02-11 07:42:30 +00001488 if (auto *CI = dyn_cast<CallInst>(Call)) {
1489 CallInst *SPCall = Builder.CreateGCStatepointCall(
Sanjoy Das3c520a12015-10-08 23:18:38 +00001490 StatepointID, NumPatchBytes, CallTarget, Flags, CallArgs,
1491 TransitionArgs, DeoptArgs, GCArgs, "safepoint_token");
1492
Chandler Carruth31607342019-02-11 07:42:30 +00001493 SPCall->setTailCallKind(CI->getTailCallKind());
1494 SPCall->setCallingConv(CI->getCallingConv());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001495
1496 // Currently we will fail on parameter attributes and on certain
Reid Kleckner99351962017-04-28 19:22:40 +00001497 // function attributes. In case if we can handle this set of attributes -
1498 // set up function attrs directly on statepoint and return attrs later for
1499 // gc_result intrinsic.
Chandler Carruth31607342019-02-11 07:42:30 +00001500 SPCall->setAttributes(legalizeCallAttributes(CI->getAttributes()));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001501
Chandler Carruth31607342019-02-11 07:42:30 +00001502 Token = SPCall;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001503
1504 // Put the following gc_result and gc_relocate calls immediately after the
1505 // the old call (which we're about to delete)
Chandler Carruth31607342019-02-11 07:42:30 +00001506 assert(CI->getNextNode() && "Not a terminator, must have next!");
1507 Builder.SetInsertPoint(CI->getNextNode());
1508 Builder.SetCurrentDebugLocation(CI->getNextNode()->getDebugLoc());
David Blaikie82ad7872015-02-20 23:44:24 +00001509 } else {
Chandler Carruth31607342019-02-11 07:42:30 +00001510 auto *II = cast<InvokeInst>(Call);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001511
1512 // Insert the new invoke into the old block. We'll remove the old one in a
1513 // moment at which point this will become the new terminator for the
1514 // original block.
Chandler Carruth31607342019-02-11 07:42:30 +00001515 InvokeInst *SPInvoke = Builder.CreateGCStatepointInvoke(
1516 StatepointID, NumPatchBytes, CallTarget, II->getNormalDest(),
1517 II->getUnwindDest(), Flags, CallArgs, TransitionArgs, DeoptArgs, GCArgs,
1518 "statepoint_token");
Sanjoy Das3c520a12015-10-08 23:18:38 +00001519
Chandler Carruth31607342019-02-11 07:42:30 +00001520 SPInvoke->setCallingConv(II->getCallingConv());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001521
1522 // Currently we will fail on parameter attributes and on certain
Reid Kleckner99351962017-04-28 19:22:40 +00001523 // function attributes. In case if we can handle this set of attributes -
1524 // set up function attrs directly on statepoint and return attrs later for
1525 // gc_result intrinsic.
Chandler Carruth31607342019-02-11 07:42:30 +00001526 SPInvoke->setAttributes(legalizeCallAttributes(II->getAttributes()));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001527
Chandler Carruth31607342019-02-11 07:42:30 +00001528 Token = SPInvoke;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001529
1530 // Generate gc relocates in exceptional path
Chandler Carruth31607342019-02-11 07:42:30 +00001531 BasicBlock *UnwindBlock = II->getUnwindDest();
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001532 assert(!isa<PHINode>(UnwindBlock->begin()) &&
1533 UnwindBlock->getUniquePredecessor() &&
Philip Reames69e51ca2015-04-13 18:07:21 +00001534 "can't safely insert in this block!");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001535
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001536 Builder.SetInsertPoint(&*UnwindBlock->getFirstInsertionPt());
Chandler Carruth31607342019-02-11 07:42:30 +00001537 Builder.SetCurrentDebugLocation(II->getDebugLoc());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001538
Chen Lid71999e2015-12-26 07:54:32 +00001539 // Attach exceptional gc relocates to the landingpad.
1540 Instruction *ExceptionalToken = UnwindBlock->getLandingPadInst();
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001541 Result.UnwindToken = ExceptionalToken;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001542
Sanjoy Das3c520a12015-10-08 23:18:38 +00001543 const unsigned LiveStartIdx = Statepoint(Token).gcArgsStartIdx();
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001544 CreateGCRelocates(LiveVariables, LiveStartIdx, BasePtrs, ExceptionalToken,
1545 Builder);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001546
1547 // Generate gc relocates and returns for normal block
Chandler Carruth31607342019-02-11 07:42:30 +00001548 BasicBlock *NormalDest = II->getNormalDest();
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001549 assert(!isa<PHINode>(NormalDest->begin()) &&
1550 NormalDest->getUniquePredecessor() &&
Philip Reames69e51ca2015-04-13 18:07:21 +00001551 "can't safely insert in this block!");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001552
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001553 Builder.SetInsertPoint(&*NormalDest->getFirstInsertionPt());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001554
1555 // gc relocates will be generated later as if it were regular call
1556 // statepoint
Philip Reamesd16a9b12015-02-20 01:06:44 +00001557 }
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001558 assert(Token && "Should be set in one of the above branches!");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001559
Sanjoy Das49e974b2016-04-05 23:18:35 +00001560 if (IsDeoptimize) {
1561 // If we're wrapping an @llvm.experimental.deoptimize in a statepoint, we
1562 // transform the tail-call like structure to a call to a void function
1563 // followed by unreachable to get better codegen.
1564 Replacements.push_back(
Chandler Carruth31607342019-02-11 07:42:30 +00001565 DeferredReplacement::createDeoptimizeReplacement(Call));
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001566 } else {
Sanjoy Das49e974b2016-04-05 23:18:35 +00001567 Token->setName("statepoint_token");
Chandler Carruth31607342019-02-11 07:42:30 +00001568 if (!Call->getType()->isVoidTy() && !Call->use_empty()) {
1569 StringRef Name = Call->hasName() ? Call->getName() : "";
1570 CallInst *GCResult = Builder.CreateGCResult(Token, Call->getType(), Name);
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00001571 GCResult->setAttributes(
1572 AttributeList::get(GCResult->getContext(), AttributeList::ReturnIndex,
Chandler Carruth31607342019-02-11 07:42:30 +00001573 Call->getAttributes().getRetAttributes()));
Sanjoy Das49e974b2016-04-05 23:18:35 +00001574
1575 // We cannot RAUW or delete CS.getInstruction() because it could be in the
1576 // live set of some other safepoint, in which case that safepoint's
1577 // PartiallyConstructedSafepointRecord will hold a raw pointer to this
1578 // llvm::Instruction. Instead, we defer the replacement and deletion to
1579 // after the live sets have been made explicit in the IR, and we no longer
1580 // have raw pointers to worry about.
Sanjoy Das8d89a2b2016-04-05 23:18:53 +00001581 Replacements.emplace_back(
Chandler Carruth31607342019-02-11 07:42:30 +00001582 DeferredReplacement::createRAUW(Call, GCResult));
Sanjoy Das49e974b2016-04-05 23:18:35 +00001583 } else {
Chandler Carruth31607342019-02-11 07:42:30 +00001584 Replacements.emplace_back(DeferredReplacement::createDelete(Call));
Sanjoy Das49e974b2016-04-05 23:18:35 +00001585 }
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001586 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00001587
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001588 Result.StatepointToken = Token;
Philip Reames0a3240f2015-02-20 21:34:11 +00001589
Philip Reamesd16a9b12015-02-20 01:06:44 +00001590 // Second, create a gc.relocate for every live variable
Sanjoy Das3c520a12015-10-08 23:18:38 +00001591 const unsigned LiveStartIdx = Statepoint(Token).gcArgsStartIdx();
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001592 CreateGCRelocates(LiveVariables, LiveStartIdx, BasePtrs, Token, Builder);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001593}
1594
Philip Reamesd16a9b12015-02-20 01:06:44 +00001595// Replace an existing gc.statepoint with a new one and a set of gc.relocates
1596// which make the relocations happening at this safepoint explicit.
Philip Reames704e78b2015-04-10 22:34:56 +00001597//
Philip Reamesd16a9b12015-02-20 01:06:44 +00001598// WARNING: Does not do any fixup to adjust users of the original live
1599// values. That's the callers responsibility.
1600static void
Chandler Carruth31607342019-02-11 07:42:30 +00001601makeStatepointExplicit(DominatorTree &DT, CallBase *Call,
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001602 PartiallyConstructedSafepointRecord &Result,
1603 std::vector<DeferredReplacement> &Replacements) {
Sanjoy Das1ede5362015-10-08 23:18:22 +00001604 const auto &LiveSet = Result.LiveSet;
1605 const auto &PointerToBase = Result.PointerToBase;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001606
1607 // Convert to vector for efficient cross referencing.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001608 SmallVector<Value *, 64> BaseVec, LiveVec;
1609 LiveVec.reserve(LiveSet.size());
1610 BaseVec.reserve(LiveSet.size());
1611 for (Value *L : LiveSet) {
1612 LiveVec.push_back(L);
Philip Reames74ce2e72015-07-21 16:51:17 +00001613 assert(PointerToBase.count(L));
Sanjoy Das1ede5362015-10-08 23:18:22 +00001614 Value *Base = PointerToBase.find(L)->second;
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001615 BaseVec.push_back(Base);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001616 }
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001617 assert(LiveVec.size() == BaseVec.size());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001618
Philip Reamesd16a9b12015-02-20 01:06:44 +00001619 // Do the actual rewriting and delete the old statepoint
Chandler Carruth31607342019-02-11 07:42:30 +00001620 makeStatepointExplicitImpl(Call, BaseVec, LiveVec, Result, Replacements);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001621}
1622
1623// Helper function for the relocationViaAlloca.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001624//
1625// It receives iterator to the statepoint gc relocates and emits a store to the
1626// assigned location (via allocaMap) for the each one of them. It adds the
1627// visited values into the visitedLiveValues set, which we will later use them
1628// for sanity checking.
Philip Reamesd16a9b12015-02-20 01:06:44 +00001629static void
Sanjoy Das5665c992015-05-11 23:47:27 +00001630insertRelocationStores(iterator_range<Value::user_iterator> GCRelocs,
James Y Knight14359ef2019-02-01 20:44:24 +00001631 DenseMap<Value *, AllocaInst *> &AllocaMap,
Sanjoy Das5665c992015-05-11 23:47:27 +00001632 DenseSet<Value *> &VisitedLiveValues) {
Sanjoy Das5665c992015-05-11 23:47:27 +00001633 for (User *U : GCRelocs) {
Manuel Jacob83eefa62016-01-05 04:03:00 +00001634 GCRelocateInst *Relocate = dyn_cast<GCRelocateInst>(U);
1635 if (!Relocate)
Philip Reamesd16a9b12015-02-20 01:06:44 +00001636 continue;
1637
Sanjoy Das565f7862016-01-29 16:54:49 +00001638 Value *OriginalValue = Relocate->getDerivedPtr();
Sanjoy Das5665c992015-05-11 23:47:27 +00001639 assert(AllocaMap.count(OriginalValue));
1640 Value *Alloca = AllocaMap[OriginalValue];
Philip Reamesd16a9b12015-02-20 01:06:44 +00001641
1642 // Emit store into the related alloca
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001643 // All gc_relocates are i8 addrspace(1)* typed, and it must be bitcasted to
Sanjoy Das89c54912015-05-11 18:49:34 +00001644 // the correct type according to alloca.
Manuel Jacob83eefa62016-01-05 04:03:00 +00001645 assert(Relocate->getNextNode() &&
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001646 "Should always have one since it's not a terminator");
Manuel Jacob83eefa62016-01-05 04:03:00 +00001647 IRBuilder<> Builder(Relocate->getNextNode());
Sanjoy Das89c54912015-05-11 18:49:34 +00001648 Value *CastedRelocatedValue =
Manuel Jacob83eefa62016-01-05 04:03:00 +00001649 Builder.CreateBitCast(Relocate,
Philip Reamesece70b82015-09-09 23:57:18 +00001650 cast<AllocaInst>(Alloca)->getAllocatedType(),
Manuel Jacob83eefa62016-01-05 04:03:00 +00001651 suffixed_name_or(Relocate, ".casted", ""));
Sanjoy Das89c54912015-05-11 18:49:34 +00001652
Sanjoy Das5665c992015-05-11 23:47:27 +00001653 StoreInst *Store = new StoreInst(CastedRelocatedValue, Alloca);
1654 Store->insertAfter(cast<Instruction>(CastedRelocatedValue));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001655
1656#ifndef NDEBUG
Sanjoy Das5665c992015-05-11 23:47:27 +00001657 VisitedLiveValues.insert(OriginalValue);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001658#endif
1659 }
1660}
1661
Igor Laevskye0317182015-05-19 15:59:05 +00001662// Helper function for the "relocationViaAlloca". Similar to the
1663// "insertRelocationStores" but works for rematerialized values.
Joseph Tremouletadc23762016-02-05 01:42:52 +00001664static void insertRematerializationStores(
1665 const RematerializedValueMapTy &RematerializedValues,
James Y Knight14359ef2019-02-01 20:44:24 +00001666 DenseMap<Value *, AllocaInst *> &AllocaMap,
Joseph Tremouletadc23762016-02-05 01:42:52 +00001667 DenseSet<Value *> &VisitedLiveValues) {
Igor Laevskye0317182015-05-19 15:59:05 +00001668 for (auto RematerializedValuePair: RematerializedValues) {
1669 Instruction *RematerializedValue = RematerializedValuePair.first;
1670 Value *OriginalValue = RematerializedValuePair.second;
1671
1672 assert(AllocaMap.count(OriginalValue) &&
1673 "Can not find alloca for rematerialized value");
1674 Value *Alloca = AllocaMap[OriginalValue];
1675
1676 StoreInst *Store = new StoreInst(RematerializedValue, Alloca);
1677 Store->insertAfter(RematerializedValue);
1678
1679#ifndef NDEBUG
1680 VisitedLiveValues.insert(OriginalValue);
1681#endif
1682 }
1683}
1684
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001685/// Do all the relocation update via allocas and mem2reg
Philip Reamesd16a9b12015-02-20 01:06:44 +00001686static void relocationViaAlloca(
Igor Laevsky285fe842015-05-19 16:29:43 +00001687 Function &F, DominatorTree &DT, ArrayRef<Value *> Live,
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001688 ArrayRef<PartiallyConstructedSafepointRecord> Records) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001689#ifndef NDEBUG
Philip Reamesa6ebf072015-03-27 05:53:16 +00001690 // record initial number of (static) allocas; we'll check we have the same
1691 // number when we get done.
1692 int InitialAllocaNum = 0;
Benjamin Kramer135f7352016-06-26 12:28:59 +00001693 for (Instruction &I : F.getEntryBlock())
1694 if (isa<AllocaInst>(I))
Philip Reamesa6ebf072015-03-27 05:53:16 +00001695 InitialAllocaNum++;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001696#endif
1697
1698 // TODO-PERF: change data structures, reserve
James Y Knight14359ef2019-02-01 20:44:24 +00001699 DenseMap<Value *, AllocaInst *> AllocaMap;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001700 SmallVector<AllocaInst *, 200> PromotableAllocas;
Igor Laevskye0317182015-05-19 15:59:05 +00001701 // Used later to chack that we have enough allocas to store all values
1702 std::size_t NumRematerializedValues = 0;
Igor Laevsky285fe842015-05-19 16:29:43 +00001703 PromotableAllocas.reserve(Live.size());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001704
Igor Laevskye0317182015-05-19 15:59:05 +00001705 // Emit alloca for "LiveValue" and record it in "allocaMap" and
1706 // "PromotableAllocas"
Matt Arsenault3c1fc762017-04-10 22:27:50 +00001707 const DataLayout &DL = F.getParent()->getDataLayout();
Igor Laevskye0317182015-05-19 15:59:05 +00001708 auto emitAllocaFor = [&](Value *LiveValue) {
Matt Arsenault3c1fc762017-04-10 22:27:50 +00001709 AllocaInst *Alloca = new AllocaInst(LiveValue->getType(),
1710 DL.getAllocaAddrSpace(), "",
Igor Laevskye0317182015-05-19 15:59:05 +00001711 F.getEntryBlock().getFirstNonPHI());
Igor Laevsky285fe842015-05-19 16:29:43 +00001712 AllocaMap[LiveValue] = Alloca;
Igor Laevskye0317182015-05-19 15:59:05 +00001713 PromotableAllocas.push_back(Alloca);
1714 };
1715
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001716 // Emit alloca for each live gc pointer
1717 for (Value *V : Live)
1718 emitAllocaFor(V);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001719
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001720 // Emit allocas for rematerialized values
1721 for (const auto &Info : Records)
Igor Laevsky285fe842015-05-19 16:29:43 +00001722 for (auto RematerializedValuePair : Info.RematerializedValues) {
Igor Laevskye0317182015-05-19 15:59:05 +00001723 Value *OriginalValue = RematerializedValuePair.second;
Igor Laevsky285fe842015-05-19 16:29:43 +00001724 if (AllocaMap.count(OriginalValue) != 0)
Igor Laevskye0317182015-05-19 15:59:05 +00001725 continue;
1726
1727 emitAllocaFor(OriginalValue);
1728 ++NumRematerializedValues;
1729 }
Igor Laevsky285fe842015-05-19 16:29:43 +00001730
Philip Reamesd16a9b12015-02-20 01:06:44 +00001731 // The next two loops are part of the same conceptual operation. We need to
1732 // insert a store to the alloca after the original def and at each
1733 // redefinition. We need to insert a load before each use. These are split
1734 // into distinct loops for performance reasons.
1735
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001736 // Update gc pointer after each statepoint: either store a relocated value or
1737 // null (if no relocated value was found for this gc pointer and it is not a
1738 // gc_result). This must happen before we update the statepoint with load of
1739 // alloca otherwise we lose the link between statepoint and old def.
1740 for (const auto &Info : Records) {
Igor Laevsky285fe842015-05-19 16:29:43 +00001741 Value *Statepoint = Info.StatepointToken;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001742
1743 // This will be used for consistency check
Igor Laevsky285fe842015-05-19 16:29:43 +00001744 DenseSet<Value *> VisitedLiveValues;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001745
1746 // Insert stores for normal statepoint gc relocates
Igor Laevsky285fe842015-05-19 16:29:43 +00001747 insertRelocationStores(Statepoint->users(), AllocaMap, VisitedLiveValues);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001748
1749 // In case if it was invoke statepoint
1750 // we will insert stores for exceptional path gc relocates.
Philip Reames0a3240f2015-02-20 21:34:11 +00001751 if (isa<InvokeInst>(Statepoint)) {
Igor Laevsky285fe842015-05-19 16:29:43 +00001752 insertRelocationStores(Info.UnwindToken->users(), AllocaMap,
1753 VisitedLiveValues);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001754 }
1755
Igor Laevskye0317182015-05-19 15:59:05 +00001756 // Do similar thing with rematerialized values
Igor Laevsky285fe842015-05-19 16:29:43 +00001757 insertRematerializationStores(Info.RematerializedValues, AllocaMap,
1758 VisitedLiveValues);
Igor Laevskye0317182015-05-19 15:59:05 +00001759
Philip Reamese73300b2015-04-13 16:41:32 +00001760 if (ClobberNonLive) {
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001761 // As a debugging aid, pretend that an unrelocated pointer becomes null at
Philip Reamese73300b2015-04-13 16:41:32 +00001762 // the gc.statepoint. This will turn some subtle GC problems into
1763 // slightly easier to debug SEGVs. Note that on large IR files with
1764 // lots of gc.statepoints this is extremely costly both memory and time
1765 // wise.
1766 SmallVector<AllocaInst *, 64> ToClobber;
Igor Laevsky285fe842015-05-19 16:29:43 +00001767 for (auto Pair : AllocaMap) {
Philip Reamese73300b2015-04-13 16:41:32 +00001768 Value *Def = Pair.first;
James Y Knight14359ef2019-02-01 20:44:24 +00001769 AllocaInst *Alloca = Pair.second;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001770
Philip Reamese73300b2015-04-13 16:41:32 +00001771 // This value was relocated
Igor Laevsky285fe842015-05-19 16:29:43 +00001772 if (VisitedLiveValues.count(Def)) {
Philip Reamese73300b2015-04-13 16:41:32 +00001773 continue;
1774 }
1775 ToClobber.push_back(Alloca);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001776 }
Philip Reamesfa2fcf172015-02-20 19:51:56 +00001777
Philip Reamese73300b2015-04-13 16:41:32 +00001778 auto InsertClobbersAt = [&](Instruction *IP) {
1779 for (auto *AI : ToClobber) {
Eduard Burtescu90c44492016-01-18 00:10:01 +00001780 auto PT = cast<PointerType>(AI->getAllocatedType());
Philip Reamese73300b2015-04-13 16:41:32 +00001781 Constant *CPN = ConstantPointerNull::get(PT);
Igor Laevsky285fe842015-05-19 16:29:43 +00001782 StoreInst *Store = new StoreInst(CPN, AI);
1783 Store->insertBefore(IP);
Philip Reamese73300b2015-04-13 16:41:32 +00001784 }
1785 };
1786
1787 // Insert the clobbering stores. These may get intermixed with the
1788 // gc.results and gc.relocates, but that's fine.
1789 if (auto II = dyn_cast<InvokeInst>(Statepoint)) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001790 InsertClobbersAt(&*II->getNormalDest()->getFirstInsertionPt());
1791 InsertClobbersAt(&*II->getUnwindDest()->getFirstInsertionPt());
Philip Reamese73300b2015-04-13 16:41:32 +00001792 } else {
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001793 InsertClobbersAt(cast<Instruction>(Statepoint)->getNextNode());
Philip Reamesfa2fcf172015-02-20 19:51:56 +00001794 }
David Blaikie82ad7872015-02-20 23:44:24 +00001795 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00001796 }
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001797
1798 // Update use with load allocas and add store for gc_relocated.
Igor Laevsky285fe842015-05-19 16:29:43 +00001799 for (auto Pair : AllocaMap) {
1800 Value *Def = Pair.first;
James Y Knight14359ef2019-02-01 20:44:24 +00001801 AllocaInst *Alloca = Pair.second;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001802
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001803 // We pre-record the uses of allocas so that we dont have to worry about
1804 // later update that changes the user information..
1805
Igor Laevsky285fe842015-05-19 16:29:43 +00001806 SmallVector<Instruction *, 20> Uses;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001807 // PERF: trade a linear scan for repeated reallocation
Vedant Kumare0b5f862018-05-10 23:01:54 +00001808 Uses.reserve(Def->getNumUses());
Igor Laevsky285fe842015-05-19 16:29:43 +00001809 for (User *U : Def->users()) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001810 if (!isa<ConstantExpr>(U)) {
1811 // If the def has a ConstantExpr use, then the def is either a
1812 // ConstantExpr use itself or null. In either case
1813 // (recursively in the first, directly in the second), the oop
1814 // it is ultimately dependent on is null and this particular
1815 // use does not need to be fixed up.
Igor Laevsky285fe842015-05-19 16:29:43 +00001816 Uses.push_back(cast<Instruction>(U));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001817 }
1818 }
1819
Fangrui Song0cac7262018-09-27 02:13:45 +00001820 llvm::sort(Uses);
Igor Laevsky285fe842015-05-19 16:29:43 +00001821 auto Last = std::unique(Uses.begin(), Uses.end());
1822 Uses.erase(Last, Uses.end());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001823
Igor Laevsky285fe842015-05-19 16:29:43 +00001824 for (Instruction *Use : Uses) {
1825 if (isa<PHINode>(Use)) {
1826 PHINode *Phi = cast<PHINode>(Use);
1827 for (unsigned i = 0; i < Phi->getNumIncomingValues(); i++) {
1828 if (Def == Phi->getIncomingValue(i)) {
James Y Knight14359ef2019-02-01 20:44:24 +00001829 LoadInst *Load =
1830 new LoadInst(Alloca->getAllocatedType(), Alloca, "",
1831 Phi->getIncomingBlock(i)->getTerminator());
Igor Laevsky285fe842015-05-19 16:29:43 +00001832 Phi->setIncomingValue(i, Load);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001833 }
1834 }
1835 } else {
James Y Knight14359ef2019-02-01 20:44:24 +00001836 LoadInst *Load =
1837 new LoadInst(Alloca->getAllocatedType(), Alloca, "", Use);
Igor Laevsky285fe842015-05-19 16:29:43 +00001838 Use->replaceUsesOfWith(Def, Load);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001839 }
1840 }
1841
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001842 // Emit store for the initial gc value. Store must be inserted after load,
1843 // otherwise store will be in alloca's use list and an extra load will be
1844 // inserted before it.
Igor Laevsky285fe842015-05-19 16:29:43 +00001845 StoreInst *Store = new StoreInst(Def, Alloca);
1846 if (Instruction *Inst = dyn_cast<Instruction>(Def)) {
1847 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(Inst)) {
Chandler Carruthedb12a82018-10-15 10:04:59 +00001848 // InvokeInst is a terminator so the store need to be inserted into its
1849 // normal destination block.
Igor Laevsky285fe842015-05-19 16:29:43 +00001850 BasicBlock *NormalDest = Invoke->getNormalDest();
1851 Store->insertBefore(NormalDest->getFirstNonPHI());
Philip Reames6da37852015-03-04 00:13:52 +00001852 } else {
Igor Laevsky285fe842015-05-19 16:29:43 +00001853 assert(!Inst->isTerminator() &&
Chandler Carruthedb12a82018-10-15 10:04:59 +00001854 "The only terminator that can produce a value is "
Philip Reames6da37852015-03-04 00:13:52 +00001855 "InvokeInst which is handled above.");
Igor Laevsky285fe842015-05-19 16:29:43 +00001856 Store->insertAfter(Inst);
Philip Reames6da37852015-03-04 00:13:52 +00001857 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00001858 } else {
Igor Laevsky285fe842015-05-19 16:29:43 +00001859 assert(isa<Argument>(Def));
1860 Store->insertAfter(cast<Instruction>(Alloca));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001861 }
1862 }
1863
Igor Laevsky285fe842015-05-19 16:29:43 +00001864 assert(PromotableAllocas.size() == Live.size() + NumRematerializedValues &&
Philip Reamesd16a9b12015-02-20 01:06:44 +00001865 "we must have the same allocas with lives");
1866 if (!PromotableAllocas.empty()) {
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001867 // Apply mem2reg to promote alloca to SSA
Philip Reamesd16a9b12015-02-20 01:06:44 +00001868 PromoteMemToReg(PromotableAllocas, DT);
1869 }
1870
1871#ifndef NDEBUG
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001872 for (auto &I : F.getEntryBlock())
1873 if (isa<AllocaInst>(I))
Philip Reamesa6ebf072015-03-27 05:53:16 +00001874 InitialAllocaNum--;
1875 assert(InitialAllocaNum == 0 && "We must not introduce any extra allocas");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001876#endif
1877}
1878
1879/// Implement a unique function which doesn't require we sort the input
1880/// vector. Doing so has the effect of changing the output of a couple of
1881/// tests in ways which make them less useful in testing fused safepoints.
Philip Reamesd2b66462015-02-20 22:39:41 +00001882template <typename T> static void unique_unsorted(SmallVectorImpl<T> &Vec) {
Benjamin Kramer258ea0d2015-06-13 19:50:38 +00001883 SmallSet<T, 8> Seen;
David Majnemerc7004902016-08-12 04:32:37 +00001884 Vec.erase(remove_if(Vec, [&](const T &V) { return !Seen.insert(V).second; }),
1885 Vec.end());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001886}
1887
Philip Reamesd16a9b12015-02-20 01:06:44 +00001888/// Insert holders so that each Value is obviously live through the entire
Philip Reamesf209a152015-04-13 20:00:30 +00001889/// lifetime of the call.
Chandler Carruth31607342019-02-11 07:42:30 +00001890static void insertUseHolderAfter(CallBase *Call, const ArrayRef<Value *> Values,
Philip Reamesf209a152015-04-13 20:00:30 +00001891 SmallVectorImpl<CallInst *> &Holders) {
Philip Reames21142752015-04-13 19:07:47 +00001892 if (Values.empty())
1893 // No values to hold live, might as well not insert the empty holder
1894 return;
1895
Chandler Carruth31607342019-02-11 07:42:30 +00001896 Module *M = Call->getModule();
Philip Reamesf209a152015-04-13 20:00:30 +00001897 // Use a dummy vararg function to actually hold the values live
James Y Knight13680222019-02-01 02:28:03 +00001898 FunctionCallee Func = M->getOrInsertFunction(
1899 "__tmp_use", FunctionType::get(Type::getVoidTy(M->getContext()), true));
Chandler Carruth31607342019-02-11 07:42:30 +00001900 if (isa<CallInst>(Call)) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001901 // For call safepoints insert dummy calls right after safepoint
Chandler Carruth31607342019-02-11 07:42:30 +00001902 Holders.push_back(
1903 CallInst::Create(Func, Values, "", &*++Call->getIterator()));
Philip Reamesf209a152015-04-13 20:00:30 +00001904 return;
1905 }
1906 // For invoke safepooints insert dummy calls both in normal and
1907 // exceptional destination blocks
Chandler Carruth31607342019-02-11 07:42:30 +00001908 auto *II = cast<InvokeInst>(Call);
Philip Reamesf209a152015-04-13 20:00:30 +00001909 Holders.push_back(CallInst::Create(
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001910 Func, Values, "", &*II->getNormalDest()->getFirstInsertionPt()));
Philip Reamesf209a152015-04-13 20:00:30 +00001911 Holders.push_back(CallInst::Create(
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001912 Func, Values, "", &*II->getUnwindDest()->getFirstInsertionPt()));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001913}
1914
1915static void findLiveReferences(
Chandler Carruth31607342019-02-11 07:42:30 +00001916 Function &F, DominatorTree &DT, ArrayRef<CallBase *> toUpdate,
Philip Reamesd2b66462015-02-20 22:39:41 +00001917 MutableArrayRef<struct PartiallyConstructedSafepointRecord> records) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00001918 GCPtrLivenessData OriginalLivenessData;
1919 computeLiveInValues(DT, F, OriginalLivenessData);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001920 for (size_t i = 0; i < records.size(); i++) {
1921 struct PartiallyConstructedSafepointRecord &info = records[i];
Sanjoy Dasa3244872016-06-17 00:45:00 +00001922 analyzeParsePointLiveness(DT, OriginalLivenessData, toUpdate[i], info);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001923 }
1924}
1925
Igor Laevskye0317182015-05-19 15:59:05 +00001926// Helper function for the "rematerializeLiveValues". It walks use chain
Anna Thomas8cd7de12016-09-20 21:36:02 +00001927// starting from the "CurrentValue" until it reaches the root of the chain, i.e.
1928// the base or a value it cannot process. Only "simple" values are processed
1929// (currently it is GEP's and casts). The returned root is examined by the
1930// callers of findRematerializableChainToBasePointer. Fills "ChainToBase" array
1931// with all visited values.
1932static Value* findRematerializableChainToBasePointer(
Igor Laevskye0317182015-05-19 15:59:05 +00001933 SmallVectorImpl<Instruction*> &ChainToBase,
Anna Thomas8cd7de12016-09-20 21:36:02 +00001934 Value *CurrentValue) {
Igor Laevskye0317182015-05-19 15:59:05 +00001935 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurrentValue)) {
1936 ChainToBase.push_back(GEP);
1937 return findRematerializableChainToBasePointer(ChainToBase,
Anna Thomas8cd7de12016-09-20 21:36:02 +00001938 GEP->getPointerOperand());
Igor Laevskye0317182015-05-19 15:59:05 +00001939 }
1940
1941 if (CastInst *CI = dyn_cast<CastInst>(CurrentValue)) {
Igor Laevskye0317182015-05-19 15:59:05 +00001942 if (!CI->isNoopCast(CI->getModule()->getDataLayout()))
Anna Thomas8cd7de12016-09-20 21:36:02 +00001943 return CI;
Igor Laevskye0317182015-05-19 15:59:05 +00001944
1945 ChainToBase.push_back(CI);
Manuel Jacob9db5b932015-12-28 20:14:05 +00001946 return findRematerializableChainToBasePointer(ChainToBase,
Anna Thomas8cd7de12016-09-20 21:36:02 +00001947 CI->getOperand(0));
Igor Laevskye0317182015-05-19 15:59:05 +00001948 }
1949
Anna Thomas8cd7de12016-09-20 21:36:02 +00001950 // We have reached the root of the chain, which is either equal to the base or
1951 // is the first unsupported value along the use chain.
1952 return CurrentValue;
Igor Laevskye0317182015-05-19 15:59:05 +00001953}
1954
1955// Helper function for the "rematerializeLiveValues". Compute cost of the use
1956// chain we are going to rematerialize.
1957static unsigned
1958chainToBasePointerCost(SmallVectorImpl<Instruction*> &Chain,
1959 TargetTransformInfo &TTI) {
1960 unsigned Cost = 0;
1961
1962 for (Instruction *Instr : Chain) {
1963 if (CastInst *CI = dyn_cast<CastInst>(Instr)) {
1964 assert(CI->isNoopCast(CI->getModule()->getDataLayout()) &&
1965 "non noop cast is found during rematerialization");
1966
1967 Type *SrcTy = CI->getOperand(0)->getType();
Jonas Paulssonfccc7d62017-04-12 11:49:08 +00001968 Cost += TTI.getCastInstrCost(CI->getOpcode(), CI->getType(), SrcTy, CI);
Igor Laevskye0317182015-05-19 15:59:05 +00001969
1970 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Instr)) {
1971 // Cost of the address calculation
Eduard Burtescu19eb0312016-01-19 17:28:00 +00001972 Type *ValTy = GEP->getSourceElementType();
Igor Laevskye0317182015-05-19 15:59:05 +00001973 Cost += TTI.getAddressComputationCost(ValTy);
1974
1975 // And cost of the GEP itself
1976 // TODO: Use TTI->getGEPCost here (it exists, but appears to be not
1977 // allowed for the external usage)
1978 if (!GEP->hasAllConstantIndices())
1979 Cost += 2;
1980
1981 } else {
Hiroshi Inouef2096492018-06-14 05:41:49 +00001982 llvm_unreachable("unsupported instruction type during rematerialization");
Igor Laevskye0317182015-05-19 15:59:05 +00001983 }
1984 }
1985
1986 return Cost;
1987}
1988
Anna Thomas8cd7de12016-09-20 21:36:02 +00001989static bool AreEquivalentPhiNodes(PHINode &OrigRootPhi, PHINode &AlternateRootPhi) {
Anna Thomas8cd7de12016-09-20 21:36:02 +00001990 unsigned PhiNum = OrigRootPhi.getNumIncomingValues();
1991 if (PhiNum != AlternateRootPhi.getNumIncomingValues() ||
1992 OrigRootPhi.getParent() != AlternateRootPhi.getParent())
1993 return false;
1994 // Map of incoming values and their corresponding basic blocks of
1995 // OrigRootPhi.
1996 SmallDenseMap<Value *, BasicBlock *, 8> CurrentIncomingValues;
1997 for (unsigned i = 0; i < PhiNum; i++)
1998 CurrentIncomingValues[OrigRootPhi.getIncomingValue(i)] =
1999 OrigRootPhi.getIncomingBlock(i);
2000
2001 // Both current and base PHIs should have same incoming values and
2002 // the same basic blocks corresponding to the incoming values.
2003 for (unsigned i = 0; i < PhiNum; i++) {
2004 auto CIVI =
2005 CurrentIncomingValues.find(AlternateRootPhi.getIncomingValue(i));
2006 if (CIVI == CurrentIncomingValues.end())
2007 return false;
2008 BasicBlock *CurrentIncomingBB = CIVI->second;
2009 if (CurrentIncomingBB != AlternateRootPhi.getIncomingBlock(i))
2010 return false;
2011 }
2012 return true;
Anna Thomas8cd7de12016-09-20 21:36:02 +00002013}
2014
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002015// From the statepoint live set pick values that are cheaper to recompute then
2016// to relocate. Remove this values from the live set, rematerialize them after
Igor Laevskye0317182015-05-19 15:59:05 +00002017// statepoint and record them in "Info" structure. Note that similar to
2018// relocated values we don't do any user adjustments here.
Chandler Carruth31607342019-02-11 07:42:30 +00002019static void rematerializeLiveValues(CallBase *Call,
Igor Laevskye0317182015-05-19 15:59:05 +00002020 PartiallyConstructedSafepointRecord &Info,
2021 TargetTransformInfo &TTI) {
Aaron Ballmanff7d4fa2015-05-20 14:53:50 +00002022 const unsigned int ChainLengthThreshold = 10;
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +00002023
Igor Laevskye0317182015-05-19 15:59:05 +00002024 // Record values we are going to delete from this statepoint live set.
2025 // We can not di this in following loop due to iterator invalidation.
2026 SmallVector<Value *, 32> LiveValuesToBeDeleted;
2027
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002028 for (Value *LiveValue: Info.LiveSet) {
Eric Christopher563d0b92018-05-21 10:27:36 +00002029 // For each live pointer find its defining chain
Igor Laevskye0317182015-05-19 15:59:05 +00002030 SmallVector<Instruction *, 3> ChainToBase;
Philip Reames74ce2e72015-07-21 16:51:17 +00002031 assert(Info.PointerToBase.count(LiveValue));
Anna Thomas8cd7de12016-09-20 21:36:02 +00002032 Value *RootOfChain =
Igor Laevskye0317182015-05-19 15:59:05 +00002033 findRematerializableChainToBasePointer(ChainToBase,
Anna Thomas8cd7de12016-09-20 21:36:02 +00002034 LiveValue);
2035
Igor Laevskye0317182015-05-19 15:59:05 +00002036 // Nothing to do, or chain is too long
Anna Thomas8cd7de12016-09-20 21:36:02 +00002037 if ( ChainToBase.size() == 0 ||
Igor Laevskye0317182015-05-19 15:59:05 +00002038 ChainToBase.size() > ChainLengthThreshold)
2039 continue;
2040
Anna Thomas8cd7de12016-09-20 21:36:02 +00002041 // Handle the scenario where the RootOfChain is not equal to the
2042 // Base Value, but they are essentially the same phi values.
2043 if (RootOfChain != Info.PointerToBase[LiveValue]) {
2044 PHINode *OrigRootPhi = dyn_cast<PHINode>(RootOfChain);
2045 PHINode *AlternateRootPhi = dyn_cast<PHINode>(Info.PointerToBase[LiveValue]);
2046 if (!OrigRootPhi || !AlternateRootPhi)
2047 continue;
2048 // PHI nodes that have the same incoming values, and belonging to the same
2049 // basic blocks are essentially the same SSA value. When the original phi
2050 // has incoming values with different base pointers, the original phi is
2051 // marked as conflict, and an additional `AlternateRootPhi` with the same
2052 // incoming values get generated by the findBasePointer function. We need
2053 // to identify the newly generated AlternateRootPhi (.base version of phi)
2054 // and RootOfChain (the original phi node itself) are the same, so that we
2055 // can rematerialize the gep and casts. This is a workaround for the
Hiroshi Inoueef1c2ba2017-07-01 07:12:15 +00002056 // deficiency in the findBasePointer algorithm.
Anna Thomas8cd7de12016-09-20 21:36:02 +00002057 if (!AreEquivalentPhiNodes(*OrigRootPhi, *AlternateRootPhi))
2058 continue;
2059 // Now that the phi nodes are proved to be the same, assert that
2060 // findBasePointer's newly generated AlternateRootPhi is present in the
2061 // liveset of the call.
2062 assert(Info.LiveSet.count(AlternateRootPhi));
2063 }
Igor Laevskye0317182015-05-19 15:59:05 +00002064 // Compute cost of this chain
2065 unsigned Cost = chainToBasePointerCost(ChainToBase, TTI);
2066 // TODO: We can also account for cases when we will be able to remove some
2067 // of the rematerialized values by later optimization passes. I.e if
2068 // we rematerialized several intersecting chains. Or if original values
2069 // don't have any uses besides this statepoint.
2070
2071 // For invokes we need to rematerialize each chain twice - for normal and
2072 // for unwind basic blocks. Model this by multiplying cost by two.
Chandler Carruth31607342019-02-11 07:42:30 +00002073 if (isa<InvokeInst>(Call)) {
Igor Laevskye0317182015-05-19 15:59:05 +00002074 Cost *= 2;
2075 }
2076 // If it's too expensive - skip it
2077 if (Cost >= RematerializationThreshold)
2078 continue;
2079
2080 // Remove value from the live set
2081 LiveValuesToBeDeleted.push_back(LiveValue);
2082
2083 // Clone instructions and record them inside "Info" structure
2084
2085 // Walk backwards to visit top-most instructions first
2086 std::reverse(ChainToBase.begin(), ChainToBase.end());
2087
2088 // Utility function which clones all instructions from "ChainToBase"
2089 // and inserts them before "InsertBefore". Returns rematerialized value
2090 // which should be used after statepoint.
Anna Thomas82c37172016-09-22 13:13:06 +00002091 auto rematerializeChain = [&ChainToBase](
2092 Instruction *InsertBefore, Value *RootOfChain, Value *AlternateLiveBase) {
Igor Laevskye0317182015-05-19 15:59:05 +00002093 Instruction *LastClonedValue = nullptr;
2094 Instruction *LastValue = nullptr;
2095 for (Instruction *Instr: ChainToBase) {
Hiroshi Inouebb703e82017-07-02 03:24:54 +00002096 // Only GEP's and casts are supported as we need to be careful to not
Igor Laevskye0317182015-05-19 15:59:05 +00002097 // introduce any new uses of pointers not in the liveset.
2098 // Note that it's fine to introduce new uses of pointers which were
2099 // otherwise not used after this statepoint.
2100 assert(isa<GetElementPtrInst>(Instr) || isa<CastInst>(Instr));
2101
2102 Instruction *ClonedValue = Instr->clone();
2103 ClonedValue->insertBefore(InsertBefore);
2104 ClonedValue->setName(Instr->getName() + ".remat");
2105
2106 // If it is not first instruction in the chain then it uses previously
2107 // cloned value. We should update it to use cloned value.
2108 if (LastClonedValue) {
2109 assert(LastValue);
2110 ClonedValue->replaceUsesOfWith(LastValue, LastClonedValue);
2111#ifndef NDEBUG
Igor Laevskyd83f6972015-05-21 13:02:14 +00002112 for (auto OpValue : ClonedValue->operand_values()) {
Anna Thomas82c37172016-09-22 13:13:06 +00002113 // Assert that cloned instruction does not use any instructions from
2114 // this chain other than LastClonedValue
David Majnemer0d955d02016-08-11 22:21:41 +00002115 assert(!is_contained(ChainToBase, OpValue) &&
Igor Laevskyd83f6972015-05-21 13:02:14 +00002116 "incorrect use in rematerialization chain");
Anna Thomas82c37172016-09-22 13:13:06 +00002117 // Assert that the cloned instruction does not use the RootOfChain
2118 // or the AlternateLiveBase.
2119 assert(OpValue != RootOfChain && OpValue != AlternateLiveBase);
Igor Laevskye0317182015-05-19 15:59:05 +00002120 }
2121#endif
Anna Thomas82c37172016-09-22 13:13:06 +00002122 } else {
2123 // For the first instruction, replace the use of unrelocated base i.e.
2124 // RootOfChain/OrigRootPhi, with the corresponding PHI present in the
2125 // live set. They have been proved to be the same PHI nodes. Note
2126 // that the *only* use of the RootOfChain in the ChainToBase list is
2127 // the first Value in the list.
2128 if (RootOfChain != AlternateLiveBase)
2129 ClonedValue->replaceUsesOfWith(RootOfChain, AlternateLiveBase);
Igor Laevskye0317182015-05-19 15:59:05 +00002130 }
2131
2132 LastClonedValue = ClonedValue;
2133 LastValue = Instr;
2134 }
2135 assert(LastClonedValue);
2136 return LastClonedValue;
2137 };
2138
2139 // Different cases for calls and invokes. For invokes we need to clone
2140 // instructions both on normal and unwind path.
Chandler Carruth31607342019-02-11 07:42:30 +00002141 if (isa<CallInst>(Call)) {
2142 Instruction *InsertBefore = Call->getNextNode();
Igor Laevskye0317182015-05-19 15:59:05 +00002143 assert(InsertBefore);
Anna Thomas82c37172016-09-22 13:13:06 +00002144 Instruction *RematerializedValue = rematerializeChain(
2145 InsertBefore, RootOfChain, Info.PointerToBase[LiveValue]);
Igor Laevskye0317182015-05-19 15:59:05 +00002146 Info.RematerializedValues[RematerializedValue] = LiveValue;
2147 } else {
Chandler Carruth31607342019-02-11 07:42:30 +00002148 auto *Invoke = cast<InvokeInst>(Call);
Igor Laevskye0317182015-05-19 15:59:05 +00002149
2150 Instruction *NormalInsertBefore =
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00002151 &*Invoke->getNormalDest()->getFirstInsertionPt();
Igor Laevskye0317182015-05-19 15:59:05 +00002152 Instruction *UnwindInsertBefore =
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00002153 &*Invoke->getUnwindDest()->getFirstInsertionPt();
Igor Laevskye0317182015-05-19 15:59:05 +00002154
Anna Thomas82c37172016-09-22 13:13:06 +00002155 Instruction *NormalRematerializedValue = rematerializeChain(
2156 NormalInsertBefore, RootOfChain, Info.PointerToBase[LiveValue]);
2157 Instruction *UnwindRematerializedValue = rematerializeChain(
2158 UnwindInsertBefore, RootOfChain, Info.PointerToBase[LiveValue]);
Igor Laevskye0317182015-05-19 15:59:05 +00002159
2160 Info.RematerializedValues[NormalRematerializedValue] = LiveValue;
2161 Info.RematerializedValues[UnwindRematerializedValue] = LiveValue;
2162 }
2163 }
2164
2165 // Remove rematerializaed values from the live set
2166 for (auto LiveValue: LiveValuesToBeDeleted) {
Igor Laevskyfb1811d2016-05-04 14:55:36 +00002167 Info.LiveSet.remove(LiveValue);
Igor Laevskye0317182015-05-19 15:59:05 +00002168 }
2169}
2170
Justin Bogner843fb202015-12-15 19:40:57 +00002171static bool insertParsePoints(Function &F, DominatorTree &DT,
2172 TargetTransformInfo &TTI,
Chandler Carruth31607342019-02-11 07:42:30 +00002173 SmallVectorImpl<CallBase *> &ToUpdate) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00002174#ifndef NDEBUG
2175 // sanity check the input
Chandler Carruth31607342019-02-11 07:42:30 +00002176 std::set<CallBase *> Uniqued;
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002177 Uniqued.insert(ToUpdate.begin(), ToUpdate.end());
2178 assert(Uniqued.size() == ToUpdate.size() && "no duplicates please!");
Philip Reamesd16a9b12015-02-20 01:06:44 +00002179
Chandler Carruth31607342019-02-11 07:42:30 +00002180 for (CallBase *Call : ToUpdate)
2181 assert(Call->getFunction() == &F);
Philip Reamesd16a9b12015-02-20 01:06:44 +00002182#endif
2183
Philip Reames69e51ca2015-04-13 18:07:21 +00002184 // When inserting gc.relocates for invokes, we need to be able to insert at
2185 // the top of the successor blocks. See the comment on
2186 // normalForInvokeSafepoint on exactly what is needed. Note that this step
Philip Reamesf209a152015-04-13 20:00:30 +00002187 // may restructure the CFG.
Chandler Carruth31607342019-02-11 07:42:30 +00002188 for (CallBase *Call : ToUpdate) {
2189 auto *II = dyn_cast<InvokeInst>(Call);
2190 if (!II)
Philip Reamesf209a152015-04-13 20:00:30 +00002191 continue;
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002192 normalizeForInvokeSafepoint(II->getNormalDest(), II->getParent(), DT);
2193 normalizeForInvokeSafepoint(II->getUnwindDest(), II->getParent(), DT);
Philip Reamesf209a152015-04-13 20:00:30 +00002194 }
Philip Reames69e51ca2015-04-13 18:07:21 +00002195
Philip Reamesd16a9b12015-02-20 01:06:44 +00002196 // A list of dummy calls added to the IR to keep various values obviously
2197 // live in the IR. We'll remove all of these when done.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002198 SmallVector<CallInst *, 64> Holders;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002199
Philip Reamesb70cecd2017-06-02 23:03:26 +00002200 // Insert a dummy call with all of the deopt operands we'll need for the
2201 // actual safepoint insertion as arguments. This ensures reference operands
2202 // in the deopt argument list are considered live through the safepoint (and
Philip Reamesd16a9b12015-02-20 01:06:44 +00002203 // thus makes sure they get relocated.)
Chandler Carruth31607342019-02-11 07:42:30 +00002204 for (CallBase *Call : ToUpdate) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00002205 SmallVector<Value *, 64> DeoptValues;
Sanjoy Das25ec1a32015-10-16 02:41:00 +00002206
Chandler Carruth31607342019-02-11 07:42:30 +00002207 for (Value *Arg : GetDeoptBundleOperands(Call)) {
Philip Reames8531d8c2015-04-10 21:48:25 +00002208 assert(!isUnhandledGCPointerType(Arg->getType()) &&
2209 "support for FCA unimplemented");
2210 if (isHandledGCPointerType(Arg->getType()))
Philip Reamesd16a9b12015-02-20 01:06:44 +00002211 DeoptValues.push_back(Arg);
2212 }
Sanjoy Das25ec1a32015-10-16 02:41:00 +00002213
Chandler Carruth31607342019-02-11 07:42:30 +00002214 insertUseHolderAfter(Call, DeoptValues, Holders);
Philip Reamesd16a9b12015-02-20 01:06:44 +00002215 }
2216
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002217 SmallVector<PartiallyConstructedSafepointRecord, 64> Records(ToUpdate.size());
Philip Reamesd16a9b12015-02-20 01:06:44 +00002218
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002219 // A) Identify all gc pointers which are statically live at the given call
Philip Reamesd16a9b12015-02-20 01:06:44 +00002220 // site.
Justin Bogner843fb202015-12-15 19:40:57 +00002221 findLiveReferences(F, DT, ToUpdate, Records);
Philip Reamesd16a9b12015-02-20 01:06:44 +00002222
2223 // B) Find the base pointers for each live pointer
2224 /* scope for caching */ {
2225 // Cache the 'defining value' relation used in the computation and
2226 // insertion of base phis and selects. This ensures that we don't insert
2227 // large numbers of duplicate base_phis.
2228 DefiningValueMapTy DVCache;
2229
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002230 for (size_t i = 0; i < Records.size(); i++) {
2231 PartiallyConstructedSafepointRecord &info = Records[i];
2232 findBasePointers(DT, DVCache, ToUpdate[i], info);
Philip Reamesd16a9b12015-02-20 01:06:44 +00002233 }
2234 } // end of cache scope
2235
2236 // The base phi insertion logic (for any safepoint) may have inserted new
2237 // instructions which are now live at some safepoint. The simplest such
2238 // example is:
2239 // loop:
2240 // phi a <-- will be a new base_phi here
2241 // safepoint 1 <-- that needs to be live here
2242 // gep a + 1
2243 // safepoint 2
2244 // br loop
Philip Reamesd16a9b12015-02-20 01:06:44 +00002245 // We insert some dummy calls after each safepoint to definitely hold live
2246 // the base pointers which were identified for that safepoint. We'll then
2247 // ask liveness for _every_ base inserted to see what is now live. Then we
2248 // remove the dummy calls.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002249 Holders.reserve(Holders.size() + Records.size());
2250 for (size_t i = 0; i < Records.size(); i++) {
2251 PartiallyConstructedSafepointRecord &Info = Records[i];
Philip Reamesd16a9b12015-02-20 01:06:44 +00002252
2253 SmallVector<Value *, 128> Bases;
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002254 for (auto Pair : Info.PointerToBase)
Philip Reamesd16a9b12015-02-20 01:06:44 +00002255 Bases.push_back(Pair.second);
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002256
2257 insertUseHolderAfter(ToUpdate[i], Bases, Holders);
Philip Reamesd16a9b12015-02-20 01:06:44 +00002258 }
2259
Philip Reamesdf1ef082015-04-10 22:53:14 +00002260 // By selecting base pointers, we've effectively inserted new uses. Thus, we
2261 // need to rerun liveness. We may *also* have inserted new defs, but that's
2262 // not the key issue.
Justin Bogner843fb202015-12-15 19:40:57 +00002263 recomputeLiveInValues(F, DT, ToUpdate, Records);
Philip Reamesd16a9b12015-02-20 01:06:44 +00002264
Philip Reamesd16a9b12015-02-20 01:06:44 +00002265 if (PrintBasePointers) {
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002266 for (auto &Info : Records) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00002267 errs() << "Base Pairs: (w/Relocation)\n";
Manuel Jacoba4efd8a2015-12-23 00:19:45 +00002268 for (auto Pair : Info.PointerToBase) {
2269 errs() << " derived ";
2270 Pair.first->printAsOperand(errs(), false);
2271 errs() << " base ";
2272 Pair.second->printAsOperand(errs(), false);
2273 errs() << "\n";
2274 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00002275 }
2276 }
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002277
Manuel Jacob990dfa62015-12-22 16:50:44 +00002278 // It is possible that non-constant live variables have a constant base. For
2279 // example, a GEP with a variable offset from a global. In this case we can
2280 // remove it from the liveset. We already don't add constants to the liveset
2281 // because we assume they won't move at runtime and the GC doesn't need to be
2282 // informed about them. The same reasoning applies if the base is constant.
2283 // Note that the relocation placement code relies on this filtering for
2284 // correctness as it expects the base to be in the liveset, which isn't true
2285 // if the base is constant.
2286 for (auto &Info : Records)
2287 for (auto &BasePair : Info.PointerToBase)
2288 if (isa<Constant>(BasePair.second))
Igor Laevskyfb1811d2016-05-04 14:55:36 +00002289 Info.LiveSet.remove(BasePair.first);
Manuel Jacob990dfa62015-12-22 16:50:44 +00002290
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002291 for (CallInst *CI : Holders)
2292 CI->eraseFromParent();
2293
2294 Holders.clear();
Philip Reamesd16a9b12015-02-20 01:06:44 +00002295
Igor Laevskye0317182015-05-19 15:59:05 +00002296 // In order to reduce live set of statepoint we might choose to rematerialize
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002297 // some values instead of relocating them. This is purely an optimization and
Igor Laevskye0317182015-05-19 15:59:05 +00002298 // does not influence correctness.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002299 for (size_t i = 0; i < Records.size(); i++)
2300 rematerializeLiveValues(ToUpdate[i], Records[i], TTI);
Igor Laevskye0317182015-05-19 15:59:05 +00002301
Sanjoy Das25ec1a32015-10-16 02:41:00 +00002302 // We need this to safely RAUW and delete call or invoke return values that
2303 // may themselves be live over a statepoint. For details, please see usage in
2304 // makeStatepointExplicitImpl.
2305 std::vector<DeferredReplacement> Replacements;
2306
Philip Reamesd16a9b12015-02-20 01:06:44 +00002307 // Now run through and replace the existing statepoints with new ones with
2308 // the live variables listed. We do not yet update uses of the values being
2309 // relocated. We have references to live variables that need to
2310 // survive to the last iteration of this loop. (By construction, the
2311 // previous statepoint can not be a live variable, thus we can and remove
2312 // the old statepoint calls as we go.)
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002313 for (size_t i = 0; i < Records.size(); i++)
Sanjoy Das25ec1a32015-10-16 02:41:00 +00002314 makeStatepointExplicit(DT, ToUpdate[i], Records[i], Replacements);
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002315
Chandler Carruth31607342019-02-11 07:42:30 +00002316 ToUpdate.clear(); // prevent accident use of invalid calls.
Philip Reamesd16a9b12015-02-20 01:06:44 +00002317
Sanjoy Das25ec1a32015-10-16 02:41:00 +00002318 for (auto &PR : Replacements)
2319 PR.doReplacement();
2320
2321 Replacements.clear();
2322
2323 for (auto &Info : Records) {
2324 // These live sets may contain state Value pointers, since we replaced calls
2325 // with operand bundles with calls wrapped in gc.statepoint, and some of
2326 // those calls may have been def'ing live gc pointers. Clear these out to
2327 // avoid accidentally using them.
2328 //
2329 // TODO: We should create a separate data structure that does not contain
2330 // these live sets, and migrate to using that data structure from this point
2331 // onward.
2332 Info.LiveSet.clear();
2333 Info.PointerToBase.clear();
2334 }
2335
Philip Reamesd16a9b12015-02-20 01:06:44 +00002336 // Do all the fixups of the original live variables to their relocated selves
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002337 SmallVector<Value *, 128> Live;
2338 for (size_t i = 0; i < Records.size(); i++) {
2339 PartiallyConstructedSafepointRecord &Info = Records[i];
Sanjoy Das25ec1a32015-10-16 02:41:00 +00002340
Philip Reamesd16a9b12015-02-20 01:06:44 +00002341 // We can't simply save the live set from the original insertion. One of
2342 // the live values might be the result of a call which needs a safepoint.
2343 // That Value* no longer exists and we need to use the new gc_result.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002344 // Thankfully, the live set is embedded in the statepoint (and updated), so
Philip Reamesd16a9b12015-02-20 01:06:44 +00002345 // we just grab that.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002346 Statepoint Statepoint(Info.StatepointToken);
2347 Live.insert(Live.end(), Statepoint.gc_args_begin(),
2348 Statepoint.gc_args_end());
Philip Reames9a2e01d2015-04-13 17:35:55 +00002349#ifndef NDEBUG
2350 // Do some basic sanity checks on our liveness results before performing
2351 // relocation. Relocation can and will turn mistakes in liveness results
2352 // into non-sensical code which is must harder to debug.
2353 // TODO: It would be nice to test consistency as well
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002354 assert(DT.isReachableFromEntry(Info.StatepointToken->getParent()) &&
Philip Reames9a2e01d2015-04-13 17:35:55 +00002355 "statepoint must be reachable or liveness is meaningless");
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002356 for (Value *V : Statepoint.gc_args()) {
Philip Reames9a2e01d2015-04-13 17:35:55 +00002357 if (!isa<Instruction>(V))
2358 // Non-instruction values trivial dominate all possible uses
2359 continue;
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002360 auto *LiveInst = cast<Instruction>(V);
Philip Reames9a2e01d2015-04-13 17:35:55 +00002361 assert(DT.isReachableFromEntry(LiveInst->getParent()) &&
2362 "unreachable values should never be live");
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002363 assert(DT.dominates(LiveInst, Info.StatepointToken) &&
Philip Reames9a2e01d2015-04-13 17:35:55 +00002364 "basic SSA liveness expectation violated by liveness analysis");
2365 }
2366#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +00002367 }
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002368 unique_unsorted(Live);
Philip Reamesd16a9b12015-02-20 01:06:44 +00002369
Nick Lewyckyeb3231e2015-02-20 07:14:02 +00002370#ifndef NDEBUG
Philip Reamesd16a9b12015-02-20 01:06:44 +00002371 // sanity check
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002372 for (auto *Ptr : Live)
Philip Reames5715f572016-01-09 01:31:13 +00002373 assert(isHandledGCPointerType(Ptr->getType()) &&
2374 "must be a gc pointer type");
Nick Lewyckyeb3231e2015-02-20 07:14:02 +00002375#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +00002376
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002377 relocationViaAlloca(F, DT, Live, Records);
2378 return !Records.empty();
Philip Reamesd16a9b12015-02-20 01:06:44 +00002379}
2380
Chandler Carruth31607342019-02-11 07:42:30 +00002381// Handles both return values and arguments for Functions and calls.
Sanjoy Das353a19e2015-06-02 22:33:37 +00002382template <typename AttrHolder>
Igor Laevskydde00292015-10-23 22:42:44 +00002383static void RemoveNonValidAttrAtIndex(LLVMContext &Ctx, AttrHolder &AH,
2384 unsigned Index) {
Sanjoy Das353a19e2015-06-02 22:33:37 +00002385 AttrBuilder R;
2386 if (AH.getDereferenceableBytes(Index))
2387 R.addAttribute(Attribute::get(Ctx, Attribute::Dereferenceable,
2388 AH.getDereferenceableBytes(Index)));
2389 if (AH.getDereferenceableOrNullBytes(Index))
2390 R.addAttribute(Attribute::get(Ctx, Attribute::DereferenceableOrNull,
2391 AH.getDereferenceableOrNullBytes(Index)));
Reid Klecknera0b45f42017-05-03 18:17:31 +00002392 if (AH.getAttributes().hasAttribute(Index, Attribute::NoAlias))
Igor Laevsky1ef06552015-10-26 19:06:01 +00002393 R.addAttribute(Attribute::NoAlias);
Sanjoy Das353a19e2015-06-02 22:33:37 +00002394
2395 if (!R.empty())
Reid Kleckneree4930b2017-05-02 22:07:37 +00002396 AH.setAttributes(AH.getAttributes().removeAttributes(Ctx, Index, R));
Vasileios Kalintiris9f77f612015-06-03 08:51:30 +00002397}
Sanjoy Das353a19e2015-06-02 22:33:37 +00002398
Fedor Sergeev4b86d792017-12-15 09:32:11 +00002399static void stripNonValidAttributesFromPrototype(Function &F) {
Sanjoy Das353a19e2015-06-02 22:33:37 +00002400 LLVMContext &Ctx = F.getContext();
2401
2402 for (Argument &A : F.args())
2403 if (isa<PointerType>(A.getType()))
Reid Klecknera0b45f42017-05-03 18:17:31 +00002404 RemoveNonValidAttrAtIndex(Ctx, F,
2405 A.getArgNo() + AttributeList::FirstArgIndex);
Sanjoy Das353a19e2015-06-02 22:33:37 +00002406
2407 if (isa<PointerType>(F.getReturnType()))
Reid Klecknerb5180542017-03-21 16:57:19 +00002408 RemoveNonValidAttrAtIndex(Ctx, F, AttributeList::ReturnIndex);
Sanjoy Das353a19e2015-06-02 22:33:37 +00002409}
2410
Fedor Sergeev4b86d792017-12-15 09:32:11 +00002411/// Certain metadata on instructions are invalid after running RS4GC.
2412/// Optimizations that run after RS4GC can incorrectly use this metadata to
2413/// optimize functions. We drop such metadata on the instruction.
2414static void stripInvalidMetadataFromInstruction(Instruction &I) {
Anna Thomas4b027e82017-06-12 21:26:53 +00002415 if (!isa<LoadInst>(I) && !isa<StoreInst>(I))
2416 return;
2417 // These are the attributes that are still valid on loads and stores after
2418 // RS4GC.
2419 // The metadata implying dereferenceability and noalias are (conservatively)
2420 // dropped. This is because semantically, after RewriteStatepointsForGC runs,
2421 // all calls to gc.statepoint "free" the entire heap. Also, gc.statepoint can
2422 // touch the entire heap including noalias objects. Note: The reasoning is
2423 // same as stripping the dereferenceability and noalias attributes that are
2424 // analogous to the metadata counterparts.
2425 // We also drop the invariant.load metadata on the load because that metadata
2426 // implies the address operand to the load points to memory that is never
2427 // changed once it became dereferenceable. This is no longer true after RS4GC.
2428 // Similar reasoning applies to invariant.group metadata, which applies to
2429 // loads within a group.
2430 unsigned ValidMetadataAfterRS4GC[] = {LLVMContext::MD_tbaa,
2431 LLVMContext::MD_range,
2432 LLVMContext::MD_alias_scope,
2433 LLVMContext::MD_nontemporal,
2434 LLVMContext::MD_nonnull,
2435 LLVMContext::MD_align,
2436 LLVMContext::MD_type};
2437
2438 // Drops all metadata on the instruction other than ValidMetadataAfterRS4GC.
2439 I.dropUnknownNonDebugMetadata(ValidMetadataAfterRS4GC);
Anna Thomas4b027e82017-06-12 21:26:53 +00002440}
2441
Fedor Sergeev4b86d792017-12-15 09:32:11 +00002442static void stripNonValidDataFromBody(Function &F) {
Sanjoy Das353a19e2015-06-02 22:33:37 +00002443 if (F.empty())
2444 return;
2445
2446 LLVMContext &Ctx = F.getContext();
2447 MDBuilder Builder(Ctx);
2448
Anna Thomas729dafc2017-11-02 18:24:04 +00002449 // Set of invariantstart instructions that we need to remove.
2450 // Use this to avoid invalidating the instruction iterator.
2451 SmallVector<IntrinsicInst*, 12> InvariantStartInstructions;
2452
Nico Rieck78199512015-08-06 19:10:45 +00002453 for (Instruction &I : instructions(F)) {
Anna Thomas729dafc2017-11-02 18:24:04 +00002454 // invariant.start on memory location implies that the referenced memory
2455 // location is constant and unchanging. This is no longer true after
2456 // RewriteStatepointsForGC runs because there can be calls to gc.statepoint
2457 // which frees the entire heap and the presence of invariant.start allows
2458 // the optimizer to sink the load of a memory location past a statepoint,
2459 // which is incorrect.
2460 if (auto *II = dyn_cast<IntrinsicInst>(&I))
2461 if (II->getIntrinsicID() == Intrinsic::invariant_start) {
2462 InvariantStartInstructions.push_back(II);
2463 continue;
2464 }
2465
Ivan A. Kosarev4d0ff0c2018-01-17 13:29:54 +00002466 if (MDNode *Tag = I.getMetadata(LLVMContext::MD_tbaa)) {
2467 MDNode *MutableTBAA = Builder.createMutableTBAAAccessTag(Tag);
Sanjoy Das353a19e2015-06-02 22:33:37 +00002468 I.setMetadata(LLVMContext::MD_tbaa, MutableTBAA);
2469 }
2470
Anna Thomas4b027e82017-06-12 21:26:53 +00002471 stripInvalidMetadataFromInstruction(I);
2472
Chandler Carruth31607342019-02-11 07:42:30 +00002473 if (auto *Call = dyn_cast<CallBase>(&I)) {
2474 for (int i = 0, e = Call->arg_size(); i != e; i++)
2475 if (isa<PointerType>(Call->getArgOperand(i)->getType()))
2476 RemoveNonValidAttrAtIndex(Ctx, *Call,
2477 i + AttributeList::FirstArgIndex);
2478 if (isa<PointerType>(Call->getType()))
2479 RemoveNonValidAttrAtIndex(Ctx, *Call, AttributeList::ReturnIndex);
Sanjoy Das353a19e2015-06-02 22:33:37 +00002480 }
2481 }
Anna Thomas729dafc2017-11-02 18:24:04 +00002482
2483 // Delete the invariant.start instructions and RAUW undef.
2484 for (auto *II : InvariantStartInstructions) {
2485 II->replaceAllUsesWith(UndefValue::get(II->getType()));
2486 II->eraseFromParent();
2487 }
Sanjoy Das353a19e2015-06-02 22:33:37 +00002488}
2489
Philip Reamesd16a9b12015-02-20 01:06:44 +00002490/// Returns true if this function should be rewritten by this pass. The main
2491/// point of this function is as an extension point for custom logic.
2492static bool shouldRewriteStatepointsIn(Function &F) {
2493 // TODO: This should check the GCStrategy
Philip Reames2ef029c2015-02-20 18:56:14 +00002494 if (F.hasGC()) {
Mehdi Amini599ebf22016-01-08 02:28:20 +00002495 const auto &FunctionGCName = F.getGC();
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +00002496 const StringRef StatepointExampleName("statepoint-example");
2497 const StringRef CoreCLRName("coreclr");
2498 return (StatepointExampleName == FunctionGCName) ||
NAKAMURA Takumi5582a6a2015-05-25 01:43:34 +00002499 (CoreCLRName == FunctionGCName);
2500 } else
Philip Reames2ef029c2015-02-20 18:56:14 +00002501 return false;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002502}
2503
Fedor Sergeev4b86d792017-12-15 09:32:11 +00002504static void stripNonValidData(Module &M) {
Sanjoy Das353a19e2015-06-02 22:33:37 +00002505#ifndef NDEBUG
Eugene Zelenko75075ef2017-09-01 21:37:29 +00002506 assert(llvm::any_of(M, shouldRewriteStatepointsIn) && "precondition!");
Sanjoy Das353a19e2015-06-02 22:33:37 +00002507#endif
2508
2509 for (Function &F : M)
Igor Laevskydde00292015-10-23 22:42:44 +00002510 stripNonValidAttributesFromPrototype(F);
Sanjoy Das353a19e2015-06-02 22:33:37 +00002511
2512 for (Function &F : M)
Anna Thomas729dafc2017-11-02 18:24:04 +00002513 stripNonValidDataFromBody(F);
Sanjoy Das353a19e2015-06-02 22:33:37 +00002514}
2515
Fedor Sergeev4b86d792017-12-15 09:32:11 +00002516bool RewriteStatepointsForGC::runOnFunction(Function &F, DominatorTree &DT,
2517 TargetTransformInfo &TTI,
2518 const TargetLibraryInfo &TLI) {
2519 assert(!F.isDeclaration() && !F.empty() &&
2520 "need function body to rewrite statepoints in");
2521 assert(shouldRewriteStatepointsIn(F) && "mismatch in rewrite decision");
Philip Reames704e78b2015-04-10 22:34:56 +00002522
Daniel Neilson2574d7c2017-07-27 16:49:39 +00002523 auto NeedsRewrite = [&TLI](Instruction &I) {
Chandler Carruth31607342019-02-11 07:42:30 +00002524 if (const auto *Call = dyn_cast<CallBase>(&I))
2525 return !callsGCLeafFunction(Call, TLI) && !isStatepoint(Call);
Sanjoy Das40992972016-01-29 01:03:17 +00002526 return false;
Sanjoy Das25ec1a32015-10-16 02:41:00 +00002527 };
2528
Daniel Neilson82daad32018-03-05 22:27:30 +00002529 // Delete any unreachable statepoints so that we don't have unrewritten
2530 // statepoints surviving this pass. This makes testing easier and the
2531 // resulting IR less confusing to human readers.
Chijun Sima21a8b602018-08-03 05:08:17 +00002532 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
2533 bool MadeChange = removeUnreachableBlocks(F, nullptr, &DTU);
2534 // Flush the Dominator Tree.
2535 DTU.getDomTree();
Daniel Neilson82daad32018-03-05 22:27:30 +00002536
Philip Reames85b36a82015-04-10 22:07:04 +00002537 // Gather all the statepoints which need rewritten. Be careful to only
2538 // consider those in reachable code since we need to ask dominance queries
2539 // when rewriting. We'll delete the unreachable ones in a moment.
Chandler Carruth31607342019-02-11 07:42:30 +00002540 SmallVector<CallBase *, 64> ParsePointNeeded;
Nico Rieck78199512015-08-06 19:10:45 +00002541 for (Instruction &I : instructions(F)) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00002542 // TODO: only the ones with the flag set!
Sanjoy Das25ec1a32015-10-16 02:41:00 +00002543 if (NeedsRewrite(I)) {
Daniel Neilson82daad32018-03-05 22:27:30 +00002544 // NOTE removeUnreachableBlocks() is stronger than
2545 // DominatorTree::isReachableFromEntry(). In other words
2546 // removeUnreachableBlocks can remove some blocks for which
2547 // isReachableFromEntry() returns true.
2548 assert(DT.isReachableFromEntry(I.getParent()) &&
2549 "no unreachable blocks expected");
Chandler Carruth31607342019-02-11 07:42:30 +00002550 ParsePointNeeded.push_back(cast<CallBase>(&I));
Philip Reames85b36a82015-04-10 22:07:04 +00002551 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00002552 }
2553
2554 // Return early if no work to do.
2555 if (ParsePointNeeded.empty())
Philip Reames85b36a82015-04-10 22:07:04 +00002556 return MadeChange;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002557
Philip Reames85b36a82015-04-10 22:07:04 +00002558 // As a prepass, go ahead and aggressively destroy single entry phi nodes.
2559 // These are created by LCSSA. They have the effect of increasing the size
2560 // of liveness sets for no good reason. It may be harder to do this post
2561 // insertion since relocations and base phis can confuse things.
2562 for (BasicBlock &BB : F)
2563 if (BB.getUniquePredecessor()) {
2564 MadeChange = true;
2565 FoldSingleEntryPHINodes(&BB);
2566 }
2567
Philip Reames971dc3a2015-08-12 22:11:45 +00002568 // Before we start introducing relocations, we want to tweak the IR a bit to
Fangrui Songf78650a2018-07-30 19:41:25 +00002569 // avoid unfortunate code generation effects. The main example is that we
Philip Reames971dc3a2015-08-12 22:11:45 +00002570 // want to try to make sure the comparison feeding a branch is after any
2571 // safepoints. Otherwise, we end up with a comparison of pre-relocation
2572 // values feeding a branch after relocation. This is semantically correct,
2573 // but results in extra register pressure since both the pre-relocation and
2574 // post-relocation copies must be available in registers. For code without
2575 // relocations this is handled elsewhere, but teaching the scheduler to
2576 // reverse the transform we're about to do would be slightly complex.
2577 // Note: This may extend the live range of the inputs to the icmp and thus
2578 // increase the liveset of any statepoint we move over. This is profitable
2579 // as long as all statepoints are in rare blocks. If we had in-register
2580 // lowering for live values this would be a much safer transform.
Chandler Carruthedb12a82018-10-15 10:04:59 +00002581 auto getConditionInst = [](Instruction *TI) -> Instruction * {
Philip Reames971dc3a2015-08-12 22:11:45 +00002582 if (auto *BI = dyn_cast<BranchInst>(TI))
2583 if (BI->isConditional())
2584 return dyn_cast<Instruction>(BI->getCondition());
2585 // TODO: Extend this to handle switches
2586 return nullptr;
2587 };
2588 for (BasicBlock &BB : F) {
Chandler Carruthedb12a82018-10-15 10:04:59 +00002589 Instruction *TI = BB.getTerminator();
Philip Reames971dc3a2015-08-12 22:11:45 +00002590 if (auto *Cond = getConditionInst(TI))
2591 // TODO: Handle more than just ICmps here. We should be able to move
Fangrui Songf78650a2018-07-30 19:41:25 +00002592 // most instructions without side effects or memory access.
Philip Reames971dc3a2015-08-12 22:11:45 +00002593 if (isa<ICmpInst>(Cond) && Cond->hasOneUse()) {
2594 MadeChange = true;
2595 Cond->moveBefore(TI);
2596 }
2597 }
2598
Philip Reamesa6575102019-01-24 16:08:18 +00002599 // Nasty workaround - The base computation code in the main algorithm doesn't
2600 // consider the fact that a GEP can be used to convert a scalar to a vector.
2601 // The right fix for this is to integrate GEPs into the base rewriting
2602 // algorithm properly, this is just a short term workaround to prevent
2603 // crashes by canonicalizing such GEPs into fully vector GEPs.
2604 for (Instruction &I : instructions(F)) {
2605 if (!isa<GetElementPtrInst>(I))
2606 continue;
2607
2608 unsigned VF = 0;
Philip Reamesa6575102019-01-24 16:08:18 +00002609 for (unsigned i = 0; i < I.getNumOperands(); i++)
Philip Reames4d683ee2019-01-24 16:34:00 +00002610 if (I.getOperand(i)->getType()->isVectorTy()) {
2611 assert(VF == 0 ||
2612 VF == I.getOperand(i)->getType()->getVectorNumElements());
Philip Reamesa6575102019-01-24 16:08:18 +00002613 VF = I.getOperand(i)->getType()->getVectorNumElements();
Philip Reames4d683ee2019-01-24 16:34:00 +00002614 }
Philip Reamesa6575102019-01-24 16:08:18 +00002615
Philip Reames4d683ee2019-01-24 16:34:00 +00002616 // It's the vector to scalar traversal through the pointer operand which
2617 // confuses base pointer rewriting, so limit ourselves to that case.
2618 if (!I.getOperand(0)->getType()->isVectorTy() && VF != 0) {
Philip Reamesa6575102019-01-24 16:08:18 +00002619 IRBuilder<> B(&I);
Philip Reames4d683ee2019-01-24 16:34:00 +00002620 auto *Splat = B.CreateVectorSplat(VF, I.getOperand(0));
2621 I.setOperand(0, Splat);
2622 MadeChange = true;
Philip Reamesa6575102019-01-24 16:08:18 +00002623 }
2624 }
2625
Justin Bogner843fb202015-12-15 19:40:57 +00002626 MadeChange |= insertParsePoints(F, DT, TTI, ParsePointNeeded);
Philip Reames85b36a82015-04-10 22:07:04 +00002627 return MadeChange;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002628}
Philip Reamesdf1ef082015-04-10 22:53:14 +00002629
2630// liveness computation via standard dataflow
2631// -------------------------------------------------------------------
2632
2633// TODO: Consider using bitvectors for liveness, the set of potentially
2634// interesting values should be small and easy to pre-compute.
2635
Philip Reamesdf1ef082015-04-10 22:53:14 +00002636/// Compute the live-in set for the location rbegin starting from
2637/// the live-out set of the basic block
Sanjoy Das61c76e32016-06-26 04:55:32 +00002638static void computeLiveInValues(BasicBlock::reverse_iterator Begin,
2639 BasicBlock::reverse_iterator End,
Igor Laevskyfb1811d2016-05-04 14:55:36 +00002640 SetVector<Value *> &LiveTmp) {
Sanjoy Das61c76e32016-06-26 04:55:32 +00002641 for (auto &I : make_range(Begin, End)) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00002642 // KILL/Def - Remove this definition from LiveIn
Sanjoy Das61c76e32016-06-26 04:55:32 +00002643 LiveTmp.remove(&I);
Philip Reamesdf1ef082015-04-10 22:53:14 +00002644
2645 // Don't consider *uses* in PHI nodes, we handle their contribution to
2646 // predecessor blocks when we seed the LiveOut sets
2647 if (isa<PHINode>(I))
2648 continue;
2649
2650 // USE - Add to the LiveIn set for this instruction
Sanjoy Das61c76e32016-06-26 04:55:32 +00002651 for (Value *V : I.operands()) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00002652 assert(!isUnhandledGCPointerType(V->getType()) &&
2653 "support for FCA unimplemented");
Philip Reames63294cb2015-04-26 19:48:03 +00002654 if (isHandledGCPointerType(V->getType()) && !isa<Constant>(V)) {
2655 // The choice to exclude all things constant here is slightly subtle.
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002656 // There are two independent reasons:
Philip Reames63294cb2015-04-26 19:48:03 +00002657 // - We assume that things which are constant (from LLVM's definition)
2658 // do not move at runtime. For example, the address of a global
2659 // variable is fixed, even though it's contents may not be.
2660 // - Second, we can't disallow arbitrary inttoptr constants even
2661 // if the language frontend does. Optimization passes are free to
2662 // locally exploit facts without respect to global reachability. This
2663 // can create sections of code which are dynamically unreachable and
2664 // contain just about anything. (see constants.ll in tests)
Philip Reamesdf1ef082015-04-10 22:53:14 +00002665 LiveTmp.insert(V);
2666 }
2667 }
2668 }
2669}
2670
Igor Laevskyfb1811d2016-05-04 14:55:36 +00002671static void computeLiveOutSeed(BasicBlock *BB, SetVector<Value *> &LiveTmp) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00002672 for (BasicBlock *Succ : successors(BB)) {
Sanjoy Das83186b02016-06-26 04:55:30 +00002673 for (auto &I : *Succ) {
2674 PHINode *PN = dyn_cast<PHINode>(&I);
2675 if (!PN)
2676 break;
2677
2678 Value *V = PN->getIncomingValueForBlock(BB);
Philip Reamesdf1ef082015-04-10 22:53:14 +00002679 assert(!isUnhandledGCPointerType(V->getType()) &&
2680 "support for FCA unimplemented");
Sanjoy Das83186b02016-06-26 04:55:30 +00002681 if (isHandledGCPointerType(V->getType()) && !isa<Constant>(V))
Philip Reamesdf1ef082015-04-10 22:53:14 +00002682 LiveTmp.insert(V);
Philip Reamesdf1ef082015-04-10 22:53:14 +00002683 }
2684 }
2685}
2686
Igor Laevskyfb1811d2016-05-04 14:55:36 +00002687static SetVector<Value *> computeKillSet(BasicBlock *BB) {
2688 SetVector<Value *> KillSet;
Philip Reamesdf1ef082015-04-10 22:53:14 +00002689 for (Instruction &I : *BB)
2690 if (isHandledGCPointerType(I.getType()))
2691 KillSet.insert(&I);
2692 return KillSet;
2693}
2694
Philip Reames9638ff92015-04-11 00:06:47 +00002695#ifndef NDEBUG
Philip Reamesdf1ef082015-04-10 22:53:14 +00002696/// Check that the items in 'Live' dominate 'TI'. This is used as a basic
2697/// sanity check for the liveness computation.
Igor Laevskyfb1811d2016-05-04 14:55:36 +00002698static void checkBasicSSA(DominatorTree &DT, SetVector<Value *> &Live,
Chandler Carruthedb12a82018-10-15 10:04:59 +00002699 Instruction *TI, bool TermOkay = false) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00002700 for (Value *V : Live) {
2701 if (auto *I = dyn_cast<Instruction>(V)) {
2702 // The terminator can be a member of the LiveOut set. LLVM's definition
2703 // of instruction dominance states that V does not dominate itself. As
2704 // such, we need to special case this to allow it.
2705 if (TermOkay && TI == I)
2706 continue;
2707 assert(DT.dominates(I, TI) &&
2708 "basic SSA liveness expectation violated by liveness analysis");
2709 }
2710 }
Philip Reamesdf1ef082015-04-10 22:53:14 +00002711}
2712
2713/// Check that all the liveness sets used during the computation of liveness
2714/// obey basic SSA properties. This is useful for finding cases where we miss
2715/// a def.
2716static void checkBasicSSA(DominatorTree &DT, GCPtrLivenessData &Data,
2717 BasicBlock &BB) {
2718 checkBasicSSA(DT, Data.LiveSet[&BB], BB.getTerminator());
2719 checkBasicSSA(DT, Data.LiveOut[&BB], BB.getTerminator(), true);
2720 checkBasicSSA(DT, Data.LiveIn[&BB], BB.getTerminator());
2721}
Philip Reames9638ff92015-04-11 00:06:47 +00002722#endif
Philip Reamesdf1ef082015-04-10 22:53:14 +00002723
2724static void computeLiveInValues(DominatorTree &DT, Function &F,
2725 GCPtrLivenessData &Data) {
Matthias Braunb30f2f512016-01-30 01:24:31 +00002726 SmallSetVector<BasicBlock *, 32> Worklist;
Philip Reamesdf1ef082015-04-10 22:53:14 +00002727
2728 // Seed the liveness for each individual block
2729 for (BasicBlock &BB : F) {
2730 Data.KillSet[&BB] = computeKillSet(&BB);
2731 Data.LiveSet[&BB].clear();
2732 computeLiveInValues(BB.rbegin(), BB.rend(), Data.LiveSet[&BB]);
2733
2734#ifndef NDEBUG
2735 for (Value *Kill : Data.KillSet[&BB])
2736 assert(!Data.LiveSet[&BB].count(Kill) && "live set contains kill");
2737#endif
2738
Igor Laevskyfb1811d2016-05-04 14:55:36 +00002739 Data.LiveOut[&BB] = SetVector<Value *>();
Philip Reamesdf1ef082015-04-10 22:53:14 +00002740 computeLiveOutSeed(&BB, Data.LiveOut[&BB]);
2741 Data.LiveIn[&BB] = Data.LiveSet[&BB];
Igor Laevskyfb1811d2016-05-04 14:55:36 +00002742 Data.LiveIn[&BB].set_union(Data.LiveOut[&BB]);
2743 Data.LiveIn[&BB].set_subtract(Data.KillSet[&BB]);
Philip Reamesdf1ef082015-04-10 22:53:14 +00002744 if (!Data.LiveIn[&BB].empty())
Sanjoy Dasb2df57a2016-06-26 04:55:26 +00002745 Worklist.insert(pred_begin(&BB), pred_end(&BB));
Philip Reamesdf1ef082015-04-10 22:53:14 +00002746 }
2747
2748 // Propagate that liveness until stable
2749 while (!Worklist.empty()) {
Sanjoy Dasb2df57a2016-06-26 04:55:26 +00002750 BasicBlock *BB = Worklist.pop_back_val();
Philip Reamesdf1ef082015-04-10 22:53:14 +00002751
Sanjoy Dasb2df57a2016-06-26 04:55:26 +00002752 // Compute our new liveout set, then exit early if it hasn't changed despite
2753 // the contribution of our successor.
Igor Laevskyfb1811d2016-05-04 14:55:36 +00002754 SetVector<Value *> LiveOut = Data.LiveOut[BB];
Philip Reamesdf1ef082015-04-10 22:53:14 +00002755 const auto OldLiveOutSize = LiveOut.size();
2756 for (BasicBlock *Succ : successors(BB)) {
2757 assert(Data.LiveIn.count(Succ));
Igor Laevskyfb1811d2016-05-04 14:55:36 +00002758 LiveOut.set_union(Data.LiveIn[Succ]);
Philip Reamesdf1ef082015-04-10 22:53:14 +00002759 }
2760 // assert OutLiveOut is a subset of LiveOut
2761 if (OldLiveOutSize == LiveOut.size()) {
2762 // If the sets are the same size, then we didn't actually add anything
Sanjoy Dasb2df57a2016-06-26 04:55:26 +00002763 // when unioning our successors LiveIn. Thus, the LiveIn of this block
Philip Reamesdf1ef082015-04-10 22:53:14 +00002764 // hasn't changed.
2765 continue;
2766 }
2767 Data.LiveOut[BB] = LiveOut;
2768
2769 // Apply the effects of this basic block
Igor Laevskyfb1811d2016-05-04 14:55:36 +00002770 SetVector<Value *> LiveTmp = LiveOut;
2771 LiveTmp.set_union(Data.LiveSet[BB]);
2772 LiveTmp.set_subtract(Data.KillSet[BB]);
Philip Reamesdf1ef082015-04-10 22:53:14 +00002773
2774 assert(Data.LiveIn.count(BB));
Igor Laevskyfb1811d2016-05-04 14:55:36 +00002775 const SetVector<Value *> &OldLiveIn = Data.LiveIn[BB];
Philip Reamesdf1ef082015-04-10 22:53:14 +00002776 // assert: OldLiveIn is a subset of LiveTmp
2777 if (OldLiveIn.size() != LiveTmp.size()) {
2778 Data.LiveIn[BB] = LiveTmp;
Sanjoy Dasb2df57a2016-06-26 04:55:26 +00002779 Worklist.insert(pred_begin(BB), pred_end(BB));
Philip Reamesdf1ef082015-04-10 22:53:14 +00002780 }
Sanjoy Dasb2df57a2016-06-26 04:55:26 +00002781 } // while (!Worklist.empty())
Philip Reamesdf1ef082015-04-10 22:53:14 +00002782
2783#ifndef NDEBUG
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002784 // Sanity check our output against SSA properties. This helps catch any
Philip Reamesdf1ef082015-04-10 22:53:14 +00002785 // missing kills during the above iteration.
Sanjoy Dasb2df57a2016-06-26 04:55:26 +00002786 for (BasicBlock &BB : F)
Philip Reamesdf1ef082015-04-10 22:53:14 +00002787 checkBasicSSA(DT, Data, BB);
Philip Reamesdf1ef082015-04-10 22:53:14 +00002788#endif
2789}
2790
2791static void findLiveSetAtInst(Instruction *Inst, GCPtrLivenessData &Data,
2792 StatepointLiveSetTy &Out) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00002793 BasicBlock *BB = Inst->getParent();
2794
2795 // Note: The copy is intentional and required
2796 assert(Data.LiveOut.count(BB));
Igor Laevskyfb1811d2016-05-04 14:55:36 +00002797 SetVector<Value *> LiveOut = Data.LiveOut[BB];
Philip Reamesdf1ef082015-04-10 22:53:14 +00002798
2799 // We want to handle the statepoint itself oddly. It's
2800 // call result is not live (normal), nor are it's arguments
2801 // (unless they're used again later). This adjustment is
2802 // specifically what we need to relocate
Duncan P. N. Exon Smith5c001c32016-08-30 00:13:12 +00002803 computeLiveInValues(BB->rbegin(), ++Inst->getIterator().getReverse(),
2804 LiveOut);
Igor Laevskyfb1811d2016-05-04 14:55:36 +00002805 LiveOut.remove(Inst);
Philip Reamesdf1ef082015-04-10 22:53:14 +00002806 Out.insert(LiveOut.begin(), LiveOut.end());
2807}
2808
2809static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData,
Chandler Carruth31607342019-02-11 07:42:30 +00002810 CallBase *Call,
Philip Reamesdf1ef082015-04-10 22:53:14 +00002811 PartiallyConstructedSafepointRecord &Info) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00002812 StatepointLiveSetTy Updated;
Chandler Carruth31607342019-02-11 07:42:30 +00002813 findLiveSetAtInst(Call, RevisedLivenessData, Updated);
Philip Reamesdf1ef082015-04-10 22:53:14 +00002814
Philip Reamesdf1ef082015-04-10 22:53:14 +00002815 // We may have base pointers which are now live that weren't before. We need
2816 // to update the PointerToBase structure to reflect this.
2817 for (auto V : Updated)
Sanjoy Das255532f2016-06-26 04:55:23 +00002818 if (Info.PointerToBase.insert({V, V}).second) {
Max Kazantseva13e1632017-12-28 12:03:12 +00002819 assert(isKnownBaseResult(V) &&
2820 "Can't find base for unexpected live value!");
Philip Reamesdf1ef082015-04-10 22:53:14 +00002821 continue;
2822 }
2823
2824#ifndef NDEBUG
Sanjoy Das255532f2016-06-26 04:55:23 +00002825 for (auto V : Updated)
Philip Reamesdf1ef082015-04-10 22:53:14 +00002826 assert(Info.PointerToBase.count(V) &&
Sanjoy Das255532f2016-06-26 04:55:23 +00002827 "Must be able to find base for live value!");
Philip Reamesdf1ef082015-04-10 22:53:14 +00002828#endif
2829
2830 // Remove any stale base mappings - this can happen since our liveness is
Sanjoy Das255532f2016-06-26 04:55:23 +00002831 // more precise then the one inherent in the base pointer analysis.
Philip Reamesdf1ef082015-04-10 22:53:14 +00002832 DenseSet<Value *> ToErase;
2833 for (auto KVPair : Info.PointerToBase)
2834 if (!Updated.count(KVPair.first))
2835 ToErase.insert(KVPair.first);
Sanjoy Das255532f2016-06-26 04:55:23 +00002836
2837 for (auto *V : ToErase)
Philip Reamesdf1ef082015-04-10 22:53:14 +00002838 Info.PointerToBase.erase(V);
2839
2840#ifndef NDEBUG
2841 for (auto KVPair : Info.PointerToBase)
2842 assert(Updated.count(KVPair.first) && "record for non-live value");
2843#endif
2844
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002845 Info.LiveSet = Updated;
Philip Reamesdf1ef082015-04-10 22:53:14 +00002846}