blob: 4cb3bed49c55ccd4471b0a9ee6f0588b728f3efb [file] [log] [blame]
Philip Reames47cc6732015-02-04 00:37:33 +00001//===- PlaceSafepoints.cpp - Place GC Safepoints --------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Place garbage collection safepoints at appropriate locations in the IR. This
11// does not make relocation semantics or variable liveness explicit. That's
12// done by RewriteStatepointsForGC.
13//
Philip Reamesd4a912f2015-02-09 22:44:03 +000014// Terminology:
15// - A call is said to be "parseable" if there is a stack map generated for the
16// return PC of the call. A runtime can determine where values listed in the
17// deopt arguments and (after RewriteStatepointsForGC) gc arguments are located
18// on the stack when the code is suspended inside such a call. Every parse
19// point is represented by a call wrapped in an gc.statepoint intrinsic.
20// - A "poll" is an explicit check in the generated code to determine if the
21// runtime needs the generated code to cooperate by calling a helper routine
22// and thus suspending its execution at a known state. The call to the helper
23// routine will be parseable. The (gc & runtime specific) logic of a poll is
24// assumed to be provided in a function of the name "gc.safepoint_poll".
25//
26// We aim to insert polls such that running code can quickly be brought to a
27// well defined state for inspection by the collector. In the current
28// implementation, this is done via the insertion of poll sites at method entry
29// and the backedge of most loops. We try to avoid inserting more polls than
30// are neccessary to ensure a finite period between poll sites. This is not
31// because the poll itself is expensive in the generated code; it's not. Polls
32// do tend to impact the optimizer itself in negative ways; we'd like to avoid
33// perturbing the optimization of the method as much as we can.
34//
35// We also need to make most call sites parseable. The callee might execute a
36// poll (or otherwise be inspected by the GC). If so, the entire stack
37// (including the suspended frame of the current method) must be parseable.
38//
Philip Reames47cc6732015-02-04 00:37:33 +000039// This pass will insert:
Philip Reamesd4a912f2015-02-09 22:44:03 +000040// - Call parse points ("call safepoints") for any call which may need to
41// reach a safepoint during the execution of the callee function.
42// - Backedge safepoint polls and entry safepoint polls to ensure that
43// executing code reaches a safepoint poll in a finite amount of time.
Philip Reames47cc6732015-02-04 00:37:33 +000044//
Philip Reamesd4a912f2015-02-09 22:44:03 +000045// We do not currently support return statepoints, but adding them would not
46// be hard. They are not required for correctness - entry safepoints are an
47// alternative - but some GCs may prefer them. Patches welcome.
Philip Reames47cc6732015-02-04 00:37:33 +000048//
49//===----------------------------------------------------------------------===//
50
51#include "llvm/Pass.h"
Chandler Carruth30d69c22015-02-13 10:01:29 +000052#include "llvm/IR/LegacyPassManager.h"
Philip Reames47cc6732015-02-04 00:37:33 +000053#include "llvm/ADT/SetOperations.h"
Philip Reames5708cca2015-05-12 20:43:48 +000054#include "llvm/ADT/SetVector.h"
Philip Reames47cc6732015-02-04 00:37:33 +000055#include "llvm/ADT/Statistic.h"
56#include "llvm/Analysis/LoopPass.h"
57#include "llvm/Analysis/LoopInfo.h"
58#include "llvm/Analysis/ScalarEvolution.h"
59#include "llvm/Analysis/ScalarEvolutionExpressions.h"
60#include "llvm/Analysis/CFG.h"
61#include "llvm/Analysis/InstructionSimplify.h"
62#include "llvm/IR/BasicBlock.h"
63#include "llvm/IR/CallSite.h"
64#include "llvm/IR/Dominators.h"
65#include "llvm/IR/Function.h"
66#include "llvm/IR/IRBuilder.h"
67#include "llvm/IR/InstIterator.h"
68#include "llvm/IR/Instructions.h"
69#include "llvm/IR/Intrinsics.h"
70#include "llvm/IR/IntrinsicInst.h"
71#include "llvm/IR/Module.h"
72#include "llvm/IR/Statepoint.h"
73#include "llvm/IR/Value.h"
74#include "llvm/IR/Verifier.h"
75#include "llvm/Support/Debug.h"
76#include "llvm/Support/CommandLine.h"
77#include "llvm/Support/raw_ostream.h"
78#include "llvm/Transforms/Scalar.h"
79#include "llvm/Transforms/Utils/BasicBlockUtils.h"
80#include "llvm/Transforms/Utils/Cloning.h"
81#include "llvm/Transforms/Utils/Local.h"
82
83#define DEBUG_TYPE "safepoint-placement"
84STATISTIC(NumEntrySafepoints, "Number of entry safepoints inserted");
85STATISTIC(NumCallSafepoints, "Number of call safepoints inserted");
86STATISTIC(NumBackedgeSafepoints, "Number of backedge safepoints inserted");
87
88STATISTIC(CallInLoop, "Number of loops w/o safepoints due to calls in loop");
89STATISTIC(FiniteExecution, "Number of loops w/o safepoints finite execution");
90
91using namespace llvm;
92
93// Ignore oppurtunities to avoid placing safepoints on backedges, useful for
94// validation
Philip Reames1f3e5c12015-02-20 23:32:03 +000095static cl::opt<bool> AllBackedges("spp-all-backedges", cl::Hidden,
96 cl::init(false));
Philip Reames47cc6732015-02-04 00:37:33 +000097
98/// If true, do not place backedge safepoints in counted loops.
Philip Reames1f3e5c12015-02-20 23:32:03 +000099static cl::opt<bool> SkipCounted("spp-counted", cl::Hidden, cl::init(true));
Philip Reames47cc6732015-02-04 00:37:33 +0000100
101// If true, split the backedge of a loop when placing the safepoint, otherwise
102// split the latch block itself. Both are useful to support for
103// experimentation, but in practice, it looks like splitting the backedge
104// optimizes better.
Philip Reames1f3e5c12015-02-20 23:32:03 +0000105static cl::opt<bool> SplitBackedge("spp-split-backedge", cl::Hidden,
106 cl::init(false));
Philip Reames47cc6732015-02-04 00:37:33 +0000107
108// Print tracing output
Philip Reames1f3e5c12015-02-20 23:32:03 +0000109static cl::opt<bool> TraceLSP("spp-trace", cl::Hidden, cl::init(false));
Philip Reames47cc6732015-02-04 00:37:33 +0000110
111namespace {
112
113/** An analysis pass whose purpose is to identify each of the backedges in
114 the function which require a safepoint poll to be inserted. */
115struct PlaceBackedgeSafepointsImpl : public LoopPass {
116 static char ID;
117
118 /// The output of the pass - gives a list of each backedge (described by
119 /// pointing at the branch) which need a poll inserted.
120 std::vector<TerminatorInst *> PollLocations;
121
122 /// True unless we're running spp-no-calls in which case we need to disable
123 /// the call dependend placement opts.
124 bool CallSafepointsEnabled;
125 PlaceBackedgeSafepointsImpl(bool CallSafepoints = false)
126 : LoopPass(ID), CallSafepointsEnabled(CallSafepoints) {
Philip Reames5a9685d2015-02-04 00:39:57 +0000127 initializePlaceBackedgeSafepointsImplPass(*PassRegistry::getPassRegistry());
Philip Reames47cc6732015-02-04 00:37:33 +0000128 }
129
130 bool runOnLoop(Loop *, LPPassManager &LPM) override;
131
132 void getAnalysisUsage(AnalysisUsage &AU) const override {
Philip Reames57bdac92015-05-12 20:56:33 +0000133 AU.addRequired<DominatorTreeWrapperPass>();
Philip Reames47cc6732015-02-04 00:37:33 +0000134 AU.addRequired<ScalarEvolution>();
Philip Reames47cc6732015-02-04 00:37:33 +0000135 // We no longer modify the IR at all in this pass. Thus all
136 // analysis are preserved.
137 AU.setPreservesAll();
138 }
139};
140}
141
Philip Reames1f3e5c12015-02-20 23:32:03 +0000142static cl::opt<bool> NoEntry("spp-no-entry", cl::Hidden, cl::init(false));
143static cl::opt<bool> NoCall("spp-no-call", cl::Hidden, cl::init(false));
144static cl::opt<bool> NoBackedge("spp-no-backedge", cl::Hidden, cl::init(false));
Philip Reames47cc6732015-02-04 00:37:33 +0000145
146namespace {
147struct PlaceSafepoints : public ModulePass {
148 static char ID; // Pass identification, replacement for typeid
149
Philip Reames47cc6732015-02-04 00:37:33 +0000150 PlaceSafepoints() : ModulePass(ID) {
151 initializePlaceSafepointsPass(*PassRegistry::getPassRegistry());
Philip Reames47cc6732015-02-04 00:37:33 +0000152 }
153 bool runOnModule(Module &M) override {
154 bool modified = false;
155 for (Function &F : M) {
156 modified |= runOnFunction(F);
157 }
158 return modified;
159 }
160 bool runOnFunction(Function &F);
161
162 void getAnalysisUsage(AnalysisUsage &AU) const override {
163 // We modify the graph wholesale (inlining, block insertion, etc). We
164 // preserve nothing at the moment. We could potentially preserve dom tree
165 // if that was worth doing
166 }
167};
168}
169
170// Insert a safepoint poll immediately before the given instruction. Does
171// not handle the parsability of state at the runtime call, that's the
172// callers job.
Philip Reames5a9685d2015-02-04 00:39:57 +0000173static void
174InsertSafepointPoll(DominatorTree &DT, Instruction *after,
175 std::vector<CallSite> &ParsePointsNeeded /*rval*/);
Philip Reames47cc6732015-02-04 00:37:33 +0000176
177static bool isGCLeafFunction(const CallSite &CS);
178
179static bool needsStatepoint(const CallSite &CS) {
180 if (isGCLeafFunction(CS))
181 return false;
182 if (CS.isCall()) {
183 CallInst *call = cast<CallInst>(CS.getInstruction());
184 if (call->isInlineAsm())
185 return false;
186 }
187 if (isStatepoint(CS) || isGCRelocate(CS) || isGCResult(CS)) {
188 return false;
189 }
190 return true;
191}
192
Philip Reames5a9685d2015-02-04 00:39:57 +0000193static Value *ReplaceWithStatepoint(const CallSite &CS, Pass *P);
Philip Reames47cc6732015-02-04 00:37:33 +0000194
195/// Returns true if this loop is known to contain a call safepoint which
196/// must unconditionally execute on any iteration of the loop which returns
197/// to the loop header via an edge from Pred. Returns a conservative correct
198/// answer; i.e. false is always valid.
199static bool containsUnconditionalCallSafepoint(Loop *L, BasicBlock *Header,
200 BasicBlock *Pred,
201 DominatorTree &DT) {
202 // In general, we're looking for any cut of the graph which ensures
203 // there's a call safepoint along every edge between Header and Pred.
204 // For the moment, we look only for the 'cuts' that consist of a single call
205 // instruction in a block which is dominated by the Header and dominates the
206 // loop latch (Pred) block. Somewhat surprisingly, walking the entire chain
207 // of such dominating blocks gets substaintially more occurences than just
208 // checking the Pred and Header blocks themselves. This may be due to the
209 // density of loop exit conditions caused by range and null checks.
210 // TODO: structure this as an analysis pass, cache the result for subloops,
211 // avoid dom tree recalculations
212 assert(DT.dominates(Header, Pred) && "loop latch not dominated by header?");
213
214 BasicBlock *Current = Pred;
215 while (true) {
216 for (Instruction &I : *Current) {
Benjamin Kramer3a09ef62015-04-10 14:50:08 +0000217 if (auto CS = CallSite(&I))
Philip Reames47cc6732015-02-04 00:37:33 +0000218 // Note: Technically, needing a safepoint isn't quite the right
219 // condition here. We should instead be checking if the target method
220 // has an
221 // unconditional poll. In practice, this is only a theoretical concern
222 // since we don't have any methods with conditional-only safepoint
223 // polls.
224 if (needsStatepoint(CS))
225 return true;
226 }
227
228 if (Current == Header)
229 break;
230 Current = DT.getNode(Current)->getIDom()->getBlock();
231 }
232
233 return false;
234}
235
236/// Returns true if this loop is known to terminate in a finite number of
237/// iterations. Note that this function may return false for a loop which
238/// does actual terminate in a finite constant number of iterations due to
239/// conservatism in the analysis.
240static bool mustBeFiniteCountedLoop(Loop *L, ScalarEvolution *SE,
Philip Reames5a9685d2015-02-04 00:39:57 +0000241 BasicBlock *Pred) {
Philip Reames47cc6732015-02-04 00:37:33 +0000242 // Only used when SkipCounted is off
243 const unsigned upperTripBound = 8192;
244
245 // A conservative bound on the loop as a whole.
246 const SCEV *MaxTrips = SE->getMaxBackedgeTakenCount(L);
247 if (MaxTrips != SE->getCouldNotCompute()) {
248 if (SE->getUnsignedRange(MaxTrips).getUnsignedMax().ult(upperTripBound))
249 return true;
250 if (SkipCounted &&
251 SE->getUnsignedRange(MaxTrips).getUnsignedMax().isIntN(32))
252 return true;
253 }
254
255 // If this is a conditional branch to the header with the alternate path
256 // being outside the loop, we can ask questions about the execution frequency
257 // of the exit block.
258 if (L->isLoopExiting(Pred)) {
259 // This returns an exact expression only. TODO: We really only need an
260 // upper bound here, but SE doesn't expose that.
261 const SCEV *MaxExec = SE->getExitCount(L, Pred);
262 if (MaxExec != SE->getCouldNotCompute()) {
263 if (SE->getUnsignedRange(MaxExec).getUnsignedMax().ult(upperTripBound))
264 return true;
265 if (SkipCounted &&
266 SE->getUnsignedRange(MaxExec).getUnsignedMax().isIntN(32))
267 return true;
268 }
269 }
270
271 return /* not finite */ false;
272}
273
274static void scanOneBB(Instruction *start, Instruction *end,
Philip Reames5a9685d2015-02-04 00:39:57 +0000275 std::vector<CallInst *> &calls,
276 std::set<BasicBlock *> &seen,
277 std::vector<BasicBlock *> &worklist) {
Philip Reames47cc6732015-02-04 00:37:33 +0000278 for (BasicBlock::iterator itr(start);
279 itr != start->getParent()->end() && itr != BasicBlock::iterator(end);
280 itr++) {
281 if (CallInst *CI = dyn_cast<CallInst>(&*itr)) {
282 calls.push_back(CI);
283 }
284 // FIXME: This code does not handle invokes
285 assert(!dyn_cast<InvokeInst>(&*itr) &&
286 "support for invokes in poll code needed");
287 // Only add the successor blocks if we reach the terminator instruction
288 // without encountering end first
289 if (itr->isTerminator()) {
290 BasicBlock *BB = itr->getParent();
Philip Reamesa29de872015-02-09 22:26:11 +0000291 for (BasicBlock *Succ : successors(BB)) {
Philip Reames47cc6732015-02-04 00:37:33 +0000292 if (seen.count(Succ) == 0) {
293 worklist.push_back(Succ);
294 seen.insert(Succ);
295 }
296 }
297 }
298 }
299}
300static void scanInlinedCode(Instruction *start, Instruction *end,
Philip Reames5a9685d2015-02-04 00:39:57 +0000301 std::vector<CallInst *> &calls,
302 std::set<BasicBlock *> &seen) {
Philip Reames47cc6732015-02-04 00:37:33 +0000303 calls.clear();
304 std::vector<BasicBlock *> worklist;
305 seen.insert(start->getParent());
306 scanOneBB(start, end, calls, seen, worklist);
307 while (!worklist.empty()) {
308 BasicBlock *BB = worklist.back();
309 worklist.pop_back();
310 scanOneBB(&*BB->begin(), end, calls, seen, worklist);
311 }
312}
313
314bool PlaceBackedgeSafepointsImpl::runOnLoop(Loop *L, LPPassManager &LPM) {
315 ScalarEvolution *SE = &getAnalysis<ScalarEvolution>();
Philip Reames57bdac92015-05-12 20:56:33 +0000316 DominatorTree *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Philip Reames47cc6732015-02-04 00:37:33 +0000317
Philip Reames5708cca2015-05-12 20:43:48 +0000318 // Loop through all loop latches (branches controlling backedges). We need
319 // to place a safepoint on every backedge (potentially).
320 // Note: In common usage, there will be only one edge due to LoopSimplify
321 // having run sometime earlier in the pipeline, but this code must be correct
322 // w.r.t. loops with multiple backedges.
Philip Reames47cc6732015-02-04 00:37:33 +0000323 BasicBlock *header = L->getHeader();
324
Philip Reames5708cca2015-05-12 20:43:48 +0000325 SmallVector<BasicBlock*, 16> LoopLatches;
326 L->getLoopLatches(LoopLatches);
327 for (BasicBlock *pred : LoopLatches) {
328 assert(L->contains(pred));
Philip Reames47cc6732015-02-04 00:37:33 +0000329
330 // Make a policy decision about whether this loop needs a safepoint or
331 // not. Note that this is about unburdening the optimizer in loops, not
332 // avoiding the runtime cost of the actual safepoint.
333 if (!AllBackedges) {
334 if (mustBeFiniteCountedLoop(L, SE, pred)) {
335 if (TraceLSP)
336 errs() << "skipping safepoint placement in finite loop\n";
337 FiniteExecution++;
338 continue;
339 }
340 if (CallSafepointsEnabled &&
Philip Reames57bdac92015-05-12 20:56:33 +0000341 containsUnconditionalCallSafepoint(L, header, pred, *DT)) {
Philip Reames47cc6732015-02-04 00:37:33 +0000342 // Note: This is only semantically legal since we won't do any further
343 // IPO or inlining before the actual call insertion.. If we hadn't, we
344 // might latter loose this call safepoint.
345 if (TraceLSP)
346 errs() << "skipping safepoint placement due to unconditional call\n";
347 CallInLoop++;
348 continue;
349 }
350 }
351
352 // TODO: We can create an inner loop which runs a finite number of
353 // iterations with an outer loop which contains a safepoint. This would
354 // not help runtime performance that much, but it might help our ability to
355 // optimize the inner loop.
356
Philip Reames47cc6732015-02-04 00:37:33 +0000357 // Safepoint insertion would involve creating a new basic block (as the
358 // target of the current backedge) which does the safepoint (of all live
359 // variables) and branches to the true header
360 TerminatorInst *term = pred->getTerminator();
361
362 if (TraceLSP) {
363 errs() << "[LSP] terminator instruction: ";
364 term->dump();
365 }
366
367 PollLocations.push_back(term);
368 }
369
Philip Reames5708cca2015-05-12 20:43:48 +0000370 return false;
Philip Reames47cc6732015-02-04 00:37:33 +0000371}
372
373static Instruction *findLocationForEntrySafepoint(Function &F,
374 DominatorTree &DT) {
375
376 // Conceptually, this poll needs to be on method entry, but in
377 // practice, we place it as late in the entry block as possible. We
378 // can place it as late as we want as long as it dominates all calls
379 // that can grow the stack. This, combined with backedge polls,
380 // give us all the progress guarantees we need.
381
382 // Due to the way the frontend generates IR, we may have a couple of initial
383 // basic blocks before the first bytecode. These will be single-entry
384 // single-exit blocks which conceptually are just part of the first 'real
385 // basic block'. Since we don't have deopt state until the first bytecode,
386 // walk forward until we've found the first unconditional branch or merge.
387
388 // hasNextInstruction and nextInstruction are used to iterate
389 // through a "straight line" execution sequence.
390
391 auto hasNextInstruction = [](Instruction *I) {
392 if (!I->isTerminator()) {
393 return true;
394 }
395 BasicBlock *nextBB = I->getParent()->getUniqueSuccessor();
396 return nextBB && (nextBB->getUniquePredecessor() != nullptr);
397 };
398
399 auto nextInstruction = [&hasNextInstruction](Instruction *I) {
400 assert(hasNextInstruction(I) &&
401 "first check if there is a next instruction!");
402 if (I->isTerminator()) {
403 return I->getParent()->getUniqueSuccessor()->begin();
404 } else {
405 return std::next(BasicBlock::iterator(I));
406 }
407 };
408
409 Instruction *cursor = nullptr;
410 for (cursor = F.getEntryBlock().begin(); hasNextInstruction(cursor);
411 cursor = nextInstruction(cursor)) {
412
Philip Reames47cc6732015-02-04 00:37:33 +0000413 // We need to stop going forward as soon as we see a call that can
414 // grow the stack (i.e. the call target has a non-zero frame
415 // size).
Benjamin Kramer3a09ef62015-04-10 14:50:08 +0000416 if (CallSite(cursor)) {
Philip Reames47cc6732015-02-04 00:37:33 +0000417 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(cursor)) {
418 // llvm.assume(...) are not really calls.
419 if (II->getIntrinsicID() == Intrinsic::assume) {
420 continue;
421 }
Philip Reames2e78fa42015-04-26 19:41:23 +0000422 // llvm.frameescape() intrinsic is not a real call. The intrinsic can
423 // exist only in the entry block.
424 // Inserting a statepoint before llvm.frameescape() may split the
425 // entry block, and push the intrinsic out of the entry block.
426 if (II->getIntrinsicID() == Intrinsic::frameescape) {
427 continue;
428 }
Philip Reames47cc6732015-02-04 00:37:33 +0000429 }
430 break;
431 }
432 }
433
Philip Reames5a9685d2015-02-04 00:39:57 +0000434 assert((hasNextInstruction(cursor) || cursor->isTerminator()) &&
435 "either we stopped because of a call, or because of terminator");
Philip Reames47cc6732015-02-04 00:37:33 +0000436
437 if (cursor->isTerminator()) {
438 return cursor;
439 }
440
441 BasicBlock *BB = cursor->getParent();
442 SplitBlock(BB, cursor, nullptr);
443
444 // Note: SplitBlock modifies the DT. Simply passing a Pass (which is a
445 // module pass) is not enough.
446 DT.recalculate(F);
Adam Nemete340f852015-05-06 08:18:41 +0000447
Philip Reames47cc6732015-02-04 00:37:33 +0000448 // SplitBlock updates the DT
Adam Nemete340f852015-05-06 08:18:41 +0000449 DEBUG(DT.verifyDomTree());
Philip Reames47cc6732015-02-04 00:37:33 +0000450
451 return BB->getTerminator();
452}
453
454/// Identify the list of call sites which need to be have parseable state
455static void findCallSafepoints(Function &F,
456 std::vector<CallSite> &Found /*rval*/) {
457 assert(Found.empty() && "must be empty!");
Philip Reamesa29de872015-02-09 22:26:11 +0000458 for (Instruction &I : inst_range(F)) {
459 Instruction *inst = &I;
Philip Reames47cc6732015-02-04 00:37:33 +0000460 if (isa<CallInst>(inst) || isa<InvokeInst>(inst)) {
461 CallSite CS(inst);
462
463 // No safepoint needed or wanted
464 if (!needsStatepoint(CS)) {
465 continue;
466 }
467
468 Found.push_back(CS);
469 }
470 }
471}
472
473/// Implement a unique function which doesn't require we sort the input
474/// vector. Doing so has the effect of changing the output of a couple of
475/// tests in ways which make them less useful in testing fused safepoints.
476template <typename T> static void unique_unsorted(std::vector<T> &vec) {
477 std::set<T> seen;
478 std::vector<T> tmp;
479 vec.reserve(vec.size());
480 std::swap(tmp, vec);
481 for (auto V : tmp) {
482 if (seen.insert(V).second) {
483 vec.push_back(V);
484 }
485 }
486}
487
Philip Reamesb1ed02f2015-02-09 21:48:05 +0000488static std::string GCSafepointPollName("gc.safepoint_poll");
489
490static bool isGCSafepointPoll(Function &F) {
491 return F.getName().equals(GCSafepointPollName);
492}
493
Philip Reames0b1b3872015-02-21 00:09:09 +0000494/// Returns true if this function should be rewritten to include safepoint
495/// polls and parseable call sites. The main point of this function is to be
496/// an extension point for custom logic.
497static bool shouldRewriteFunction(Function &F) {
498 // TODO: This should check the GCStrategy
499 if (F.hasGC()) {
500 const std::string StatepointExampleName("statepoint-example");
501 return StatepointExampleName == F.getGC();
502 } else
503 return false;
504}
505
506// TODO: These should become properties of the GCStrategy, possibly with
507// command line overrides.
508static bool enableEntrySafepoints(Function &F) { return !NoEntry; }
509static bool enableBackedgeSafepoints(Function &F) { return !NoBackedge; }
510static bool enableCallSafepoints(Function &F) { return !NoCall; }
511
Igor Laevsky5e23e162015-05-08 11:59:09 +0000512// Normalize basic block to make it ready to be target of invoke statepoint.
513// Ensure that 'BB' does not have phi nodes. It may require spliting it.
514static BasicBlock *normalizeForInvokeSafepoint(BasicBlock *BB,
515 BasicBlock *InvokeParent) {
516 BasicBlock *ret = BB;
517
518 if (!BB->getUniquePredecessor()) {
519 ret = SplitBlockPredecessors(BB, InvokeParent, "");
520 }
521
522 // Now that 'ret' has unique predecessor we can safely remove all phi nodes
523 // from it
524 FoldSingleEntryPHINodes(ret);
525 assert(!isa<PHINode>(ret->begin()));
526
527 return ret;
528}
Philip Reames0b1b3872015-02-21 00:09:09 +0000529
Philip Reames47cc6732015-02-04 00:37:33 +0000530bool PlaceSafepoints::runOnFunction(Function &F) {
531 if (F.isDeclaration() || F.empty()) {
532 // This is a declaration, nothing to do. Must exit early to avoid crash in
533 // dom tree calculation
534 return false;
535 }
536
Philip Reames7e7dc3e2015-02-10 00:04:53 +0000537 if (isGCSafepointPoll(F)) {
538 // Given we're inlining this inside of safepoint poll insertion, this
539 // doesn't make any sense. Note that we do make any contained calls
540 // parseable after we inline a poll.
541 return false;
542 }
543
Philip Reames0b1b3872015-02-21 00:09:09 +0000544 if (!shouldRewriteFunction(F))
545 return false;
546
Philip Reames47cc6732015-02-04 00:37:33 +0000547 bool modified = false;
548
549 // In various bits below, we rely on the fact that uses are reachable from
550 // defs. When there are basic blocks unreachable from the entry, dominance
551 // and reachablity queries return non-sensical results. Thus, we preprocess
552 // the function to ensure these properties hold.
553 modified |= removeUnreachableBlocks(F);
554
555 // STEP 1 - Insert the safepoint polling locations. We do not need to
556 // actually insert parse points yet. That will be done for all polls and
557 // calls in a single pass.
558
559 // Note: With the migration, we need to recompute this for each 'pass'. Once
560 // we merge these, we'll do it once before the analysis
561 DominatorTree DT;
562
563 std::vector<CallSite> ParsePointNeeded;
564
Philip Reames0b1b3872015-02-21 00:09:09 +0000565 if (enableBackedgeSafepoints(F)) {
Philip Reames47cc6732015-02-04 00:37:33 +0000566 // Construct a pass manager to run the LoopPass backedge logic. We
567 // need the pass manager to handle scheduling all the loop passes
568 // appropriately. Doing this by hand is painful and just not worth messing
569 // with for the moment.
Chandler Carruth30d69c22015-02-13 10:01:29 +0000570 legacy::FunctionPassManager FPM(F.getParent());
Philip Reames0b1b3872015-02-21 00:09:09 +0000571 bool CanAssumeCallSafepoints = enableCallSafepoints(F);
Philip Reames47cc6732015-02-04 00:37:33 +0000572 PlaceBackedgeSafepointsImpl *PBS =
Philip Reamesb1ed02f2015-02-09 21:48:05 +0000573 new PlaceBackedgeSafepointsImpl(CanAssumeCallSafepoints);
Philip Reames47cc6732015-02-04 00:37:33 +0000574 FPM.add(PBS);
Philip Reames47cc6732015-02-04 00:37:33 +0000575 FPM.run(F);
576
577 // We preserve dominance information when inserting the poll, otherwise
578 // we'd have to recalculate this on every insert
579 DT.recalculate(F);
580
Philip Reames5708cca2015-05-12 20:43:48 +0000581 auto &PollLocations = PBS->PollLocations;
582
583 auto OrderByBBName = [](Instruction *a, Instruction *b) {
584 return a->getParent()->getName() < b->getParent()->getName();
585 };
586 // We need the order of list to be stable so that naming ends up stable
587 // when we split edges. This makes test cases much easier to write.
588 std::sort(PollLocations.begin(), PollLocations.end(), OrderByBBName);
589
590 // We can sometimes end up with duplicate poll locations. This happens if
591 // a single loop is visited more than once. The fact this happens seems
592 // wrong, but it does happen for the split-backedge.ll test case.
593 PollLocations.erase(std::unique(PollLocations.begin(),
594 PollLocations.end()),
595 PollLocations.end());
596
Philip Reames47cc6732015-02-04 00:37:33 +0000597 // Insert a poll at each point the analysis pass identified
Philip Reames5708cca2015-05-12 20:43:48 +0000598 for (size_t i = 0; i < PollLocations.size(); i++) {
Philip Reames47cc6732015-02-04 00:37:33 +0000599 // We are inserting a poll, the function is modified
600 modified = true;
601
602 // The poll location must be the terminator of a loop latch block.
Philip Reames5708cca2015-05-12 20:43:48 +0000603 TerminatorInst *Term = PollLocations[i];
Philip Reames47cc6732015-02-04 00:37:33 +0000604
605 std::vector<CallSite> ParsePoints;
606 if (SplitBackedge) {
607 // Split the backedge of the loop and insert the poll within that new
608 // basic block. This creates a loop with two latches per original
609 // latch (which is non-ideal), but this appears to be easier to
610 // optimize in practice than inserting the poll immediately before the
611 // latch test.
612
613 // Since this is a latch, at least one of the successors must dominate
614 // it. Its possible that we have a) duplicate edges to the same header
615 // and b) edges to distinct loop headers. We need to insert pools on
Philip Reames5708cca2015-05-12 20:43:48 +0000616 // each.
617 SetVector<BasicBlock *> Headers;
Philip Reames47cc6732015-02-04 00:37:33 +0000618 for (unsigned i = 0; i < Term->getNumSuccessors(); i++) {
619 BasicBlock *Succ = Term->getSuccessor(i);
620 if (DT.dominates(Succ, Term->getParent())) {
621 Headers.insert(Succ);
622 }
623 }
624 assert(!Headers.empty() && "poll location is not a loop latch?");
625
626 // The split loop structure here is so that we only need to recalculate
627 // the dominator tree once. Alternatively, we could just keep it up to
628 // date and use a more natural merged loop.
Philip Reames5708cca2015-05-12 20:43:48 +0000629 SetVector<BasicBlock *> SplitBackedges;
Philip Reames47cc6732015-02-04 00:37:33 +0000630 for (BasicBlock *Header : Headers) {
631 BasicBlock *NewBB = SplitEdge(Term->getParent(), Header, nullptr);
632 SplitBackedges.insert(NewBB);
633 }
634 DT.recalculate(F);
635 for (BasicBlock *NewBB : SplitBackedges) {
Philip Reames5708cca2015-05-12 20:43:48 +0000636 std::vector<CallSite> RuntimeCalls;
637 InsertSafepointPoll(DT, NewBB->getTerminator(), RuntimeCalls);
Philip Reames47cc6732015-02-04 00:37:33 +0000638 NumBackedgeSafepoints++;
Philip Reames5708cca2015-05-12 20:43:48 +0000639 ParsePointNeeded.insert(ParsePointNeeded.end(), RuntimeCalls.begin(),
640 RuntimeCalls.end());
Philip Reames47cc6732015-02-04 00:37:33 +0000641 }
642
643 } else {
644 // Split the latch block itself, right before the terminator.
Philip Reames5708cca2015-05-12 20:43:48 +0000645 std::vector<CallSite> RuntimeCalls;
646 InsertSafepointPoll(DT, Term, RuntimeCalls);
Philip Reames47cc6732015-02-04 00:37:33 +0000647 NumBackedgeSafepoints++;
Philip Reames5708cca2015-05-12 20:43:48 +0000648 ParsePointNeeded.insert(ParsePointNeeded.end(), RuntimeCalls.begin(),
649 RuntimeCalls.end());
Philip Reames47cc6732015-02-04 00:37:33 +0000650 }
651
Philip Reames47cc6732015-02-04 00:37:33 +0000652 // Record the parse points for later use
653 ParsePointNeeded.insert(ParsePointNeeded.end(), ParsePoints.begin(),
654 ParsePoints.end());
655 }
656 }
657
Philip Reames0b1b3872015-02-21 00:09:09 +0000658 if (enableEntrySafepoints(F)) {
Philip Reames47cc6732015-02-04 00:37:33 +0000659 DT.recalculate(F);
660 Instruction *term = findLocationForEntrySafepoint(F, DT);
661 if (!term) {
662 // policy choice not to insert?
663 } else {
664 std::vector<CallSite> RuntimeCalls;
665 InsertSafepointPoll(DT, term, RuntimeCalls);
666 modified = true;
667 NumEntrySafepoints++;
668 ParsePointNeeded.insert(ParsePointNeeded.end(), RuntimeCalls.begin(),
669 RuntimeCalls.end());
670 }
671 }
672
Philip Reames0b1b3872015-02-21 00:09:09 +0000673 if (enableCallSafepoints(F)) {
Philip Reames47cc6732015-02-04 00:37:33 +0000674 DT.recalculate(F);
675 std::vector<CallSite> Calls;
676 findCallSafepoints(F, Calls);
677 NumCallSafepoints += Calls.size();
Philip Reames5a9685d2015-02-04 00:39:57 +0000678 ParsePointNeeded.insert(ParsePointNeeded.end(), Calls.begin(), Calls.end());
Philip Reames47cc6732015-02-04 00:37:33 +0000679 }
680
681 // Unique the vectors since we can end up with duplicates if we scan the call
682 // site for call safepoints after we add it for entry or backedge. The
683 // only reason we need tracking at all is that some functions might have
684 // polls but not call safepoints and thus we might miss marking the runtime
685 // calls for the polls. (This is useful in test cases!)
686 unique_unsorted(ParsePointNeeded);
687
688 // Any parse point (no matter what source) will be handled here
689 DT.recalculate(F); // Needed?
690
691 // We're about to start modifying the function
692 if (!ParsePointNeeded.empty())
693 modified = true;
694
695 // Now run through and insert the safepoints, but do _NOT_ update or remove
696 // any existing uses. We have references to live variables that need to
697 // survive to the last iteration of this loop.
698 std::vector<Value *> Results;
699 Results.reserve(ParsePointNeeded.size());
700 for (size_t i = 0; i < ParsePointNeeded.size(); i++) {
701 CallSite &CS = ParsePointNeeded[i];
Igor Laevsky5e23e162015-05-08 11:59:09 +0000702
703 // For invoke statepoints we need to remove all phi nodes at the normal
704 // destination block.
705 // Reason for this is that we can place gc_result only after last phi node
706 // in basic block. We will get malformed code after RAUW for the
707 // gc_result if one of this phi nodes uses result from the invoke.
708 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(CS.getInstruction())) {
709 normalizeForInvokeSafepoint(Invoke->getNormalDest(),
710 Invoke->getParent());
711 }
712
Philip Reames47cc6732015-02-04 00:37:33 +0000713 Value *GCResult = ReplaceWithStatepoint(CS, nullptr);
714 Results.push_back(GCResult);
715 }
716 assert(Results.size() == ParsePointNeeded.size());
717
718 // Adjust all users of the old call sites to use the new ones instead
719 for (size_t i = 0; i < ParsePointNeeded.size(); i++) {
720 CallSite &CS = ParsePointNeeded[i];
721 Value *GCResult = Results[i];
722 if (GCResult) {
Igor Laevsky5e23e162015-05-08 11:59:09 +0000723 // Can not RAUW for the gc result in case of phi nodes preset.
724 assert(!isa<PHINode>(cast<Instruction>(GCResult)->getParent()->begin()));
Philip Reames47cc6732015-02-04 00:37:33 +0000725
726 // Replace all uses with the new call
727 CS.getInstruction()->replaceAllUsesWith(GCResult);
728 }
729
730 // Now that we've handled all uses, remove the original call itself
731 // Note: The insert point can't be the deleted instruction!
732 CS.getInstruction()->eraseFromParent();
733 }
734 return modified;
735}
736
737char PlaceBackedgeSafepointsImpl::ID = 0;
738char PlaceSafepoints::ID = 0;
739
Philip Reames5a9685d2015-02-04 00:39:57 +0000740ModulePass *llvm::createPlaceSafepointsPass() { return new PlaceSafepoints(); }
Philip Reames47cc6732015-02-04 00:37:33 +0000741
742INITIALIZE_PASS_BEGIN(PlaceBackedgeSafepointsImpl,
743 "place-backedge-safepoints-impl",
744 "Place Backedge Safepoints", false, false)
745INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
Philip Reames57bdac92015-05-12 20:56:33 +0000746INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Philip Reames47cc6732015-02-04 00:37:33 +0000747INITIALIZE_PASS_END(PlaceBackedgeSafepointsImpl,
748 "place-backedge-safepoints-impl",
749 "Place Backedge Safepoints", false, false)
750
751INITIALIZE_PASS_BEGIN(PlaceSafepoints, "place-safepoints", "Place Safepoints",
752 false, false)
753INITIALIZE_PASS_END(PlaceSafepoints, "place-safepoints", "Place Safepoints",
754 false, false)
755
756static bool isGCLeafFunction(const CallSite &CS) {
757 Instruction *inst = CS.getInstruction();
Aaron Ballman94d4d332015-02-05 13:52:42 +0000758 if (isa<IntrinsicInst>(inst)) {
Aaron Ballman1b072b32015-02-05 13:40:04 +0000759 // Most LLVM intrinsics are things which can never take a safepoint.
760 // As a result, we don't need to have the stack parsable at the
761 // callsite. This is a highly useful optimization since intrinsic
762 // calls are fairly prevelent, particularly in debug builds.
763 return true;
Philip Reames47cc6732015-02-04 00:37:33 +0000764 }
765
766 // If this function is marked explicitly as a leaf call, we don't need to
767 // place a safepoint of it. In fact, for correctness we *can't* in many
768 // cases. Note: Indirect calls return Null for the called function,
769 // these obviously aren't runtime functions with attributes
770 // TODO: Support attributes on the call site as well.
771 const Function *F = CS.getCalledFunction();
772 bool isLeaf =
773 F &&
774 F->getFnAttribute("gc-leaf-function").getValueAsString().equals("true");
775 if (isLeaf) {
776 return true;
777 }
778 return false;
779}
780
Philip Reames5a9685d2015-02-04 00:39:57 +0000781static void
782InsertSafepointPoll(DominatorTree &DT, Instruction *term,
783 std::vector<CallSite> &ParsePointsNeeded /*rval*/) {
Philip Reames47cc6732015-02-04 00:37:33 +0000784 Module *M = term->getParent()->getParent()->getParent();
785 assert(M);
786
787 // Inline the safepoint poll implementation - this will get all the branch,
788 // control flow, etc.. Most importantly, it will introduce the actual slow
789 // path call - where we need to insert a safepoint (parsepoint).
790 FunctionType *ftype =
791 FunctionType::get(Type::getVoidTy(M->getContext()), false);
792 assert(ftype && "null?");
793 // Note: This cast can fail if there's a function of the same name with a
794 // different type inserted previously
795 Function *F =
796 dyn_cast<Function>(M->getOrInsertFunction("gc.safepoint_poll", ftype));
Ramkumar Ramachandra3edf74f2015-02-09 23:02:10 +0000797 assert(F && "void @gc.safepoint_poll() must be defined");
798 assert(!F->empty() && "gc.safepoint_poll must be a non-empty function");
Philip Reames47cc6732015-02-04 00:37:33 +0000799 CallInst *poll = CallInst::Create(F, "", term);
800
801 // Record some information about the call site we're replacing
802 BasicBlock *OrigBB = term->getParent();
803 BasicBlock::iterator before(poll), after(poll);
804 bool isBegin(false);
805 if (before == term->getParent()->begin()) {
806 isBegin = true;
807 } else {
808 before--;
809 }
810 after++;
811 assert(after != poll->getParent()->end() && "must have successor");
812 assert(DT.dominates(before, after) && "trivially true");
813
814 // do the actual inlining
815 InlineFunctionInfo IFI;
816 bool inlineStatus = InlineFunction(poll, IFI);
817 assert(inlineStatus && "inline must succeed");
Philip Reames72634d62015-02-04 05:11:20 +0000818 (void)inlineStatus; // suppress warning in release-asserts
Philip Reames47cc6732015-02-04 00:37:33 +0000819
820 // Check post conditions
821 assert(IFI.StaticAllocas.empty() && "can't have allocs");
822
823 std::vector<CallInst *> calls; // new calls
824 std::set<BasicBlock *> BBs; // new BBs + insertee
825 // Include only the newly inserted instructions, Note: begin may not be valid
826 // if we inserted to the beginning of the basic block
827 BasicBlock::iterator start;
828 if (isBegin) {
829 start = OrigBB->begin();
830 } else {
831 start = before;
832 start++;
833 }
834
835 // If your poll function includes an unreachable at the end, that's not
836 // valid. Bugpoint likes to create this, so check for it.
837 assert(isPotentiallyReachable(&*start, &*after, nullptr, nullptr) &&
838 "malformed poll function");
839
840 scanInlinedCode(&*(start), &*(after), calls, BBs);
841
842 // Recompute since we've invalidated cached data. Conceptually we
843 // shouldn't need to do this, but implementation wise we appear to. Needed
844 // so we can insert safepoints correctly.
845 // TODO: update more cheaply
846 DT.recalculate(*after->getParent()->getParent());
847
848 assert(!calls.empty() && "slow path not found for safepoint poll");
849
850 // Record the fact we need a parsable state at the runtime call contained in
851 // the poll function. This is required so that the runtime knows how to
852 // parse the last frame when we actually take the safepoint (i.e. execute
853 // the slow path)
854 assert(ParsePointsNeeded.empty());
855 for (size_t i = 0; i < calls.size(); i++) {
856
857 // No safepoint needed or wanted
858 if (!needsStatepoint(calls[i])) {
859 continue;
860 }
861
862 // These are likely runtime calls. Should we assert that via calling
863 // convention or something?
864 ParsePointsNeeded.push_back(CallSite(calls[i]));
865 }
866 assert(ParsePointsNeeded.size() <= calls.size());
867}
868
Philip Reames47cc6732015-02-04 00:37:33 +0000869/// Replaces the given call site (Call or Invoke) with a gc.statepoint
870/// intrinsic with an empty deoptimization arguments list. This does
871/// NOT do explicit relocation for GC support.
872static Value *ReplaceWithStatepoint(const CallSite &CS, /* to replace */
873 Pass *P) {
NAKAMURA Takumi2a5bd542015-05-07 10:18:46 +0000874 assert(CS.getInstruction()->getParent()->getParent()->getParent() &&
875 "must be set");
Philip Reames47cc6732015-02-04 00:37:33 +0000876
877 // TODO: technically, a pass is not allowed to get functions from within a
878 // function pass since it might trigger a new function addition. Refactor
879 // this logic out to the initialization of the pass. Doesn't appear to
880 // matter in practice.
881
Philip Reames47cc6732015-02-04 00:37:33 +0000882 // Then go ahead and use the builder do actually do the inserts. We insert
883 // immediately before the previous instruction under the assumption that all
884 // arguments will be available here. We can't insert afterwards since we may
885 // be replacing a terminator.
Sanjoy Das93abd812015-05-06 23:53:19 +0000886 IRBuilder<> Builder(CS.getInstruction());
Philip Reamesb1ed02f2015-02-09 21:48:05 +0000887
888 // Note: The gc args are not filled in at this time, that's handled by
889 // RewriteStatepointsForGC (which is currently under review).
890
Philip Reames47cc6732015-02-04 00:37:33 +0000891 // Create the statepoint given all the arguments
Sanjoy Das93abd812015-05-06 23:53:19 +0000892 Instruction *Token = nullptr;
Sanjoy Dasabf15602015-05-06 23:53:21 +0000893 AttributeSet OriginalAttrs;
894
Philip Reames47cc6732015-02-04 00:37:33 +0000895 if (CS.isCall()) {
Sanjoy Das93abd812015-05-06 23:53:19 +0000896 CallInst *ToReplace = cast<CallInst>(CS.getInstruction());
Sanjoy Dasabe1c682015-05-06 23:53:09 +0000897 CallInst *Call = Builder.CreateGCStatepointCall(
Ramkumar Ramachandra3408f3e2015-02-26 00:35:56 +0000898 CS.getCalledValue(), makeArrayRef(CS.arg_begin(), CS.arg_end()), None,
899 None, "safepoint_token");
Sanjoy Das93abd812015-05-06 23:53:19 +0000900 Call->setTailCall(ToReplace->isTailCall());
901 Call->setCallingConv(ToReplace->getCallingConv());
Philip Reames47cc6732015-02-04 00:37:33 +0000902
903 // Before we have to worry about GC semantics, all attributes are legal
Philip Reames47cc6732015-02-04 00:37:33 +0000904 // TODO: handle param attributes
Sanjoy Dasabf15602015-05-06 23:53:21 +0000905 OriginalAttrs = ToReplace->getAttributes();
906
907 // In case if we can handle this set of attributes - set up function
908 // attributes directly on statepoint and return attributes later for
909 // gc_result intrinsic.
910 Call->setAttributes(OriginalAttrs.getFnAttributes());
Philip Reames47cc6732015-02-04 00:37:33 +0000911
Sanjoy Das93abd812015-05-06 23:53:19 +0000912 Token = Call;
Philip Reames47cc6732015-02-04 00:37:33 +0000913
914 // Put the following gc_result and gc_relocate calls immediately after the
Sanjoy Dasabf15602015-05-06 23:53:21 +0000915 // the old call (which we're about to delete).
916 assert(ToReplace->getNextNode() && "not a terminator, must have next");
917 Builder.SetInsertPoint(ToReplace->getNextNode());
918 Builder.SetCurrentDebugLocation(ToReplace->getNextNode()->getDebugLoc());
Philip Reames47cc6732015-02-04 00:37:33 +0000919 } else if (CS.isInvoke()) {
Sanjoy Das93abd812015-05-06 23:53:19 +0000920 InvokeInst *ToReplace = cast<InvokeInst>(CS.getInstruction());
Philip Reames47cc6732015-02-04 00:37:33 +0000921
922 // Insert the new invoke into the old block. We'll remove the old one in a
923 // moment at which point this will become the new terminator for the
924 // original block.
Sanjoy Das93abd812015-05-06 23:53:19 +0000925 Builder.SetInsertPoint(ToReplace->getParent());
926 InvokeInst *Invoke = Builder.CreateGCStatepointInvoke(
927 CS.getCalledValue(), ToReplace->getNormalDest(),
928 ToReplace->getUnwindDest(), makeArrayRef(CS.arg_begin(), CS.arg_end()),
Sanjoy Dasabe1c682015-05-06 23:53:09 +0000929 Builder.getInt32(0), None, "safepoint_token");
Philip Reames47cc6732015-02-04 00:37:33 +0000930
931 // Currently we will fail on parameter attributes and on certain
932 // function attributes.
Sanjoy Dasabf15602015-05-06 23:53:21 +0000933 OriginalAttrs = ToReplace->getAttributes();
934
935 // In case if we can handle this set of attributes - set up function
936 // attributes directly on statepoint and return attributes later for
937 // gc_result intrinsic.
Sanjoy Das93abd812015-05-06 23:53:19 +0000938 Invoke->setAttributes(OriginalAttrs.getFnAttributes());
Philip Reames47cc6732015-02-04 00:37:33 +0000939
Sanjoy Das93abd812015-05-06 23:53:19 +0000940 Token = Invoke;
Philip Reames47cc6732015-02-04 00:37:33 +0000941
942 // We'll insert the gc.result into the normal block
Igor Laevsky5e23e162015-05-08 11:59:09 +0000943 BasicBlock *NormalDest = ToReplace->getNormalDest();
944 // Can not insert gc.result in case of phi nodes preset.
945 // Should have removed this cases prior to runnning this function
946 assert(!isa<PHINode>(NormalDest->begin()));
947 Instruction *IP = &*(NormalDest->getFirstInsertionPt());
948 Builder.SetInsertPoint(IP);
Philip Reames47cc6732015-02-04 00:37:33 +0000949 } else {
950 llvm_unreachable("unexpect type of CallSite");
951 }
Sanjoy Das93abd812015-05-06 23:53:19 +0000952 assert(Token);
Philip Reames47cc6732015-02-04 00:37:33 +0000953
954 // Handle the return value of the original call - update all uses to use a
955 // gc_result hanging off the statepoint node we just inserted
956
957 // Only add the gc_result iff there is actually a used result
958 if (!CS.getType()->isVoidTy() && !CS.getInstruction()->use_empty()) {
Sanjoy Das93abd812015-05-06 23:53:19 +0000959 std::string TakenName =
960 CS.getInstruction()->hasName() ? CS.getInstruction()->getName() : "";
961 CallInst *GCResult = Builder.CreateGCResult(Token, CS.getType(), TakenName);
Sanjoy Dasabf15602015-05-06 23:53:21 +0000962 GCResult->setAttributes(OriginalAttrs.getRetAttributes());
Sanjoy Das93abd812015-05-06 23:53:19 +0000963 return GCResult;
Philip Reames47cc6732015-02-04 00:37:33 +0000964 } else {
965 // No return value for the call.
966 return nullptr;
967 }
968}