blob: a40079ca8e76e871d8becfb6b58f232049d57cf9 [file] [log] [blame]
Chris Lattner530d4bf2003-05-29 15:11:31 +00001//===- InlineFunction.cpp - Code to perform function inlining -------------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner530d4bf2003-05-29 15:11:31 +00009//
10// This file implements inlining of a function into a call site, resolving
11// parameters and the return value as appropriate.
12//
Chris Lattner530d4bf2003-05-29 15:11:31 +000013//===----------------------------------------------------------------------===//
14
15#include "llvm/Transforms/Utils/Cloning.h"
Weiming Zhao45d4cb92015-11-24 18:57:06 +000016#include "llvm/ADT/SetVector.h"
Joseph Tremoulete92e0a92016-09-04 01:23:20 +000017#include "llvm/ADT/SmallPtrSet.h"
Hal Finkel94146652014-07-24 14:25:39 +000018#include "llvm/ADT/SmallSet.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000019#include "llvm/ADT/SmallVector.h"
20#include "llvm/ADT/StringExtras.h"
Hal Finkelff0bcb62014-07-25 15:50:08 +000021#include "llvm/Analysis/AliasAnalysis.h"
Daniel Jasperaec2fa32016-12-19 08:22:17 +000022#include "llvm/Analysis/AssumptionCache.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000023#include "llvm/Analysis/CallGraph.h"
Hal Finkelff0bcb62014-07-25 15:50:08 +000024#include "llvm/Analysis/CaptureTracking.h"
David Majnemer8a1c45d2015-12-12 05:38:55 +000025#include "llvm/Analysis/EHPersonalities.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000026#include "llvm/Analysis/InstructionSimplify.h"
Hal Finkel94146652014-07-24 14:25:39 +000027#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000028#include "llvm/IR/Attributes.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000029#include "llvm/IR/CallSite.h"
Reid Klecknerf0915aa2014-05-15 20:11:28 +000030#include "llvm/IR/CFG.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000031#include "llvm/IR/Constants.h"
32#include "llvm/IR/DataLayout.h"
Chandler Carruth9a4c9e52014-03-06 00:46:21 +000033#include "llvm/IR/DebugInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000034#include "llvm/IR/DerivedTypes.h"
Adrian Prantl3e2659e2015-01-30 19:37:48 +000035#include "llvm/IR/DIBuilder.h"
Hal Finkelff0bcb62014-07-25 15:50:08 +000036#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000037#include "llvm/IR/IRBuilder.h"
38#include "llvm/IR/Instructions.h"
39#include "llvm/IR/IntrinsicInst.h"
40#include "llvm/IR/Intrinsics.h"
Hal Finkel94146652014-07-24 14:25:39 +000041#include "llvm/IR/MDBuilder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000042#include "llvm/IR/Module.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000043#include "llvm/Transforms/Utils/Local.h"
Hal Finkelff0bcb62014-07-25 15:50:08 +000044#include "llvm/Support/CommandLine.h"
45#include <algorithm>
Hans Wennborg083ca9b2015-10-06 23:24:35 +000046
Chris Lattnerdf3c3422004-01-09 06:12:26 +000047using namespace llvm;
Chris Lattner530d4bf2003-05-29 15:11:31 +000048
Hal Finkelff0bcb62014-07-25 15:50:08 +000049static cl::opt<bool>
James Molloy6b95d8e2014-09-04 13:23:08 +000050EnableNoAliasConversion("enable-noalias-to-md-conversion", cl::init(true),
Hal Finkelff0bcb62014-07-25 15:50:08 +000051 cl::Hidden,
52 cl::desc("Convert noalias attributes to metadata during inlining."));
53
Hal Finkel68dc3c72014-10-15 23:44:41 +000054static cl::opt<bool>
55PreserveAlignmentAssumptions("preserve-alignment-assumptions-during-inlining",
56 cl::init(true), cl::Hidden,
57 cl::desc("Convert align attributes to assumptions during inlining."));
58
Eric Christopherf16bee82012-03-26 19:09:38 +000059bool llvm::InlineFunction(CallInst *CI, InlineFunctionInfo &IFI,
Chandler Carruth7b560d42015-09-09 17:55:00 +000060 AAResults *CalleeAAR, bool InsertLifetime) {
61 return InlineFunction(CallSite(CI), IFI, CalleeAAR, InsertLifetime);
Chris Lattner0841fb12006-01-14 20:07:50 +000062}
Eric Christopherf16bee82012-03-26 19:09:38 +000063bool llvm::InlineFunction(InvokeInst *II, InlineFunctionInfo &IFI,
Chandler Carruth7b560d42015-09-09 17:55:00 +000064 AAResults *CalleeAAR, bool InsertLifetime) {
65 return InlineFunction(CallSite(II), IFI, CalleeAAR, InsertLifetime);
Chris Lattner0841fb12006-01-14 20:07:50 +000066}
Chris Lattner0cc265e2003-08-24 06:59:16 +000067
John McCallbd04b742011-05-27 18:34:38 +000068namespace {
David Majnemer654e1302015-07-31 17:58:14 +000069 /// A class for recording information about inlining a landing pad.
70 class LandingPadInliningInfo {
Dmitri Gribenkodbeafa72012-06-09 00:01:45 +000071 BasicBlock *OuterResumeDest; ///< Destination of the invoke's unwind.
72 BasicBlock *InnerResumeDest; ///< Destination for the callee's resume.
73 LandingPadInst *CallerLPad; ///< LandingPadInst associated with the invoke.
74 PHINode *InnerEHValuesPHI; ///< PHI for EH values from landingpad insts.
Bill Wendling0c2d82b2012-01-31 01:22:03 +000075 SmallVector<Value*, 8> UnwindDestPHIValues;
Bill Wendlingfa284402011-07-28 07:31:46 +000076
Bill Wendling55421f02011-08-14 08:01:36 +000077 public:
David Majnemer654e1302015-07-31 17:58:14 +000078 LandingPadInliningInfo(InvokeInst *II)
Craig Topperf40110f2014-04-25 05:29:35 +000079 : OuterResumeDest(II->getUnwindDest()), InnerResumeDest(nullptr),
80 CallerLPad(nullptr), InnerEHValuesPHI(nullptr) {
Bill Wendling55421f02011-08-14 08:01:36 +000081 // If there are PHI nodes in the unwind destination block, we need to keep
82 // track of which values came into them from the invoke before removing
83 // the edge from this block.
84 llvm::BasicBlock *InvokeBB = II->getParent();
Bill Wendlingea6e9352012-01-31 01:25:54 +000085 BasicBlock::iterator I = OuterResumeDest->begin();
Bill Wendling55421f02011-08-14 08:01:36 +000086 for (; isa<PHINode>(I); ++I) {
John McCallbd04b742011-05-27 18:34:38 +000087 // Save the value to use for this edge.
Bill Wendling55421f02011-08-14 08:01:36 +000088 PHINode *PHI = cast<PHINode>(I);
89 UnwindDestPHIValues.push_back(PHI->getIncomingValueForBlock(InvokeBB));
90 }
91
Bill Wendlingf3cae512012-01-31 00:56:53 +000092 CallerLPad = cast<LandingPadInst>(I);
John McCallbd04b742011-05-27 18:34:38 +000093 }
94
Sanjay Patel0fdb4372015-03-10 19:42:57 +000095 /// The outer unwind destination is the target of
Bill Wendlingea6e9352012-01-31 01:25:54 +000096 /// unwind edges introduced for calls within the inlined function.
Bill Wendling0c2d82b2012-01-31 01:22:03 +000097 BasicBlock *getOuterResumeDest() const {
Bill Wendlingea6e9352012-01-31 01:25:54 +000098 return OuterResumeDest;
John McCallbd04b742011-05-27 18:34:38 +000099 }
100
Bill Wendling3fd879d2012-01-31 01:48:40 +0000101 BasicBlock *getInnerResumeDest();
Bill Wendling55421f02011-08-14 08:01:36 +0000102
103 LandingPadInst *getLandingPadInst() const { return CallerLPad; }
104
Sanjay Patel0fdb4372015-03-10 19:42:57 +0000105 /// Forward the 'resume' instruction to the caller's landing pad block.
106 /// When the landing pad block has only one predecessor, this is
Bill Wendling55421f02011-08-14 08:01:36 +0000107 /// a simple branch. When there is more than one predecessor, we need to
108 /// split the landing pad block after the landingpad instruction and jump
109 /// to there.
Bill Wendling56f15bf2013-03-22 20:31:05 +0000110 void forwardResume(ResumeInst *RI,
Craig Topper71b7b682014-08-21 05:55:13 +0000111 SmallPtrSetImpl<LandingPadInst*> &InlinedLPads);
Bill Wendling55421f02011-08-14 08:01:36 +0000112
Sanjay Patel0fdb4372015-03-10 19:42:57 +0000113 /// Add incoming-PHI values to the unwind destination block for the given
114 /// basic block, using the values for the original invoke's source block.
John McCallbd04b742011-05-27 18:34:38 +0000115 void addIncomingPHIValuesFor(BasicBlock *BB) const {
Bill Wendlingea6e9352012-01-31 01:25:54 +0000116 addIncomingPHIValuesForInto(BB, OuterResumeDest);
John McCall046c47e2011-05-28 07:45:59 +0000117 }
Bill Wendlingad088e62011-07-30 05:42:50 +0000118
John McCall046c47e2011-05-28 07:45:59 +0000119 void addIncomingPHIValuesForInto(BasicBlock *src, BasicBlock *dest) const {
120 BasicBlock::iterator I = dest->begin();
John McCallbd04b742011-05-27 18:34:38 +0000121 for (unsigned i = 0, e = UnwindDestPHIValues.size(); i != e; ++i, ++I) {
Bill Wendlingad088e62011-07-30 05:42:50 +0000122 PHINode *phi = cast<PHINode>(I);
123 phi->addIncoming(UnwindDestPHIValues[i], src);
John McCallbd04b742011-05-27 18:34:38 +0000124 }
125 }
126 };
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000127} // anonymous namespace
John McCallbd04b742011-05-27 18:34:38 +0000128
Sanjay Patel0fdb4372015-03-10 19:42:57 +0000129/// Get or create a target for the branch from ResumeInsts.
David Majnemer654e1302015-07-31 17:58:14 +0000130BasicBlock *LandingPadInliningInfo::getInnerResumeDest() {
Bill Wendling55421f02011-08-14 08:01:36 +0000131 if (InnerResumeDest) return InnerResumeDest;
132
133 // Split the landing pad.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000134 BasicBlock::iterator SplitPoint = ++CallerLPad->getIterator();
Bill Wendling55421f02011-08-14 08:01:36 +0000135 InnerResumeDest =
136 OuterResumeDest->splitBasicBlock(SplitPoint,
137 OuterResumeDest->getName() + ".body");
138
139 // The number of incoming edges we expect to the inner landing pad.
140 const unsigned PHICapacity = 2;
141
142 // Create corresponding new PHIs for all the PHIs in the outer landing pad.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000143 Instruction *InsertPoint = &InnerResumeDest->front();
Bill Wendling55421f02011-08-14 08:01:36 +0000144 BasicBlock::iterator I = OuterResumeDest->begin();
145 for (unsigned i = 0, e = UnwindDestPHIValues.size(); i != e; ++i, ++I) {
146 PHINode *OuterPHI = cast<PHINode>(I);
147 PHINode *InnerPHI = PHINode::Create(OuterPHI->getType(), PHICapacity,
148 OuterPHI->getName() + ".lpad-body",
149 InsertPoint);
150 OuterPHI->replaceAllUsesWith(InnerPHI);
151 InnerPHI->addIncoming(OuterPHI, OuterResumeDest);
152 }
153
154 // Create a PHI for the exception values.
155 InnerEHValuesPHI = PHINode::Create(CallerLPad->getType(), PHICapacity,
156 "eh.lpad-body", InsertPoint);
157 CallerLPad->replaceAllUsesWith(InnerEHValuesPHI);
158 InnerEHValuesPHI->addIncoming(CallerLPad, OuterResumeDest);
159
160 // All done.
161 return InnerResumeDest;
162}
163
Sanjay Patel0fdb4372015-03-10 19:42:57 +0000164/// Forward the 'resume' instruction to the caller's landing pad block.
165/// When the landing pad block has only one predecessor, this is a simple
Bill Wendling55421f02011-08-14 08:01:36 +0000166/// branch. When there is more than one predecessor, we need to split the
167/// landing pad block after the landingpad instruction and jump to there.
David Majnemer654e1302015-07-31 17:58:14 +0000168void LandingPadInliningInfo::forwardResume(
169 ResumeInst *RI, SmallPtrSetImpl<LandingPadInst *> &InlinedLPads) {
Bill Wendling3fd879d2012-01-31 01:48:40 +0000170 BasicBlock *Dest = getInnerResumeDest();
Bill Wendling55421f02011-08-14 08:01:36 +0000171 BasicBlock *Src = RI->getParent();
172
173 BranchInst::Create(Dest, Src);
174
175 // Update the PHIs in the destination. They were inserted in an order which
176 // makes this work.
177 addIncomingPHIValuesForInto(Src, Dest);
178
179 InnerEHValuesPHI->addIncoming(RI->getOperand(0), Src);
180 RI->eraseFromParent();
181}
182
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000183/// Helper for getUnwindDestToken/getUnwindDestTokenHelper.
184static Value *getParentPad(Value *EHPad) {
185 if (auto *FPI = dyn_cast<FuncletPadInst>(EHPad))
186 return FPI->getParentPad();
187 return cast<CatchSwitchInst>(EHPad)->getParentPad();
188}
189
190typedef DenseMap<Instruction *, Value *> UnwindDestMemoTy;
191
192/// Helper for getUnwindDestToken that does the descendant-ward part of
193/// the search.
194static Value *getUnwindDestTokenHelper(Instruction *EHPad,
195 UnwindDestMemoTy &MemoMap) {
196 SmallVector<Instruction *, 8> Worklist(1, EHPad);
197
198 while (!Worklist.empty()) {
199 Instruction *CurrentPad = Worklist.pop_back_val();
200 // We only put pads on the worklist that aren't in the MemoMap. When
201 // we find an unwind dest for a pad we may update its ancestors, but
202 // the queue only ever contains uncles/great-uncles/etc. of CurrentPad,
203 // so they should never get updated while queued on the worklist.
204 assert(!MemoMap.count(CurrentPad));
205 Value *UnwindDestToken = nullptr;
206 if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(CurrentPad)) {
207 if (CatchSwitch->hasUnwindDest()) {
208 UnwindDestToken = CatchSwitch->getUnwindDest()->getFirstNonPHI();
209 } else {
210 // Catchswitch doesn't have a 'nounwind' variant, and one might be
211 // annotated as "unwinds to caller" when really it's nounwind (see
212 // e.g. SimplifyCFGOpt::SimplifyUnreachable), so we can't infer the
213 // parent's unwind dest from this. We can check its catchpads'
214 // descendants, since they might include a cleanuppad with an
215 // "unwinds to caller" cleanupret, which can be trusted.
216 for (auto HI = CatchSwitch->handler_begin(),
217 HE = CatchSwitch->handler_end();
218 HI != HE && !UnwindDestToken; ++HI) {
219 BasicBlock *HandlerBlock = *HI;
220 auto *CatchPad = cast<CatchPadInst>(HandlerBlock->getFirstNonPHI());
221 for (User *Child : CatchPad->users()) {
222 // Intentionally ignore invokes here -- since the catchswitch is
223 // marked "unwind to caller", it would be a verifier error if it
224 // contained an invoke which unwinds out of it, so any invoke we'd
225 // encounter must unwind to some child of the catch.
226 if (!isa<CleanupPadInst>(Child) && !isa<CatchSwitchInst>(Child))
227 continue;
228
229 Instruction *ChildPad = cast<Instruction>(Child);
230 auto Memo = MemoMap.find(ChildPad);
231 if (Memo == MemoMap.end()) {
Joseph Tremoulete92e0a92016-09-04 01:23:20 +0000232 // Haven't figured out this child pad yet; queue it.
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000233 Worklist.push_back(ChildPad);
234 continue;
235 }
236 // We've already checked this child, but might have found that
237 // it offers no proof either way.
238 Value *ChildUnwindDestToken = Memo->second;
239 if (!ChildUnwindDestToken)
240 continue;
241 // We already know the child's unwind dest, which can either
242 // be ConstantTokenNone to indicate unwind to caller, or can
243 // be another child of the catchpad. Only the former indicates
244 // the unwind dest of the catchswitch.
245 if (isa<ConstantTokenNone>(ChildUnwindDestToken)) {
246 UnwindDestToken = ChildUnwindDestToken;
247 break;
248 }
249 assert(getParentPad(ChildUnwindDestToken) == CatchPad);
250 }
251 }
252 }
253 } else {
254 auto *CleanupPad = cast<CleanupPadInst>(CurrentPad);
255 for (User *U : CleanupPad->users()) {
256 if (auto *CleanupRet = dyn_cast<CleanupReturnInst>(U)) {
257 if (BasicBlock *RetUnwindDest = CleanupRet->getUnwindDest())
258 UnwindDestToken = RetUnwindDest->getFirstNonPHI();
259 else
260 UnwindDestToken = ConstantTokenNone::get(CleanupPad->getContext());
261 break;
262 }
263 Value *ChildUnwindDestToken;
264 if (auto *Invoke = dyn_cast<InvokeInst>(U)) {
265 ChildUnwindDestToken = Invoke->getUnwindDest()->getFirstNonPHI();
266 } else if (isa<CleanupPadInst>(U) || isa<CatchSwitchInst>(U)) {
267 Instruction *ChildPad = cast<Instruction>(U);
268 auto Memo = MemoMap.find(ChildPad);
269 if (Memo == MemoMap.end()) {
270 // Haven't resolved this child yet; queue it and keep searching.
271 Worklist.push_back(ChildPad);
272 continue;
273 }
274 // We've checked this child, but still need to ignore it if it
275 // had no proof either way.
276 ChildUnwindDestToken = Memo->second;
277 if (!ChildUnwindDestToken)
278 continue;
279 } else {
280 // Not a relevant user of the cleanuppad
281 continue;
282 }
283 // In a well-formed program, the child/invoke must either unwind to
284 // an(other) child of the cleanup, or exit the cleanup. In the
285 // first case, continue searching.
286 if (isa<Instruction>(ChildUnwindDestToken) &&
287 getParentPad(ChildUnwindDestToken) == CleanupPad)
288 continue;
289 UnwindDestToken = ChildUnwindDestToken;
290 break;
291 }
292 }
293 // If we haven't found an unwind dest for CurrentPad, we may have queued its
294 // children, so move on to the next in the worklist.
295 if (!UnwindDestToken)
296 continue;
297
298 // Now we know that CurrentPad unwinds to UnwindDestToken. It also exits
299 // any ancestors of CurrentPad up to but not including UnwindDestToken's
300 // parent pad. Record this in the memo map, and check to see if the
301 // original EHPad being queried is one of the ones exited.
302 Value *UnwindParent;
303 if (auto *UnwindPad = dyn_cast<Instruction>(UnwindDestToken))
304 UnwindParent = getParentPad(UnwindPad);
305 else
306 UnwindParent = nullptr;
307 bool ExitedOriginalPad = false;
308 for (Instruction *ExitedPad = CurrentPad;
309 ExitedPad && ExitedPad != UnwindParent;
310 ExitedPad = dyn_cast<Instruction>(getParentPad(ExitedPad))) {
311 // Skip over catchpads since they just follow their catchswitches.
312 if (isa<CatchPadInst>(ExitedPad))
313 continue;
314 MemoMap[ExitedPad] = UnwindDestToken;
315 ExitedOriginalPad |= (ExitedPad == EHPad);
316 }
317
318 if (ExitedOriginalPad)
319 return UnwindDestToken;
320
321 // Continue the search.
322 }
323
324 // No definitive information is contained within this funclet.
325 return nullptr;
326}
327
328/// Given an EH pad, find where it unwinds. If it unwinds to an EH pad,
329/// return that pad instruction. If it unwinds to caller, return
330/// ConstantTokenNone. If it does not have a definitive unwind destination,
331/// return nullptr.
332///
333/// This routine gets invoked for calls in funclets in inlinees when inlining
334/// an invoke. Since many funclets don't have calls inside them, it's queried
335/// on-demand rather than building a map of pads to unwind dests up front.
336/// Determining a funclet's unwind dest may require recursively searching its
337/// descendants, and also ancestors and cousins if the descendants don't provide
338/// an answer. Since most funclets will have their unwind dest immediately
339/// available as the unwind dest of a catchswitch or cleanupret, this routine
340/// searches top-down from the given pad and then up. To avoid worst-case
341/// quadratic run-time given that approach, it uses a memo map to avoid
342/// re-processing funclet trees. The callers that rewrite the IR as they go
343/// take advantage of this, for correctness, by checking/forcing rewritten
344/// pads' entries to match the original callee view.
345static Value *getUnwindDestToken(Instruction *EHPad,
346 UnwindDestMemoTy &MemoMap) {
347 // Catchpads unwind to the same place as their catchswitch;
348 // redirct any queries on catchpads so the code below can
349 // deal with just catchswitches and cleanuppads.
350 if (auto *CPI = dyn_cast<CatchPadInst>(EHPad))
351 EHPad = CPI->getCatchSwitch();
352
353 // Check if we've already determined the unwind dest for this pad.
354 auto Memo = MemoMap.find(EHPad);
355 if (Memo != MemoMap.end())
356 return Memo->second;
357
358 // Search EHPad and, if necessary, its descendants.
359 Value *UnwindDestToken = getUnwindDestTokenHelper(EHPad, MemoMap);
360 assert((UnwindDestToken == nullptr) != (MemoMap.count(EHPad) != 0));
361 if (UnwindDestToken)
362 return UnwindDestToken;
363
364 // No information is available for this EHPad from itself or any of its
365 // descendants. An unwind all the way out to a pad in the caller would
366 // need also to agree with the unwind dest of the parent funclet, so
367 // search up the chain to try to find a funclet with information. Put
368 // null entries in the memo map to avoid re-processing as we go up.
369 MemoMap[EHPad] = nullptr;
Joseph Tremoulete92e0a92016-09-04 01:23:20 +0000370#ifndef NDEBUG
371 SmallPtrSet<Instruction *, 4> TempMemos;
372 TempMemos.insert(EHPad);
373#endif
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000374 Instruction *LastUselessPad = EHPad;
375 Value *AncestorToken;
376 for (AncestorToken = getParentPad(EHPad);
377 auto *AncestorPad = dyn_cast<Instruction>(AncestorToken);
378 AncestorToken = getParentPad(AncestorToken)) {
379 // Skip over catchpads since they just follow their catchswitches.
380 if (isa<CatchPadInst>(AncestorPad))
381 continue;
Joseph Tremoulete92e0a92016-09-04 01:23:20 +0000382 // If the MemoMap had an entry mapping AncestorPad to nullptr, since we
383 // haven't yet called getUnwindDestTokenHelper for AncestorPad in this
384 // call to getUnwindDestToken, that would mean that AncestorPad had no
385 // information in itself, its descendants, or its ancestors. If that
386 // were the case, then we should also have recorded the lack of information
387 // for the descendant that we're coming from. So assert that we don't
388 // find a null entry in the MemoMap for AncestorPad.
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000389 assert(!MemoMap.count(AncestorPad) || MemoMap[AncestorPad]);
390 auto AncestorMemo = MemoMap.find(AncestorPad);
391 if (AncestorMemo == MemoMap.end()) {
392 UnwindDestToken = getUnwindDestTokenHelper(AncestorPad, MemoMap);
393 } else {
394 UnwindDestToken = AncestorMemo->second;
395 }
396 if (UnwindDestToken)
397 break;
398 LastUselessPad = AncestorPad;
Joseph Tremoulete92e0a92016-09-04 01:23:20 +0000399 MemoMap[LastUselessPad] = nullptr;
400#ifndef NDEBUG
401 TempMemos.insert(LastUselessPad);
402#endif
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000403 }
404
Joseph Tremoulete92e0a92016-09-04 01:23:20 +0000405 // We know that getUnwindDestTokenHelper was called on LastUselessPad and
406 // returned nullptr (and likewise for EHPad and any of its ancestors up to
407 // LastUselessPad), so LastUselessPad has no information from below. Since
408 // getUnwindDestTokenHelper must investigate all downward paths through
409 // no-information nodes to prove that a node has no information like this,
410 // and since any time it finds information it records it in the MemoMap for
411 // not just the immediately-containing funclet but also any ancestors also
412 // exited, it must be the case that, walking downward from LastUselessPad,
413 // visiting just those nodes which have not been mapped to an unwind dest
414 // by getUnwindDestTokenHelper (the nullptr TempMemos notwithstanding, since
415 // they are just used to keep getUnwindDestTokenHelper from repeating work),
416 // any node visited must have been exhaustively searched with no information
417 // for it found.
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000418 SmallVector<Instruction *, 8> Worklist(1, LastUselessPad);
419 while (!Worklist.empty()) {
420 Instruction *UselessPad = Worklist.pop_back_val();
Joseph Tremoulete92e0a92016-09-04 01:23:20 +0000421 auto Memo = MemoMap.find(UselessPad);
422 if (Memo != MemoMap.end() && Memo->second) {
423 // Here the name 'UselessPad' is a bit of a misnomer, because we've found
424 // that it is a funclet that does have information about unwinding to
425 // a particular destination; its parent was a useless pad.
426 // Since its parent has no information, the unwind edge must not escape
427 // the parent, and must target a sibling of this pad. This local unwind
428 // gives us no information about EHPad. Leave it and the subtree rooted
429 // at it alone.
430 assert(getParentPad(Memo->second) == getParentPad(UselessPad));
431 continue;
432 }
433 // We know we don't have information for UselesPad. If it has an entry in
434 // the MemoMap (mapping it to nullptr), it must be one of the TempMemos
435 // added on this invocation of getUnwindDestToken; if a previous invocation
436 // recorded nullptr, it would have had to prove that the ancestors of
437 // UselessPad, which include LastUselessPad, had no information, and that
438 // in turn would have required proving that the descendants of
439 // LastUselesPad, which include EHPad, have no information about
440 // LastUselessPad, which would imply that EHPad was mapped to nullptr in
441 // the MemoMap on that invocation, which isn't the case if we got here.
442 assert(!MemoMap.count(UselessPad) || TempMemos.count(UselessPad));
443 // Assert as we enumerate users that 'UselessPad' doesn't have any unwind
444 // information that we'd be contradicting by making a map entry for it
445 // (which is something that getUnwindDestTokenHelper must have proved for
446 // us to get here). Just assert on is direct users here; the checks in
447 // this downward walk at its descendants will verify that they don't have
448 // any unwind edges that exit 'UselessPad' either (i.e. they either have no
449 // unwind edges or unwind to a sibling).
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000450 MemoMap[UselessPad] = UnwindDestToken;
451 if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(UselessPad)) {
Joseph Tremoulete92e0a92016-09-04 01:23:20 +0000452 assert(CatchSwitch->getUnwindDest() == nullptr && "Expected useless pad");
453 for (BasicBlock *HandlerBlock : CatchSwitch->handlers()) {
454 auto *CatchPad = HandlerBlock->getFirstNonPHI();
455 for (User *U : CatchPad->users()) {
456 assert(
457 (!isa<InvokeInst>(U) ||
458 (getParentPad(
459 cast<InvokeInst>(U)->getUnwindDest()->getFirstNonPHI()) ==
460 CatchPad)) &&
461 "Expected useless pad");
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000462 if (isa<CatchSwitchInst>(U) || isa<CleanupPadInst>(U))
463 Worklist.push_back(cast<Instruction>(U));
Joseph Tremoulete92e0a92016-09-04 01:23:20 +0000464 }
465 }
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000466 } else {
467 assert(isa<CleanupPadInst>(UselessPad));
Joseph Tremoulete92e0a92016-09-04 01:23:20 +0000468 for (User *U : UselessPad->users()) {
469 assert(!isa<CleanupReturnInst>(U) && "Expected useless pad");
470 assert((!isa<InvokeInst>(U) ||
471 (getParentPad(
472 cast<InvokeInst>(U)->getUnwindDest()->getFirstNonPHI()) ==
473 UselessPad)) &&
474 "Expected useless pad");
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000475 if (isa<CatchSwitchInst>(U) || isa<CleanupPadInst>(U))
476 Worklist.push_back(cast<Instruction>(U));
Joseph Tremoulete92e0a92016-09-04 01:23:20 +0000477 }
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000478 }
479 }
480
481 return UnwindDestToken;
482}
483
Sanjay Patel0fdb4372015-03-10 19:42:57 +0000484/// When we inline a basic block into an invoke,
485/// we have to turn all of the calls that can throw into invokes.
486/// This function analyze BB to see if there are any calls, and if so,
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000487/// it rewrites them to be invokes that jump to InvokeDest and fills in the PHI
Chris Lattner8900f3e2009-09-01 18:44:06 +0000488/// nodes in that block with the values specified in InvokeDestPHIValues.
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000489static BasicBlock *HandleCallsInBlockInlinedThroughInvoke(
490 BasicBlock *BB, BasicBlock *UnwindEdge,
491 UnwindDestMemoTy *FuncletUnwindMap = nullptr) {
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000492 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000493 Instruction *I = &*BBI++;
Bill Wendling55421f02011-08-14 08:01:36 +0000494
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000495 // We only need to check for function calls: inlined invoke
496 // instructions require no special handling.
497 CallInst *CI = dyn_cast<CallInst>(I);
John McCallbd04b742011-05-27 18:34:38 +0000498
Manman Ren87a2adc2013-10-31 21:56:03 +0000499 if (!CI || CI->doesNotThrow() || isa<InlineAsm>(CI->getCalledValue()))
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000500 continue;
Bill Wendling518a2052012-01-31 01:05:20 +0000501
Sanjoy Dasb51325d2016-03-11 19:08:34 +0000502 // We do not need to (and in fact, cannot) convert possibly throwing calls
Sanjoy Das021de052016-03-31 00:18:46 +0000503 // to @llvm.experimental_deoptimize (resp. @llvm.experimental.guard) into
504 // invokes. The caller's "segment" of the deoptimization continuation
505 // attached to the newly inlined @llvm.experimental_deoptimize
506 // (resp. @llvm.experimental.guard) call should contain the exception
507 // handling logic, if any.
Sanjoy Dasb51325d2016-03-11 19:08:34 +0000508 if (auto *F = CI->getCalledFunction())
Sanjoy Das021de052016-03-31 00:18:46 +0000509 if (F->getIntrinsicID() == Intrinsic::experimental_deoptimize ||
510 F->getIntrinsicID() == Intrinsic::experimental_guard)
Sanjoy Dasb51325d2016-03-11 19:08:34 +0000511 continue;
512
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000513 if (auto FuncletBundle = CI->getOperandBundle(LLVMContext::OB_funclet)) {
514 // This call is nested inside a funclet. If that funclet has an unwind
515 // destination within the inlinee, then unwinding out of this call would
516 // be UB. Rewriting this call to an invoke which targets the inlined
517 // invoke's unwind dest would give the call's parent funclet multiple
518 // unwind destinations, which is something that subsequent EH table
519 // generation can't handle and that the veirifer rejects. So when we
520 // see such a call, leave it as a call.
521 auto *FuncletPad = cast<Instruction>(FuncletBundle->Inputs[0]);
522 Value *UnwindDestToken =
523 getUnwindDestToken(FuncletPad, *FuncletUnwindMap);
524 if (UnwindDestToken && !isa<ConstantTokenNone>(UnwindDestToken))
525 continue;
526#ifndef NDEBUG
527 Instruction *MemoKey;
528 if (auto *CatchPad = dyn_cast<CatchPadInst>(FuncletPad))
529 MemoKey = CatchPad->getCatchSwitch();
530 else
531 MemoKey = FuncletPad;
532 assert(FuncletUnwindMap->count(MemoKey) &&
533 (*FuncletUnwindMap)[MemoKey] == UnwindDestToken &&
534 "must get memoized to avoid confusing later searches");
535#endif // NDEBUG
536 }
537
Kuba Breckaddfdba32016-11-14 21:41:13 +0000538 changeToInvokeAndSplitBasicBlock(CI, UnwindEdge);
David Majnemer654e1302015-07-31 17:58:14 +0000539 return BB;
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000540 }
David Majnemer654e1302015-07-31 17:58:14 +0000541 return nullptr;
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000542}
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000543
Sanjay Patel0fdb4372015-03-10 19:42:57 +0000544/// If we inlined an invoke site, we need to convert calls
Bill Wendling0aef16a2012-02-06 21:44:22 +0000545/// in the body of the inlined function into invokes.
Chris Lattner908d7952006-01-13 19:05:59 +0000546///
Nick Lewycky12a130b2009-02-03 04:34:40 +0000547/// II is the invoke instruction being inlined. FirstNewBlock is the first
Chris Lattner908d7952006-01-13 19:05:59 +0000548/// block of the inlined code (the last block is the end of the function),
549/// and InlineCodeInfo is information about the code that got inlined.
David Majnemer654e1302015-07-31 17:58:14 +0000550static void HandleInlinedLandingPad(InvokeInst *II, BasicBlock *FirstNewBlock,
551 ClonedCodeInfo &InlinedCodeInfo) {
Chris Lattner908d7952006-01-13 19:05:59 +0000552 BasicBlock *InvokeDest = II->getUnwindDest();
Chris Lattner908d7952006-01-13 19:05:59 +0000553
554 Function *Caller = FirstNewBlock->getParent();
Duncan Sands7c8fb1a2008-09-05 12:37:12 +0000555
Chris Lattner908d7952006-01-13 19:05:59 +0000556 // The inlined code is currently at the end of the function, scan from the
557 // start of the inlined code to its end, checking for stuff we need to
Bill Wendling173c71f2013-03-21 23:30:12 +0000558 // rewrite.
David Majnemer654e1302015-07-31 17:58:14 +0000559 LandingPadInliningInfo Invoke(II);
Bill Wendling173c71f2013-03-21 23:30:12 +0000560
Bill Wendling56f15bf2013-03-22 20:31:05 +0000561 // Get all of the inlined landing pad instructions.
562 SmallPtrSet<LandingPadInst*, 16> InlinedLPads;
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000563 for (Function::iterator I = FirstNewBlock->getIterator(), E = Caller->end();
564 I != E; ++I)
Bill Wendling56f15bf2013-03-22 20:31:05 +0000565 if (InvokeInst *II = dyn_cast<InvokeInst>(I->getTerminator()))
566 InlinedLPads.insert(II->getLandingPadInst());
567
Mark Seabornef3dbb92013-12-08 00:50:58 +0000568 // Append the clauses from the outer landing pad instruction into the inlined
569 // landing pad instructions.
570 LandingPadInst *OuterLPad = Invoke.getLandingPadInst();
Craig Topper46276792014-08-24 23:23:06 +0000571 for (LandingPadInst *InlinedLPad : InlinedLPads) {
Mark Seabornef3dbb92013-12-08 00:50:58 +0000572 unsigned OuterNum = OuterLPad->getNumClauses();
573 InlinedLPad->reserveClauses(OuterNum);
574 for (unsigned OuterIdx = 0; OuterIdx != OuterNum; ++OuterIdx)
575 InlinedLPad->addClause(OuterLPad->getClause(OuterIdx));
Mark Seaborn1b3dd352013-12-08 00:51:21 +0000576 if (OuterLPad->isCleanup())
577 InlinedLPad->setCleanup(true);
Mark Seabornef3dbb92013-12-08 00:50:58 +0000578 }
579
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000580 for (Function::iterator BB = FirstNewBlock->getIterator(), E = Caller->end();
581 BB != E; ++BB) {
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000582 if (InlinedCodeInfo.ContainsCalls)
David Majnemer654e1302015-07-31 17:58:14 +0000583 if (BasicBlock *NewBB = HandleCallsInBlockInlinedThroughInvoke(
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000584 &*BB, Invoke.getOuterResumeDest()))
David Majnemer654e1302015-07-31 17:58:14 +0000585 // Update any PHI nodes in the exceptional block to indicate that there
586 // is now a new entry in them.
587 Invoke.addIncomingPHIValuesFor(NewBB);
Duncan Sands7c8fb1a2008-09-05 12:37:12 +0000588
Bill Wendling173c71f2013-03-21 23:30:12 +0000589 // Forward any resumes that are remaining here.
Bill Wendling621699d2012-01-31 01:14:49 +0000590 if (ResumeInst *RI = dyn_cast<ResumeInst>(BB->getTerminator()))
Bill Wendling56f15bf2013-03-22 20:31:05 +0000591 Invoke.forwardResume(RI, InlinedLPads);
Chris Lattner908d7952006-01-13 19:05:59 +0000592 }
593
594 // Now that everything is happy, we have one final detail. The PHI nodes in
595 // the exception destination block still have entries due to the original
Bill Wendling173c71f2013-03-21 23:30:12 +0000596 // invoke instruction. Eliminate these entries (which might even delete the
Chris Lattner908d7952006-01-13 19:05:59 +0000597 // PHI node) now.
598 InvokeDest->removePredecessor(II->getParent());
599}
600
David Majnemer654e1302015-07-31 17:58:14 +0000601/// If we inlined an invoke site, we need to convert calls
602/// in the body of the inlined function into invokes.
603///
604/// II is the invoke instruction being inlined. FirstNewBlock is the first
605/// block of the inlined code (the last block is the end of the function),
606/// and InlineCodeInfo is information about the code that got inlined.
607static void HandleInlinedEHPad(InvokeInst *II, BasicBlock *FirstNewBlock,
608 ClonedCodeInfo &InlinedCodeInfo) {
609 BasicBlock *UnwindDest = II->getUnwindDest();
610 Function *Caller = FirstNewBlock->getParent();
611
612 assert(UnwindDest->getFirstNonPHI()->isEHPad() && "unexpected BasicBlock!");
613
614 // If there are PHI nodes in the unwind destination block, we need to keep
615 // track of which values came into them from the invoke before removing the
616 // edge from this block.
617 SmallVector<Value *, 8> UnwindDestPHIValues;
618 llvm::BasicBlock *InvokeBB = II->getParent();
619 for (Instruction &I : *UnwindDest) {
620 // Save the value to use for this edge.
621 PHINode *PHI = dyn_cast<PHINode>(&I);
622 if (!PHI)
623 break;
624 UnwindDestPHIValues.push_back(PHI->getIncomingValueForBlock(InvokeBB));
625 }
626
627 // Add incoming-PHI values to the unwind destination block for the given basic
628 // block, using the values for the original invoke's source block.
629 auto UpdatePHINodes = [&](BasicBlock *Src) {
630 BasicBlock::iterator I = UnwindDest->begin();
631 for (Value *V : UnwindDestPHIValues) {
632 PHINode *PHI = cast<PHINode>(I);
633 PHI->addIncoming(V, Src);
634 ++I;
635 }
636 };
637
David Majnemer8a1c45d2015-12-12 05:38:55 +0000638 // This connects all the instructions which 'unwind to caller' to the invoke
639 // destination.
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000640 UnwindDestMemoTy FuncletUnwindMap;
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000641 for (Function::iterator BB = FirstNewBlock->getIterator(), E = Caller->end();
642 BB != E; ++BB) {
David Majnemer654e1302015-07-31 17:58:14 +0000643 if (auto *CRI = dyn_cast<CleanupReturnInst>(BB->getTerminator())) {
644 if (CRI->unwindsToCaller()) {
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000645 auto *CleanupPad = CRI->getCleanupPad();
646 CleanupReturnInst::Create(CleanupPad, UnwindDest, CRI);
David Majnemer654e1302015-07-31 17:58:14 +0000647 CRI->eraseFromParent();
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000648 UpdatePHINodes(&*BB);
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000649 // Finding a cleanupret with an unwind destination would confuse
650 // subsequent calls to getUnwindDestToken, so map the cleanuppad
651 // to short-circuit any such calls and recognize this as an "unwind
652 // to caller" cleanup.
653 assert(!FuncletUnwindMap.count(CleanupPad) ||
654 isa<ConstantTokenNone>(FuncletUnwindMap[CleanupPad]));
655 FuncletUnwindMap[CleanupPad] =
656 ConstantTokenNone::get(Caller->getContext());
David Majnemer654e1302015-07-31 17:58:14 +0000657 }
658 }
David Majnemer8a1c45d2015-12-12 05:38:55 +0000659
660 Instruction *I = BB->getFirstNonPHI();
661 if (!I->isEHPad())
662 continue;
663
664 Instruction *Replacement = nullptr;
David Majnemerbbfc7212015-12-14 18:34:23 +0000665 if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(I)) {
David Majnemer8a1c45d2015-12-12 05:38:55 +0000666 if (CatchSwitch->unwindsToCaller()) {
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000667 Value *UnwindDestToken;
668 if (auto *ParentPad =
669 dyn_cast<Instruction>(CatchSwitch->getParentPad())) {
670 // This catchswitch is nested inside another funclet. If that
671 // funclet has an unwind destination within the inlinee, then
672 // unwinding out of this catchswitch would be UB. Rewriting this
673 // catchswitch to unwind to the inlined invoke's unwind dest would
674 // give the parent funclet multiple unwind destinations, which is
675 // something that subsequent EH table generation can't handle and
676 // that the veirifer rejects. So when we see such a call, leave it
677 // as "unwind to caller".
678 UnwindDestToken = getUnwindDestToken(ParentPad, FuncletUnwindMap);
679 if (UnwindDestToken && !isa<ConstantTokenNone>(UnwindDestToken))
680 continue;
681 } else {
682 // This catchswitch has no parent to inherit constraints from, and
683 // none of its descendants can have an unwind edge that exits it and
684 // targets another funclet in the inlinee. It may or may not have a
685 // descendant that definitively has an unwind to caller. In either
686 // case, we'll have to assume that any unwinds out of it may need to
687 // be routed to the caller, so treat it as though it has a definitive
688 // unwind to caller.
689 UnwindDestToken = ConstantTokenNone::get(Caller->getContext());
690 }
David Majnemer8a1c45d2015-12-12 05:38:55 +0000691 auto *NewCatchSwitch = CatchSwitchInst::Create(
692 CatchSwitch->getParentPad(), UnwindDest,
693 CatchSwitch->getNumHandlers(), CatchSwitch->getName(),
694 CatchSwitch);
695 for (BasicBlock *PadBB : CatchSwitch->handlers())
696 NewCatchSwitch->addHandler(PadBB);
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000697 // Propagate info for the old catchswitch over to the new one in
698 // the unwind map. This also serves to short-circuit any subsequent
699 // checks for the unwind dest of this catchswitch, which would get
700 // confused if they found the outer handler in the callee.
701 FuncletUnwindMap[NewCatchSwitch] = UnwindDestToken;
David Majnemer8a1c45d2015-12-12 05:38:55 +0000702 Replacement = NewCatchSwitch;
703 }
704 } else if (!isa<FuncletPadInst>(I)) {
705 llvm_unreachable("unexpected EHPad!");
706 }
707
708 if (Replacement) {
709 Replacement->takeName(I);
710 I->replaceAllUsesWith(Replacement);
711 I->eraseFromParent();
712 UpdatePHINodes(&*BB);
713 }
David Majnemer654e1302015-07-31 17:58:14 +0000714 }
715
716 if (InlinedCodeInfo.ContainsCalls)
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000717 for (Function::iterator BB = FirstNewBlock->getIterator(),
718 E = Caller->end();
719 BB != E; ++BB)
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000720 if (BasicBlock *NewBB = HandleCallsInBlockInlinedThroughInvoke(
721 &*BB, UnwindDest, &FuncletUnwindMap))
David Majnemer654e1302015-07-31 17:58:14 +0000722 // Update any PHI nodes in the exceptional block to indicate that there
723 // is now a new entry in them.
724 UpdatePHINodes(NewBB);
725
726 // Now that everything is happy, we have one final detail. The PHI nodes in
727 // the exception destination block still have entries due to the original
728 // invoke instruction. Eliminate these entries (which might even delete the
729 // PHI node) now.
730 UnwindDest->removePredecessor(InvokeBB);
731}
732
Hal Finkel50316d92016-04-28 23:00:04 +0000733/// When inlining a call site that has !llvm.mem.parallel_loop_access metadata,
734/// that metadata should be propagated to all memory-accessing cloned
735/// instructions.
736static void PropagateParallelLoopAccessMetadata(CallSite CS,
737 ValueToValueMapTy &VMap) {
738 MDNode *M =
739 CS.getInstruction()->getMetadata(LLVMContext::MD_mem_parallel_loop_access);
740 if (!M)
741 return;
742
743 for (ValueToValueMapTy::iterator VMI = VMap.begin(), VMIE = VMap.end();
744 VMI != VMIE; ++VMI) {
745 if (!VMI->second)
746 continue;
747
748 Instruction *NI = dyn_cast<Instruction>(VMI->second);
749 if (!NI)
750 continue;
751
752 if (MDNode *PM = NI->getMetadata(LLVMContext::MD_mem_parallel_loop_access)) {
753 M = MDNode::concatenate(PM, M);
754 NI->setMetadata(LLVMContext::MD_mem_parallel_loop_access, M);
755 } else if (NI->mayReadOrWriteMemory()) {
756 NI->setMetadata(LLVMContext::MD_mem_parallel_loop_access, M);
757 }
758 }
759}
760
Sanjay Patel0fdb4372015-03-10 19:42:57 +0000761/// When inlining a function that contains noalias scope metadata,
762/// this metadata needs to be cloned so that the inlined blocks
Sanjay Patel65d533c2017-01-02 19:05:11 +0000763/// have different "unique scopes" at every call site. Were this not done, then
Hal Finkel94146652014-07-24 14:25:39 +0000764/// aliasing scopes from a function inlined into a caller multiple times could
765/// not be differentiated (and this would lead to miscompiles because the
766/// non-aliasing property communicated by the metadata could have
767/// call-site-specific control dependencies).
768static void CloneAliasScopeMetadata(CallSite CS, ValueToValueMapTy &VMap) {
769 const Function *CalledFunc = CS.getCalledFunction();
770 SetVector<const MDNode *> MD;
771
772 // Note: We could only clone the metadata if it is already used in the
773 // caller. I'm omitting that check here because it might confuse
774 // inter-procedural alias analysis passes. We can revisit this if it becomes
775 // an efficiency or overhead problem.
776
Benjamin Kramer135f7352016-06-26 12:28:59 +0000777 for (const BasicBlock &I : *CalledFunc)
778 for (const Instruction &J : I) {
779 if (const MDNode *M = J.getMetadata(LLVMContext::MD_alias_scope))
Hal Finkel94146652014-07-24 14:25:39 +0000780 MD.insert(M);
Benjamin Kramer135f7352016-06-26 12:28:59 +0000781 if (const MDNode *M = J.getMetadata(LLVMContext::MD_noalias))
Hal Finkel94146652014-07-24 14:25:39 +0000782 MD.insert(M);
783 }
784
785 if (MD.empty())
786 return;
787
788 // Walk the existing metadata, adding the complete (perhaps cyclic) chain to
789 // the set.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000790 SmallVector<const Metadata *, 16> Queue(MD.begin(), MD.end());
Hal Finkel94146652014-07-24 14:25:39 +0000791 while (!Queue.empty()) {
792 const MDNode *M = cast<MDNode>(Queue.pop_back_val());
793 for (unsigned i = 0, ie = M->getNumOperands(); i != ie; ++i)
794 if (const MDNode *M1 = dyn_cast<MDNode>(M->getOperand(i)))
795 if (MD.insert(M1))
796 Queue.push_back(M1);
797 }
798
799 // Now we have a complete set of all metadata in the chains used to specify
800 // the noalias scopes and the lists of those scopes.
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000801 SmallVector<TempMDTuple, 16> DummyNodes;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000802 DenseMap<const MDNode *, TrackingMDNodeRef> MDMap;
Benjamin Kramer135f7352016-06-26 12:28:59 +0000803 for (const MDNode *I : MD) {
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000804 DummyNodes.push_back(MDTuple::getTemporary(CalledFunc->getContext(), None));
Benjamin Kramer135f7352016-06-26 12:28:59 +0000805 MDMap[I].reset(DummyNodes.back().get());
Hal Finkel94146652014-07-24 14:25:39 +0000806 }
807
808 // Create new metadata nodes to replace the dummy nodes, replacing old
809 // metadata references with either a dummy node or an already-created new
810 // node.
Benjamin Kramer135f7352016-06-26 12:28:59 +0000811 for (const MDNode *I : MD) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000812 SmallVector<Metadata *, 4> NewOps;
Benjamin Kramer135f7352016-06-26 12:28:59 +0000813 for (unsigned i = 0, ie = I->getNumOperands(); i != ie; ++i) {
814 const Metadata *V = I->getOperand(i);
Hal Finkel94146652014-07-24 14:25:39 +0000815 if (const MDNode *M = dyn_cast<MDNode>(V))
816 NewOps.push_back(MDMap[M]);
817 else
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000818 NewOps.push_back(const_cast<Metadata *>(V));
Hal Finkel94146652014-07-24 14:25:39 +0000819 }
820
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000821 MDNode *NewM = MDNode::get(CalledFunc->getContext(), NewOps);
Benjamin Kramer135f7352016-06-26 12:28:59 +0000822 MDTuple *TempM = cast<MDTuple>(MDMap[I]);
Duncan P. N. Exon Smith946fdcc2015-01-19 20:36:39 +0000823 assert(TempM->isTemporary() && "Expected temporary node");
Hal Finkel94146652014-07-24 14:25:39 +0000824
825 TempM->replaceAllUsesWith(NewM);
826 }
827
828 // Now replace the metadata in the new inlined instructions with the
829 // repacements from the map.
830 for (ValueToValueMapTy::iterator VMI = VMap.begin(), VMIE = VMap.end();
831 VMI != VMIE; ++VMI) {
832 if (!VMI->second)
833 continue;
834
835 Instruction *NI = dyn_cast<Instruction>(VMI->second);
836 if (!NI)
837 continue;
838
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000839 if (MDNode *M = NI->getMetadata(LLVMContext::MD_alias_scope)) {
Hal Finkel61c38612014-08-14 21:09:37 +0000840 MDNode *NewMD = MDMap[M];
841 // If the call site also had alias scope metadata (a list of scopes to
842 // which instructions inside it might belong), propagate those scopes to
843 // the inlined instructions.
844 if (MDNode *CSM =
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000845 CS.getInstruction()->getMetadata(LLVMContext::MD_alias_scope))
Hal Finkel61c38612014-08-14 21:09:37 +0000846 NewMD = MDNode::concatenate(NewMD, CSM);
847 NI->setMetadata(LLVMContext::MD_alias_scope, NewMD);
848 } else if (NI->mayReadOrWriteMemory()) {
849 if (MDNode *M =
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000850 CS.getInstruction()->getMetadata(LLVMContext::MD_alias_scope))
Hal Finkel61c38612014-08-14 21:09:37 +0000851 NI->setMetadata(LLVMContext::MD_alias_scope, M);
852 }
Hal Finkel94146652014-07-24 14:25:39 +0000853
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000854 if (MDNode *M = NI->getMetadata(LLVMContext::MD_noalias)) {
Hal Finkel61c38612014-08-14 21:09:37 +0000855 MDNode *NewMD = MDMap[M];
856 // If the call site also had noalias metadata (a list of scopes with
857 // which instructions inside it don't alias), propagate those scopes to
858 // the inlined instructions.
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000859 if (MDNode *CSM =
860 CS.getInstruction()->getMetadata(LLVMContext::MD_noalias))
Hal Finkel61c38612014-08-14 21:09:37 +0000861 NewMD = MDNode::concatenate(NewMD, CSM);
862 NI->setMetadata(LLVMContext::MD_noalias, NewMD);
863 } else if (NI->mayReadOrWriteMemory()) {
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000864 if (MDNode *M = CS.getInstruction()->getMetadata(LLVMContext::MD_noalias))
Hal Finkel61c38612014-08-14 21:09:37 +0000865 NI->setMetadata(LLVMContext::MD_noalias, M);
866 }
Hal Finkel94146652014-07-24 14:25:39 +0000867 }
Hal Finkel94146652014-07-24 14:25:39 +0000868}
869
Sanjay Patel0fdb4372015-03-10 19:42:57 +0000870/// If the inlined function has noalias arguments,
871/// then add new alias scopes for each noalias argument, tag the mapped noalias
Hal Finkelff0bcb62014-07-25 15:50:08 +0000872/// parameters with noalias metadata specifying the new scope, and tag all
873/// non-derived loads, stores and memory intrinsics with the new alias scopes.
874static void AddAliasScopeMetadata(CallSite CS, ValueToValueMapTy &VMap,
Chandler Carruth7b560d42015-09-09 17:55:00 +0000875 const DataLayout &DL, AAResults *CalleeAAR) {
Hal Finkelff0bcb62014-07-25 15:50:08 +0000876 if (!EnableNoAliasConversion)
877 return;
878
879 const Function *CalledFunc = CS.getCalledFunction();
880 SmallVector<const Argument *, 4> NoAliasArgs;
881
Sanjay Patel42c73552016-01-13 22:16:48 +0000882 for (const Argument &Arg : CalledFunc->args())
883 if (Arg.hasNoAliasAttr() && !Arg.use_empty())
884 NoAliasArgs.push_back(&Arg);
Hal Finkelff0bcb62014-07-25 15:50:08 +0000885
886 if (NoAliasArgs.empty())
887 return;
888
889 // To do a good job, if a noalias variable is captured, we need to know if
890 // the capture point dominates the particular use we're considering.
891 DominatorTree DT;
892 DT.recalculate(const_cast<Function&>(*CalledFunc));
893
894 // noalias indicates that pointer values based on the argument do not alias
895 // pointer values which are not based on it. So we add a new "scope" for each
896 // noalias function argument. Accesses using pointers based on that argument
897 // become part of that alias scope, accesses using pointers not based on that
898 // argument are tagged as noalias with that scope.
899
900 DenseMap<const Argument *, MDNode *> NewScopes;
901 MDBuilder MDB(CalledFunc->getContext());
902
903 // Create a new scope domain for this function.
904 MDNode *NewDomain =
905 MDB.createAnonymousAliasScopeDomain(CalledFunc->getName());
906 for (unsigned i = 0, e = NoAliasArgs.size(); i != e; ++i) {
907 const Argument *A = NoAliasArgs[i];
908
909 std::string Name = CalledFunc->getName();
910 if (A->hasName()) {
911 Name += ": %";
912 Name += A->getName();
913 } else {
914 Name += ": argument ";
915 Name += utostr(i);
916 }
917
918 // Note: We always create a new anonymous root here. This is true regardless
919 // of the linkage of the callee because the aliasing "scope" is not just a
920 // property of the callee, but also all control dependencies in the caller.
921 MDNode *NewScope = MDB.createAnonymousAliasScope(NewDomain, Name);
922 NewScopes.insert(std::make_pair(A, NewScope));
923 }
924
925 // Iterate over all new instructions in the map; for all memory-access
926 // instructions, add the alias scope metadata.
927 for (ValueToValueMapTy::iterator VMI = VMap.begin(), VMIE = VMap.end();
928 VMI != VMIE; ++VMI) {
929 if (const Instruction *I = dyn_cast<Instruction>(VMI->first)) {
930 if (!VMI->second)
931 continue;
932
933 Instruction *NI = dyn_cast<Instruction>(VMI->second);
934 if (!NI)
935 continue;
936
Hal Finkel0c083022014-09-01 09:01:39 +0000937 bool IsArgMemOnlyCall = false, IsFuncCall = false;
Hal Finkelff0bcb62014-07-25 15:50:08 +0000938 SmallVector<const Value *, 2> PtrArgs;
939
940 if (const LoadInst *LI = dyn_cast<LoadInst>(I))
941 PtrArgs.push_back(LI->getPointerOperand());
942 else if (const StoreInst *SI = dyn_cast<StoreInst>(I))
943 PtrArgs.push_back(SI->getPointerOperand());
944 else if (const VAArgInst *VAAI = dyn_cast<VAArgInst>(I))
945 PtrArgs.push_back(VAAI->getPointerOperand());
946 else if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(I))
947 PtrArgs.push_back(CXI->getPointerOperand());
948 else if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(I))
949 PtrArgs.push_back(RMWI->getPointerOperand());
Hal Finkeld2dee162014-08-14 16:44:03 +0000950 else if (ImmutableCallSite ICS = ImmutableCallSite(I)) {
Hal Finkela3708df2014-08-30 12:48:33 +0000951 // If we know that the call does not access memory, then we'll still
952 // know that about the inlined clone of this call site, and we don't
953 // need to add metadata.
Hal Finkeld2dee162014-08-14 16:44:03 +0000954 if (ICS.doesNotAccessMemory())
955 continue;
956
Hal Finkel0c083022014-09-01 09:01:39 +0000957 IsFuncCall = true;
Chandler Carruth7b560d42015-09-09 17:55:00 +0000958 if (CalleeAAR) {
959 FunctionModRefBehavior MRB = CalleeAAR->getModRefBehavior(ICS);
Chandler Carruth194f59c2015-07-22 23:15:57 +0000960 if (MRB == FMRB_OnlyAccessesArgumentPointees ||
961 MRB == FMRB_OnlyReadsArgumentPointees)
Hal Finkel0c083022014-09-01 09:01:39 +0000962 IsArgMemOnlyCall = true;
963 }
964
Sanjay Patele01dcab2016-01-13 21:39:26 +0000965 for (Value *Arg : ICS.args()) {
Hal Finkela3708df2014-08-30 12:48:33 +0000966 // We need to check the underlying objects of all arguments, not just
967 // the pointer arguments, because we might be passing pointers as
968 // integers, etc.
Hal Finkel0c083022014-09-01 09:01:39 +0000969 // However, if we know that the call only accesses pointer arguments,
Hal Finkeld2dee162014-08-14 16:44:03 +0000970 // then we only need to check the pointer arguments.
Sanjay Patele01dcab2016-01-13 21:39:26 +0000971 if (IsArgMemOnlyCall && !Arg->getType()->isPointerTy())
Hal Finkel0c083022014-09-01 09:01:39 +0000972 continue;
Hal Finkelff0bcb62014-07-25 15:50:08 +0000973
Sanjay Patele01dcab2016-01-13 21:39:26 +0000974 PtrArgs.push_back(Arg);
Hal Finkel0c083022014-09-01 09:01:39 +0000975 }
976 }
Hal Finkelcbb85f22014-09-01 04:26:40 +0000977
Hal Finkelff0bcb62014-07-25 15:50:08 +0000978 // If we found no pointers, then this instruction is not suitable for
979 // pairing with an instruction to receive aliasing metadata.
Hal Finkeld2dee162014-08-14 16:44:03 +0000980 // However, if this is a call, this we might just alias with none of the
981 // noalias arguments.
Hal Finkelcbb85f22014-09-01 04:26:40 +0000982 if (PtrArgs.empty() && !IsFuncCall)
Hal Finkelff0bcb62014-07-25 15:50:08 +0000983 continue;
984
985 // It is possible that there is only one underlying object, but you
986 // need to go through several PHIs to see it, and thus could be
987 // repeated in the Objects list.
988 SmallPtrSet<const Value *, 4> ObjSet;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000989 SmallVector<Metadata *, 4> Scopes, NoAliases;
Hal Finkelff0bcb62014-07-25 15:50:08 +0000990
991 SmallSetVector<const Argument *, 4> NAPtrArgs;
Sanjay Patele01dcab2016-01-13 21:39:26 +0000992 for (const Value *V : PtrArgs) {
Hal Finkelff0bcb62014-07-25 15:50:08 +0000993 SmallVector<Value *, 4> Objects;
Sanjay Patele01dcab2016-01-13 21:39:26 +0000994 GetUnderlyingObjects(const_cast<Value*>(V),
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000995 Objects, DL, /* LI = */ nullptr);
Hal Finkelff0bcb62014-07-25 15:50:08 +0000996
997 for (Value *O : Objects)
998 ObjSet.insert(O);
999 }
1000
Hal Finkel2d3d6da2014-08-29 16:33:41 +00001001 // Figure out if we're derived from anything that is not a noalias
Hal Finkelff0bcb62014-07-25 15:50:08 +00001002 // argument.
Hal Finkela3708df2014-08-30 12:48:33 +00001003 bool CanDeriveViaCapture = false, UsesAliasingPtr = false;
1004 for (const Value *V : ObjSet) {
1005 // Is this value a constant that cannot be derived from any pointer
1006 // value (we need to exclude constant expressions, for example, that
1007 // are formed from arithmetic on global symbols).
1008 bool IsNonPtrConst = isa<ConstantInt>(V) || isa<ConstantFP>(V) ||
1009 isa<ConstantPointerNull>(V) ||
1010 isa<ConstantDataVector>(V) || isa<UndefValue>(V);
Hal Finkelcbb85f22014-09-01 04:26:40 +00001011 if (IsNonPtrConst)
1012 continue;
1013
1014 // If this is anything other than a noalias argument, then we cannot
1015 // completely describe the aliasing properties using alias.scope
1016 // metadata (and, thus, won't add any).
1017 if (const Argument *A = dyn_cast<Argument>(V)) {
1018 if (!A->hasNoAliasAttr())
1019 UsesAliasingPtr = true;
1020 } else {
Hal Finkela3708df2014-08-30 12:48:33 +00001021 UsesAliasingPtr = true;
Hal Finkelff0bcb62014-07-25 15:50:08 +00001022 }
Hal Finkelcbb85f22014-09-01 04:26:40 +00001023
1024 // If this is not some identified function-local object (which cannot
1025 // directly alias a noalias argument), or some other argument (which,
1026 // by definition, also cannot alias a noalias argument), then we could
1027 // alias a noalias argument that has been captured).
1028 if (!isa<Argument>(V) &&
1029 !isIdentifiedFunctionLocal(const_cast<Value*>(V)))
1030 CanDeriveViaCapture = true;
Hal Finkela3708df2014-08-30 12:48:33 +00001031 }
Hal Finkelcbb85f22014-09-01 04:26:40 +00001032
1033 // A function call can always get captured noalias pointers (via other
1034 // parameters, globals, etc.).
1035 if (IsFuncCall && !IsArgMemOnlyCall)
1036 CanDeriveViaCapture = true;
1037
Hal Finkelff0bcb62014-07-25 15:50:08 +00001038 // First, we want to figure out all of the sets with which we definitely
1039 // don't alias. Iterate over all noalias set, and add those for which:
1040 // 1. The noalias argument is not in the set of objects from which we
1041 // definitely derive.
1042 // 2. The noalias argument has not yet been captured.
Hal Finkelcbb85f22014-09-01 04:26:40 +00001043 // An arbitrary function that might load pointers could see captured
1044 // noalias arguments via other noalias arguments or globals, and so we
1045 // must always check for prior capture.
Hal Finkelff0bcb62014-07-25 15:50:08 +00001046 for (const Argument *A : NoAliasArgs) {
1047 if (!ObjSet.count(A) && (!CanDeriveViaCapture ||
Hal Finkela3708df2014-08-30 12:48:33 +00001048 // It might be tempting to skip the
1049 // PointerMayBeCapturedBefore check if
1050 // A->hasNoCaptureAttr() is true, but this is
1051 // incorrect because nocapture only guarantees
1052 // that no copies outlive the function, not
1053 // that the value cannot be locally captured.
Hal Finkelff0bcb62014-07-25 15:50:08 +00001054 !PointerMayBeCapturedBefore(A,
1055 /* ReturnCaptures */ false,
1056 /* StoreCaptures */ false, I, &DT)))
1057 NoAliases.push_back(NewScopes[A]);
1058 }
1059
1060 if (!NoAliases.empty())
Duncan P. N. Exon Smith3872d002014-11-01 00:10:31 +00001061 NI->setMetadata(LLVMContext::MD_noalias,
1062 MDNode::concatenate(
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001063 NI->getMetadata(LLVMContext::MD_noalias),
Duncan P. N. Exon Smith3872d002014-11-01 00:10:31 +00001064 MDNode::get(CalledFunc->getContext(), NoAliases)));
Hal Finkela3708df2014-08-30 12:48:33 +00001065
Hal Finkelff0bcb62014-07-25 15:50:08 +00001066 // Next, we want to figure out all of the sets to which we might belong.
Hal Finkela3708df2014-08-30 12:48:33 +00001067 // We might belong to a set if the noalias argument is in the set of
1068 // underlying objects. If there is some non-noalias argument in our list
1069 // of underlying objects, then we cannot add a scope because the fact
1070 // that some access does not alias with any set of our noalias arguments
1071 // cannot itself guarantee that it does not alias with this access
1072 // (because there is some pointer of unknown origin involved and the
1073 // other access might also depend on this pointer). We also cannot add
1074 // scopes to arbitrary functions unless we know they don't access any
1075 // non-parameter pointer-values.
1076 bool CanAddScopes = !UsesAliasingPtr;
Hal Finkelcbb85f22014-09-01 04:26:40 +00001077 if (CanAddScopes && IsFuncCall)
1078 CanAddScopes = IsArgMemOnlyCall;
Hal Finkelff0bcb62014-07-25 15:50:08 +00001079
Hal Finkela3708df2014-08-30 12:48:33 +00001080 if (CanAddScopes)
1081 for (const Argument *A : NoAliasArgs) {
1082 if (ObjSet.count(A))
1083 Scopes.push_back(NewScopes[A]);
1084 }
1085
Hal Finkelff0bcb62014-07-25 15:50:08 +00001086 if (!Scopes.empty())
Duncan P. N. Exon Smith3872d002014-11-01 00:10:31 +00001087 NI->setMetadata(
1088 LLVMContext::MD_alias_scope,
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001089 MDNode::concatenate(NI->getMetadata(LLVMContext::MD_alias_scope),
Duncan P. N. Exon Smith3872d002014-11-01 00:10:31 +00001090 MDNode::get(CalledFunc->getContext(), Scopes)));
Hal Finkelff0bcb62014-07-25 15:50:08 +00001091 }
1092 }
1093}
1094
Hal Finkel68dc3c72014-10-15 23:44:41 +00001095/// If the inlined function has non-byval align arguments, then
1096/// add @llvm.assume-based alignment assumptions to preserve this information.
1097static void AddAlignmentAssumptions(CallSite CS, InlineFunctionInfo &IFI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001098 if (!PreserveAlignmentAssumptions || !IFI.GetAssumptionCache)
Hal Finkel68dc3c72014-10-15 23:44:41 +00001099 return;
Sanjay Patelaea60842016-12-31 17:54:05 +00001100
1101 AssumptionCache *AC = &(*IFI.GetAssumptionCache)(*CS.getCaller());
Mehdi Amini46a43552015-03-04 18:43:29 +00001102 auto &DL = CS.getCaller()->getParent()->getDataLayout();
Hal Finkel68dc3c72014-10-15 23:44:41 +00001103
1104 // To avoid inserting redundant assumptions, we should check for assumptions
1105 // already in the caller. To do this, we might need a DT of the caller.
1106 DominatorTree DT;
1107 bool DTCalculated = false;
1108
Chandler Carruth66b31302015-01-04 12:03:27 +00001109 Function *CalledFunc = CS.getCalledFunction();
1110 for (Function::arg_iterator I = CalledFunc->arg_begin(),
1111 E = CalledFunc->arg_end();
1112 I != E; ++I) {
Hal Finkel68dc3c72014-10-15 23:44:41 +00001113 unsigned Align = I->getType()->isPointerTy() ? I->getParamAlignment() : 0;
1114 if (Align && !I->hasByValOrInAllocaAttr() && !I->hasNUses(0)) {
1115 if (!DTCalculated) {
1116 DT.recalculate(const_cast<Function&>(*CS.getInstruction()->getParent()
1117 ->getParent()));
1118 DTCalculated = true;
1119 }
1120
1121 // If we can already prove the asserted alignment in the context of the
1122 // caller, then don't bother inserting the assumption.
1123 Value *Arg = CS.getArgument(I->getArgNo());
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001124 if (getKnownAlignment(Arg, DL, CS.getInstruction(), AC, &DT) >= Align)
Hal Finkel68dc3c72014-10-15 23:44:41 +00001125 continue;
1126
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001127 CallInst *NewAssumption = IRBuilder<>(CS.getInstruction())
1128 .CreateAlignmentAssumption(DL, Arg, Align);
Sanjay Patelaea60842016-12-31 17:54:05 +00001129 AC->registerAssumption(NewAssumption);
Hal Finkel68dc3c72014-10-15 23:44:41 +00001130 }
1131 }
1132}
1133
Sanjay Patel0fdb4372015-03-10 19:42:57 +00001134/// Once we have cloned code over from a callee into the caller,
1135/// update the specified callgraph to reflect the changes we made.
1136/// Note that it's possible that not all code was copied over, so only
Duncan Sands46911f12008-09-08 11:05:51 +00001137/// some edges of the callgraph may remain.
1138static void UpdateCallGraphAfterInlining(CallSite CS,
Chris Lattner5de3b8b2006-07-12 18:29:36 +00001139 Function::iterator FirstNewBlock,
Rafael Espindola229e38f2010-10-13 01:36:30 +00001140 ValueToValueMapTy &VMap,
Chris Lattner2eee5d32010-04-22 23:37:35 +00001141 InlineFunctionInfo &IFI) {
1142 CallGraph &CG = *IFI.CG;
Duncan Sands46911f12008-09-08 11:05:51 +00001143 const Function *Caller = CS.getInstruction()->getParent()->getParent();
1144 const Function *Callee = CS.getCalledFunction();
Chris Lattner0841fb12006-01-14 20:07:50 +00001145 CallGraphNode *CalleeNode = CG[Callee];
1146 CallGraphNode *CallerNode = CG[Caller];
Duncan Sands7c8fb1a2008-09-05 12:37:12 +00001147
Chris Lattner5de3b8b2006-07-12 18:29:36 +00001148 // Since we inlined some uninlined call sites in the callee into the caller,
Chris Lattner0841fb12006-01-14 20:07:50 +00001149 // add edges from the caller to all of the callees of the callee.
Gabor Greif5aa19222009-01-15 18:40:09 +00001150 CallGraphNode::iterator I = CalleeNode->begin(), E = CalleeNode->end();
1151
1152 // Consider the case where CalleeNode == CallerNode.
Gabor Greiff1abfdc2009-01-17 00:09:08 +00001153 CallGraphNode::CalledFunctionsVector CallCache;
Gabor Greif5aa19222009-01-15 18:40:09 +00001154 if (CalleeNode == CallerNode) {
1155 CallCache.assign(I, E);
1156 I = CallCache.begin();
1157 E = CallCache.end();
1158 }
1159
1160 for (; I != E; ++I) {
Chris Lattner063d0652009-09-01 06:31:31 +00001161 const Value *OrigCall = I->first;
Duncan Sands7c8fb1a2008-09-05 12:37:12 +00001162
Rafael Espindola229e38f2010-10-13 01:36:30 +00001163 ValueToValueMapTy::iterator VMI = VMap.find(OrigCall);
Chris Lattnerb3c64f72006-07-12 21:37:11 +00001164 // Only copy the edge if the call was inlined!
Craig Topperf40110f2014-04-25 05:29:35 +00001165 if (VMI == VMap.end() || VMI->second == nullptr)
Chris Lattner5eef6ad2009-08-27 03:51:50 +00001166 continue;
1167
1168 // If the call was inlined, but then constant folded, there is no edge to
1169 // add. Check for this case.
Chris Lattner016c00a2010-04-22 21:31:00 +00001170 Instruction *NewCall = dyn_cast<Instruction>(VMI->second);
Sanjay Patelc04b6f22015-03-11 15:12:32 +00001171 if (!NewCall)
1172 continue;
Chris Lattnerc2432b92010-05-01 01:26:13 +00001173
Sanjay Patelc04b6f22015-03-11 15:12:32 +00001174 // We do not treat intrinsic calls like real function calls because we
1175 // expect them to become inline code; do not add an edge for an intrinsic.
1176 CallSite CS = CallSite(NewCall);
1177 if (CS && CS.getCalledFunction() && CS.getCalledFunction()->isIntrinsic())
1178 continue;
1179
Chris Lattnerc2432b92010-05-01 01:26:13 +00001180 // Remember that this call site got inlined for the client of
1181 // InlineFunction.
1182 IFI.InlinedCalls.push_back(NewCall);
1183
Chris Lattner016c00a2010-04-22 21:31:00 +00001184 // It's possible that inlining the callsite will cause it to go from an
1185 // indirect to a direct call by resolving a function pointer. If this
1186 // happens, set the callee of the new call site to a more precise
1187 // destination. This can also happen if the call graph node of the caller
1188 // was just unnecessarily imprecise.
Craig Topperf40110f2014-04-25 05:29:35 +00001189 if (!I->second->getFunction())
Chris Lattner016c00a2010-04-22 21:31:00 +00001190 if (Function *F = CallSite(NewCall).getCalledFunction()) {
1191 // Indirect call site resolved to direct call.
Gabor Greif7b0a5fd2010-07-27 15:02:37 +00001192 CallerNode->addCalledFunction(CallSite(NewCall), CG[F]);
1193
Chris Lattner016c00a2010-04-22 21:31:00 +00001194 continue;
1195 }
Gabor Greif7b0a5fd2010-07-27 15:02:37 +00001196
1197 CallerNode->addCalledFunction(CallSite(NewCall), I->second);
Chris Lattner5de3b8b2006-07-12 18:29:36 +00001198 }
Chris Lattner5eef6ad2009-08-27 03:51:50 +00001199
Dale Johannesen0aeabdf2009-01-13 22:43:37 +00001200 // Update the call graph by deleting the edge from Callee to Caller. We must
1201 // do this after the loop above in case Caller and Callee are the same.
1202 CallerNode->removeCallEdgeFor(CS);
Chris Lattner0841fb12006-01-14 20:07:50 +00001203}
1204
Julien Lerouge957e91c2014-04-15 18:01:54 +00001205static void HandleByValArgumentInit(Value *Dst, Value *Src, Module *M,
1206 BasicBlock *InsertBlock,
1207 InlineFunctionInfo &IFI) {
Julien Lerouge957e91c2014-04-15 18:01:54 +00001208 Type *AggTy = cast<PointerType>(Src->getType())->getElementType();
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001209 IRBuilder<> Builder(InsertBlock, InsertBlock->begin());
Julien Lerouge957e91c2014-04-15 18:01:54 +00001210
Mehdi Amini46a43552015-03-04 18:43:29 +00001211 Value *Size = Builder.getInt64(M->getDataLayout().getTypeStoreSize(AggTy));
Julien Lerouge957e91c2014-04-15 18:01:54 +00001212
1213 // Always generate a memcpy of alignment 1 here because we don't know
1214 // the alignment of the src pointer. Other optimizations can infer
1215 // better alignment.
Pete Cooper67cf9a72015-11-19 05:56:52 +00001216 Builder.CreateMemCpy(Dst, Src, Size, /*Align=*/1);
Julien Lerouge957e91c2014-04-15 18:01:54 +00001217}
1218
Sanjay Patel0fdb4372015-03-10 19:42:57 +00001219/// When inlining a call site that has a byval argument,
Chris Lattner0f114952010-12-20 08:10:40 +00001220/// we have to make the implicit memcpy explicit by adding it.
David Majnemer120f4a02013-11-03 12:22:13 +00001221static Value *HandleByValArgument(Value *Arg, Instruction *TheCall,
Chris Lattner00997442010-12-20 07:57:41 +00001222 const Function *CalledFunc,
1223 InlineFunctionInfo &IFI,
Reid Klecknerdd3f3ed2014-11-04 02:02:14 +00001224 unsigned ByValAlignment) {
Matt Arsenaultbe558882014-04-23 20:58:57 +00001225 PointerType *ArgTy = cast<PointerType>(Arg->getType());
1226 Type *AggTy = ArgTy->getElementType();
Chris Lattner0f114952010-12-20 08:10:40 +00001227
Chandler Carruth66b31302015-01-04 12:03:27 +00001228 Function *Caller = TheCall->getParent()->getParent();
1229
Chris Lattner0f114952010-12-20 08:10:40 +00001230 // If the called function is readonly, then it could not mutate the caller's
1231 // copy of the byval'd memory. In this case, it is safe to elide the copy and
1232 // temporary.
David Majnemer120f4a02013-11-03 12:22:13 +00001233 if (CalledFunc->onlyReadsMemory()) {
Chris Lattner0f114952010-12-20 08:10:40 +00001234 // If the byval argument has a specified alignment that is greater than the
1235 // passed in pointer, then we either have to round up the input pointer or
1236 // give up on this transformation.
1237 if (ByValAlignment <= 1) // 0 = unspecified, 1 = no particular alignment.
David Majnemer120f4a02013-11-03 12:22:13 +00001238 return Arg;
Chris Lattner0f114952010-12-20 08:10:40 +00001239
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001240 AssumptionCache *AC =
1241 IFI.GetAssumptionCache ? &(*IFI.GetAssumptionCache)(*Caller) : nullptr;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001242 const DataLayout &DL = Caller->getParent()->getDataLayout();
1243
Chris Lattner20fca482010-12-25 20:42:38 +00001244 // If the pointer is already known to be sufficiently aligned, or if we can
1245 // round it up to a larger alignment, then we don't need a temporary.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001246 if (getOrEnforceKnownAlignment(Arg, ByValAlignment, DL, TheCall, AC) >=
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001247 ByValAlignment)
David Majnemer120f4a02013-11-03 12:22:13 +00001248 return Arg;
Chris Lattner0f114952010-12-20 08:10:40 +00001249
Chris Lattner20fca482010-12-25 20:42:38 +00001250 // Otherwise, we have to make a memcpy to get a safe alignment. This is bad
1251 // for code quality, but rarely happens and is required for correctness.
Chris Lattner0f114952010-12-20 08:10:40 +00001252 }
Chris Lattner00997442010-12-20 07:57:41 +00001253
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001254 // Create the alloca. If we have DataLayout, use nice alignment.
Mehdi Amini46a43552015-03-04 18:43:29 +00001255 unsigned Align =
1256 Caller->getParent()->getDataLayout().getPrefTypeAlignment(AggTy);
1257
Chris Lattner00997442010-12-20 07:57:41 +00001258 // If the byval had an alignment specified, we *must* use at least that
1259 // alignment, as it is required by the byval argument (and uses of the
1260 // pointer inside the callee).
1261 Align = std::max(Align, ByValAlignment);
1262
Craig Topperf40110f2014-04-25 05:29:35 +00001263 Value *NewAlloca = new AllocaInst(AggTy, nullptr, Align, Arg->getName(),
Chris Lattner00997442010-12-20 07:57:41 +00001264 &*Caller->begin()->begin());
Julien Lerougebe4fe322014-04-15 18:06:46 +00001265 IFI.StaticAllocas.push_back(cast<AllocaInst>(NewAlloca));
Chris Lattner00997442010-12-20 07:57:41 +00001266
1267 // Uses of the argument in the function should use our new alloca
1268 // instead.
1269 return NewAlloca;
1270}
1271
Sanjay Patel0fdb4372015-03-10 19:42:57 +00001272// Check whether this Value is used by a lifetime intrinsic.
Nick Lewyckya68ec832011-05-22 05:22:10 +00001273static bool isUsedByLifetimeMarker(Value *V) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001274 for (User *U : V->users()) {
1275 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U)) {
Nick Lewyckya68ec832011-05-22 05:22:10 +00001276 switch (II->getIntrinsicID()) {
1277 default: break;
1278 case Intrinsic::lifetime_start:
1279 case Intrinsic::lifetime_end:
1280 return true;
1281 }
1282 }
1283 }
1284 return false;
1285}
1286
Sanjay Patel0fdb4372015-03-10 19:42:57 +00001287// Check whether the given alloca already has
Nick Lewyckya68ec832011-05-22 05:22:10 +00001288// lifetime.start or lifetime.end intrinsics.
1289static bool hasLifetimeMarkers(AllocaInst *AI) {
Matt Arsenaultbe558882014-04-23 20:58:57 +00001290 Type *Ty = AI->getType();
1291 Type *Int8PtrTy = Type::getInt8PtrTy(Ty->getContext(),
1292 Ty->getPointerAddressSpace());
1293 if (Ty == Int8PtrTy)
Nick Lewyckya68ec832011-05-22 05:22:10 +00001294 return isUsedByLifetimeMarker(AI);
1295
Nick Lewycky9711b5c2011-06-14 00:59:24 +00001296 // Do a scan to find all the casts to i8*.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001297 for (User *U : AI->users()) {
1298 if (U->getType() != Int8PtrTy) continue;
1299 if (U->stripPointerCasts() != AI) continue;
1300 if (isUsedByLifetimeMarker(U))
Nick Lewyckya68ec832011-05-22 05:22:10 +00001301 return true;
1302 }
1303 return false;
1304}
1305
David Blaikiedf706282015-01-21 22:57:29 +00001306/// Rebuild the entire inlined-at chain for this instruction so that the top of
1307/// the chain now is inlined-at the new call site.
1308static DebugLoc
Benjamin Kramerbdc49562016-06-12 15:39:02 +00001309updateInlinedAtInfo(const DebugLoc &DL, DILocation *InlinedAtNode,
1310 LLVMContext &Ctx,
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001311 DenseMap<const DILocation *, DILocation *> &IANodes) {
1312 SmallVector<DILocation *, 3> InlinedAtLocations;
1313 DILocation *Last = InlinedAtNode;
1314 DILocation *CurInlinedAt = DL;
David Blaikiedf706282015-01-21 22:57:29 +00001315
1316 // Gather all the inlined-at nodes
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001317 while (DILocation *IA = CurInlinedAt->getInlinedAt()) {
David Blaikiedf706282015-01-21 22:57:29 +00001318 // Skip any we've already built nodes for
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001319 if (DILocation *Found = IANodes[IA]) {
David Blaikiedf706282015-01-21 22:57:29 +00001320 Last = Found;
1321 break;
1322 }
1323
1324 InlinedAtLocations.push_back(IA);
Duncan P. N. Exon Smithec819c02015-03-30 19:49:49 +00001325 CurInlinedAt = IA;
Devang Patel35797402011-07-08 18:01:31 +00001326 }
Eric Christopherf16bee82012-03-26 19:09:38 +00001327
David Blaikiedf706282015-01-21 22:57:29 +00001328 // Starting from the top, rebuild the nodes to point to the new inlined-at
1329 // location (then rebuilding the rest of the chain behind it) and update the
1330 // map of already-constructed inlined-at nodes.
David Majnemerd7708772016-06-24 04:05:21 +00001331 for (const DILocation *MD : reverse(InlinedAtLocations)) {
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001332 Last = IANodes[MD] = DILocation::getDistinct(
David Blaikiedf706282015-01-21 22:57:29 +00001333 Ctx, MD->getLine(), MD->getColumn(), MD->getScope(), Last);
1334 }
1335
1336 // And finally create the normal location for this instruction, referring to
1337 // the new inlined-at chain.
Duncan P. N. Exon Smithec819c02015-03-30 19:49:49 +00001338 return DebugLoc::get(DL.getLine(), DL.getCol(), DL.getScope(), Last);
Devang Patel35797402011-07-08 18:01:31 +00001339}
1340
Reid Kleckner6ee00a22016-08-12 22:23:04 +00001341/// Return the result of AI->isStaticAlloca() if AI were moved to the entry
1342/// block. Allocas used in inalloca calls and allocas of dynamic array size
1343/// cannot be static.
1344static bool allocaWouldBeStaticInEntry(const AllocaInst *AI ) {
1345 return isa<Constant>(AI->getArraySize()) && !AI->isUsedWithInAlloca();
1346}
1347
Sanjay Patel0fdb4372015-03-10 19:42:57 +00001348/// Update inlined instructions' line numbers to
Devang Patel35797402011-07-08 18:01:31 +00001349/// to encode location where these instructions are inlined.
1350static void fixupLineNumbers(Function *Fn, Function::iterator FI,
Andrea Di Biagio32d5aed2016-12-07 10:37:26 +00001351 Instruction *TheCall, bool CalleeHasDebugInfo) {
Benjamin Kramer4ca41fd2016-06-12 17:30:47 +00001352 const DebugLoc &TheCallDL = TheCall->getDebugLoc();
Duncan P. N. Exon Smithec819c02015-03-30 19:49:49 +00001353 if (!TheCallDL)
Devang Patel35797402011-07-08 18:01:31 +00001354 return;
1355
David Blaikiedf706282015-01-21 22:57:29 +00001356 auto &Ctx = Fn->getContext();
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001357 DILocation *InlinedAtNode = TheCallDL;
David Blaikiedf706282015-01-21 22:57:29 +00001358
1359 // Create a unique call site, not to be confused with any other call from the
1360 // same location.
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001361 InlinedAtNode = DILocation::getDistinct(
David Blaikiedf706282015-01-21 22:57:29 +00001362 Ctx, InlinedAtNode->getLine(), InlinedAtNode->getColumn(),
1363 InlinedAtNode->getScope(), InlinedAtNode->getInlinedAt());
1364
1365 // Cache the inlined-at nodes as they're built so they are reused, without
1366 // this every instruction's inlined-at chain would become distinct from each
1367 // other.
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001368 DenseMap<const DILocation *, DILocation *> IANodes;
David Blaikiedf706282015-01-21 22:57:29 +00001369
Devang Patel35797402011-07-08 18:01:31 +00001370 for (; FI != Fn->end(); ++FI) {
1371 for (BasicBlock::iterator BI = FI->begin(), BE = FI->end();
1372 BI != BE; ++BI) {
Andrea Di Biagioeff22832016-12-07 12:01:45 +00001373 if (DebugLoc DL = BI->getDebugLoc()) {
1374 BI->setDebugLoc(
1375 updateInlinedAtInfo(DL, InlinedAtNode, BI->getContext(), IANodes));
1376 continue;
Devang Patelbb23a4a2011-08-10 21:50:54 +00001377 }
Andrea Di Biagioeff22832016-12-07 12:01:45 +00001378
1379 if (CalleeHasDebugInfo)
1380 continue;
1381
1382 // If the inlined instruction has no line number, make it look as if it
1383 // originates from the call location. This is important for
1384 // ((__always_inline__, __nodebug__)) functions which must use caller
1385 // location for all instructions in their function body.
1386
1387 // Don't update static allocas, as they may get moved later.
1388 if (auto *AI = dyn_cast<AllocaInst>(BI))
1389 if (allocaWouldBeStaticInEntry(AI))
1390 continue;
1391
1392 BI->setDebugLoc(TheCallDL);
Devang Patel35797402011-07-08 18:01:31 +00001393 }
1394 }
1395}
1396
Sanjay Patel0fdb4372015-03-10 19:42:57 +00001397/// This function inlines the called function into the basic block of the
1398/// caller. This returns false if it is not possible to inline this call.
1399/// The program is still in a well defined state if this occurs though.
Bill Wendlingce0c2292012-01-31 01:01:16 +00001400///
1401/// Note that this only does one level of inlining. For example, if the
1402/// instruction 'call B' is inlined, and 'B' calls 'C', then the call to 'C' now
1403/// exists in the instruction stream. Similarly this will inline a recursive
1404/// function by one level.
Eric Christopherf16bee82012-03-26 19:09:38 +00001405bool llvm::InlineFunction(CallSite CS, InlineFunctionInfo &IFI,
Chandler Carruth7b560d42015-09-09 17:55:00 +00001406 AAResults *CalleeAAR, bool InsertLifetime) {
Chris Lattner0cc265e2003-08-24 06:59:16 +00001407 Instruction *TheCall = CS.getInstruction();
1408 assert(TheCall->getParent() && TheCall->getParent()->getParent() &&
1409 "Instruction not in function!");
Chris Lattner530d4bf2003-05-29 15:11:31 +00001410
Chris Lattner4ba01ec2010-04-22 23:07:58 +00001411 // If IFI has any state in it, zap it before we fill it in.
1412 IFI.reset();
Easwaran Ramanb1bd3982016-03-08 00:36:35 +00001413
Chris Lattner0cc265e2003-08-24 06:59:16 +00001414 const Function *CalledFunc = CS.getCalledFunction();
Craig Topperf40110f2014-04-25 05:29:35 +00001415 if (!CalledFunc || // Can't inline external function or indirect
Reid Spencer5301e7c2007-01-30 20:08:39 +00001416 CalledFunc->isDeclaration() || // call, or call to a vararg function!
Eric Christopher1d385382010-03-24 23:35:21 +00001417 CalledFunc->getFunctionType()->isVarArg()) return false;
Chris Lattner530d4bf2003-05-29 15:11:31 +00001418
Sanjoy Das2d161452015-11-18 06:23:38 +00001419 // The inliner does not know how to inline through calls with operand bundles
1420 // in general ...
1421 if (CS.hasOperandBundles()) {
David Majnemer3bb88c02015-12-15 21:27:27 +00001422 for (int i = 0, e = CS.getNumOperandBundles(); i != e; ++i) {
1423 uint32_t Tag = CS.getOperandBundleAt(i).getTagID();
1424 // ... but it knows how to inline through "deopt" operand bundles ...
1425 if (Tag == LLVMContext::OB_deopt)
1426 continue;
1427 // ... and "funclet" operand bundles.
1428 if (Tag == LLVMContext::OB_funclet)
1429 continue;
1430
Sanjoy Das2d161452015-11-18 06:23:38 +00001431 return false;
David Majnemer3bb88c02015-12-15 21:27:27 +00001432 }
Sanjoy Das2d161452015-11-18 06:23:38 +00001433 }
Sanjoy Das0a1bee82015-10-23 20:09:55 +00001434
Duncan Sandsaa31b922007-12-19 21:13:37 +00001435 // If the call to the callee cannot throw, set the 'nounwind' flag on any
1436 // calls that we inline.
1437 bool MarkNoUnwind = CS.doesNotThrow();
1438
Chris Lattner0cc265e2003-08-24 06:59:16 +00001439 BasicBlock *OrigBB = TheCall->getParent();
Chris Lattner530d4bf2003-05-29 15:11:31 +00001440 Function *Caller = OrigBB->getParent();
1441
Gordon Henriksenb969c592007-12-25 03:10:07 +00001442 // GC poses two hazards to inlining, which only occur when the callee has GC:
1443 // 1. If the caller has no GC, then the callee's GC must be propagated to the
1444 // caller.
1445 // 2. If the caller has a differing GC, it is invalid to inline.
Gordon Henriksend930f912008-08-17 18:44:35 +00001446 if (CalledFunc->hasGC()) {
1447 if (!Caller->hasGC())
1448 Caller->setGC(CalledFunc->getGC());
1449 else if (CalledFunc->getGC() != Caller->getGC())
Gordon Henriksenb969c592007-12-25 03:10:07 +00001450 return false;
1451 }
Duncan Sands7c8fb1a2008-09-05 12:37:12 +00001452
Benjamin Kramer4d2b8712011-12-02 18:37:31 +00001453 // Get the personality function from the callee if it contains a landing pad.
David Majnemer7fddecc2015-06-17 20:52:32 +00001454 Constant *CalledPersonality =
David Majnemereba62792015-10-13 22:08:17 +00001455 CalledFunc->hasPersonalityFn()
1456 ? CalledFunc->getPersonalityFn()->stripPointerCasts()
1457 : nullptr;
Benjamin Kramer4d2b8712011-12-02 18:37:31 +00001458
Bill Wendling55421f02011-08-14 08:01:36 +00001459 // Find the personality function used by the landing pads of the caller. If it
1460 // exists, then check to see that it matches the personality function used in
1461 // the callee.
David Majnemer7fddecc2015-06-17 20:52:32 +00001462 Constant *CallerPersonality =
David Majnemereba62792015-10-13 22:08:17 +00001463 Caller->hasPersonalityFn()
1464 ? Caller->getPersonalityFn()->stripPointerCasts()
1465 : nullptr;
David Majnemer7fddecc2015-06-17 20:52:32 +00001466 if (CalledPersonality) {
1467 if (!CallerPersonality)
1468 Caller->setPersonalityFn(CalledPersonality);
1469 // If the personality functions match, then we can perform the
1470 // inlining. Otherwise, we can't inline.
1471 // TODO: This isn't 100% true. Some personality functions are proper
1472 // supersets of others and can be used in place of the other.
1473 else if (CalledPersonality != CallerPersonality)
1474 return false;
Bill Wendlingce0c2292012-01-31 01:01:16 +00001475 }
Bill Wendling55421f02011-08-14 08:01:36 +00001476
David Majnemer8a1c45d2015-12-12 05:38:55 +00001477 // We need to figure out which funclet the callsite was in so that we may
1478 // properly nest the callee.
1479 Instruction *CallSiteEHPad = nullptr;
David Majnemer3bb88c02015-12-15 21:27:27 +00001480 if (CallerPersonality) {
1481 EHPersonality Personality = classifyEHPersonality(CallerPersonality);
David Majnemer8a1c45d2015-12-12 05:38:55 +00001482 if (isFuncletEHPersonality(Personality)) {
David Majnemer3bb88c02015-12-15 21:27:27 +00001483 Optional<OperandBundleUse> ParentFunclet =
1484 CS.getOperandBundle(LLVMContext::OB_funclet);
1485 if (ParentFunclet)
1486 CallSiteEHPad = cast<FuncletPadInst>(ParentFunclet->Inputs.front());
David Majnemer8a1c45d2015-12-12 05:38:55 +00001487
1488 // OK, the inlining site is legal. What about the target function?
1489
1490 if (CallSiteEHPad) {
1491 if (Personality == EHPersonality::MSVC_CXX) {
1492 // The MSVC personality cannot tolerate catches getting inlined into
1493 // cleanup funclets.
1494 if (isa<CleanupPadInst>(CallSiteEHPad)) {
1495 // Ok, the call site is within a cleanuppad. Let's check the callee
1496 // for catchpads.
1497 for (const BasicBlock &CalledBB : *CalledFunc) {
David Majnemer3bb88c02015-12-15 21:27:27 +00001498 if (isa<CatchSwitchInst>(CalledBB.getFirstNonPHI()))
David Majnemer8a1c45d2015-12-12 05:38:55 +00001499 return false;
1500 }
1501 }
1502 } else if (isAsynchronousEHPersonality(Personality)) {
1503 // SEH is even less tolerant, there may not be any sort of exceptional
1504 // funclet in the callee.
1505 for (const BasicBlock &CalledBB : *CalledFunc) {
1506 if (CalledBB.isEHPad())
1507 return false;
1508 }
1509 }
1510 }
1511 }
1512 }
1513
David Majnemer223538f2016-02-23 17:11:04 +00001514 // Determine if we are dealing with a call in an EHPad which does not unwind
1515 // to caller.
1516 bool EHPadForCallUnwindsLocally = false;
1517 if (CallSiteEHPad && CS.isCall()) {
1518 UnwindDestMemoTy FuncletUnwindMap;
1519 Value *CallSiteUnwindDestToken =
1520 getUnwindDestToken(CallSiteEHPad, FuncletUnwindMap);
1521
1522 EHPadForCallUnwindsLocally =
1523 CallSiteUnwindDestToken &&
1524 !isa<ConstantTokenNone>(CallSiteUnwindDestToken);
1525 }
1526
Chris Lattner9fc977e2004-02-04 01:41:09 +00001527 // Get an iterator to the last basic block in the function, which will have
1528 // the new function inlined after it.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001529 Function::iterator LastBlock = --Caller->end();
Chris Lattner9fc977e2004-02-04 01:41:09 +00001530
Chris Lattner18ef3fd2004-02-04 02:51:48 +00001531 // Make sure to capture all of the return instructions from the cloned
Chris Lattner530d4bf2003-05-29 15:11:31 +00001532 // function.
Chris Lattnerd84dbb32009-08-27 04:02:30 +00001533 SmallVector<ReturnInst*, 8> Returns;
Chris Lattner908d7952006-01-13 19:05:59 +00001534 ClonedCodeInfo InlinedFunctionInfo;
Dale Johannesen845e5822009-03-04 02:09:48 +00001535 Function::iterator FirstNewBlock;
Duncan Sandsaa31b922007-12-19 21:13:37 +00001536
Devang Patelb8f11de2010-06-23 23:55:51 +00001537 { // Scope to destroy VMap after cloning.
Rafael Espindola229e38f2010-10-13 01:36:30 +00001538 ValueToValueMapTy VMap;
Julien Lerouge957e91c2014-04-15 18:01:54 +00001539 // Keep a list of pair (dst, src) to emit byval initializations.
1540 SmallVector<std::pair<Value*, Value*>, 4> ByValInit;
Chris Lattnerbe853d72006-05-27 01:28:04 +00001541
Mehdi Amini46a43552015-03-04 18:43:29 +00001542 auto &DL = Caller->getParent()->getDataLayout();
1543
Dan Gohman3ada1e12008-06-20 17:11:32 +00001544 assert(CalledFunc->arg_size() == CS.arg_size() &&
Chris Lattner18ef3fd2004-02-04 02:51:48 +00001545 "No varargs calls can be inlined!");
Duncan Sands7c8fb1a2008-09-05 12:37:12 +00001546
Chris Lattner908117b2008-01-11 06:09:30 +00001547 // Calculate the vector of arguments to pass into the function cloner, which
1548 // matches up the formal to the actual argument values.
Chris Lattner18ef3fd2004-02-04 02:51:48 +00001549 CallSite::arg_iterator AI = CS.arg_begin();
Chris Lattner908117b2008-01-11 06:09:30 +00001550 unsigned ArgNo = 0;
Chris Lattner531f9e92005-03-15 04:54:21 +00001551 for (Function::const_arg_iterator I = CalledFunc->arg_begin(),
Chris Lattner908117b2008-01-11 06:09:30 +00001552 E = CalledFunc->arg_end(); I != E; ++I, ++AI, ++ArgNo) {
1553 Value *ActualArg = *AI;
Duncan Sands7c8fb1a2008-09-05 12:37:12 +00001554
Duncan Sands053c9872008-01-27 18:12:58 +00001555 // When byval arguments actually inlined, we need to make the copy implied
1556 // by them explicit. However, we don't do this if the callee is readonly
1557 // or readnone, because the copy would be unneeded: the callee doesn't
1558 // modify the struct.
Nick Lewycky612d70b2011-11-20 19:09:04 +00001559 if (CS.isByValArgument(ArgNo)) {
David Majnemer120f4a02013-11-03 12:22:13 +00001560 ActualArg = HandleByValArgument(ActualArg, TheCall, CalledFunc, IFI,
Reid Klecknerdd3f3ed2014-11-04 02:02:14 +00001561 CalledFunc->getParamAlignment(ArgNo+1));
Reid Kleckner9b2cc642014-04-21 20:48:47 +00001562 if (ActualArg != *AI)
Julien Lerouge957e91c2014-04-15 18:01:54 +00001563 ByValInit.push_back(std::make_pair(ActualArg, (Value*) *AI));
Chris Lattner908117b2008-01-11 06:09:30 +00001564 }
Duncan Sands7c8fb1a2008-09-05 12:37:12 +00001565
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001566 VMap[&*I] = ActualArg;
Chris Lattner908117b2008-01-11 06:09:30 +00001567 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001568
Hal Finkel68dc3c72014-10-15 23:44:41 +00001569 // Add alignment assumptions if necessary. We do this before the inlined
1570 // instructions are actually cloned into the caller so that we can easily
1571 // check what will be known at the start of the inlined code.
1572 AddAlignmentAssumptions(CS, IFI);
1573
Chris Lattnerbe853d72006-05-27 01:28:04 +00001574 // We want the inliner to prune the code as it copies. We would LOVE to
1575 // have no dead or constant instructions leftover after inlining occurs
1576 // (which can happen, e.g., because an argument was constant), but we'll be
1577 // happy with whatever the cloner can do.
Mehdi Amini46a43552015-03-04 18:43:29 +00001578 CloneAndPruneFunctionInto(Caller, CalledFunc, VMap,
Dan Gohmanca26f792010-08-26 15:41:53 +00001579 /*ModuleLevelChanges=*/false, Returns, ".i",
Easwaran Ramanb1bd3982016-03-08 00:36:35 +00001580 &InlinedFunctionInfo, TheCall);
Duncan Sands7c8fb1a2008-09-05 12:37:12 +00001581
Chris Lattner5de3b8b2006-07-12 18:29:36 +00001582 // Remember the first block that is newly cloned over.
1583 FirstNewBlock = LastBlock; ++FirstNewBlock;
Duncan Sands7c8fb1a2008-09-05 12:37:12 +00001584
Julien Lerouge957e91c2014-04-15 18:01:54 +00001585 // Inject byval arguments initialization.
1586 for (std::pair<Value*, Value*> &Init : ByValInit)
1587 HandleByValArgumentInit(Init.first, Init.second, Caller->getParent(),
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001588 &*FirstNewBlock, IFI);
Julien Lerouge957e91c2014-04-15 18:01:54 +00001589
David Majnemer3bb88c02015-12-15 21:27:27 +00001590 Optional<OperandBundleUse> ParentDeopt =
1591 CS.getOperandBundle(LLVMContext::OB_deopt);
1592 if (ParentDeopt) {
Sanjoy Das2d161452015-11-18 06:23:38 +00001593 SmallVector<OperandBundleDef, 2> OpDefs;
1594
1595 for (auto &VH : InlinedFunctionInfo.OperandBundleCallSites) {
Sanjoy Dasab0626e2015-12-19 22:40:28 +00001596 Instruction *I = dyn_cast_or_null<Instruction>(VH);
1597 if (!I) continue; // instruction was DCE'd or RAUW'ed to undef
Sanjoy Das2d161452015-11-18 06:23:38 +00001598
1599 OpDefs.clear();
1600
1601 CallSite ICS(I);
1602 OpDefs.reserve(ICS.getNumOperandBundles());
1603
1604 for (unsigned i = 0, e = ICS.getNumOperandBundles(); i < e; ++i) {
1605 auto ChildOB = ICS.getOperandBundleAt(i);
1606 if (ChildOB.getTagID() != LLVMContext::OB_deopt) {
1607 // If the inlined call has other operand bundles, let them be
1608 OpDefs.emplace_back(ChildOB);
1609 continue;
1610 }
1611
1612 // It may be useful to separate this logic (of handling operand
1613 // bundles) out to a separate "policy" component if this gets crowded.
1614 // Prepend the parent's deoptimization continuation to the newly
1615 // inlined call's deoptimization continuation.
1616 std::vector<Value *> MergedDeoptArgs;
David Majnemer3bb88c02015-12-15 21:27:27 +00001617 MergedDeoptArgs.reserve(ParentDeopt->Inputs.size() +
Sanjoy Das2d161452015-11-18 06:23:38 +00001618 ChildOB.Inputs.size());
1619
1620 MergedDeoptArgs.insert(MergedDeoptArgs.end(),
David Majnemer3bb88c02015-12-15 21:27:27 +00001621 ParentDeopt->Inputs.begin(),
1622 ParentDeopt->Inputs.end());
Sanjoy Das2d161452015-11-18 06:23:38 +00001623 MergedDeoptArgs.insert(MergedDeoptArgs.end(), ChildOB.Inputs.begin(),
1624 ChildOB.Inputs.end());
1625
Sanjoy Das8da1f952015-12-08 03:50:32 +00001626 OpDefs.emplace_back("deopt", std::move(MergedDeoptArgs));
Sanjoy Das2d161452015-11-18 06:23:38 +00001627 }
1628
1629 Instruction *NewI = nullptr;
1630 if (isa<CallInst>(I))
1631 NewI = CallInst::Create(cast<CallInst>(I), OpDefs, I);
1632 else
1633 NewI = InvokeInst::Create(cast<InvokeInst>(I), OpDefs, I);
1634
1635 // Note: the RAUW does the appropriate fixup in VMap, so we need to do
1636 // this even if the call returns void.
1637 I->replaceAllUsesWith(NewI);
1638
1639 VH = nullptr;
1640 I->eraseFromParent();
1641 }
1642 }
1643
Chris Lattner5de3b8b2006-07-12 18:29:36 +00001644 // Update the callgraph if requested.
Chandler Carruth0ee8bb12016-12-27 01:24:50 +00001645 if (IFI.CG)
Devang Patelb8f11de2010-06-23 23:55:51 +00001646 UpdateCallGraphAfterInlining(CS, FirstNewBlock, VMap, IFI);
Devang Patel35797402011-07-08 18:01:31 +00001647
Andrea Di Biagio32d5aed2016-12-07 10:37:26 +00001648 // For 'nodebug' functions, the associated DISubprogram is always null.
1649 // Conservatively avoid propagating the callsite debug location to
1650 // instructions inlined from a function whose DISubprogram is not null.
1651 fixupLineNumbers(Caller, FirstNewBlock, TheCall,
1652 CalledFunc->getSubprogram() != nullptr);
Hal Finkel94146652014-07-24 14:25:39 +00001653
1654 // Clone existing noalias metadata if necessary.
1655 CloneAliasScopeMetadata(CS, VMap);
Hal Finkelff0bcb62014-07-25 15:50:08 +00001656
1657 // Add noalias metadata if necessary.
Chandler Carruth7b560d42015-09-09 17:55:00 +00001658 AddAliasScopeMetadata(CS, VMap, DL, CalleeAAR);
Hal Finkel74c2f352014-09-07 12:44:26 +00001659
Hal Finkel50316d92016-04-28 23:00:04 +00001660 // Propagate llvm.mem.parallel_loop_access if necessary.
1661 PropagateParallelLoopAccessMetadata(CS, VMap);
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001662
1663 // Register any cloned assumptions.
1664 if (IFI.GetAssumptionCache)
1665 for (BasicBlock &NewBlock :
1666 make_range(FirstNewBlock->getIterator(), Caller->end()))
1667 for (Instruction &I : NewBlock) {
1668 if (auto *II = dyn_cast<IntrinsicInst>(&I))
1669 if (II->getIntrinsicID() == Intrinsic::assume)
1670 (*IFI.GetAssumptionCache)(*Caller).registerAssumption(II);
1671 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001672 }
Duncan Sands7c8fb1a2008-09-05 12:37:12 +00001673
Chris Lattner530d4bf2003-05-29 15:11:31 +00001674 // If there are any alloca instructions in the block that used to be the entry
1675 // block for the callee, move them to the entry block of the caller. First
1676 // calculate which instruction they should be inserted before. We insert the
1677 // instructions at the end of the current alloca list.
Chris Lattner257492c2006-01-13 18:16:48 +00001678 {
Chris Lattner0cc265e2003-08-24 06:59:16 +00001679 BasicBlock::iterator InsertPoint = Caller->begin()->begin();
Chris Lattner18ef3fd2004-02-04 02:51:48 +00001680 for (BasicBlock::iterator I = FirstNewBlock->begin(),
Chris Lattner5eef6ad2009-08-27 03:51:50 +00001681 E = FirstNewBlock->end(); I != E; ) {
1682 AllocaInst *AI = dyn_cast<AllocaInst>(I++);
Craig Topperf40110f2014-04-25 05:29:35 +00001683 if (!AI) continue;
Chris Lattner5eef6ad2009-08-27 03:51:50 +00001684
1685 // If the alloca is now dead, remove it. This often occurs due to code
1686 // specialization.
1687 if (AI->use_empty()) {
1688 AI->eraseFromParent();
1689 continue;
Chris Lattner6ef6d062006-09-13 19:23:57 +00001690 }
Chris Lattner5eef6ad2009-08-27 03:51:50 +00001691
Reid Kleckner6ee00a22016-08-12 22:23:04 +00001692 if (!allocaWouldBeStaticInEntry(AI))
Chris Lattner5eef6ad2009-08-27 03:51:50 +00001693 continue;
1694
Chris Lattnercd3af962010-12-06 07:43:04 +00001695 // Keep track of the static allocas that we inline into the caller.
Chris Lattner4ba01ec2010-04-22 23:07:58 +00001696 IFI.StaticAllocas.push_back(AI);
Chris Lattnerb1cba3f2009-08-27 04:20:52 +00001697
Chris Lattner5eef6ad2009-08-27 03:51:50 +00001698 // Scan for the block of allocas that we can move over, and move them
1699 // all at once.
1700 while (isa<AllocaInst>(I) &&
Reid Kleckner6ee00a22016-08-12 22:23:04 +00001701 allocaWouldBeStaticInEntry(cast<AllocaInst>(I))) {
Chris Lattner4ba01ec2010-04-22 23:07:58 +00001702 IFI.StaticAllocas.push_back(cast<AllocaInst>(I));
Chris Lattner5eef6ad2009-08-27 03:51:50 +00001703 ++I;
Chris Lattnerb1cba3f2009-08-27 04:20:52 +00001704 }
Chris Lattner5eef6ad2009-08-27 03:51:50 +00001705
1706 // Transfer all of the allocas over in a block. Using splice means
1707 // that the instructions aren't removed from the symbol table, then
1708 // reinserted.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001709 Caller->getEntryBlock().getInstList().splice(
1710 InsertPoint, FirstNewBlock->getInstList(), AI->getIterator(), I);
Chris Lattner5eef6ad2009-08-27 03:51:50 +00001711 }
Adrian Prantl4d365252015-01-30 01:55:25 +00001712 // Move any dbg.declares describing the allocas into the entry basic block.
Adrian Prantl3e2659e2015-01-30 19:37:48 +00001713 DIBuilder DIB(*Caller->getParent());
Adrian Prantl133e1022015-01-30 19:42:59 +00001714 for (auto &AI : IFI.StaticAllocas)
1715 replaceDbgDeclareForAlloca(AI, AI, DIB, /*Deref=*/false);
Chris Lattner0cc265e2003-08-24 06:59:16 +00001716 }
Chris Lattner530d4bf2003-05-29 15:11:31 +00001717
Sanjoy Dasb51325d2016-03-11 19:08:34 +00001718 bool InlinedMustTailCalls = false, InlinedDeoptimizeCalls = false;
Reid Klecknerf0915aa2014-05-15 20:11:28 +00001719 if (InlinedFunctionInfo.ContainsCalls) {
Reid Kleckner6af21242014-05-15 20:39:42 +00001720 CallInst::TailCallKind CallSiteTailKind = CallInst::TCK_None;
1721 if (CallInst *CI = dyn_cast<CallInst>(TheCall))
1722 CallSiteTailKind = CI->getTailCallKind();
1723
Reid Klecknerf0915aa2014-05-15 20:11:28 +00001724 for (Function::iterator BB = FirstNewBlock, E = Caller->end(); BB != E;
1725 ++BB) {
1726 for (Instruction &I : *BB) {
1727 CallInst *CI = dyn_cast<CallInst>(&I);
1728 if (!CI)
1729 continue;
1730
Sanjoy Dasb51325d2016-03-11 19:08:34 +00001731 if (Function *F = CI->getCalledFunction())
1732 InlinedDeoptimizeCalls |=
1733 F->getIntrinsicID() == Intrinsic::experimental_deoptimize;
1734
Reid Klecknerf0915aa2014-05-15 20:11:28 +00001735 // We need to reduce the strength of any inlined tail calls. For
1736 // musttail, we have to avoid introducing potential unbounded stack
1737 // growth. For example, if functions 'f' and 'g' are mutually recursive
1738 // with musttail, we can inline 'g' into 'f' so long as we preserve
1739 // musttail on the cloned call to 'f'. If either the inlined call site
1740 // or the cloned call site is *not* musttail, the program already has
1741 // one frame of stack growth, so it's safe to remove musttail. Here is
1742 // a table of example transformations:
1743 //
1744 // f -> musttail g -> musttail f ==> f -> musttail f
1745 // f -> musttail g -> tail f ==> f -> tail f
1746 // f -> g -> musttail f ==> f -> f
1747 // f -> g -> tail f ==> f -> f
1748 CallInst::TailCallKind ChildTCK = CI->getTailCallKind();
1749 ChildTCK = std::min(CallSiteTailKind, ChildTCK);
Reid Klecknerdd3f3ed2014-11-04 02:02:14 +00001750 CI->setTailCallKind(ChildTCK);
Reid Klecknerf0915aa2014-05-15 20:11:28 +00001751 InlinedMustTailCalls |= CI->isMustTailCall();
1752
1753 // Calls inlined through a 'nounwind' call site should be marked
1754 // 'nounwind'.
1755 if (MarkNoUnwind)
1756 CI->setDoesNotThrow();
1757 }
1758 }
1759 }
1760
Nick Lewyckya68ec832011-05-22 05:22:10 +00001761 // Leave lifetime markers for the static alloca's, scoping them to the
1762 // function we just inlined.
Chad Rosier07d37bc2012-02-25 02:56:01 +00001763 if (InsertLifetime && !IFI.StaticAllocas.empty()) {
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001764 IRBuilder<> builder(&FirstNewBlock->front());
Nick Lewyckya68ec832011-05-22 05:22:10 +00001765 for (unsigned ai = 0, ae = IFI.StaticAllocas.size(); ai != ae; ++ai) {
1766 AllocaInst *AI = IFI.StaticAllocas[ai];
Arnold Schwaighoferc9277f42016-09-09 22:40:27 +00001767 // Don't mark swifterror allocas. They can't have bitcast uses.
1768 if (AI->isSwiftError())
1769 continue;
Nick Lewyckya68ec832011-05-22 05:22:10 +00001770
1771 // If the alloca is already scoped to something smaller than the whole
1772 // function then there's no need to add redundant, less accurate markers.
1773 if (hasLifetimeMarkers(AI))
1774 continue;
1775
Alexey Samsonovcfd662f2012-11-13 07:15:32 +00001776 // Try to determine the size of the allocation.
Craig Topperf40110f2014-04-25 05:29:35 +00001777 ConstantInt *AllocaSize = nullptr;
Alexey Samsonovcfd662f2012-11-13 07:15:32 +00001778 if (ConstantInt *AIArraySize =
1779 dyn_cast<ConstantInt>(AI->getArraySize())) {
Mehdi Amini46a43552015-03-04 18:43:29 +00001780 auto &DL = Caller->getParent()->getDataLayout();
1781 Type *AllocaType = AI->getAllocatedType();
1782 uint64_t AllocaTypeSize = DL.getTypeAllocSize(AllocaType);
1783 uint64_t AllocaArraySize = AIArraySize->getLimitedValue();
Akira Hatanaka2cc2b632015-04-20 16:11:05 +00001784
1785 // Don't add markers for zero-sized allocas.
1786 if (AllocaArraySize == 0)
1787 continue;
1788
Mehdi Amini46a43552015-03-04 18:43:29 +00001789 // Check that array size doesn't saturate uint64_t and doesn't
1790 // overflow when it's multiplied by type size.
1791 if (AllocaArraySize != ~0ULL &&
1792 UINT64_MAX / AllocaArraySize >= AllocaTypeSize) {
1793 AllocaSize = ConstantInt::get(Type::getInt64Ty(AI->getContext()),
1794 AllocaArraySize * AllocaTypeSize);
Alexey Samsonovcfd662f2012-11-13 07:15:32 +00001795 }
1796 }
1797
1798 builder.CreateLifetimeStart(AI, AllocaSize);
Reid Kleckner900d46f2014-05-15 21:10:46 +00001799 for (ReturnInst *RI : Returns) {
Sanjoy Das18b92962016-04-01 02:51:26 +00001800 // Don't insert llvm.lifetime.end calls between a musttail or deoptimize
1801 // call and a return. The return kills all local allocas.
Reid Klecknere31acf22014-08-12 00:05:15 +00001802 if (InlinedMustTailCalls &&
1803 RI->getParent()->getTerminatingMustTailCall())
Reid Kleckner900d46f2014-05-15 21:10:46 +00001804 continue;
Sanjoy Das18b92962016-04-01 02:51:26 +00001805 if (InlinedDeoptimizeCalls &&
1806 RI->getParent()->getTerminatingDeoptimizeCall())
1807 continue;
Reid Klecknerf0915aa2014-05-15 20:11:28 +00001808 IRBuilder<>(RI).CreateLifetimeEnd(AI, AllocaSize);
Reid Kleckner900d46f2014-05-15 21:10:46 +00001809 }
Nick Lewyckya68ec832011-05-22 05:22:10 +00001810 }
1811 }
1812
Chris Lattner2be06072006-01-13 19:34:14 +00001813 // If the inlined code contained dynamic alloca instructions, wrap the inlined
1814 // code with llvm.stacksave/llvm.stackrestore intrinsics.
1815 if (InlinedFunctionInfo.ContainsDynamicAllocas) {
1816 Module *M = Caller->getParent();
Chris Lattner2be06072006-01-13 19:34:14 +00001817 // Get the two intrinsics we care about.
Chris Lattner88b36f12009-10-17 05:39:39 +00001818 Function *StackSave = Intrinsic::getDeclaration(M, Intrinsic::stacksave);
1819 Function *StackRestore=Intrinsic::getDeclaration(M,Intrinsic::stackrestore);
Chris Lattner5de3b8b2006-07-12 18:29:36 +00001820
Chris Lattner2be06072006-01-13 19:34:14 +00001821 // Insert the llvm.stacksave.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001822 CallInst *SavedPtr = IRBuilder<>(&*FirstNewBlock, FirstNewBlock->begin())
David Blaikieff6409d2015-05-18 22:13:54 +00001823 .CreateCall(StackSave, {}, "savedstack");
Duncan Sands7c8fb1a2008-09-05 12:37:12 +00001824
Chris Lattner2be06072006-01-13 19:34:14 +00001825 // Insert a call to llvm.stackrestore before any return instructions in the
1826 // inlined function.
Reid Kleckner900d46f2014-05-15 21:10:46 +00001827 for (ReturnInst *RI : Returns) {
Sanjoy Dasf83ab6d2016-04-01 02:51:30 +00001828 // Don't insert llvm.stackrestore calls between a musttail or deoptimize
1829 // call and a return. The return will restore the stack pointer.
Reid Klecknere31acf22014-08-12 00:05:15 +00001830 if (InlinedMustTailCalls && RI->getParent()->getTerminatingMustTailCall())
Reid Kleckner900d46f2014-05-15 21:10:46 +00001831 continue;
Sanjoy Dasf83ab6d2016-04-01 02:51:30 +00001832 if (InlinedDeoptimizeCalls && RI->getParent()->getTerminatingDeoptimizeCall())
1833 continue;
Reid Klecknerf0915aa2014-05-15 20:11:28 +00001834 IRBuilder<>(RI).CreateCall(StackRestore, SavedPtr);
Reid Kleckner900d46f2014-05-15 21:10:46 +00001835 }
Chris Lattner9f3dced2005-05-06 06:47:52 +00001836 }
1837
Joseph Tremouletb41632b2016-01-20 02:15:15 +00001838 // If we are inlining for an invoke instruction, we must make sure to rewrite
1839 // any call instructions into invoke instructions. This is sensitive to which
1840 // funclet pads were top-level in the inlinee, so must be done before
1841 // rewriting the "parent pad" links.
1842 if (auto *II = dyn_cast<InvokeInst>(TheCall)) {
1843 BasicBlock *UnwindDest = II->getUnwindDest();
1844 Instruction *FirstNonPHI = UnwindDest->getFirstNonPHI();
1845 if (isa<LandingPadInst>(FirstNonPHI)) {
1846 HandleInlinedLandingPad(II, &*FirstNewBlock, InlinedFunctionInfo);
1847 } else {
1848 HandleInlinedEHPad(II, &*FirstNewBlock, InlinedFunctionInfo);
1849 }
1850 }
1851
David Majnemer3bb88c02015-12-15 21:27:27 +00001852 // Update the lexical scopes of the new funclets and callsites.
1853 // Anything that had 'none' as its parent is now nested inside the callsite's
1854 // EHPad.
1855
David Majnemer8a1c45d2015-12-12 05:38:55 +00001856 if (CallSiteEHPad) {
1857 for (Function::iterator BB = FirstNewBlock->getIterator(),
1858 E = Caller->end();
1859 BB != E; ++BB) {
David Majnemer3bb88c02015-12-15 21:27:27 +00001860 // Add bundle operands to any top-level call sites.
1861 SmallVector<OperandBundleDef, 1> OpBundles;
1862 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E;) {
1863 Instruction *I = &*BBI++;
1864 CallSite CS(I);
1865 if (!CS)
1866 continue;
1867
1868 // Skip call sites which are nounwind intrinsics.
1869 auto *CalledFn =
1870 dyn_cast<Function>(CS.getCalledValue()->stripPointerCasts());
1871 if (CalledFn && CalledFn->isIntrinsic() && CS.doesNotThrow())
1872 continue;
1873
1874 // Skip call sites which already have a "funclet" bundle.
1875 if (CS.getOperandBundle(LLVMContext::OB_funclet))
1876 continue;
1877
1878 CS.getOperandBundlesAsDefs(OpBundles);
1879 OpBundles.emplace_back("funclet", CallSiteEHPad);
1880
1881 Instruction *NewInst;
1882 if (CS.isCall())
1883 NewInst = CallInst::Create(cast<CallInst>(I), OpBundles, I);
1884 else
1885 NewInst = InvokeInst::Create(cast<InvokeInst>(I), OpBundles, I);
David Majnemer3bb88c02015-12-15 21:27:27 +00001886 NewInst->takeName(I);
1887 I->replaceAllUsesWith(NewInst);
1888 I->eraseFromParent();
1889
1890 OpBundles.clear();
1891 }
1892
David Majnemer223538f2016-02-23 17:11:04 +00001893 // It is problematic if the inlinee has a cleanupret which unwinds to
1894 // caller and we inline it into a call site which doesn't unwind but into
1895 // an EH pad that does. Such an edge must be dynamically unreachable.
1896 // As such, we replace the cleanupret with unreachable.
1897 if (auto *CleanupRet = dyn_cast<CleanupReturnInst>(BB->getTerminator()))
1898 if (CleanupRet->unwindsToCaller() && EHPadForCallUnwindsLocally)
David Majnemere14e7bc2016-06-25 08:19:55 +00001899 changeToUnreachable(CleanupRet, /*UseLLVMTrap=*/false);
David Majnemer223538f2016-02-23 17:11:04 +00001900
David Majnemer8a1c45d2015-12-12 05:38:55 +00001901 Instruction *I = BB->getFirstNonPHI();
1902 if (!I->isEHPad())
1903 continue;
1904
David Majnemerbbfc7212015-12-14 18:34:23 +00001905 if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(I)) {
David Majnemer8a1c45d2015-12-12 05:38:55 +00001906 if (isa<ConstantTokenNone>(CatchSwitch->getParentPad()))
1907 CatchSwitch->setParentPad(CallSiteEHPad);
1908 } else {
1909 auto *FPI = cast<FuncletPadInst>(I);
1910 if (isa<ConstantTokenNone>(FPI->getParentPad()))
1911 FPI->setParentPad(CallSiteEHPad);
1912 }
1913 }
1914 }
1915
Sanjoy Dasb51325d2016-03-11 19:08:34 +00001916 if (InlinedDeoptimizeCalls) {
1917 // We need to at least remove the deoptimizing returns from the Return set,
1918 // so that the control flow from those returns does not get merged into the
1919 // caller (but terminate it instead). If the caller's return type does not
1920 // match the callee's return type, we also need to change the return type of
1921 // the intrinsic.
1922 if (Caller->getReturnType() == TheCall->getType()) {
1923 auto NewEnd = remove_if(Returns, [](ReturnInst *RI) {
1924 return RI->getParent()->getTerminatingDeoptimizeCall() != nullptr;
1925 });
1926 Returns.erase(NewEnd, Returns.end());
1927 } else {
1928 SmallVector<ReturnInst *, 8> NormalReturns;
1929 Function *NewDeoptIntrinsic = Intrinsic::getDeclaration(
1930 Caller->getParent(), Intrinsic::experimental_deoptimize,
1931 {Caller->getReturnType()});
1932
1933 for (ReturnInst *RI : Returns) {
1934 CallInst *DeoptCall = RI->getParent()->getTerminatingDeoptimizeCall();
1935 if (!DeoptCall) {
1936 NormalReturns.push_back(RI);
1937 continue;
1938 }
1939
Sanjoy Dase0aa4142016-05-12 01:17:38 +00001940 // The calling convention on the deoptimize call itself may be bogus,
1941 // since the code we're inlining may have undefined behavior (and may
1942 // never actually execute at runtime); but all
1943 // @llvm.experimental.deoptimize declarations have to have the same
1944 // calling convention in a well-formed module.
1945 auto CallingConv = DeoptCall->getCalledFunction()->getCallingConv();
1946 NewDeoptIntrinsic->setCallingConv(CallingConv);
Sanjoy Dasb51325d2016-03-11 19:08:34 +00001947 auto *CurBB = RI->getParent();
1948 RI->eraseFromParent();
1949
1950 SmallVector<Value *, 4> CallArgs(DeoptCall->arg_begin(),
1951 DeoptCall->arg_end());
1952
1953 SmallVector<OperandBundleDef, 1> OpBundles;
1954 DeoptCall->getOperandBundlesAsDefs(OpBundles);
1955 DeoptCall->eraseFromParent();
1956 assert(!OpBundles.empty() &&
1957 "Expected at least the deopt operand bundle");
1958
1959 IRBuilder<> Builder(CurBB);
Sanjoy Dasdd77e1e2016-04-09 00:22:59 +00001960 CallInst *NewDeoptCall =
Sanjoy Dasb51325d2016-03-11 19:08:34 +00001961 Builder.CreateCall(NewDeoptIntrinsic, CallArgs, OpBundles);
Sanjoy Dasdd77e1e2016-04-09 00:22:59 +00001962 NewDeoptCall->setCallingConv(CallingConv);
Sanjoy Dasb51325d2016-03-11 19:08:34 +00001963 if (NewDeoptCall->getType()->isVoidTy())
1964 Builder.CreateRetVoid();
1965 else
1966 Builder.CreateRet(NewDeoptCall);
1967 }
1968
1969 // Leave behind the normal returns so we can merge control flow.
1970 std::swap(Returns, NormalReturns);
1971 }
1972 }
1973
Reid Klecknerf0915aa2014-05-15 20:11:28 +00001974 // Handle any inlined musttail call sites. In order for a new call site to be
1975 // musttail, the source of the clone and the inlined call site must have been
1976 // musttail. Therefore it's safe to return without merging control into the
1977 // phi below.
1978 if (InlinedMustTailCalls) {
1979 // Check if we need to bitcast the result of any musttail calls.
1980 Type *NewRetTy = Caller->getReturnType();
1981 bool NeedBitCast = !TheCall->use_empty() && TheCall->getType() != NewRetTy;
1982
1983 // Handle the returns preceded by musttail calls separately.
1984 SmallVector<ReturnInst *, 8> NormalReturns;
1985 for (ReturnInst *RI : Returns) {
Reid Klecknere31acf22014-08-12 00:05:15 +00001986 CallInst *ReturnedMustTail =
1987 RI->getParent()->getTerminatingMustTailCall();
Reid Klecknerf0915aa2014-05-15 20:11:28 +00001988 if (!ReturnedMustTail) {
1989 NormalReturns.push_back(RI);
1990 continue;
1991 }
1992 if (!NeedBitCast)
1993 continue;
1994
1995 // Delete the old return and any preceding bitcast.
1996 BasicBlock *CurBB = RI->getParent();
1997 auto *OldCast = dyn_cast_or_null<BitCastInst>(RI->getReturnValue());
1998 RI->eraseFromParent();
1999 if (OldCast)
2000 OldCast->eraseFromParent();
2001
2002 // Insert a new bitcast and return with the right type.
2003 IRBuilder<> Builder(CurBB);
2004 Builder.CreateRet(Builder.CreateBitCast(ReturnedMustTail, NewRetTy));
2005 }
2006
2007 // Leave behind the normal returns so we can merge control flow.
2008 std::swap(Returns, NormalReturns);
2009 }
2010
Chandler Carruth0ee8bb12016-12-27 01:24:50 +00002011 // Now that all of the transforms on the inlined code have taken place but
2012 // before we splice the inlined code into the CFG and lose track of which
2013 // blocks were actually inlined, collect the call sites. We only do this if
2014 // call graph updates weren't requested, as those provide value handle based
2015 // tracking of inlined call sites instead.
2016 if (InlinedFunctionInfo.ContainsCalls && !IFI.CG) {
2017 // Otherwise just collect the raw call sites that were inlined.
2018 for (BasicBlock &NewBB :
2019 make_range(FirstNewBlock->getIterator(), Caller->end()))
2020 for (Instruction &I : NewBB)
2021 if (auto CS = CallSite(&I))
2022 IFI.InlinedCallSites.push_back(CS);
2023 }
2024
Chris Lattner0fa8c7c2004-02-04 04:17:06 +00002025 // If we cloned in _exactly one_ basic block, and if that block ends in a
2026 // return instruction, we splice the body of the inlined callee directly into
2027 // the calling basic block.
2028 if (Returns.size() == 1 && std::distance(FirstNewBlock, Caller->end()) == 1) {
2029 // Move all of the instructions right before the call.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002030 OrigBB->getInstList().splice(TheCall->getIterator(),
2031 FirstNewBlock->getInstList(),
Chris Lattner0fa8c7c2004-02-04 04:17:06 +00002032 FirstNewBlock->begin(), FirstNewBlock->end());
2033 // Remove the cloned basic block.
2034 Caller->getBasicBlockList().pop_back();
Misha Brukmanb1c93172005-04-21 23:48:37 +00002035
Chris Lattner0fa8c7c2004-02-04 04:17:06 +00002036 // If the call site was an invoke instruction, add a branch to the normal
2037 // destination.
Adrian Prantl15db52b2013-04-23 19:56:03 +00002038 if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall)) {
2039 BranchInst *NewBr = BranchInst::Create(II->getNormalDest(), TheCall);
2040 NewBr->setDebugLoc(Returns[0]->getDebugLoc());
2041 }
Chris Lattner0fa8c7c2004-02-04 04:17:06 +00002042
2043 // If the return instruction returned a value, replace uses of the call with
2044 // uses of the returned value.
Devang Patel841322b2008-03-04 21:15:15 +00002045 if (!TheCall->use_empty()) {
2046 ReturnInst *R = Returns[0];
Eli Friedman36b90262009-05-08 00:22:04 +00002047 if (TheCall == R->getReturnValue())
Owen Andersonb292b8c2009-07-30 23:03:37 +00002048 TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
Eli Friedman36b90262009-05-08 00:22:04 +00002049 else
2050 TheCall->replaceAllUsesWith(R->getReturnValue());
Devang Patel841322b2008-03-04 21:15:15 +00002051 }
Chris Lattner0fa8c7c2004-02-04 04:17:06 +00002052 // Since we are now done with the Call/Invoke, we can delete it.
Dan Gohman158ff2c2008-06-21 22:08:46 +00002053 TheCall->eraseFromParent();
Chris Lattner0fa8c7c2004-02-04 04:17:06 +00002054
2055 // Since we are now done with the return instruction, delete it also.
Dan Gohman158ff2c2008-06-21 22:08:46 +00002056 Returns[0]->eraseFromParent();
Chris Lattner0fa8c7c2004-02-04 04:17:06 +00002057
2058 // We are now done with the inlining.
2059 return true;
2060 }
2061
2062 // Otherwise, we have the normal case, of more than one block to inline or
2063 // multiple return sites.
2064
Chris Lattner18ef3fd2004-02-04 02:51:48 +00002065 // We want to clone the entire callee function into the hole between the
2066 // "starter" and "ender" blocks. How we accomplish this depends on whether
2067 // this is an invoke instruction or a call instruction.
2068 BasicBlock *AfterCallBB;
Craig Topperf40110f2014-04-25 05:29:35 +00002069 BranchInst *CreatedBranchToNormalDest = nullptr;
Chris Lattner18ef3fd2004-02-04 02:51:48 +00002070 if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall)) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00002071
Chris Lattner18ef3fd2004-02-04 02:51:48 +00002072 // Add an unconditional branch to make this look like the CallInst case...
Adrian Prantl15db52b2013-04-23 19:56:03 +00002073 CreatedBranchToNormalDest = BranchInst::Create(II->getNormalDest(), TheCall);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002074
Chris Lattner18ef3fd2004-02-04 02:51:48 +00002075 // Split the basic block. This guarantees that no PHI nodes will have to be
2076 // updated due to new incoming edges, and make the invoke case more
2077 // symmetric to the call case.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002078 AfterCallBB =
2079 OrigBB->splitBasicBlock(CreatedBranchToNormalDest->getIterator(),
2080 CalledFunc->getName() + ".exit");
Misha Brukmanb1c93172005-04-21 23:48:37 +00002081
Chris Lattner18ef3fd2004-02-04 02:51:48 +00002082 } else { // It's a call
Chris Lattner0fa8c7c2004-02-04 04:17:06 +00002083 // If this is a call instruction, we need to split the basic block that
2084 // the call lives in.
Chris Lattner18ef3fd2004-02-04 02:51:48 +00002085 //
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002086 AfterCallBB = OrigBB->splitBasicBlock(TheCall->getIterator(),
2087 CalledFunc->getName() + ".exit");
Chris Lattner18ef3fd2004-02-04 02:51:48 +00002088 }
2089
Chris Lattner0fa8c7c2004-02-04 04:17:06 +00002090 // Change the branch that used to go to AfterCallBB to branch to the first
2091 // basic block of the inlined function.
2092 //
2093 TerminatorInst *Br = OrigBB->getTerminator();
Misha Brukmanb1c93172005-04-21 23:48:37 +00002094 assert(Br && Br->getOpcode() == Instruction::Br &&
Chris Lattner0fa8c7c2004-02-04 04:17:06 +00002095 "splitBasicBlock broken!");
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002096 Br->setOperand(0, &*FirstNewBlock);
Chris Lattner0fa8c7c2004-02-04 04:17:06 +00002097
2098 // Now that the function is correct, make it a little bit nicer. In
2099 // particular, move the basic blocks inserted from the end of the function
2100 // into the space made by splitting the source basic block.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002101 Caller->getBasicBlockList().splice(AfterCallBB->getIterator(),
2102 Caller->getBasicBlockList(), FirstNewBlock,
2103 Caller->end());
Chris Lattner0fa8c7c2004-02-04 04:17:06 +00002104
Chris Lattner18ef3fd2004-02-04 02:51:48 +00002105 // Handle all of the return instructions that we just cloned in, and eliminate
2106 // any users of the original call/invoke instruction.
Chris Lattner229907c2011-07-18 04:54:35 +00002107 Type *RTy = CalledFunc->getReturnType();
Dan Gohman3b18fd72008-06-20 01:03:44 +00002108
Craig Topperf40110f2014-04-25 05:29:35 +00002109 PHINode *PHI = nullptr;
Dan Gohmanfa1211f2008-07-23 00:34:11 +00002110 if (Returns.size() > 1) {
Chris Lattner18ef3fd2004-02-04 02:51:48 +00002111 // The PHI node should go at the front of the new basic block to merge all
2112 // possible incoming values.
Chris Lattner18ef3fd2004-02-04 02:51:48 +00002113 if (!TheCall->use_empty()) {
Jay Foad52131342011-03-30 11:28:46 +00002114 PHI = PHINode::Create(RTy, Returns.size(), TheCall->getName(),
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002115 &AfterCallBB->front());
Dan Gohmanfa1211f2008-07-23 00:34:11 +00002116 // Anything that used the result of the function call should now use the
2117 // PHI node as their operand.
Duncan Sands7c8fb1a2008-09-05 12:37:12 +00002118 TheCall->replaceAllUsesWith(PHI);
Chris Lattner18ef3fd2004-02-04 02:51:48 +00002119 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002120
Gabor Greif5aa19222009-01-15 18:40:09 +00002121 // Loop over all of the return instructions adding entries to the PHI node
2122 // as appropriate.
Dan Gohmanfa1211f2008-07-23 00:34:11 +00002123 if (PHI) {
2124 for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
2125 ReturnInst *RI = Returns[i];
2126 assert(RI->getReturnValue()->getType() == PHI->getType() &&
2127 "Ret value not consistent in function!");
2128 PHI->addIncoming(RI->getReturnValue(), RI->getParent());
Devang Patel780b3ca62008-03-07 20:06:16 +00002129 }
2130 }
2131
Gabor Greif8c573f72009-01-16 23:08:50 +00002132 // Add a branch to the merge points and remove return instructions.
Richard Trieu624c2eb2013-04-30 22:45:10 +00002133 DebugLoc Loc;
Chris Lattner18ef3fd2004-02-04 02:51:48 +00002134 for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
Richard Trieu624c2eb2013-04-30 22:45:10 +00002135 ReturnInst *RI = Returns[i];
Adrian Prantl09416382013-04-30 17:08:16 +00002136 BranchInst* BI = BranchInst::Create(AfterCallBB, RI);
Richard Trieu624c2eb2013-04-30 22:45:10 +00002137 Loc = RI->getDebugLoc();
2138 BI->setDebugLoc(Loc);
Devang Patel64d0f072008-03-10 18:34:00 +00002139 RI->eraseFromParent();
Chris Lattner18ef3fd2004-02-04 02:51:48 +00002140 }
Adrian Prantl09416382013-04-30 17:08:16 +00002141 // We need to set the debug location to *somewhere* inside the
Adrian Prantl8beccf92013-04-30 17:33:32 +00002142 // inlined function. The line number may be nonsensical, but the
Adrian Prantl09416382013-04-30 17:08:16 +00002143 // instruction will at least be associated with the right
2144 // function.
2145 if (CreatedBranchToNormalDest)
Richard Trieu624c2eb2013-04-30 22:45:10 +00002146 CreatedBranchToNormalDest->setDebugLoc(Loc);
Devang Patel64d0f072008-03-10 18:34:00 +00002147 } else if (!Returns.empty()) {
2148 // Otherwise, if there is exactly one return value, just replace anything
2149 // using the return value of the call with the computed value.
Eli Friedman36b90262009-05-08 00:22:04 +00002150 if (!TheCall->use_empty()) {
2151 if (TheCall == Returns[0]->getReturnValue())
Owen Andersonb292b8c2009-07-30 23:03:37 +00002152 TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
Eli Friedman36b90262009-05-08 00:22:04 +00002153 else
2154 TheCall->replaceAllUsesWith(Returns[0]->getReturnValue());
2155 }
Duncan Sands7c8fb1a2008-09-05 12:37:12 +00002156
Jay Foad61ea0e42011-06-23 09:09:15 +00002157 // Update PHI nodes that use the ReturnBB to use the AfterCallBB.
2158 BasicBlock *ReturnBB = Returns[0]->getParent();
2159 ReturnBB->replaceAllUsesWith(AfterCallBB);
2160
Devang Patel64d0f072008-03-10 18:34:00 +00002161 // Splice the code from the return block into the block that it will return
2162 // to, which contains the code that was after the call.
Devang Patel64d0f072008-03-10 18:34:00 +00002163 AfterCallBB->getInstList().splice(AfterCallBB->begin(),
2164 ReturnBB->getInstList());
Duncan Sands7c8fb1a2008-09-05 12:37:12 +00002165
Adrian Prantl15db52b2013-04-23 19:56:03 +00002166 if (CreatedBranchToNormalDest)
2167 CreatedBranchToNormalDest->setDebugLoc(Returns[0]->getDebugLoc());
2168
Devang Patel64d0f072008-03-10 18:34:00 +00002169 // Delete the return instruction now and empty ReturnBB now.
2170 Returns[0]->eraseFromParent();
2171 ReturnBB->eraseFromParent();
Chris Lattner6e79e552004-10-17 23:21:07 +00002172 } else if (!TheCall->use_empty()) {
2173 // No returns, but something is using the return value of the call. Just
2174 // nuke the result.
Owen Andersonb292b8c2009-07-30 23:03:37 +00002175 TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
Chris Lattner18ef3fd2004-02-04 02:51:48 +00002176 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002177
Chris Lattner18ef3fd2004-02-04 02:51:48 +00002178 // Since we are now done with the Call/Invoke, we can delete it.
Chris Lattner6e79e552004-10-17 23:21:07 +00002179 TheCall->eraseFromParent();
Chris Lattner530d4bf2003-05-29 15:11:31 +00002180
Reid Klecknerf0915aa2014-05-15 20:11:28 +00002181 // If we inlined any musttail calls and the original return is now
2182 // unreachable, delete it. It can only contain a bitcast and ret.
Easwaran Ramanb1bd3982016-03-08 00:36:35 +00002183 if (InlinedMustTailCalls && pred_begin(AfterCallBB) == pred_end(AfterCallBB))
Reid Klecknerf0915aa2014-05-15 20:11:28 +00002184 AfterCallBB->eraseFromParent();
2185
Chris Lattnerfc3fe5c2003-08-24 04:06:56 +00002186 // We should always be able to fold the entry block of the function into the
2187 // single predecessor of the block...
Chris Lattner0328d752004-04-16 05:17:59 +00002188 assert(cast<BranchInst>(Br)->isUnconditional() && "splitBasicBlock broken!");
Chris Lattnerfc3fe5c2003-08-24 04:06:56 +00002189 BasicBlock *CalleeEntry = cast<BranchInst>(Br)->getSuccessor(0);
Chris Lattner0fa8c7c2004-02-04 04:17:06 +00002190
Chris Lattner0328d752004-04-16 05:17:59 +00002191 // Splice the code entry block into calling block, right before the
2192 // unconditional branch.
Eric Christopher96513122011-06-23 06:24:52 +00002193 CalleeEntry->replaceAllUsesWith(OrigBB); // Update PHI nodes
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002194 OrigBB->getInstList().splice(Br->getIterator(), CalleeEntry->getInstList());
Chris Lattner0328d752004-04-16 05:17:59 +00002195
2196 // Remove the unconditional branch.
2197 OrigBB->getInstList().erase(Br);
2198
2199 // Now we can remove the CalleeEntry block, which is now empty.
2200 Caller->getBasicBlockList().erase(CalleeEntry);
Duncan Sands7c8fb1a2008-09-05 12:37:12 +00002201
Duncan Sands9d9a4e22010-11-17 11:16:23 +00002202 // If we inserted a phi node, check to see if it has a single value (e.g. all
2203 // the entries are the same or undef). If so, remove the PHI so it doesn't
2204 // block other optimizations.
Bill Wendlingce0c2292012-01-31 01:01:16 +00002205 if (PHI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002206 AssumptionCache *AC =
2207 IFI.GetAssumptionCache ? &(*IFI.GetAssumptionCache)(*Caller) : nullptr;
Mehdi Amini46a43552015-03-04 18:43:29 +00002208 auto &DL = Caller->getParent()->getDataLayout();
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002209 if (Value *V = SimplifyInstruction(PHI, DL, nullptr, nullptr, AC)) {
Duncan Sands9d9a4e22010-11-17 11:16:23 +00002210 PHI->replaceAllUsesWith(V);
2211 PHI->eraseFromParent();
2212 }
Bill Wendlingce0c2292012-01-31 01:01:16 +00002213 }
Duncan Sands9d9a4e22010-11-17 11:16:23 +00002214
Chris Lattner530d4bf2003-05-29 15:11:31 +00002215 return true;
2216}