blob: cc83ee7bafce6b83add6d28d24fce60422416fc1 [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"
Easwaran Raman12585b02017-01-20 22:44:04 +000023#include "llvm/Analysis/BlockFrequencyInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000024#include "llvm/Analysis/CallGraph.h"
Hal Finkelff0bcb62014-07-25 15:50:08 +000025#include "llvm/Analysis/CaptureTracking.h"
David Majnemer8a1c45d2015-12-12 05:38:55 +000026#include "llvm/Analysis/EHPersonalities.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000027#include "llvm/Analysis/InstructionSimplify.h"
Hal Finkel94146652014-07-24 14:25:39 +000028#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000029#include "llvm/IR/Attributes.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000030#include "llvm/IR/CallSite.h"
Reid Klecknerf0915aa2014-05-15 20:11:28 +000031#include "llvm/IR/CFG.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000032#include "llvm/IR/Constants.h"
33#include "llvm/IR/DataLayout.h"
Chandler Carruth9a4c9e52014-03-06 00:46:21 +000034#include "llvm/IR/DebugInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000035#include "llvm/IR/DerivedTypes.h"
Adrian Prantl3e2659e2015-01-30 19:37:48 +000036#include "llvm/IR/DIBuilder.h"
Hal Finkelff0bcb62014-07-25 15:50:08 +000037#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000038#include "llvm/IR/IRBuilder.h"
39#include "llvm/IR/Instructions.h"
40#include "llvm/IR/IntrinsicInst.h"
41#include "llvm/IR/Intrinsics.h"
Hal Finkel94146652014-07-24 14:25:39 +000042#include "llvm/IR/MDBuilder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000043#include "llvm/IR/Module.h"
Hal Finkelff0bcb62014-07-25 15:50:08 +000044#include "llvm/Support/CommandLine.h"
Easwaran Raman12585b02017-01-20 22:44:04 +000045#include "llvm/Transforms/Utils/Local.h"
Hal Finkelff0bcb62014-07-25 15:50:08 +000046#include <algorithm>
Hans Wennborg083ca9b2015-10-06 23:24:35 +000047
Chris Lattnerdf3c3422004-01-09 06:12:26 +000048using namespace llvm;
Chris Lattner530d4bf2003-05-29 15:11:31 +000049
Hal Finkelff0bcb62014-07-25 15:50:08 +000050static cl::opt<bool>
James Molloy6b95d8e2014-09-04 13:23:08 +000051EnableNoAliasConversion("enable-noalias-to-md-conversion", cl::init(true),
Hal Finkelff0bcb62014-07-25 15:50:08 +000052 cl::Hidden,
53 cl::desc("Convert noalias attributes to metadata during inlining."));
54
Hal Finkel68dc3c72014-10-15 23:44:41 +000055static cl::opt<bool>
56PreserveAlignmentAssumptions("preserve-alignment-assumptions-during-inlining",
57 cl::init(true), cl::Hidden,
58 cl::desc("Convert align attributes to assumptions during inlining."));
59
Eric Christopherf16bee82012-03-26 19:09:38 +000060bool llvm::InlineFunction(CallInst *CI, InlineFunctionInfo &IFI,
Chandler Carruth7b560d42015-09-09 17:55:00 +000061 AAResults *CalleeAAR, bool InsertLifetime) {
62 return InlineFunction(CallSite(CI), IFI, CalleeAAR, InsertLifetime);
Chris Lattner0841fb12006-01-14 20:07:50 +000063}
Eric Christopherf16bee82012-03-26 19:09:38 +000064bool llvm::InlineFunction(InvokeInst *II, InlineFunctionInfo &IFI,
Chandler Carruth7b560d42015-09-09 17:55:00 +000065 AAResults *CalleeAAR, bool InsertLifetime) {
66 return InlineFunction(CallSite(II), IFI, CalleeAAR, InsertLifetime);
Chris Lattner0841fb12006-01-14 20:07:50 +000067}
Chris Lattner0cc265e2003-08-24 06:59:16 +000068
John McCallbd04b742011-05-27 18:34:38 +000069namespace {
David Majnemer654e1302015-07-31 17:58:14 +000070 /// A class for recording information about inlining a landing pad.
71 class LandingPadInliningInfo {
Dmitri Gribenkodbeafa72012-06-09 00:01:45 +000072 BasicBlock *OuterResumeDest; ///< Destination of the invoke's unwind.
73 BasicBlock *InnerResumeDest; ///< Destination for the callee's resume.
74 LandingPadInst *CallerLPad; ///< LandingPadInst associated with the invoke.
75 PHINode *InnerEHValuesPHI; ///< PHI for EH values from landingpad insts.
Bill Wendling0c2d82b2012-01-31 01:22:03 +000076 SmallVector<Value*, 8> UnwindDestPHIValues;
Bill Wendlingfa284402011-07-28 07:31:46 +000077
Bill Wendling55421f02011-08-14 08:01:36 +000078 public:
David Majnemer654e1302015-07-31 17:58:14 +000079 LandingPadInliningInfo(InvokeInst *II)
Craig Topperf40110f2014-04-25 05:29:35 +000080 : OuterResumeDest(II->getUnwindDest()), InnerResumeDest(nullptr),
81 CallerLPad(nullptr), InnerEHValuesPHI(nullptr) {
Bill Wendling55421f02011-08-14 08:01:36 +000082 // If there are PHI nodes in the unwind destination block, we need to keep
83 // track of which values came into them from the invoke before removing
84 // the edge from this block.
85 llvm::BasicBlock *InvokeBB = II->getParent();
Bill Wendlingea6e9352012-01-31 01:25:54 +000086 BasicBlock::iterator I = OuterResumeDest->begin();
Bill Wendling55421f02011-08-14 08:01:36 +000087 for (; isa<PHINode>(I); ++I) {
John McCallbd04b742011-05-27 18:34:38 +000088 // Save the value to use for this edge.
Bill Wendling55421f02011-08-14 08:01:36 +000089 PHINode *PHI = cast<PHINode>(I);
90 UnwindDestPHIValues.push_back(PHI->getIncomingValueForBlock(InvokeBB));
91 }
92
Bill Wendlingf3cae512012-01-31 00:56:53 +000093 CallerLPad = cast<LandingPadInst>(I);
John McCallbd04b742011-05-27 18:34:38 +000094 }
95
Sanjay Patel0fdb4372015-03-10 19:42:57 +000096 /// The outer unwind destination is the target of
Bill Wendlingea6e9352012-01-31 01:25:54 +000097 /// unwind edges introduced for calls within the inlined function.
Bill Wendling0c2d82b2012-01-31 01:22:03 +000098 BasicBlock *getOuterResumeDest() const {
Bill Wendlingea6e9352012-01-31 01:25:54 +000099 return OuterResumeDest;
John McCallbd04b742011-05-27 18:34:38 +0000100 }
101
Bill Wendling3fd879d2012-01-31 01:48:40 +0000102 BasicBlock *getInnerResumeDest();
Bill Wendling55421f02011-08-14 08:01:36 +0000103
104 LandingPadInst *getLandingPadInst() const { return CallerLPad; }
105
Sanjay Patel0fdb4372015-03-10 19:42:57 +0000106 /// Forward the 'resume' instruction to the caller's landing pad block.
107 /// When the landing pad block has only one predecessor, this is
Bill Wendling55421f02011-08-14 08:01:36 +0000108 /// a simple branch. When there is more than one predecessor, we need to
109 /// split the landing pad block after the landingpad instruction and jump
110 /// to there.
Bill Wendling56f15bf2013-03-22 20:31:05 +0000111 void forwardResume(ResumeInst *RI,
Craig Topper71b7b682014-08-21 05:55:13 +0000112 SmallPtrSetImpl<LandingPadInst*> &InlinedLPads);
Bill Wendling55421f02011-08-14 08:01:36 +0000113
Sanjay Patel0fdb4372015-03-10 19:42:57 +0000114 /// Add incoming-PHI values to the unwind destination block for the given
115 /// basic block, using the values for the original invoke's source block.
John McCallbd04b742011-05-27 18:34:38 +0000116 void addIncomingPHIValuesFor(BasicBlock *BB) const {
Bill Wendlingea6e9352012-01-31 01:25:54 +0000117 addIncomingPHIValuesForInto(BB, OuterResumeDest);
John McCall046c47e2011-05-28 07:45:59 +0000118 }
Bill Wendlingad088e62011-07-30 05:42:50 +0000119
John McCall046c47e2011-05-28 07:45:59 +0000120 void addIncomingPHIValuesForInto(BasicBlock *src, BasicBlock *dest) const {
121 BasicBlock::iterator I = dest->begin();
John McCallbd04b742011-05-27 18:34:38 +0000122 for (unsigned i = 0, e = UnwindDestPHIValues.size(); i != e; ++i, ++I) {
Bill Wendlingad088e62011-07-30 05:42:50 +0000123 PHINode *phi = cast<PHINode>(I);
124 phi->addIncoming(UnwindDestPHIValues[i], src);
John McCallbd04b742011-05-27 18:34:38 +0000125 }
126 }
127 };
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000128} // anonymous namespace
John McCallbd04b742011-05-27 18:34:38 +0000129
Sanjay Patel0fdb4372015-03-10 19:42:57 +0000130/// Get or create a target for the branch from ResumeInsts.
David Majnemer654e1302015-07-31 17:58:14 +0000131BasicBlock *LandingPadInliningInfo::getInnerResumeDest() {
Bill Wendling55421f02011-08-14 08:01:36 +0000132 if (InnerResumeDest) return InnerResumeDest;
133
134 // Split the landing pad.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000135 BasicBlock::iterator SplitPoint = ++CallerLPad->getIterator();
Bill Wendling55421f02011-08-14 08:01:36 +0000136 InnerResumeDest =
137 OuterResumeDest->splitBasicBlock(SplitPoint,
138 OuterResumeDest->getName() + ".body");
139
140 // The number of incoming edges we expect to the inner landing pad.
141 const unsigned PHICapacity = 2;
142
143 // Create corresponding new PHIs for all the PHIs in the outer landing pad.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000144 Instruction *InsertPoint = &InnerResumeDest->front();
Bill Wendling55421f02011-08-14 08:01:36 +0000145 BasicBlock::iterator I = OuterResumeDest->begin();
146 for (unsigned i = 0, e = UnwindDestPHIValues.size(); i != e; ++i, ++I) {
147 PHINode *OuterPHI = cast<PHINode>(I);
148 PHINode *InnerPHI = PHINode::Create(OuterPHI->getType(), PHICapacity,
149 OuterPHI->getName() + ".lpad-body",
150 InsertPoint);
151 OuterPHI->replaceAllUsesWith(InnerPHI);
152 InnerPHI->addIncoming(OuterPHI, OuterResumeDest);
153 }
154
155 // Create a PHI for the exception values.
156 InnerEHValuesPHI = PHINode::Create(CallerLPad->getType(), PHICapacity,
157 "eh.lpad-body", InsertPoint);
158 CallerLPad->replaceAllUsesWith(InnerEHValuesPHI);
159 InnerEHValuesPHI->addIncoming(CallerLPad, OuterResumeDest);
160
161 // All done.
162 return InnerResumeDest;
163}
164
Sanjay Patel0fdb4372015-03-10 19:42:57 +0000165/// Forward the 'resume' instruction to the caller's landing pad block.
166/// When the landing pad block has only one predecessor, this is a simple
Bill Wendling55421f02011-08-14 08:01:36 +0000167/// branch. When there is more than one predecessor, we need to split the
168/// landing pad block after the landingpad instruction and jump to there.
David Majnemer654e1302015-07-31 17:58:14 +0000169void LandingPadInliningInfo::forwardResume(
170 ResumeInst *RI, SmallPtrSetImpl<LandingPadInst *> &InlinedLPads) {
Bill Wendling3fd879d2012-01-31 01:48:40 +0000171 BasicBlock *Dest = getInnerResumeDest();
Bill Wendling55421f02011-08-14 08:01:36 +0000172 BasicBlock *Src = RI->getParent();
173
174 BranchInst::Create(Dest, Src);
175
176 // Update the PHIs in the destination. They were inserted in an order which
177 // makes this work.
178 addIncomingPHIValuesForInto(Src, Dest);
179
180 InnerEHValuesPHI->addIncoming(RI->getOperand(0), Src);
181 RI->eraseFromParent();
182}
183
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000184/// Helper for getUnwindDestToken/getUnwindDestTokenHelper.
185static Value *getParentPad(Value *EHPad) {
186 if (auto *FPI = dyn_cast<FuncletPadInst>(EHPad))
187 return FPI->getParentPad();
188 return cast<CatchSwitchInst>(EHPad)->getParentPad();
189}
190
191typedef DenseMap<Instruction *, Value *> UnwindDestMemoTy;
192
193/// Helper for getUnwindDestToken that does the descendant-ward part of
194/// the search.
195static Value *getUnwindDestTokenHelper(Instruction *EHPad,
196 UnwindDestMemoTy &MemoMap) {
197 SmallVector<Instruction *, 8> Worklist(1, EHPad);
198
199 while (!Worklist.empty()) {
200 Instruction *CurrentPad = Worklist.pop_back_val();
201 // We only put pads on the worklist that aren't in the MemoMap. When
202 // we find an unwind dest for a pad we may update its ancestors, but
203 // the queue only ever contains uncles/great-uncles/etc. of CurrentPad,
204 // so they should never get updated while queued on the worklist.
205 assert(!MemoMap.count(CurrentPad));
206 Value *UnwindDestToken = nullptr;
207 if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(CurrentPad)) {
208 if (CatchSwitch->hasUnwindDest()) {
209 UnwindDestToken = CatchSwitch->getUnwindDest()->getFirstNonPHI();
210 } else {
211 // Catchswitch doesn't have a 'nounwind' variant, and one might be
212 // annotated as "unwinds to caller" when really it's nounwind (see
213 // e.g. SimplifyCFGOpt::SimplifyUnreachable), so we can't infer the
214 // parent's unwind dest from this. We can check its catchpads'
215 // descendants, since they might include a cleanuppad with an
216 // "unwinds to caller" cleanupret, which can be trusted.
217 for (auto HI = CatchSwitch->handler_begin(),
218 HE = CatchSwitch->handler_end();
219 HI != HE && !UnwindDestToken; ++HI) {
220 BasicBlock *HandlerBlock = *HI;
221 auto *CatchPad = cast<CatchPadInst>(HandlerBlock->getFirstNonPHI());
222 for (User *Child : CatchPad->users()) {
223 // Intentionally ignore invokes here -- since the catchswitch is
224 // marked "unwind to caller", it would be a verifier error if it
225 // contained an invoke which unwinds out of it, so any invoke we'd
226 // encounter must unwind to some child of the catch.
227 if (!isa<CleanupPadInst>(Child) && !isa<CatchSwitchInst>(Child))
228 continue;
229
230 Instruction *ChildPad = cast<Instruction>(Child);
231 auto Memo = MemoMap.find(ChildPad);
232 if (Memo == MemoMap.end()) {
Joseph Tremoulete92e0a92016-09-04 01:23:20 +0000233 // Haven't figured out this child pad yet; queue it.
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000234 Worklist.push_back(ChildPad);
235 continue;
236 }
237 // We've already checked this child, but might have found that
238 // it offers no proof either way.
239 Value *ChildUnwindDestToken = Memo->second;
240 if (!ChildUnwindDestToken)
241 continue;
242 // We already know the child's unwind dest, which can either
243 // be ConstantTokenNone to indicate unwind to caller, or can
244 // be another child of the catchpad. Only the former indicates
245 // the unwind dest of the catchswitch.
246 if (isa<ConstantTokenNone>(ChildUnwindDestToken)) {
247 UnwindDestToken = ChildUnwindDestToken;
248 break;
249 }
250 assert(getParentPad(ChildUnwindDestToken) == CatchPad);
251 }
252 }
253 }
254 } else {
255 auto *CleanupPad = cast<CleanupPadInst>(CurrentPad);
256 for (User *U : CleanupPad->users()) {
257 if (auto *CleanupRet = dyn_cast<CleanupReturnInst>(U)) {
258 if (BasicBlock *RetUnwindDest = CleanupRet->getUnwindDest())
259 UnwindDestToken = RetUnwindDest->getFirstNonPHI();
260 else
261 UnwindDestToken = ConstantTokenNone::get(CleanupPad->getContext());
262 break;
263 }
264 Value *ChildUnwindDestToken;
265 if (auto *Invoke = dyn_cast<InvokeInst>(U)) {
266 ChildUnwindDestToken = Invoke->getUnwindDest()->getFirstNonPHI();
267 } else if (isa<CleanupPadInst>(U) || isa<CatchSwitchInst>(U)) {
268 Instruction *ChildPad = cast<Instruction>(U);
269 auto Memo = MemoMap.find(ChildPad);
270 if (Memo == MemoMap.end()) {
271 // Haven't resolved this child yet; queue it and keep searching.
272 Worklist.push_back(ChildPad);
273 continue;
274 }
275 // We've checked this child, but still need to ignore it if it
276 // had no proof either way.
277 ChildUnwindDestToken = Memo->second;
278 if (!ChildUnwindDestToken)
279 continue;
280 } else {
281 // Not a relevant user of the cleanuppad
282 continue;
283 }
284 // In a well-formed program, the child/invoke must either unwind to
285 // an(other) child of the cleanup, or exit the cleanup. In the
286 // first case, continue searching.
287 if (isa<Instruction>(ChildUnwindDestToken) &&
288 getParentPad(ChildUnwindDestToken) == CleanupPad)
289 continue;
290 UnwindDestToken = ChildUnwindDestToken;
291 break;
292 }
293 }
294 // If we haven't found an unwind dest for CurrentPad, we may have queued its
295 // children, so move on to the next in the worklist.
296 if (!UnwindDestToken)
297 continue;
298
299 // Now we know that CurrentPad unwinds to UnwindDestToken. It also exits
300 // any ancestors of CurrentPad up to but not including UnwindDestToken's
301 // parent pad. Record this in the memo map, and check to see if the
302 // original EHPad being queried is one of the ones exited.
303 Value *UnwindParent;
304 if (auto *UnwindPad = dyn_cast<Instruction>(UnwindDestToken))
305 UnwindParent = getParentPad(UnwindPad);
306 else
307 UnwindParent = nullptr;
308 bool ExitedOriginalPad = false;
309 for (Instruction *ExitedPad = CurrentPad;
310 ExitedPad && ExitedPad != UnwindParent;
311 ExitedPad = dyn_cast<Instruction>(getParentPad(ExitedPad))) {
312 // Skip over catchpads since they just follow their catchswitches.
313 if (isa<CatchPadInst>(ExitedPad))
314 continue;
315 MemoMap[ExitedPad] = UnwindDestToken;
316 ExitedOriginalPad |= (ExitedPad == EHPad);
317 }
318
319 if (ExitedOriginalPad)
320 return UnwindDestToken;
321
322 // Continue the search.
323 }
324
325 // No definitive information is contained within this funclet.
326 return nullptr;
327}
328
329/// Given an EH pad, find where it unwinds. If it unwinds to an EH pad,
330/// return that pad instruction. If it unwinds to caller, return
331/// ConstantTokenNone. If it does not have a definitive unwind destination,
332/// return nullptr.
333///
334/// This routine gets invoked for calls in funclets in inlinees when inlining
335/// an invoke. Since many funclets don't have calls inside them, it's queried
336/// on-demand rather than building a map of pads to unwind dests up front.
337/// Determining a funclet's unwind dest may require recursively searching its
338/// descendants, and also ancestors and cousins if the descendants don't provide
339/// an answer. Since most funclets will have their unwind dest immediately
340/// available as the unwind dest of a catchswitch or cleanupret, this routine
341/// searches top-down from the given pad and then up. To avoid worst-case
342/// quadratic run-time given that approach, it uses a memo map to avoid
343/// re-processing funclet trees. The callers that rewrite the IR as they go
344/// take advantage of this, for correctness, by checking/forcing rewritten
345/// pads' entries to match the original callee view.
346static Value *getUnwindDestToken(Instruction *EHPad,
347 UnwindDestMemoTy &MemoMap) {
348 // Catchpads unwind to the same place as their catchswitch;
349 // redirct any queries on catchpads so the code below can
350 // deal with just catchswitches and cleanuppads.
351 if (auto *CPI = dyn_cast<CatchPadInst>(EHPad))
352 EHPad = CPI->getCatchSwitch();
353
354 // Check if we've already determined the unwind dest for this pad.
355 auto Memo = MemoMap.find(EHPad);
356 if (Memo != MemoMap.end())
357 return Memo->second;
358
359 // Search EHPad and, if necessary, its descendants.
360 Value *UnwindDestToken = getUnwindDestTokenHelper(EHPad, MemoMap);
361 assert((UnwindDestToken == nullptr) != (MemoMap.count(EHPad) != 0));
362 if (UnwindDestToken)
363 return UnwindDestToken;
364
365 // No information is available for this EHPad from itself or any of its
366 // descendants. An unwind all the way out to a pad in the caller would
367 // need also to agree with the unwind dest of the parent funclet, so
368 // search up the chain to try to find a funclet with information. Put
369 // null entries in the memo map to avoid re-processing as we go up.
370 MemoMap[EHPad] = nullptr;
Joseph Tremoulete92e0a92016-09-04 01:23:20 +0000371#ifndef NDEBUG
372 SmallPtrSet<Instruction *, 4> TempMemos;
373 TempMemos.insert(EHPad);
374#endif
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000375 Instruction *LastUselessPad = EHPad;
376 Value *AncestorToken;
377 for (AncestorToken = getParentPad(EHPad);
378 auto *AncestorPad = dyn_cast<Instruction>(AncestorToken);
379 AncestorToken = getParentPad(AncestorToken)) {
380 // Skip over catchpads since they just follow their catchswitches.
381 if (isa<CatchPadInst>(AncestorPad))
382 continue;
Joseph Tremoulete92e0a92016-09-04 01:23:20 +0000383 // If the MemoMap had an entry mapping AncestorPad to nullptr, since we
384 // haven't yet called getUnwindDestTokenHelper for AncestorPad in this
385 // call to getUnwindDestToken, that would mean that AncestorPad had no
386 // information in itself, its descendants, or its ancestors. If that
387 // were the case, then we should also have recorded the lack of information
388 // for the descendant that we're coming from. So assert that we don't
389 // find a null entry in the MemoMap for AncestorPad.
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000390 assert(!MemoMap.count(AncestorPad) || MemoMap[AncestorPad]);
391 auto AncestorMemo = MemoMap.find(AncestorPad);
392 if (AncestorMemo == MemoMap.end()) {
393 UnwindDestToken = getUnwindDestTokenHelper(AncestorPad, MemoMap);
394 } else {
395 UnwindDestToken = AncestorMemo->second;
396 }
397 if (UnwindDestToken)
398 break;
399 LastUselessPad = AncestorPad;
Joseph Tremoulete92e0a92016-09-04 01:23:20 +0000400 MemoMap[LastUselessPad] = nullptr;
401#ifndef NDEBUG
402 TempMemos.insert(LastUselessPad);
403#endif
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000404 }
405
Joseph Tremoulete92e0a92016-09-04 01:23:20 +0000406 // We know that getUnwindDestTokenHelper was called on LastUselessPad and
407 // returned nullptr (and likewise for EHPad and any of its ancestors up to
408 // LastUselessPad), so LastUselessPad has no information from below. Since
409 // getUnwindDestTokenHelper must investigate all downward paths through
410 // no-information nodes to prove that a node has no information like this,
411 // and since any time it finds information it records it in the MemoMap for
412 // not just the immediately-containing funclet but also any ancestors also
413 // exited, it must be the case that, walking downward from LastUselessPad,
414 // visiting just those nodes which have not been mapped to an unwind dest
415 // by getUnwindDestTokenHelper (the nullptr TempMemos notwithstanding, since
416 // they are just used to keep getUnwindDestTokenHelper from repeating work),
417 // any node visited must have been exhaustively searched with no information
418 // for it found.
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000419 SmallVector<Instruction *, 8> Worklist(1, LastUselessPad);
420 while (!Worklist.empty()) {
421 Instruction *UselessPad = Worklist.pop_back_val();
Joseph Tremoulete92e0a92016-09-04 01:23:20 +0000422 auto Memo = MemoMap.find(UselessPad);
423 if (Memo != MemoMap.end() && Memo->second) {
424 // Here the name 'UselessPad' is a bit of a misnomer, because we've found
425 // that it is a funclet that does have information about unwinding to
426 // a particular destination; its parent was a useless pad.
427 // Since its parent has no information, the unwind edge must not escape
428 // the parent, and must target a sibling of this pad. This local unwind
429 // gives us no information about EHPad. Leave it and the subtree rooted
430 // at it alone.
431 assert(getParentPad(Memo->second) == getParentPad(UselessPad));
432 continue;
433 }
434 // We know we don't have information for UselesPad. If it has an entry in
435 // the MemoMap (mapping it to nullptr), it must be one of the TempMemos
436 // added on this invocation of getUnwindDestToken; if a previous invocation
437 // recorded nullptr, it would have had to prove that the ancestors of
438 // UselessPad, which include LastUselessPad, had no information, and that
439 // in turn would have required proving that the descendants of
440 // LastUselesPad, which include EHPad, have no information about
441 // LastUselessPad, which would imply that EHPad was mapped to nullptr in
442 // the MemoMap on that invocation, which isn't the case if we got here.
443 assert(!MemoMap.count(UselessPad) || TempMemos.count(UselessPad));
444 // Assert as we enumerate users that 'UselessPad' doesn't have any unwind
445 // information that we'd be contradicting by making a map entry for it
446 // (which is something that getUnwindDestTokenHelper must have proved for
447 // us to get here). Just assert on is direct users here; the checks in
448 // this downward walk at its descendants will verify that they don't have
449 // any unwind edges that exit 'UselessPad' either (i.e. they either have no
450 // unwind edges or unwind to a sibling).
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000451 MemoMap[UselessPad] = UnwindDestToken;
452 if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(UselessPad)) {
Joseph Tremoulete92e0a92016-09-04 01:23:20 +0000453 assert(CatchSwitch->getUnwindDest() == nullptr && "Expected useless pad");
454 for (BasicBlock *HandlerBlock : CatchSwitch->handlers()) {
455 auto *CatchPad = HandlerBlock->getFirstNonPHI();
456 for (User *U : CatchPad->users()) {
457 assert(
458 (!isa<InvokeInst>(U) ||
459 (getParentPad(
460 cast<InvokeInst>(U)->getUnwindDest()->getFirstNonPHI()) ==
461 CatchPad)) &&
462 "Expected useless pad");
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000463 if (isa<CatchSwitchInst>(U) || isa<CleanupPadInst>(U))
464 Worklist.push_back(cast<Instruction>(U));
Joseph Tremoulete92e0a92016-09-04 01:23:20 +0000465 }
466 }
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000467 } else {
468 assert(isa<CleanupPadInst>(UselessPad));
Joseph Tremoulete92e0a92016-09-04 01:23:20 +0000469 for (User *U : UselessPad->users()) {
470 assert(!isa<CleanupReturnInst>(U) && "Expected useless pad");
471 assert((!isa<InvokeInst>(U) ||
472 (getParentPad(
473 cast<InvokeInst>(U)->getUnwindDest()->getFirstNonPHI()) ==
474 UselessPad)) &&
475 "Expected useless pad");
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000476 if (isa<CatchSwitchInst>(U) || isa<CleanupPadInst>(U))
477 Worklist.push_back(cast<Instruction>(U));
Joseph Tremoulete92e0a92016-09-04 01:23:20 +0000478 }
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000479 }
480 }
481
482 return UnwindDestToken;
483}
484
Sanjay Patel0fdb4372015-03-10 19:42:57 +0000485/// When we inline a basic block into an invoke,
486/// we have to turn all of the calls that can throw into invokes.
487/// This function analyze BB to see if there are any calls, and if so,
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000488/// it rewrites them to be invokes that jump to InvokeDest and fills in the PHI
Chris Lattner8900f3e2009-09-01 18:44:06 +0000489/// nodes in that block with the values specified in InvokeDestPHIValues.
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000490static BasicBlock *HandleCallsInBlockInlinedThroughInvoke(
491 BasicBlock *BB, BasicBlock *UnwindEdge,
492 UnwindDestMemoTy *FuncletUnwindMap = nullptr) {
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000493 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000494 Instruction *I = &*BBI++;
Bill Wendling55421f02011-08-14 08:01:36 +0000495
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000496 // We only need to check for function calls: inlined invoke
497 // instructions require no special handling.
498 CallInst *CI = dyn_cast<CallInst>(I);
John McCallbd04b742011-05-27 18:34:38 +0000499
Manman Ren87a2adc2013-10-31 21:56:03 +0000500 if (!CI || CI->doesNotThrow() || isa<InlineAsm>(CI->getCalledValue()))
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000501 continue;
Bill Wendling518a2052012-01-31 01:05:20 +0000502
Sanjoy Dasb51325d2016-03-11 19:08:34 +0000503 // We do not need to (and in fact, cannot) convert possibly throwing calls
Sanjoy Das021de052016-03-31 00:18:46 +0000504 // to @llvm.experimental_deoptimize (resp. @llvm.experimental.guard) into
505 // invokes. The caller's "segment" of the deoptimization continuation
506 // attached to the newly inlined @llvm.experimental_deoptimize
507 // (resp. @llvm.experimental.guard) call should contain the exception
508 // handling logic, if any.
Sanjoy Dasb51325d2016-03-11 19:08:34 +0000509 if (auto *F = CI->getCalledFunction())
Sanjoy Das021de052016-03-31 00:18:46 +0000510 if (F->getIntrinsicID() == Intrinsic::experimental_deoptimize ||
511 F->getIntrinsicID() == Intrinsic::experimental_guard)
Sanjoy Dasb51325d2016-03-11 19:08:34 +0000512 continue;
513
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000514 if (auto FuncletBundle = CI->getOperandBundle(LLVMContext::OB_funclet)) {
515 // This call is nested inside a funclet. If that funclet has an unwind
516 // destination within the inlinee, then unwinding out of this call would
517 // be UB. Rewriting this call to an invoke which targets the inlined
518 // invoke's unwind dest would give the call's parent funclet multiple
519 // unwind destinations, which is something that subsequent EH table
520 // generation can't handle and that the veirifer rejects. So when we
521 // see such a call, leave it as a call.
522 auto *FuncletPad = cast<Instruction>(FuncletBundle->Inputs[0]);
523 Value *UnwindDestToken =
524 getUnwindDestToken(FuncletPad, *FuncletUnwindMap);
525 if (UnwindDestToken && !isa<ConstantTokenNone>(UnwindDestToken))
526 continue;
527#ifndef NDEBUG
528 Instruction *MemoKey;
529 if (auto *CatchPad = dyn_cast<CatchPadInst>(FuncletPad))
530 MemoKey = CatchPad->getCatchSwitch();
531 else
532 MemoKey = FuncletPad;
533 assert(FuncletUnwindMap->count(MemoKey) &&
534 (*FuncletUnwindMap)[MemoKey] == UnwindDestToken &&
535 "must get memoized to avoid confusing later searches");
536#endif // NDEBUG
537 }
538
Kuba Breckaddfdba32016-11-14 21:41:13 +0000539 changeToInvokeAndSplitBasicBlock(CI, UnwindEdge);
David Majnemer654e1302015-07-31 17:58:14 +0000540 return BB;
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000541 }
David Majnemer654e1302015-07-31 17:58:14 +0000542 return nullptr;
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000543}
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000544
Sanjay Patel0fdb4372015-03-10 19:42:57 +0000545/// If we inlined an invoke site, we need to convert calls
Bill Wendling0aef16a2012-02-06 21:44:22 +0000546/// in the body of the inlined function into invokes.
Chris Lattner908d7952006-01-13 19:05:59 +0000547///
Nick Lewycky12a130b2009-02-03 04:34:40 +0000548/// II is the invoke instruction being inlined. FirstNewBlock is the first
Chris Lattner908d7952006-01-13 19:05:59 +0000549/// block of the inlined code (the last block is the end of the function),
550/// and InlineCodeInfo is information about the code that got inlined.
David Majnemer654e1302015-07-31 17:58:14 +0000551static void HandleInlinedLandingPad(InvokeInst *II, BasicBlock *FirstNewBlock,
552 ClonedCodeInfo &InlinedCodeInfo) {
Chris Lattner908d7952006-01-13 19:05:59 +0000553 BasicBlock *InvokeDest = II->getUnwindDest();
Chris Lattner908d7952006-01-13 19:05:59 +0000554
555 Function *Caller = FirstNewBlock->getParent();
Duncan Sands7c8fb1a2008-09-05 12:37:12 +0000556
Chris Lattner908d7952006-01-13 19:05:59 +0000557 // The inlined code is currently at the end of the function, scan from the
558 // start of the inlined code to its end, checking for stuff we need to
Bill Wendling173c71f2013-03-21 23:30:12 +0000559 // rewrite.
David Majnemer654e1302015-07-31 17:58:14 +0000560 LandingPadInliningInfo Invoke(II);
Bill Wendling173c71f2013-03-21 23:30:12 +0000561
Bill Wendling56f15bf2013-03-22 20:31:05 +0000562 // Get all of the inlined landing pad instructions.
563 SmallPtrSet<LandingPadInst*, 16> InlinedLPads;
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000564 for (Function::iterator I = FirstNewBlock->getIterator(), E = Caller->end();
565 I != E; ++I)
Bill Wendling56f15bf2013-03-22 20:31:05 +0000566 if (InvokeInst *II = dyn_cast<InvokeInst>(I->getTerminator()))
567 InlinedLPads.insert(II->getLandingPadInst());
568
Mark Seabornef3dbb92013-12-08 00:50:58 +0000569 // Append the clauses from the outer landing pad instruction into the inlined
570 // landing pad instructions.
571 LandingPadInst *OuterLPad = Invoke.getLandingPadInst();
Craig Topper46276792014-08-24 23:23:06 +0000572 for (LandingPadInst *InlinedLPad : InlinedLPads) {
Mark Seabornef3dbb92013-12-08 00:50:58 +0000573 unsigned OuterNum = OuterLPad->getNumClauses();
574 InlinedLPad->reserveClauses(OuterNum);
575 for (unsigned OuterIdx = 0; OuterIdx != OuterNum; ++OuterIdx)
576 InlinedLPad->addClause(OuterLPad->getClause(OuterIdx));
Mark Seaborn1b3dd352013-12-08 00:51:21 +0000577 if (OuterLPad->isCleanup())
578 InlinedLPad->setCleanup(true);
Mark Seabornef3dbb92013-12-08 00:50:58 +0000579 }
580
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000581 for (Function::iterator BB = FirstNewBlock->getIterator(), E = Caller->end();
582 BB != E; ++BB) {
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000583 if (InlinedCodeInfo.ContainsCalls)
David Majnemer654e1302015-07-31 17:58:14 +0000584 if (BasicBlock *NewBB = HandleCallsInBlockInlinedThroughInvoke(
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000585 &*BB, Invoke.getOuterResumeDest()))
David Majnemer654e1302015-07-31 17:58:14 +0000586 // Update any PHI nodes in the exceptional block to indicate that there
587 // is now a new entry in them.
588 Invoke.addIncomingPHIValuesFor(NewBB);
Duncan Sands7c8fb1a2008-09-05 12:37:12 +0000589
Bill Wendling173c71f2013-03-21 23:30:12 +0000590 // Forward any resumes that are remaining here.
Bill Wendling621699d2012-01-31 01:14:49 +0000591 if (ResumeInst *RI = dyn_cast<ResumeInst>(BB->getTerminator()))
Bill Wendling56f15bf2013-03-22 20:31:05 +0000592 Invoke.forwardResume(RI, InlinedLPads);
Chris Lattner908d7952006-01-13 19:05:59 +0000593 }
594
595 // Now that everything is happy, we have one final detail. The PHI nodes in
596 // the exception destination block still have entries due to the original
Bill Wendling173c71f2013-03-21 23:30:12 +0000597 // invoke instruction. Eliminate these entries (which might even delete the
Chris Lattner908d7952006-01-13 19:05:59 +0000598 // PHI node) now.
599 InvokeDest->removePredecessor(II->getParent());
600}
601
David Majnemer654e1302015-07-31 17:58:14 +0000602/// If we inlined an invoke site, we need to convert calls
603/// in the body of the inlined function into invokes.
604///
605/// II is the invoke instruction being inlined. FirstNewBlock is the first
606/// block of the inlined code (the last block is the end of the function),
607/// and InlineCodeInfo is information about the code that got inlined.
608static void HandleInlinedEHPad(InvokeInst *II, BasicBlock *FirstNewBlock,
609 ClonedCodeInfo &InlinedCodeInfo) {
610 BasicBlock *UnwindDest = II->getUnwindDest();
611 Function *Caller = FirstNewBlock->getParent();
612
613 assert(UnwindDest->getFirstNonPHI()->isEHPad() && "unexpected BasicBlock!");
614
615 // If there are PHI nodes in the unwind destination block, we need to keep
616 // track of which values came into them from the invoke before removing the
617 // edge from this block.
618 SmallVector<Value *, 8> UnwindDestPHIValues;
619 llvm::BasicBlock *InvokeBB = II->getParent();
620 for (Instruction &I : *UnwindDest) {
621 // Save the value to use for this edge.
622 PHINode *PHI = dyn_cast<PHINode>(&I);
623 if (!PHI)
624 break;
625 UnwindDestPHIValues.push_back(PHI->getIncomingValueForBlock(InvokeBB));
626 }
627
628 // Add incoming-PHI values to the unwind destination block for the given basic
629 // block, using the values for the original invoke's source block.
630 auto UpdatePHINodes = [&](BasicBlock *Src) {
631 BasicBlock::iterator I = UnwindDest->begin();
632 for (Value *V : UnwindDestPHIValues) {
633 PHINode *PHI = cast<PHINode>(I);
634 PHI->addIncoming(V, Src);
635 ++I;
636 }
637 };
638
David Majnemer8a1c45d2015-12-12 05:38:55 +0000639 // This connects all the instructions which 'unwind to caller' to the invoke
640 // destination.
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000641 UnwindDestMemoTy FuncletUnwindMap;
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000642 for (Function::iterator BB = FirstNewBlock->getIterator(), E = Caller->end();
643 BB != E; ++BB) {
David Majnemer654e1302015-07-31 17:58:14 +0000644 if (auto *CRI = dyn_cast<CleanupReturnInst>(BB->getTerminator())) {
645 if (CRI->unwindsToCaller()) {
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000646 auto *CleanupPad = CRI->getCleanupPad();
647 CleanupReturnInst::Create(CleanupPad, UnwindDest, CRI);
David Majnemer654e1302015-07-31 17:58:14 +0000648 CRI->eraseFromParent();
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000649 UpdatePHINodes(&*BB);
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000650 // Finding a cleanupret with an unwind destination would confuse
651 // subsequent calls to getUnwindDestToken, so map the cleanuppad
652 // to short-circuit any such calls and recognize this as an "unwind
653 // to caller" cleanup.
654 assert(!FuncletUnwindMap.count(CleanupPad) ||
655 isa<ConstantTokenNone>(FuncletUnwindMap[CleanupPad]));
656 FuncletUnwindMap[CleanupPad] =
657 ConstantTokenNone::get(Caller->getContext());
David Majnemer654e1302015-07-31 17:58:14 +0000658 }
659 }
David Majnemer8a1c45d2015-12-12 05:38:55 +0000660
661 Instruction *I = BB->getFirstNonPHI();
662 if (!I->isEHPad())
663 continue;
664
665 Instruction *Replacement = nullptr;
David Majnemerbbfc7212015-12-14 18:34:23 +0000666 if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(I)) {
David Majnemer8a1c45d2015-12-12 05:38:55 +0000667 if (CatchSwitch->unwindsToCaller()) {
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000668 Value *UnwindDestToken;
669 if (auto *ParentPad =
670 dyn_cast<Instruction>(CatchSwitch->getParentPad())) {
671 // This catchswitch is nested inside another funclet. If that
672 // funclet has an unwind destination within the inlinee, then
673 // unwinding out of this catchswitch would be UB. Rewriting this
674 // catchswitch to unwind to the inlined invoke's unwind dest would
675 // give the parent funclet multiple unwind destinations, which is
676 // something that subsequent EH table generation can't handle and
677 // that the veirifer rejects. So when we see such a call, leave it
678 // as "unwind to caller".
679 UnwindDestToken = getUnwindDestToken(ParentPad, FuncletUnwindMap);
680 if (UnwindDestToken && !isa<ConstantTokenNone>(UnwindDestToken))
681 continue;
682 } else {
683 // This catchswitch has no parent to inherit constraints from, and
684 // none of its descendants can have an unwind edge that exits it and
685 // targets another funclet in the inlinee. It may or may not have a
686 // descendant that definitively has an unwind to caller. In either
687 // case, we'll have to assume that any unwinds out of it may need to
688 // be routed to the caller, so treat it as though it has a definitive
689 // unwind to caller.
690 UnwindDestToken = ConstantTokenNone::get(Caller->getContext());
691 }
David Majnemer8a1c45d2015-12-12 05:38:55 +0000692 auto *NewCatchSwitch = CatchSwitchInst::Create(
693 CatchSwitch->getParentPad(), UnwindDest,
694 CatchSwitch->getNumHandlers(), CatchSwitch->getName(),
695 CatchSwitch);
696 for (BasicBlock *PadBB : CatchSwitch->handlers())
697 NewCatchSwitch->addHandler(PadBB);
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000698 // Propagate info for the old catchswitch over to the new one in
699 // the unwind map. This also serves to short-circuit any subsequent
700 // checks for the unwind dest of this catchswitch, which would get
701 // confused if they found the outer handler in the callee.
702 FuncletUnwindMap[NewCatchSwitch] = UnwindDestToken;
David Majnemer8a1c45d2015-12-12 05:38:55 +0000703 Replacement = NewCatchSwitch;
704 }
705 } else if (!isa<FuncletPadInst>(I)) {
706 llvm_unreachable("unexpected EHPad!");
707 }
708
709 if (Replacement) {
710 Replacement->takeName(I);
711 I->replaceAllUsesWith(Replacement);
712 I->eraseFromParent();
713 UpdatePHINodes(&*BB);
714 }
David Majnemer654e1302015-07-31 17:58:14 +0000715 }
716
717 if (InlinedCodeInfo.ContainsCalls)
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000718 for (Function::iterator BB = FirstNewBlock->getIterator(),
719 E = Caller->end();
720 BB != E; ++BB)
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000721 if (BasicBlock *NewBB = HandleCallsInBlockInlinedThroughInvoke(
722 &*BB, UnwindDest, &FuncletUnwindMap))
David Majnemer654e1302015-07-31 17:58:14 +0000723 // Update any PHI nodes in the exceptional block to indicate that there
724 // is now a new entry in them.
725 UpdatePHINodes(NewBB);
726
727 // Now that everything is happy, we have one final detail. The PHI nodes in
728 // the exception destination block still have entries due to the original
729 // invoke instruction. Eliminate these entries (which might even delete the
730 // PHI node) now.
731 UnwindDest->removePredecessor(InvokeBB);
732}
733
Hal Finkel50316d92016-04-28 23:00:04 +0000734/// When inlining a call site that has !llvm.mem.parallel_loop_access metadata,
735/// that metadata should be propagated to all memory-accessing cloned
736/// instructions.
737static void PropagateParallelLoopAccessMetadata(CallSite CS,
738 ValueToValueMapTy &VMap) {
739 MDNode *M =
740 CS.getInstruction()->getMetadata(LLVMContext::MD_mem_parallel_loop_access);
741 if (!M)
742 return;
743
744 for (ValueToValueMapTy::iterator VMI = VMap.begin(), VMIE = VMap.end();
745 VMI != VMIE; ++VMI) {
746 if (!VMI->second)
747 continue;
748
749 Instruction *NI = dyn_cast<Instruction>(VMI->second);
750 if (!NI)
751 continue;
752
753 if (MDNode *PM = NI->getMetadata(LLVMContext::MD_mem_parallel_loop_access)) {
754 M = MDNode::concatenate(PM, M);
755 NI->setMetadata(LLVMContext::MD_mem_parallel_loop_access, M);
756 } else if (NI->mayReadOrWriteMemory()) {
757 NI->setMetadata(LLVMContext::MD_mem_parallel_loop_access, M);
758 }
759 }
760}
761
Sanjay Patel0fdb4372015-03-10 19:42:57 +0000762/// When inlining a function that contains noalias scope metadata,
763/// this metadata needs to be cloned so that the inlined blocks
Sanjay Patel65d533c2017-01-02 19:05:11 +0000764/// have different "unique scopes" at every call site. Were this not done, then
Hal Finkel94146652014-07-24 14:25:39 +0000765/// aliasing scopes from a function inlined into a caller multiple times could
766/// not be differentiated (and this would lead to miscompiles because the
767/// non-aliasing property communicated by the metadata could have
768/// call-site-specific control dependencies).
769static void CloneAliasScopeMetadata(CallSite CS, ValueToValueMapTy &VMap) {
770 const Function *CalledFunc = CS.getCalledFunction();
771 SetVector<const MDNode *> MD;
772
773 // Note: We could only clone the metadata if it is already used in the
774 // caller. I'm omitting that check here because it might confuse
775 // inter-procedural alias analysis passes. We can revisit this if it becomes
776 // an efficiency or overhead problem.
777
Benjamin Kramer135f7352016-06-26 12:28:59 +0000778 for (const BasicBlock &I : *CalledFunc)
779 for (const Instruction &J : I) {
780 if (const MDNode *M = J.getMetadata(LLVMContext::MD_alias_scope))
Hal Finkel94146652014-07-24 14:25:39 +0000781 MD.insert(M);
Benjamin Kramer135f7352016-06-26 12:28:59 +0000782 if (const MDNode *M = J.getMetadata(LLVMContext::MD_noalias))
Hal Finkel94146652014-07-24 14:25:39 +0000783 MD.insert(M);
784 }
785
786 if (MD.empty())
787 return;
788
789 // Walk the existing metadata, adding the complete (perhaps cyclic) chain to
790 // the set.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000791 SmallVector<const Metadata *, 16> Queue(MD.begin(), MD.end());
Hal Finkel94146652014-07-24 14:25:39 +0000792 while (!Queue.empty()) {
793 const MDNode *M = cast<MDNode>(Queue.pop_back_val());
794 for (unsigned i = 0, ie = M->getNumOperands(); i != ie; ++i)
795 if (const MDNode *M1 = dyn_cast<MDNode>(M->getOperand(i)))
796 if (MD.insert(M1))
797 Queue.push_back(M1);
798 }
799
800 // Now we have a complete set of all metadata in the chains used to specify
801 // the noalias scopes and the lists of those scopes.
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000802 SmallVector<TempMDTuple, 16> DummyNodes;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000803 DenseMap<const MDNode *, TrackingMDNodeRef> MDMap;
Benjamin Kramer135f7352016-06-26 12:28:59 +0000804 for (const MDNode *I : MD) {
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000805 DummyNodes.push_back(MDTuple::getTemporary(CalledFunc->getContext(), None));
Benjamin Kramer135f7352016-06-26 12:28:59 +0000806 MDMap[I].reset(DummyNodes.back().get());
Hal Finkel94146652014-07-24 14:25:39 +0000807 }
808
809 // Create new metadata nodes to replace the dummy nodes, replacing old
810 // metadata references with either a dummy node or an already-created new
811 // node.
Benjamin Kramer135f7352016-06-26 12:28:59 +0000812 for (const MDNode *I : MD) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000813 SmallVector<Metadata *, 4> NewOps;
Benjamin Kramer135f7352016-06-26 12:28:59 +0000814 for (unsigned i = 0, ie = I->getNumOperands(); i != ie; ++i) {
815 const Metadata *V = I->getOperand(i);
Hal Finkel94146652014-07-24 14:25:39 +0000816 if (const MDNode *M = dyn_cast<MDNode>(V))
817 NewOps.push_back(MDMap[M]);
818 else
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000819 NewOps.push_back(const_cast<Metadata *>(V));
Hal Finkel94146652014-07-24 14:25:39 +0000820 }
821
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000822 MDNode *NewM = MDNode::get(CalledFunc->getContext(), NewOps);
Benjamin Kramer135f7352016-06-26 12:28:59 +0000823 MDTuple *TempM = cast<MDTuple>(MDMap[I]);
Duncan P. N. Exon Smith946fdcc2015-01-19 20:36:39 +0000824 assert(TempM->isTemporary() && "Expected temporary node");
Hal Finkel94146652014-07-24 14:25:39 +0000825
826 TempM->replaceAllUsesWith(NewM);
827 }
828
829 // Now replace the metadata in the new inlined instructions with the
830 // repacements from the map.
831 for (ValueToValueMapTy::iterator VMI = VMap.begin(), VMIE = VMap.end();
832 VMI != VMIE; ++VMI) {
833 if (!VMI->second)
834 continue;
835
836 Instruction *NI = dyn_cast<Instruction>(VMI->second);
837 if (!NI)
838 continue;
839
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000840 if (MDNode *M = NI->getMetadata(LLVMContext::MD_alias_scope)) {
Hal Finkel61c38612014-08-14 21:09:37 +0000841 MDNode *NewMD = MDMap[M];
842 // If the call site also had alias scope metadata (a list of scopes to
843 // which instructions inside it might belong), propagate those scopes to
844 // the inlined instructions.
845 if (MDNode *CSM =
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000846 CS.getInstruction()->getMetadata(LLVMContext::MD_alias_scope))
Hal Finkel61c38612014-08-14 21:09:37 +0000847 NewMD = MDNode::concatenate(NewMD, CSM);
848 NI->setMetadata(LLVMContext::MD_alias_scope, NewMD);
849 } else if (NI->mayReadOrWriteMemory()) {
850 if (MDNode *M =
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000851 CS.getInstruction()->getMetadata(LLVMContext::MD_alias_scope))
Hal Finkel61c38612014-08-14 21:09:37 +0000852 NI->setMetadata(LLVMContext::MD_alias_scope, M);
853 }
Hal Finkel94146652014-07-24 14:25:39 +0000854
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000855 if (MDNode *M = NI->getMetadata(LLVMContext::MD_noalias)) {
Hal Finkel61c38612014-08-14 21:09:37 +0000856 MDNode *NewMD = MDMap[M];
857 // If the call site also had noalias metadata (a list of scopes with
858 // which instructions inside it don't alias), propagate those scopes to
859 // the inlined instructions.
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000860 if (MDNode *CSM =
861 CS.getInstruction()->getMetadata(LLVMContext::MD_noalias))
Hal Finkel61c38612014-08-14 21:09:37 +0000862 NewMD = MDNode::concatenate(NewMD, CSM);
863 NI->setMetadata(LLVMContext::MD_noalias, NewMD);
864 } else if (NI->mayReadOrWriteMemory()) {
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000865 if (MDNode *M = CS.getInstruction()->getMetadata(LLVMContext::MD_noalias))
Hal Finkel61c38612014-08-14 21:09:37 +0000866 NI->setMetadata(LLVMContext::MD_noalias, M);
867 }
Hal Finkel94146652014-07-24 14:25:39 +0000868 }
Hal Finkel94146652014-07-24 14:25:39 +0000869}
870
Sanjay Patel0fdb4372015-03-10 19:42:57 +0000871/// If the inlined function has noalias arguments,
872/// then add new alias scopes for each noalias argument, tag the mapped noalias
Hal Finkelff0bcb62014-07-25 15:50:08 +0000873/// parameters with noalias metadata specifying the new scope, and tag all
874/// non-derived loads, stores and memory intrinsics with the new alias scopes.
875static void AddAliasScopeMetadata(CallSite CS, ValueToValueMapTy &VMap,
Chandler Carruth7b560d42015-09-09 17:55:00 +0000876 const DataLayout &DL, AAResults *CalleeAAR) {
Hal Finkelff0bcb62014-07-25 15:50:08 +0000877 if (!EnableNoAliasConversion)
878 return;
879
880 const Function *CalledFunc = CS.getCalledFunction();
881 SmallVector<const Argument *, 4> NoAliasArgs;
882
Sanjay Patel42c73552016-01-13 22:16:48 +0000883 for (const Argument &Arg : CalledFunc->args())
884 if (Arg.hasNoAliasAttr() && !Arg.use_empty())
885 NoAliasArgs.push_back(&Arg);
Hal Finkelff0bcb62014-07-25 15:50:08 +0000886
887 if (NoAliasArgs.empty())
888 return;
889
890 // To do a good job, if a noalias variable is captured, we need to know if
891 // the capture point dominates the particular use we're considering.
892 DominatorTree DT;
893 DT.recalculate(const_cast<Function&>(*CalledFunc));
894
895 // noalias indicates that pointer values based on the argument do not alias
896 // pointer values which are not based on it. So we add a new "scope" for each
897 // noalias function argument. Accesses using pointers based on that argument
898 // become part of that alias scope, accesses using pointers not based on that
899 // argument are tagged as noalias with that scope.
900
901 DenseMap<const Argument *, MDNode *> NewScopes;
902 MDBuilder MDB(CalledFunc->getContext());
903
904 // Create a new scope domain for this function.
905 MDNode *NewDomain =
906 MDB.createAnonymousAliasScopeDomain(CalledFunc->getName());
907 for (unsigned i = 0, e = NoAliasArgs.size(); i != e; ++i) {
908 const Argument *A = NoAliasArgs[i];
909
910 std::string Name = CalledFunc->getName();
911 if (A->hasName()) {
912 Name += ": %";
913 Name += A->getName();
914 } else {
915 Name += ": argument ";
916 Name += utostr(i);
917 }
918
919 // Note: We always create a new anonymous root here. This is true regardless
920 // of the linkage of the callee because the aliasing "scope" is not just a
921 // property of the callee, but also all control dependencies in the caller.
922 MDNode *NewScope = MDB.createAnonymousAliasScope(NewDomain, Name);
923 NewScopes.insert(std::make_pair(A, NewScope));
924 }
925
926 // Iterate over all new instructions in the map; for all memory-access
927 // instructions, add the alias scope metadata.
928 for (ValueToValueMapTy::iterator VMI = VMap.begin(), VMIE = VMap.end();
929 VMI != VMIE; ++VMI) {
930 if (const Instruction *I = dyn_cast<Instruction>(VMI->first)) {
931 if (!VMI->second)
932 continue;
933
934 Instruction *NI = dyn_cast<Instruction>(VMI->second);
935 if (!NI)
936 continue;
937
Hal Finkel0c083022014-09-01 09:01:39 +0000938 bool IsArgMemOnlyCall = false, IsFuncCall = false;
Hal Finkelff0bcb62014-07-25 15:50:08 +0000939 SmallVector<const Value *, 2> PtrArgs;
940
941 if (const LoadInst *LI = dyn_cast<LoadInst>(I))
942 PtrArgs.push_back(LI->getPointerOperand());
943 else if (const StoreInst *SI = dyn_cast<StoreInst>(I))
944 PtrArgs.push_back(SI->getPointerOperand());
945 else if (const VAArgInst *VAAI = dyn_cast<VAArgInst>(I))
946 PtrArgs.push_back(VAAI->getPointerOperand());
947 else if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(I))
948 PtrArgs.push_back(CXI->getPointerOperand());
949 else if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(I))
950 PtrArgs.push_back(RMWI->getPointerOperand());
Hal Finkeld2dee162014-08-14 16:44:03 +0000951 else if (ImmutableCallSite ICS = ImmutableCallSite(I)) {
Hal Finkela3708df2014-08-30 12:48:33 +0000952 // If we know that the call does not access memory, then we'll still
953 // know that about the inlined clone of this call site, and we don't
954 // need to add metadata.
Hal Finkeld2dee162014-08-14 16:44:03 +0000955 if (ICS.doesNotAccessMemory())
956 continue;
957
Hal Finkel0c083022014-09-01 09:01:39 +0000958 IsFuncCall = true;
Chandler Carruth7b560d42015-09-09 17:55:00 +0000959 if (CalleeAAR) {
960 FunctionModRefBehavior MRB = CalleeAAR->getModRefBehavior(ICS);
Chandler Carruth194f59c2015-07-22 23:15:57 +0000961 if (MRB == FMRB_OnlyAccessesArgumentPointees ||
962 MRB == FMRB_OnlyReadsArgumentPointees)
Hal Finkel0c083022014-09-01 09:01:39 +0000963 IsArgMemOnlyCall = true;
964 }
965
Sanjay Patele01dcab2016-01-13 21:39:26 +0000966 for (Value *Arg : ICS.args()) {
Hal Finkela3708df2014-08-30 12:48:33 +0000967 // We need to check the underlying objects of all arguments, not just
968 // the pointer arguments, because we might be passing pointers as
969 // integers, etc.
Hal Finkel0c083022014-09-01 09:01:39 +0000970 // However, if we know that the call only accesses pointer arguments,
Hal Finkeld2dee162014-08-14 16:44:03 +0000971 // then we only need to check the pointer arguments.
Sanjay Patele01dcab2016-01-13 21:39:26 +0000972 if (IsArgMemOnlyCall && !Arg->getType()->isPointerTy())
Hal Finkel0c083022014-09-01 09:01:39 +0000973 continue;
Hal Finkelff0bcb62014-07-25 15:50:08 +0000974
Sanjay Patele01dcab2016-01-13 21:39:26 +0000975 PtrArgs.push_back(Arg);
Hal Finkel0c083022014-09-01 09:01:39 +0000976 }
977 }
Hal Finkelcbb85f22014-09-01 04:26:40 +0000978
Hal Finkelff0bcb62014-07-25 15:50:08 +0000979 // If we found no pointers, then this instruction is not suitable for
980 // pairing with an instruction to receive aliasing metadata.
Hal Finkeld2dee162014-08-14 16:44:03 +0000981 // However, if this is a call, this we might just alias with none of the
982 // noalias arguments.
Hal Finkelcbb85f22014-09-01 04:26:40 +0000983 if (PtrArgs.empty() && !IsFuncCall)
Hal Finkelff0bcb62014-07-25 15:50:08 +0000984 continue;
985
986 // It is possible that there is only one underlying object, but you
987 // need to go through several PHIs to see it, and thus could be
988 // repeated in the Objects list.
989 SmallPtrSet<const Value *, 4> ObjSet;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000990 SmallVector<Metadata *, 4> Scopes, NoAliases;
Hal Finkelff0bcb62014-07-25 15:50:08 +0000991
992 SmallSetVector<const Argument *, 4> NAPtrArgs;
Sanjay Patele01dcab2016-01-13 21:39:26 +0000993 for (const Value *V : PtrArgs) {
Hal Finkelff0bcb62014-07-25 15:50:08 +0000994 SmallVector<Value *, 4> Objects;
Sanjay Patele01dcab2016-01-13 21:39:26 +0000995 GetUnderlyingObjects(const_cast<Value*>(V),
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000996 Objects, DL, /* LI = */ nullptr);
Hal Finkelff0bcb62014-07-25 15:50:08 +0000997
998 for (Value *O : Objects)
999 ObjSet.insert(O);
1000 }
1001
Hal Finkel2d3d6da2014-08-29 16:33:41 +00001002 // Figure out if we're derived from anything that is not a noalias
Hal Finkelff0bcb62014-07-25 15:50:08 +00001003 // argument.
Hal Finkela3708df2014-08-30 12:48:33 +00001004 bool CanDeriveViaCapture = false, UsesAliasingPtr = false;
1005 for (const Value *V : ObjSet) {
1006 // Is this value a constant that cannot be derived from any pointer
1007 // value (we need to exclude constant expressions, for example, that
1008 // are formed from arithmetic on global symbols).
1009 bool IsNonPtrConst = isa<ConstantInt>(V) || isa<ConstantFP>(V) ||
1010 isa<ConstantPointerNull>(V) ||
1011 isa<ConstantDataVector>(V) || isa<UndefValue>(V);
Hal Finkelcbb85f22014-09-01 04:26:40 +00001012 if (IsNonPtrConst)
1013 continue;
1014
1015 // If this is anything other than a noalias argument, then we cannot
1016 // completely describe the aliasing properties using alias.scope
1017 // metadata (and, thus, won't add any).
1018 if (const Argument *A = dyn_cast<Argument>(V)) {
1019 if (!A->hasNoAliasAttr())
1020 UsesAliasingPtr = true;
1021 } else {
Hal Finkela3708df2014-08-30 12:48:33 +00001022 UsesAliasingPtr = true;
Hal Finkelff0bcb62014-07-25 15:50:08 +00001023 }
Hal Finkelcbb85f22014-09-01 04:26:40 +00001024
1025 // If this is not some identified function-local object (which cannot
1026 // directly alias a noalias argument), or some other argument (which,
1027 // by definition, also cannot alias a noalias argument), then we could
1028 // alias a noalias argument that has been captured).
1029 if (!isa<Argument>(V) &&
1030 !isIdentifiedFunctionLocal(const_cast<Value*>(V)))
1031 CanDeriveViaCapture = true;
Hal Finkela3708df2014-08-30 12:48:33 +00001032 }
Hal Finkelcbb85f22014-09-01 04:26:40 +00001033
1034 // A function call can always get captured noalias pointers (via other
1035 // parameters, globals, etc.).
1036 if (IsFuncCall && !IsArgMemOnlyCall)
1037 CanDeriveViaCapture = true;
1038
Hal Finkelff0bcb62014-07-25 15:50:08 +00001039 // First, we want to figure out all of the sets with which we definitely
1040 // don't alias. Iterate over all noalias set, and add those for which:
1041 // 1. The noalias argument is not in the set of objects from which we
1042 // definitely derive.
1043 // 2. The noalias argument has not yet been captured.
Hal Finkelcbb85f22014-09-01 04:26:40 +00001044 // An arbitrary function that might load pointers could see captured
1045 // noalias arguments via other noalias arguments or globals, and so we
1046 // must always check for prior capture.
Hal Finkelff0bcb62014-07-25 15:50:08 +00001047 for (const Argument *A : NoAliasArgs) {
1048 if (!ObjSet.count(A) && (!CanDeriveViaCapture ||
Hal Finkela3708df2014-08-30 12:48:33 +00001049 // It might be tempting to skip the
1050 // PointerMayBeCapturedBefore check if
1051 // A->hasNoCaptureAttr() is true, but this is
1052 // incorrect because nocapture only guarantees
1053 // that no copies outlive the function, not
1054 // that the value cannot be locally captured.
Hal Finkelff0bcb62014-07-25 15:50:08 +00001055 !PointerMayBeCapturedBefore(A,
1056 /* ReturnCaptures */ false,
1057 /* StoreCaptures */ false, I, &DT)))
1058 NoAliases.push_back(NewScopes[A]);
1059 }
1060
1061 if (!NoAliases.empty())
Duncan P. N. Exon Smith3872d002014-11-01 00:10:31 +00001062 NI->setMetadata(LLVMContext::MD_noalias,
1063 MDNode::concatenate(
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001064 NI->getMetadata(LLVMContext::MD_noalias),
Duncan P. N. Exon Smith3872d002014-11-01 00:10:31 +00001065 MDNode::get(CalledFunc->getContext(), NoAliases)));
Hal Finkela3708df2014-08-30 12:48:33 +00001066
Hal Finkelff0bcb62014-07-25 15:50:08 +00001067 // Next, we want to figure out all of the sets to which we might belong.
Hal Finkela3708df2014-08-30 12:48:33 +00001068 // We might belong to a set if the noalias argument is in the set of
1069 // underlying objects. If there is some non-noalias argument in our list
1070 // of underlying objects, then we cannot add a scope because the fact
1071 // that some access does not alias with any set of our noalias arguments
1072 // cannot itself guarantee that it does not alias with this access
1073 // (because there is some pointer of unknown origin involved and the
1074 // other access might also depend on this pointer). We also cannot add
1075 // scopes to arbitrary functions unless we know they don't access any
1076 // non-parameter pointer-values.
1077 bool CanAddScopes = !UsesAliasingPtr;
Hal Finkelcbb85f22014-09-01 04:26:40 +00001078 if (CanAddScopes && IsFuncCall)
1079 CanAddScopes = IsArgMemOnlyCall;
Hal Finkelff0bcb62014-07-25 15:50:08 +00001080
Hal Finkela3708df2014-08-30 12:48:33 +00001081 if (CanAddScopes)
1082 for (const Argument *A : NoAliasArgs) {
1083 if (ObjSet.count(A))
1084 Scopes.push_back(NewScopes[A]);
1085 }
1086
Hal Finkelff0bcb62014-07-25 15:50:08 +00001087 if (!Scopes.empty())
Duncan P. N. Exon Smith3872d002014-11-01 00:10:31 +00001088 NI->setMetadata(
1089 LLVMContext::MD_alias_scope,
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001090 MDNode::concatenate(NI->getMetadata(LLVMContext::MD_alias_scope),
Duncan P. N. Exon Smith3872d002014-11-01 00:10:31 +00001091 MDNode::get(CalledFunc->getContext(), Scopes)));
Hal Finkelff0bcb62014-07-25 15:50:08 +00001092 }
1093 }
1094}
1095
Hal Finkel68dc3c72014-10-15 23:44:41 +00001096/// If the inlined function has non-byval align arguments, then
1097/// add @llvm.assume-based alignment assumptions to preserve this information.
1098static void AddAlignmentAssumptions(CallSite CS, InlineFunctionInfo &IFI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001099 if (!PreserveAlignmentAssumptions || !IFI.GetAssumptionCache)
Hal Finkel68dc3c72014-10-15 23:44:41 +00001100 return;
Sanjay Patelaea60842016-12-31 17:54:05 +00001101
1102 AssumptionCache *AC = &(*IFI.GetAssumptionCache)(*CS.getCaller());
Mehdi Amini46a43552015-03-04 18:43:29 +00001103 auto &DL = CS.getCaller()->getParent()->getDataLayout();
Hal Finkel68dc3c72014-10-15 23:44:41 +00001104
1105 // To avoid inserting redundant assumptions, we should check for assumptions
1106 // already in the caller. To do this, we might need a DT of the caller.
1107 DominatorTree DT;
1108 bool DTCalculated = false;
1109
Chandler Carruth66b31302015-01-04 12:03:27 +00001110 Function *CalledFunc = CS.getCalledFunction();
Sanjay Patelada717e2017-02-15 14:56:11 +00001111 for (Argument &Arg : CalledFunc->args()) {
1112 unsigned Align = Arg.getType()->isPointerTy() ? Arg.getParamAlignment() : 0;
1113 if (Align && !Arg.hasByValOrInAllocaAttr() && !Arg.hasNUses(0)) {
Hal Finkel68dc3c72014-10-15 23:44:41 +00001114 if (!DTCalculated) {
1115 DT.recalculate(const_cast<Function&>(*CS.getInstruction()->getParent()
1116 ->getParent()));
1117 DTCalculated = true;
1118 }
1119
1120 // If we can already prove the asserted alignment in the context of the
1121 // caller, then don't bother inserting the assumption.
Sanjay Patelada717e2017-02-15 14:56:11 +00001122 Value *ArgVal = CS.getArgument(Arg.getArgNo());
1123 if (getKnownAlignment(ArgVal, DL, CS.getInstruction(), AC, &DT) >= Align)
Hal Finkel68dc3c72014-10-15 23:44:41 +00001124 continue;
1125
Sanjay Patelada717e2017-02-15 14:56:11 +00001126 CallInst *NewAsmp = IRBuilder<>(CS.getInstruction())
1127 .CreateAlignmentAssumption(DL, ArgVal, Align);
1128 AC->registerAssumption(NewAsmp);
Hal Finkel68dc3c72014-10-15 23:44:41 +00001129 }
1130 }
1131}
1132
Sanjay Patel0fdb4372015-03-10 19:42:57 +00001133/// Once we have cloned code over from a callee into the caller,
1134/// update the specified callgraph to reflect the changes we made.
1135/// Note that it's possible that not all code was copied over, so only
Duncan Sands46911f12008-09-08 11:05:51 +00001136/// some edges of the callgraph may remain.
1137static void UpdateCallGraphAfterInlining(CallSite CS,
Chris Lattner5de3b8b2006-07-12 18:29:36 +00001138 Function::iterator FirstNewBlock,
Rafael Espindola229e38f2010-10-13 01:36:30 +00001139 ValueToValueMapTy &VMap,
Chris Lattner2eee5d32010-04-22 23:37:35 +00001140 InlineFunctionInfo &IFI) {
1141 CallGraph &CG = *IFI.CG;
Duncan Sands46911f12008-09-08 11:05:51 +00001142 const Function *Caller = CS.getInstruction()->getParent()->getParent();
1143 const Function *Callee = CS.getCalledFunction();
Chris Lattner0841fb12006-01-14 20:07:50 +00001144 CallGraphNode *CalleeNode = CG[Callee];
1145 CallGraphNode *CallerNode = CG[Caller];
Duncan Sands7c8fb1a2008-09-05 12:37:12 +00001146
Chris Lattner5de3b8b2006-07-12 18:29:36 +00001147 // Since we inlined some uninlined call sites in the callee into the caller,
Chris Lattner0841fb12006-01-14 20:07:50 +00001148 // add edges from the caller to all of the callees of the callee.
Gabor Greif5aa19222009-01-15 18:40:09 +00001149 CallGraphNode::iterator I = CalleeNode->begin(), E = CalleeNode->end();
1150
1151 // Consider the case where CalleeNode == CallerNode.
Gabor Greiff1abfdc2009-01-17 00:09:08 +00001152 CallGraphNode::CalledFunctionsVector CallCache;
Gabor Greif5aa19222009-01-15 18:40:09 +00001153 if (CalleeNode == CallerNode) {
1154 CallCache.assign(I, E);
1155 I = CallCache.begin();
1156 E = CallCache.end();
1157 }
1158
1159 for (; I != E; ++I) {
Chris Lattner063d0652009-09-01 06:31:31 +00001160 const Value *OrigCall = I->first;
Duncan Sands7c8fb1a2008-09-05 12:37:12 +00001161
Rafael Espindola229e38f2010-10-13 01:36:30 +00001162 ValueToValueMapTy::iterator VMI = VMap.find(OrigCall);
Chris Lattnerb3c64f72006-07-12 21:37:11 +00001163 // Only copy the edge if the call was inlined!
Craig Topperf40110f2014-04-25 05:29:35 +00001164 if (VMI == VMap.end() || VMI->second == nullptr)
Chris Lattner5eef6ad2009-08-27 03:51:50 +00001165 continue;
1166
1167 // If the call was inlined, but then constant folded, there is no edge to
1168 // add. Check for this case.
Chris Lattner016c00a2010-04-22 21:31:00 +00001169 Instruction *NewCall = dyn_cast<Instruction>(VMI->second);
Sanjay Patelc04b6f22015-03-11 15:12:32 +00001170 if (!NewCall)
1171 continue;
Chris Lattnerc2432b92010-05-01 01:26:13 +00001172
Sanjay Patelc04b6f22015-03-11 15:12:32 +00001173 // We do not treat intrinsic calls like real function calls because we
1174 // expect them to become inline code; do not add an edge for an intrinsic.
1175 CallSite CS = CallSite(NewCall);
1176 if (CS && CS.getCalledFunction() && CS.getCalledFunction()->isIntrinsic())
1177 continue;
1178
Chris Lattnerc2432b92010-05-01 01:26:13 +00001179 // Remember that this call site got inlined for the client of
1180 // InlineFunction.
1181 IFI.InlinedCalls.push_back(NewCall);
1182
Chris Lattner016c00a2010-04-22 21:31:00 +00001183 // It's possible that inlining the callsite will cause it to go from an
1184 // indirect to a direct call by resolving a function pointer. If this
1185 // happens, set the callee of the new call site to a more precise
1186 // destination. This can also happen if the call graph node of the caller
1187 // was just unnecessarily imprecise.
Craig Topperf40110f2014-04-25 05:29:35 +00001188 if (!I->second->getFunction())
Chris Lattner016c00a2010-04-22 21:31:00 +00001189 if (Function *F = CallSite(NewCall).getCalledFunction()) {
1190 // Indirect call site resolved to direct call.
Gabor Greif7b0a5fd2010-07-27 15:02:37 +00001191 CallerNode->addCalledFunction(CallSite(NewCall), CG[F]);
1192
Chris Lattner016c00a2010-04-22 21:31:00 +00001193 continue;
1194 }
Gabor Greif7b0a5fd2010-07-27 15:02:37 +00001195
1196 CallerNode->addCalledFunction(CallSite(NewCall), I->second);
Chris Lattner5de3b8b2006-07-12 18:29:36 +00001197 }
Chris Lattner5eef6ad2009-08-27 03:51:50 +00001198
Dale Johannesen0aeabdf2009-01-13 22:43:37 +00001199 // Update the call graph by deleting the edge from Callee to Caller. We must
1200 // do this after the loop above in case Caller and Callee are the same.
1201 CallerNode->removeCallEdgeFor(CS);
Chris Lattner0841fb12006-01-14 20:07:50 +00001202}
1203
Julien Lerouge957e91c2014-04-15 18:01:54 +00001204static void HandleByValArgumentInit(Value *Dst, Value *Src, Module *M,
1205 BasicBlock *InsertBlock,
1206 InlineFunctionInfo &IFI) {
Julien Lerouge957e91c2014-04-15 18:01:54 +00001207 Type *AggTy = cast<PointerType>(Src->getType())->getElementType();
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001208 IRBuilder<> Builder(InsertBlock, InsertBlock->begin());
Julien Lerouge957e91c2014-04-15 18:01:54 +00001209
Mehdi Amini46a43552015-03-04 18:43:29 +00001210 Value *Size = Builder.getInt64(M->getDataLayout().getTypeStoreSize(AggTy));
Julien Lerouge957e91c2014-04-15 18:01:54 +00001211
1212 // Always generate a memcpy of alignment 1 here because we don't know
1213 // the alignment of the src pointer. Other optimizations can infer
1214 // better alignment.
Pete Cooper67cf9a72015-11-19 05:56:52 +00001215 Builder.CreateMemCpy(Dst, Src, Size, /*Align=*/1);
Julien Lerouge957e91c2014-04-15 18:01:54 +00001216}
1217
Sanjay Patel0fdb4372015-03-10 19:42:57 +00001218/// When inlining a call site that has a byval argument,
Chris Lattner0f114952010-12-20 08:10:40 +00001219/// we have to make the implicit memcpy explicit by adding it.
David Majnemer120f4a02013-11-03 12:22:13 +00001220static Value *HandleByValArgument(Value *Arg, Instruction *TheCall,
Chris Lattner00997442010-12-20 07:57:41 +00001221 const Function *CalledFunc,
1222 InlineFunctionInfo &IFI,
Reid Klecknerdd3f3ed2014-11-04 02:02:14 +00001223 unsigned ByValAlignment) {
Matt Arsenaultbe558882014-04-23 20:58:57 +00001224 PointerType *ArgTy = cast<PointerType>(Arg->getType());
1225 Type *AggTy = ArgTy->getElementType();
Chris Lattner0f114952010-12-20 08:10:40 +00001226
Chandler Carruth66b31302015-01-04 12:03:27 +00001227 Function *Caller = TheCall->getParent()->getParent();
1228
Chris Lattner0f114952010-12-20 08:10:40 +00001229 // If the called function is readonly, then it could not mutate the caller's
1230 // copy of the byval'd memory. In this case, it is safe to elide the copy and
1231 // temporary.
David Majnemer120f4a02013-11-03 12:22:13 +00001232 if (CalledFunc->onlyReadsMemory()) {
Chris Lattner0f114952010-12-20 08:10:40 +00001233 // If the byval argument has a specified alignment that is greater than the
1234 // passed in pointer, then we either have to round up the input pointer or
1235 // give up on this transformation.
1236 if (ByValAlignment <= 1) // 0 = unspecified, 1 = no particular alignment.
David Majnemer120f4a02013-11-03 12:22:13 +00001237 return Arg;
Chris Lattner0f114952010-12-20 08:10:40 +00001238
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001239 AssumptionCache *AC =
1240 IFI.GetAssumptionCache ? &(*IFI.GetAssumptionCache)(*Caller) : nullptr;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001241 const DataLayout &DL = Caller->getParent()->getDataLayout();
1242
Chris Lattner20fca482010-12-25 20:42:38 +00001243 // If the pointer is already known to be sufficiently aligned, or if we can
1244 // round it up to a larger alignment, then we don't need a temporary.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001245 if (getOrEnforceKnownAlignment(Arg, ByValAlignment, DL, TheCall, AC) >=
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001246 ByValAlignment)
David Majnemer120f4a02013-11-03 12:22:13 +00001247 return Arg;
Chris Lattner0f114952010-12-20 08:10:40 +00001248
Chris Lattner20fca482010-12-25 20:42:38 +00001249 // Otherwise, we have to make a memcpy to get a safe alignment. This is bad
1250 // for code quality, but rarely happens and is required for correctness.
Chris Lattner0f114952010-12-20 08:10:40 +00001251 }
Chris Lattner00997442010-12-20 07:57:41 +00001252
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001253 // Create the alloca. If we have DataLayout, use nice alignment.
Mehdi Amini46a43552015-03-04 18:43:29 +00001254 unsigned Align =
1255 Caller->getParent()->getDataLayout().getPrefTypeAlignment(AggTy);
1256
Chris Lattner00997442010-12-20 07:57:41 +00001257 // If the byval had an alignment specified, we *must* use at least that
1258 // alignment, as it is required by the byval argument (and uses of the
1259 // pointer inside the callee).
1260 Align = std::max(Align, ByValAlignment);
1261
Craig Topperf40110f2014-04-25 05:29:35 +00001262 Value *NewAlloca = new AllocaInst(AggTy, nullptr, Align, Arg->getName(),
Chris Lattner00997442010-12-20 07:57:41 +00001263 &*Caller->begin()->begin());
Julien Lerougebe4fe322014-04-15 18:06:46 +00001264 IFI.StaticAllocas.push_back(cast<AllocaInst>(NewAlloca));
Chris Lattner00997442010-12-20 07:57:41 +00001265
1266 // Uses of the argument in the function should use our new alloca
1267 // instead.
1268 return NewAlloca;
1269}
1270
Sanjay Patel0fdb4372015-03-10 19:42:57 +00001271// Check whether this Value is used by a lifetime intrinsic.
Nick Lewyckya68ec832011-05-22 05:22:10 +00001272static bool isUsedByLifetimeMarker(Value *V) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001273 for (User *U : V->users()) {
1274 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U)) {
Nick Lewyckya68ec832011-05-22 05:22:10 +00001275 switch (II->getIntrinsicID()) {
1276 default: break;
1277 case Intrinsic::lifetime_start:
1278 case Intrinsic::lifetime_end:
1279 return true;
1280 }
1281 }
1282 }
1283 return false;
1284}
1285
Sanjay Patel0fdb4372015-03-10 19:42:57 +00001286// Check whether the given alloca already has
Nick Lewyckya68ec832011-05-22 05:22:10 +00001287// lifetime.start or lifetime.end intrinsics.
1288static bool hasLifetimeMarkers(AllocaInst *AI) {
Matt Arsenaultbe558882014-04-23 20:58:57 +00001289 Type *Ty = AI->getType();
1290 Type *Int8PtrTy = Type::getInt8PtrTy(Ty->getContext(),
1291 Ty->getPointerAddressSpace());
1292 if (Ty == Int8PtrTy)
Nick Lewyckya68ec832011-05-22 05:22:10 +00001293 return isUsedByLifetimeMarker(AI);
1294
Nick Lewycky9711b5c2011-06-14 00:59:24 +00001295 // Do a scan to find all the casts to i8*.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001296 for (User *U : AI->users()) {
1297 if (U->getType() != Int8PtrTy) continue;
1298 if (U->stripPointerCasts() != AI) continue;
1299 if (isUsedByLifetimeMarker(U))
Nick Lewyckya68ec832011-05-22 05:22:10 +00001300 return true;
1301 }
1302 return false;
1303}
1304
David Blaikiedf706282015-01-21 22:57:29 +00001305/// Rebuild the entire inlined-at chain for this instruction so that the top of
1306/// the chain now is inlined-at the new call site.
1307static DebugLoc
Benjamin Kramerbdc49562016-06-12 15:39:02 +00001308updateInlinedAtInfo(const DebugLoc &DL, DILocation *InlinedAtNode,
1309 LLVMContext &Ctx,
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001310 DenseMap<const DILocation *, DILocation *> &IANodes) {
1311 SmallVector<DILocation *, 3> InlinedAtLocations;
1312 DILocation *Last = InlinedAtNode;
1313 DILocation *CurInlinedAt = DL;
David Blaikiedf706282015-01-21 22:57:29 +00001314
1315 // Gather all the inlined-at nodes
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001316 while (DILocation *IA = CurInlinedAt->getInlinedAt()) {
David Blaikiedf706282015-01-21 22:57:29 +00001317 // Skip any we've already built nodes for
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001318 if (DILocation *Found = IANodes[IA]) {
David Blaikiedf706282015-01-21 22:57:29 +00001319 Last = Found;
1320 break;
1321 }
1322
1323 InlinedAtLocations.push_back(IA);
Duncan P. N. Exon Smithec819c02015-03-30 19:49:49 +00001324 CurInlinedAt = IA;
Devang Patel35797402011-07-08 18:01:31 +00001325 }
Eric Christopherf16bee82012-03-26 19:09:38 +00001326
David Blaikiedf706282015-01-21 22:57:29 +00001327 // Starting from the top, rebuild the nodes to point to the new inlined-at
1328 // location (then rebuilding the rest of the chain behind it) and update the
1329 // map of already-constructed inlined-at nodes.
David Majnemerd7708772016-06-24 04:05:21 +00001330 for (const DILocation *MD : reverse(InlinedAtLocations)) {
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001331 Last = IANodes[MD] = DILocation::getDistinct(
David Blaikiedf706282015-01-21 22:57:29 +00001332 Ctx, MD->getLine(), MD->getColumn(), MD->getScope(), Last);
1333 }
1334
1335 // And finally create the normal location for this instruction, referring to
1336 // the new inlined-at chain.
Duncan P. N. Exon Smithec819c02015-03-30 19:49:49 +00001337 return DebugLoc::get(DL.getLine(), DL.getCol(), DL.getScope(), Last);
Devang Patel35797402011-07-08 18:01:31 +00001338}
1339
Reid Kleckner6ee00a22016-08-12 22:23:04 +00001340/// Return the result of AI->isStaticAlloca() if AI were moved to the entry
1341/// block. Allocas used in inalloca calls and allocas of dynamic array size
1342/// cannot be static.
1343static bool allocaWouldBeStaticInEntry(const AllocaInst *AI ) {
1344 return isa<Constant>(AI->getArraySize()) && !AI->isUsedWithInAlloca();
1345}
1346
Sanjay Patel0fdb4372015-03-10 19:42:57 +00001347/// Update inlined instructions' line numbers to
Devang Patel35797402011-07-08 18:01:31 +00001348/// to encode location where these instructions are inlined.
1349static void fixupLineNumbers(Function *Fn, Function::iterator FI,
Andrea Di Biagio32d5aed2016-12-07 10:37:26 +00001350 Instruction *TheCall, bool CalleeHasDebugInfo) {
Benjamin Kramer4ca41fd2016-06-12 17:30:47 +00001351 const DebugLoc &TheCallDL = TheCall->getDebugLoc();
Duncan P. N. Exon Smithec819c02015-03-30 19:49:49 +00001352 if (!TheCallDL)
Devang Patel35797402011-07-08 18:01:31 +00001353 return;
1354
David Blaikiedf706282015-01-21 22:57:29 +00001355 auto &Ctx = Fn->getContext();
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001356 DILocation *InlinedAtNode = TheCallDL;
David Blaikiedf706282015-01-21 22:57:29 +00001357
1358 // Create a unique call site, not to be confused with any other call from the
1359 // same location.
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001360 InlinedAtNode = DILocation::getDistinct(
David Blaikiedf706282015-01-21 22:57:29 +00001361 Ctx, InlinedAtNode->getLine(), InlinedAtNode->getColumn(),
1362 InlinedAtNode->getScope(), InlinedAtNode->getInlinedAt());
1363
1364 // Cache the inlined-at nodes as they're built so they are reused, without
1365 // this every instruction's inlined-at chain would become distinct from each
1366 // other.
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001367 DenseMap<const DILocation *, DILocation *> IANodes;
David Blaikiedf706282015-01-21 22:57:29 +00001368
Devang Patel35797402011-07-08 18:01:31 +00001369 for (; FI != Fn->end(); ++FI) {
1370 for (BasicBlock::iterator BI = FI->begin(), BE = FI->end();
1371 BI != BE; ++BI) {
Andrea Di Biagioeff22832016-12-07 12:01:45 +00001372 if (DebugLoc DL = BI->getDebugLoc()) {
1373 BI->setDebugLoc(
1374 updateInlinedAtInfo(DL, InlinedAtNode, BI->getContext(), IANodes));
1375 continue;
Devang Patelbb23a4a2011-08-10 21:50:54 +00001376 }
Andrea Di Biagioeff22832016-12-07 12:01:45 +00001377
1378 if (CalleeHasDebugInfo)
1379 continue;
1380
1381 // If the inlined instruction has no line number, make it look as if it
1382 // originates from the call location. This is important for
1383 // ((__always_inline__, __nodebug__)) functions which must use caller
1384 // location for all instructions in their function body.
1385
1386 // Don't update static allocas, as they may get moved later.
1387 if (auto *AI = dyn_cast<AllocaInst>(BI))
1388 if (allocaWouldBeStaticInEntry(AI))
1389 continue;
1390
1391 BI->setDebugLoc(TheCallDL);
Devang Patel35797402011-07-08 18:01:31 +00001392 }
1393 }
1394}
Easwaran Raman12585b02017-01-20 22:44:04 +00001395/// Update the block frequencies of the caller after a callee has been inlined.
1396///
1397/// Each block cloned into the caller has its block frequency scaled by the
1398/// ratio of CallSiteFreq/CalleeEntryFreq. This ensures that the cloned copy of
1399/// callee's entry block gets the same frequency as the callsite block and the
1400/// relative frequencies of all cloned blocks remain the same after cloning.
1401static void updateCallerBFI(BasicBlock *CallSiteBlock,
1402 const ValueToValueMapTy &VMap,
1403 BlockFrequencyInfo *CallerBFI,
1404 BlockFrequencyInfo *CalleeBFI,
1405 const BasicBlock &CalleeEntryBlock) {
1406 SmallPtrSet<BasicBlock *, 16> ClonedBBs;
1407 for (auto const &Entry : VMap) {
1408 if (!isa<BasicBlock>(Entry.first) || !Entry.second)
1409 continue;
1410 auto *OrigBB = cast<BasicBlock>(Entry.first);
1411 auto *ClonedBB = cast<BasicBlock>(Entry.second);
Easwaran Raman5a12f232017-02-14 22:49:28 +00001412 uint64_t Freq = CalleeBFI->getBlockFreq(OrigBB).getFrequency();
1413 if (!ClonedBBs.insert(ClonedBB).second) {
1414 // Multiple blocks in the callee might get mapped to one cloned block in
1415 // the caller since we prune the callee as we clone it. When that happens,
1416 // we want to use the maximum among the original blocks' frequencies.
1417 uint64_t NewFreq = CallerBFI->getBlockFreq(ClonedBB).getFrequency();
1418 if (NewFreq > Freq)
1419 Freq = NewFreq;
1420 }
1421 CallerBFI->setBlockFreq(ClonedBB, Freq);
Easwaran Raman12585b02017-01-20 22:44:04 +00001422 }
1423 BasicBlock *EntryClone = cast<BasicBlock>(VMap.lookup(&CalleeEntryBlock));
1424 CallerBFI->setBlockFreqAndScale(
1425 EntryClone, CallerBFI->getBlockFreq(CallSiteBlock).getFrequency(),
1426 ClonedBBs);
1427}
1428
1429/// Update the entry count of callee after inlining.
1430///
1431/// The callsite's block count is subtracted from the callee's function entry
1432/// count.
1433static void updateCalleeCount(BlockFrequencyInfo &CallerBFI, BasicBlock *CallBB,
1434 Function *Callee) {
1435 // If the callee has a original count of N, and the estimated count of
1436 // callsite is M, the new callee count is set to N - M. M is estimated from
1437 // the caller's entry count, its entry block frequency and the block frequency
1438 // of the callsite.
1439 Optional<uint64_t> CalleeCount = Callee->getEntryCount();
1440 if (!CalleeCount)
1441 return;
1442 Optional<uint64_t> CallSiteCount = CallerBFI.getBlockProfileCount(CallBB);
1443 if (!CallSiteCount)
1444 return;
1445 // Since CallSiteCount is an estimate, it could exceed the original callee
1446 // count and has to be set to 0.
1447 if (CallSiteCount.getValue() > CalleeCount.getValue())
1448 Callee->setEntryCount(0);
1449 else
1450 Callee->setEntryCount(CalleeCount.getValue() - CallSiteCount.getValue());
1451}
Devang Patel35797402011-07-08 18:01:31 +00001452
Sanjay Patel0fdb4372015-03-10 19:42:57 +00001453/// This function inlines the called function into the basic block of the
1454/// caller. This returns false if it is not possible to inline this call.
1455/// The program is still in a well defined state if this occurs though.
Bill Wendlingce0c2292012-01-31 01:01:16 +00001456///
1457/// Note that this only does one level of inlining. For example, if the
1458/// instruction 'call B' is inlined, and 'B' calls 'C', then the call to 'C' now
1459/// exists in the instruction stream. Similarly this will inline a recursive
1460/// function by one level.
Eric Christopherf16bee82012-03-26 19:09:38 +00001461bool llvm::InlineFunction(CallSite CS, InlineFunctionInfo &IFI,
Chandler Carruth7b560d42015-09-09 17:55:00 +00001462 AAResults *CalleeAAR, bool InsertLifetime) {
Chris Lattner0cc265e2003-08-24 06:59:16 +00001463 Instruction *TheCall = CS.getInstruction();
1464 assert(TheCall->getParent() && TheCall->getParent()->getParent() &&
1465 "Instruction not in function!");
Chris Lattner530d4bf2003-05-29 15:11:31 +00001466
Chris Lattner4ba01ec2010-04-22 23:07:58 +00001467 // If IFI has any state in it, zap it before we fill it in.
1468 IFI.reset();
Easwaran Raman12585b02017-01-20 22:44:04 +00001469
1470 Function *CalledFunc = CS.getCalledFunction();
Craig Topperf40110f2014-04-25 05:29:35 +00001471 if (!CalledFunc || // Can't inline external function or indirect
Reid Spencer5301e7c2007-01-30 20:08:39 +00001472 CalledFunc->isDeclaration() || // call, or call to a vararg function!
Eric Christopher1d385382010-03-24 23:35:21 +00001473 CalledFunc->getFunctionType()->isVarArg()) return false;
Chris Lattner530d4bf2003-05-29 15:11:31 +00001474
Sanjoy Das2d161452015-11-18 06:23:38 +00001475 // The inliner does not know how to inline through calls with operand bundles
1476 // in general ...
1477 if (CS.hasOperandBundles()) {
David Majnemer3bb88c02015-12-15 21:27:27 +00001478 for (int i = 0, e = CS.getNumOperandBundles(); i != e; ++i) {
1479 uint32_t Tag = CS.getOperandBundleAt(i).getTagID();
1480 // ... but it knows how to inline through "deopt" operand bundles ...
1481 if (Tag == LLVMContext::OB_deopt)
1482 continue;
1483 // ... and "funclet" operand bundles.
1484 if (Tag == LLVMContext::OB_funclet)
1485 continue;
1486
Sanjoy Das2d161452015-11-18 06:23:38 +00001487 return false;
David Majnemer3bb88c02015-12-15 21:27:27 +00001488 }
Sanjoy Das2d161452015-11-18 06:23:38 +00001489 }
Sanjoy Das0a1bee82015-10-23 20:09:55 +00001490
Duncan Sandsaa31b922007-12-19 21:13:37 +00001491 // If the call to the callee cannot throw, set the 'nounwind' flag on any
1492 // calls that we inline.
1493 bool MarkNoUnwind = CS.doesNotThrow();
1494
Chris Lattner0cc265e2003-08-24 06:59:16 +00001495 BasicBlock *OrigBB = TheCall->getParent();
Chris Lattner530d4bf2003-05-29 15:11:31 +00001496 Function *Caller = OrigBB->getParent();
1497
Gordon Henriksenb969c592007-12-25 03:10:07 +00001498 // GC poses two hazards to inlining, which only occur when the callee has GC:
1499 // 1. If the caller has no GC, then the callee's GC must be propagated to the
1500 // caller.
1501 // 2. If the caller has a differing GC, it is invalid to inline.
Gordon Henriksend930f912008-08-17 18:44:35 +00001502 if (CalledFunc->hasGC()) {
1503 if (!Caller->hasGC())
1504 Caller->setGC(CalledFunc->getGC());
1505 else if (CalledFunc->getGC() != Caller->getGC())
Gordon Henriksenb969c592007-12-25 03:10:07 +00001506 return false;
1507 }
Duncan Sands7c8fb1a2008-09-05 12:37:12 +00001508
Benjamin Kramer4d2b8712011-12-02 18:37:31 +00001509 // Get the personality function from the callee if it contains a landing pad.
David Majnemer7fddecc2015-06-17 20:52:32 +00001510 Constant *CalledPersonality =
David Majnemereba62792015-10-13 22:08:17 +00001511 CalledFunc->hasPersonalityFn()
1512 ? CalledFunc->getPersonalityFn()->stripPointerCasts()
1513 : nullptr;
Benjamin Kramer4d2b8712011-12-02 18:37:31 +00001514
Bill Wendling55421f02011-08-14 08:01:36 +00001515 // Find the personality function used by the landing pads of the caller. If it
1516 // exists, then check to see that it matches the personality function used in
1517 // the callee.
David Majnemer7fddecc2015-06-17 20:52:32 +00001518 Constant *CallerPersonality =
David Majnemereba62792015-10-13 22:08:17 +00001519 Caller->hasPersonalityFn()
1520 ? Caller->getPersonalityFn()->stripPointerCasts()
1521 : nullptr;
David Majnemer7fddecc2015-06-17 20:52:32 +00001522 if (CalledPersonality) {
1523 if (!CallerPersonality)
1524 Caller->setPersonalityFn(CalledPersonality);
1525 // If the personality functions match, then we can perform the
1526 // inlining. Otherwise, we can't inline.
1527 // TODO: This isn't 100% true. Some personality functions are proper
1528 // supersets of others and can be used in place of the other.
1529 else if (CalledPersonality != CallerPersonality)
1530 return false;
Bill Wendlingce0c2292012-01-31 01:01:16 +00001531 }
Bill Wendling55421f02011-08-14 08:01:36 +00001532
David Majnemer8a1c45d2015-12-12 05:38:55 +00001533 // We need to figure out which funclet the callsite was in so that we may
1534 // properly nest the callee.
1535 Instruction *CallSiteEHPad = nullptr;
David Majnemer3bb88c02015-12-15 21:27:27 +00001536 if (CallerPersonality) {
1537 EHPersonality Personality = classifyEHPersonality(CallerPersonality);
David Majnemer8a1c45d2015-12-12 05:38:55 +00001538 if (isFuncletEHPersonality(Personality)) {
David Majnemer3bb88c02015-12-15 21:27:27 +00001539 Optional<OperandBundleUse> ParentFunclet =
1540 CS.getOperandBundle(LLVMContext::OB_funclet);
1541 if (ParentFunclet)
1542 CallSiteEHPad = cast<FuncletPadInst>(ParentFunclet->Inputs.front());
David Majnemer8a1c45d2015-12-12 05:38:55 +00001543
1544 // OK, the inlining site is legal. What about the target function?
1545
1546 if (CallSiteEHPad) {
1547 if (Personality == EHPersonality::MSVC_CXX) {
1548 // The MSVC personality cannot tolerate catches getting inlined into
1549 // cleanup funclets.
1550 if (isa<CleanupPadInst>(CallSiteEHPad)) {
1551 // Ok, the call site is within a cleanuppad. Let's check the callee
1552 // for catchpads.
1553 for (const BasicBlock &CalledBB : *CalledFunc) {
David Majnemer3bb88c02015-12-15 21:27:27 +00001554 if (isa<CatchSwitchInst>(CalledBB.getFirstNonPHI()))
David Majnemer8a1c45d2015-12-12 05:38:55 +00001555 return false;
1556 }
1557 }
1558 } else if (isAsynchronousEHPersonality(Personality)) {
1559 // SEH is even less tolerant, there may not be any sort of exceptional
1560 // funclet in the callee.
1561 for (const BasicBlock &CalledBB : *CalledFunc) {
1562 if (CalledBB.isEHPad())
1563 return false;
1564 }
1565 }
1566 }
1567 }
1568 }
1569
David Majnemer223538f2016-02-23 17:11:04 +00001570 // Determine if we are dealing with a call in an EHPad which does not unwind
1571 // to caller.
1572 bool EHPadForCallUnwindsLocally = false;
1573 if (CallSiteEHPad && CS.isCall()) {
1574 UnwindDestMemoTy FuncletUnwindMap;
1575 Value *CallSiteUnwindDestToken =
1576 getUnwindDestToken(CallSiteEHPad, FuncletUnwindMap);
1577
1578 EHPadForCallUnwindsLocally =
1579 CallSiteUnwindDestToken &&
1580 !isa<ConstantTokenNone>(CallSiteUnwindDestToken);
1581 }
1582
Chris Lattner9fc977e2004-02-04 01:41:09 +00001583 // Get an iterator to the last basic block in the function, which will have
1584 // the new function inlined after it.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001585 Function::iterator LastBlock = --Caller->end();
Chris Lattner9fc977e2004-02-04 01:41:09 +00001586
Chris Lattner18ef3fd2004-02-04 02:51:48 +00001587 // Make sure to capture all of the return instructions from the cloned
Chris Lattner530d4bf2003-05-29 15:11:31 +00001588 // function.
Chris Lattnerd84dbb32009-08-27 04:02:30 +00001589 SmallVector<ReturnInst*, 8> Returns;
Chris Lattner908d7952006-01-13 19:05:59 +00001590 ClonedCodeInfo InlinedFunctionInfo;
Dale Johannesen845e5822009-03-04 02:09:48 +00001591 Function::iterator FirstNewBlock;
Duncan Sandsaa31b922007-12-19 21:13:37 +00001592
Devang Patelb8f11de2010-06-23 23:55:51 +00001593 { // Scope to destroy VMap after cloning.
Rafael Espindola229e38f2010-10-13 01:36:30 +00001594 ValueToValueMapTy VMap;
Julien Lerouge957e91c2014-04-15 18:01:54 +00001595 // Keep a list of pair (dst, src) to emit byval initializations.
1596 SmallVector<std::pair<Value*, Value*>, 4> ByValInit;
Chris Lattnerbe853d72006-05-27 01:28:04 +00001597
Mehdi Amini46a43552015-03-04 18:43:29 +00001598 auto &DL = Caller->getParent()->getDataLayout();
1599
Dan Gohman3ada1e12008-06-20 17:11:32 +00001600 assert(CalledFunc->arg_size() == CS.arg_size() &&
Chris Lattner18ef3fd2004-02-04 02:51:48 +00001601 "No varargs calls can be inlined!");
Duncan Sands7c8fb1a2008-09-05 12:37:12 +00001602
Chris Lattner908117b2008-01-11 06:09:30 +00001603 // Calculate the vector of arguments to pass into the function cloner, which
1604 // matches up the formal to the actual argument values.
Chris Lattner18ef3fd2004-02-04 02:51:48 +00001605 CallSite::arg_iterator AI = CS.arg_begin();
Chris Lattner908117b2008-01-11 06:09:30 +00001606 unsigned ArgNo = 0;
Chris Lattner531f9e92005-03-15 04:54:21 +00001607 for (Function::const_arg_iterator I = CalledFunc->arg_begin(),
Chris Lattner908117b2008-01-11 06:09:30 +00001608 E = CalledFunc->arg_end(); I != E; ++I, ++AI, ++ArgNo) {
1609 Value *ActualArg = *AI;
Duncan Sands7c8fb1a2008-09-05 12:37:12 +00001610
Duncan Sands053c9872008-01-27 18:12:58 +00001611 // When byval arguments actually inlined, we need to make the copy implied
1612 // by them explicit. However, we don't do this if the callee is readonly
1613 // or readnone, because the copy would be unneeded: the callee doesn't
1614 // modify the struct.
Nick Lewycky612d70b2011-11-20 19:09:04 +00001615 if (CS.isByValArgument(ArgNo)) {
David Majnemer120f4a02013-11-03 12:22:13 +00001616 ActualArg = HandleByValArgument(ActualArg, TheCall, CalledFunc, IFI,
Reid Klecknerdd3f3ed2014-11-04 02:02:14 +00001617 CalledFunc->getParamAlignment(ArgNo+1));
Reid Kleckner9b2cc642014-04-21 20:48:47 +00001618 if (ActualArg != *AI)
Julien Lerouge957e91c2014-04-15 18:01:54 +00001619 ByValInit.push_back(std::make_pair(ActualArg, (Value*) *AI));
Chris Lattner908117b2008-01-11 06:09:30 +00001620 }
Duncan Sands7c8fb1a2008-09-05 12:37:12 +00001621
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001622 VMap[&*I] = ActualArg;
Chris Lattner908117b2008-01-11 06:09:30 +00001623 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001624
Hal Finkel68dc3c72014-10-15 23:44:41 +00001625 // Add alignment assumptions if necessary. We do this before the inlined
1626 // instructions are actually cloned into the caller so that we can easily
1627 // check what will be known at the start of the inlined code.
1628 AddAlignmentAssumptions(CS, IFI);
1629
Chris Lattnerbe853d72006-05-27 01:28:04 +00001630 // We want the inliner to prune the code as it copies. We would LOVE to
1631 // have no dead or constant instructions leftover after inlining occurs
1632 // (which can happen, e.g., because an argument was constant), but we'll be
1633 // happy with whatever the cloner can do.
Mehdi Amini46a43552015-03-04 18:43:29 +00001634 CloneAndPruneFunctionInto(Caller, CalledFunc, VMap,
Dan Gohmanca26f792010-08-26 15:41:53 +00001635 /*ModuleLevelChanges=*/false, Returns, ".i",
Easwaran Ramanb1bd3982016-03-08 00:36:35 +00001636 &InlinedFunctionInfo, TheCall);
Chris Lattner5de3b8b2006-07-12 18:29:36 +00001637 // Remember the first block that is newly cloned over.
1638 FirstNewBlock = LastBlock; ++FirstNewBlock;
Duncan Sands7c8fb1a2008-09-05 12:37:12 +00001639
Easwaran Raman12585b02017-01-20 22:44:04 +00001640 if (IFI.CallerBFI != nullptr && IFI.CalleeBFI != nullptr) {
1641 // Update the BFI of blocks cloned into the caller.
1642 updateCallerBFI(OrigBB, VMap, IFI.CallerBFI, IFI.CalleeBFI,
1643 CalledFunc->front());
1644 // Update the profile count of callee.
1645 updateCalleeCount(*IFI.CallerBFI, OrigBB, CalledFunc);
1646 }
1647
Julien Lerouge957e91c2014-04-15 18:01:54 +00001648 // Inject byval arguments initialization.
1649 for (std::pair<Value*, Value*> &Init : ByValInit)
1650 HandleByValArgumentInit(Init.first, Init.second, Caller->getParent(),
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001651 &*FirstNewBlock, IFI);
Julien Lerouge957e91c2014-04-15 18:01:54 +00001652
David Majnemer3bb88c02015-12-15 21:27:27 +00001653 Optional<OperandBundleUse> ParentDeopt =
1654 CS.getOperandBundle(LLVMContext::OB_deopt);
1655 if (ParentDeopt) {
Sanjoy Das2d161452015-11-18 06:23:38 +00001656 SmallVector<OperandBundleDef, 2> OpDefs;
1657
1658 for (auto &VH : InlinedFunctionInfo.OperandBundleCallSites) {
Sanjoy Dasab0626e2015-12-19 22:40:28 +00001659 Instruction *I = dyn_cast_or_null<Instruction>(VH);
1660 if (!I) continue; // instruction was DCE'd or RAUW'ed to undef
Sanjoy Das2d161452015-11-18 06:23:38 +00001661
1662 OpDefs.clear();
1663
1664 CallSite ICS(I);
1665 OpDefs.reserve(ICS.getNumOperandBundles());
1666
1667 for (unsigned i = 0, e = ICS.getNumOperandBundles(); i < e; ++i) {
1668 auto ChildOB = ICS.getOperandBundleAt(i);
1669 if (ChildOB.getTagID() != LLVMContext::OB_deopt) {
1670 // If the inlined call has other operand bundles, let them be
1671 OpDefs.emplace_back(ChildOB);
1672 continue;
1673 }
1674
1675 // It may be useful to separate this logic (of handling operand
1676 // bundles) out to a separate "policy" component if this gets crowded.
1677 // Prepend the parent's deoptimization continuation to the newly
1678 // inlined call's deoptimization continuation.
1679 std::vector<Value *> MergedDeoptArgs;
David Majnemer3bb88c02015-12-15 21:27:27 +00001680 MergedDeoptArgs.reserve(ParentDeopt->Inputs.size() +
Sanjoy Das2d161452015-11-18 06:23:38 +00001681 ChildOB.Inputs.size());
1682
1683 MergedDeoptArgs.insert(MergedDeoptArgs.end(),
David Majnemer3bb88c02015-12-15 21:27:27 +00001684 ParentDeopt->Inputs.begin(),
1685 ParentDeopt->Inputs.end());
Sanjoy Das2d161452015-11-18 06:23:38 +00001686 MergedDeoptArgs.insert(MergedDeoptArgs.end(), ChildOB.Inputs.begin(),
1687 ChildOB.Inputs.end());
1688
Sanjoy Das8da1f952015-12-08 03:50:32 +00001689 OpDefs.emplace_back("deopt", std::move(MergedDeoptArgs));
Sanjoy Das2d161452015-11-18 06:23:38 +00001690 }
1691
1692 Instruction *NewI = nullptr;
1693 if (isa<CallInst>(I))
1694 NewI = CallInst::Create(cast<CallInst>(I), OpDefs, I);
1695 else
1696 NewI = InvokeInst::Create(cast<InvokeInst>(I), OpDefs, I);
1697
1698 // Note: the RAUW does the appropriate fixup in VMap, so we need to do
1699 // this even if the call returns void.
1700 I->replaceAllUsesWith(NewI);
1701
1702 VH = nullptr;
1703 I->eraseFromParent();
1704 }
1705 }
1706
Chris Lattner5de3b8b2006-07-12 18:29:36 +00001707 // Update the callgraph if requested.
Chandler Carruth0ee8bb12016-12-27 01:24:50 +00001708 if (IFI.CG)
Devang Patelb8f11de2010-06-23 23:55:51 +00001709 UpdateCallGraphAfterInlining(CS, FirstNewBlock, VMap, IFI);
Devang Patel35797402011-07-08 18:01:31 +00001710
Andrea Di Biagio32d5aed2016-12-07 10:37:26 +00001711 // For 'nodebug' functions, the associated DISubprogram is always null.
1712 // Conservatively avoid propagating the callsite debug location to
1713 // instructions inlined from a function whose DISubprogram is not null.
1714 fixupLineNumbers(Caller, FirstNewBlock, TheCall,
1715 CalledFunc->getSubprogram() != nullptr);
Hal Finkel94146652014-07-24 14:25:39 +00001716
1717 // Clone existing noalias metadata if necessary.
1718 CloneAliasScopeMetadata(CS, VMap);
Hal Finkelff0bcb62014-07-25 15:50:08 +00001719
1720 // Add noalias metadata if necessary.
Chandler Carruth7b560d42015-09-09 17:55:00 +00001721 AddAliasScopeMetadata(CS, VMap, DL, CalleeAAR);
Hal Finkel74c2f352014-09-07 12:44:26 +00001722
Hal Finkel50316d92016-04-28 23:00:04 +00001723 // Propagate llvm.mem.parallel_loop_access if necessary.
1724 PropagateParallelLoopAccessMetadata(CS, VMap);
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001725
1726 // Register any cloned assumptions.
1727 if (IFI.GetAssumptionCache)
1728 for (BasicBlock &NewBlock :
1729 make_range(FirstNewBlock->getIterator(), Caller->end()))
1730 for (Instruction &I : NewBlock) {
1731 if (auto *II = dyn_cast<IntrinsicInst>(&I))
1732 if (II->getIntrinsicID() == Intrinsic::assume)
1733 (*IFI.GetAssumptionCache)(*Caller).registerAssumption(II);
1734 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001735 }
Duncan Sands7c8fb1a2008-09-05 12:37:12 +00001736
Chris Lattner530d4bf2003-05-29 15:11:31 +00001737 // If there are any alloca instructions in the block that used to be the entry
1738 // block for the callee, move them to the entry block of the caller. First
1739 // calculate which instruction they should be inserted before. We insert the
1740 // instructions at the end of the current alloca list.
Chris Lattner257492c2006-01-13 18:16:48 +00001741 {
Chris Lattner0cc265e2003-08-24 06:59:16 +00001742 BasicBlock::iterator InsertPoint = Caller->begin()->begin();
Chris Lattner18ef3fd2004-02-04 02:51:48 +00001743 for (BasicBlock::iterator I = FirstNewBlock->begin(),
Chris Lattner5eef6ad2009-08-27 03:51:50 +00001744 E = FirstNewBlock->end(); I != E; ) {
1745 AllocaInst *AI = dyn_cast<AllocaInst>(I++);
Craig Topperf40110f2014-04-25 05:29:35 +00001746 if (!AI) continue;
Chris Lattner5eef6ad2009-08-27 03:51:50 +00001747
1748 // If the alloca is now dead, remove it. This often occurs due to code
1749 // specialization.
1750 if (AI->use_empty()) {
1751 AI->eraseFromParent();
1752 continue;
Chris Lattner6ef6d062006-09-13 19:23:57 +00001753 }
Chris Lattner5eef6ad2009-08-27 03:51:50 +00001754
Reid Kleckner6ee00a22016-08-12 22:23:04 +00001755 if (!allocaWouldBeStaticInEntry(AI))
Chris Lattner5eef6ad2009-08-27 03:51:50 +00001756 continue;
1757
Chris Lattnercd3af962010-12-06 07:43:04 +00001758 // Keep track of the static allocas that we inline into the caller.
Chris Lattner4ba01ec2010-04-22 23:07:58 +00001759 IFI.StaticAllocas.push_back(AI);
Chris Lattnerb1cba3f2009-08-27 04:20:52 +00001760
Chris Lattner5eef6ad2009-08-27 03:51:50 +00001761 // Scan for the block of allocas that we can move over, and move them
1762 // all at once.
1763 while (isa<AllocaInst>(I) &&
Reid Kleckner6ee00a22016-08-12 22:23:04 +00001764 allocaWouldBeStaticInEntry(cast<AllocaInst>(I))) {
Chris Lattner4ba01ec2010-04-22 23:07:58 +00001765 IFI.StaticAllocas.push_back(cast<AllocaInst>(I));
Chris Lattner5eef6ad2009-08-27 03:51:50 +00001766 ++I;
Chris Lattnerb1cba3f2009-08-27 04:20:52 +00001767 }
Chris Lattner5eef6ad2009-08-27 03:51:50 +00001768
1769 // Transfer all of the allocas over in a block. Using splice means
1770 // that the instructions aren't removed from the symbol table, then
1771 // reinserted.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001772 Caller->getEntryBlock().getInstList().splice(
1773 InsertPoint, FirstNewBlock->getInstList(), AI->getIterator(), I);
Chris Lattner5eef6ad2009-08-27 03:51:50 +00001774 }
Adrian Prantl4d365252015-01-30 01:55:25 +00001775 // Move any dbg.declares describing the allocas into the entry basic block.
Adrian Prantl3e2659e2015-01-30 19:37:48 +00001776 DIBuilder DIB(*Caller->getParent());
Adrian Prantl133e1022015-01-30 19:42:59 +00001777 for (auto &AI : IFI.StaticAllocas)
1778 replaceDbgDeclareForAlloca(AI, AI, DIB, /*Deref=*/false);
Chris Lattner0cc265e2003-08-24 06:59:16 +00001779 }
Chris Lattner530d4bf2003-05-29 15:11:31 +00001780
Sanjoy Dasb51325d2016-03-11 19:08:34 +00001781 bool InlinedMustTailCalls = false, InlinedDeoptimizeCalls = false;
Reid Klecknerf0915aa2014-05-15 20:11:28 +00001782 if (InlinedFunctionInfo.ContainsCalls) {
Reid Kleckner6af21242014-05-15 20:39:42 +00001783 CallInst::TailCallKind CallSiteTailKind = CallInst::TCK_None;
1784 if (CallInst *CI = dyn_cast<CallInst>(TheCall))
1785 CallSiteTailKind = CI->getTailCallKind();
1786
Reid Klecknerf0915aa2014-05-15 20:11:28 +00001787 for (Function::iterator BB = FirstNewBlock, E = Caller->end(); BB != E;
1788 ++BB) {
1789 for (Instruction &I : *BB) {
1790 CallInst *CI = dyn_cast<CallInst>(&I);
1791 if (!CI)
1792 continue;
1793
Sanjoy Dasb51325d2016-03-11 19:08:34 +00001794 if (Function *F = CI->getCalledFunction())
1795 InlinedDeoptimizeCalls |=
1796 F->getIntrinsicID() == Intrinsic::experimental_deoptimize;
1797
Reid Klecknerf0915aa2014-05-15 20:11:28 +00001798 // We need to reduce the strength of any inlined tail calls. For
1799 // musttail, we have to avoid introducing potential unbounded stack
1800 // growth. For example, if functions 'f' and 'g' are mutually recursive
1801 // with musttail, we can inline 'g' into 'f' so long as we preserve
1802 // musttail on the cloned call to 'f'. If either the inlined call site
1803 // or the cloned call site is *not* musttail, the program already has
1804 // one frame of stack growth, so it's safe to remove musttail. Here is
1805 // a table of example transformations:
1806 //
1807 // f -> musttail g -> musttail f ==> f -> musttail f
1808 // f -> musttail g -> tail f ==> f -> tail f
1809 // f -> g -> musttail f ==> f -> f
1810 // f -> g -> tail f ==> f -> f
1811 CallInst::TailCallKind ChildTCK = CI->getTailCallKind();
1812 ChildTCK = std::min(CallSiteTailKind, ChildTCK);
Reid Klecknerdd3f3ed2014-11-04 02:02:14 +00001813 CI->setTailCallKind(ChildTCK);
Reid Klecknerf0915aa2014-05-15 20:11:28 +00001814 InlinedMustTailCalls |= CI->isMustTailCall();
1815
1816 // Calls inlined through a 'nounwind' call site should be marked
1817 // 'nounwind'.
1818 if (MarkNoUnwind)
1819 CI->setDoesNotThrow();
1820 }
1821 }
1822 }
1823
Nick Lewyckya68ec832011-05-22 05:22:10 +00001824 // Leave lifetime markers for the static alloca's, scoping them to the
1825 // function we just inlined.
Chad Rosier07d37bc2012-02-25 02:56:01 +00001826 if (InsertLifetime && !IFI.StaticAllocas.empty()) {
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001827 IRBuilder<> builder(&FirstNewBlock->front());
Nick Lewyckya68ec832011-05-22 05:22:10 +00001828 for (unsigned ai = 0, ae = IFI.StaticAllocas.size(); ai != ae; ++ai) {
1829 AllocaInst *AI = IFI.StaticAllocas[ai];
Arnold Schwaighoferc9277f42016-09-09 22:40:27 +00001830 // Don't mark swifterror allocas. They can't have bitcast uses.
1831 if (AI->isSwiftError())
1832 continue;
Nick Lewyckya68ec832011-05-22 05:22:10 +00001833
1834 // If the alloca is already scoped to something smaller than the whole
1835 // function then there's no need to add redundant, less accurate markers.
1836 if (hasLifetimeMarkers(AI))
1837 continue;
1838
Alexey Samsonovcfd662f2012-11-13 07:15:32 +00001839 // Try to determine the size of the allocation.
Craig Topperf40110f2014-04-25 05:29:35 +00001840 ConstantInt *AllocaSize = nullptr;
Alexey Samsonovcfd662f2012-11-13 07:15:32 +00001841 if (ConstantInt *AIArraySize =
1842 dyn_cast<ConstantInt>(AI->getArraySize())) {
Mehdi Amini46a43552015-03-04 18:43:29 +00001843 auto &DL = Caller->getParent()->getDataLayout();
1844 Type *AllocaType = AI->getAllocatedType();
1845 uint64_t AllocaTypeSize = DL.getTypeAllocSize(AllocaType);
1846 uint64_t AllocaArraySize = AIArraySize->getLimitedValue();
Akira Hatanaka2cc2b632015-04-20 16:11:05 +00001847
1848 // Don't add markers for zero-sized allocas.
1849 if (AllocaArraySize == 0)
1850 continue;
1851
Mehdi Amini46a43552015-03-04 18:43:29 +00001852 // Check that array size doesn't saturate uint64_t and doesn't
1853 // overflow when it's multiplied by type size.
1854 if (AllocaArraySize != ~0ULL &&
1855 UINT64_MAX / AllocaArraySize >= AllocaTypeSize) {
1856 AllocaSize = ConstantInt::get(Type::getInt64Ty(AI->getContext()),
1857 AllocaArraySize * AllocaTypeSize);
Alexey Samsonovcfd662f2012-11-13 07:15:32 +00001858 }
1859 }
1860
1861 builder.CreateLifetimeStart(AI, AllocaSize);
Reid Kleckner900d46f2014-05-15 21:10:46 +00001862 for (ReturnInst *RI : Returns) {
Sanjoy Das18b92962016-04-01 02:51:26 +00001863 // Don't insert llvm.lifetime.end calls between a musttail or deoptimize
1864 // call and a return. The return kills all local allocas.
Reid Klecknere31acf22014-08-12 00:05:15 +00001865 if (InlinedMustTailCalls &&
1866 RI->getParent()->getTerminatingMustTailCall())
Reid Kleckner900d46f2014-05-15 21:10:46 +00001867 continue;
Sanjoy Das18b92962016-04-01 02:51:26 +00001868 if (InlinedDeoptimizeCalls &&
1869 RI->getParent()->getTerminatingDeoptimizeCall())
1870 continue;
Reid Klecknerf0915aa2014-05-15 20:11:28 +00001871 IRBuilder<>(RI).CreateLifetimeEnd(AI, AllocaSize);
Reid Kleckner900d46f2014-05-15 21:10:46 +00001872 }
Nick Lewyckya68ec832011-05-22 05:22:10 +00001873 }
1874 }
1875
Chris Lattner2be06072006-01-13 19:34:14 +00001876 // If the inlined code contained dynamic alloca instructions, wrap the inlined
1877 // code with llvm.stacksave/llvm.stackrestore intrinsics.
1878 if (InlinedFunctionInfo.ContainsDynamicAllocas) {
1879 Module *M = Caller->getParent();
Chris Lattner2be06072006-01-13 19:34:14 +00001880 // Get the two intrinsics we care about.
Chris Lattner88b36f12009-10-17 05:39:39 +00001881 Function *StackSave = Intrinsic::getDeclaration(M, Intrinsic::stacksave);
1882 Function *StackRestore=Intrinsic::getDeclaration(M,Intrinsic::stackrestore);
Chris Lattner5de3b8b2006-07-12 18:29:36 +00001883
Chris Lattner2be06072006-01-13 19:34:14 +00001884 // Insert the llvm.stacksave.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001885 CallInst *SavedPtr = IRBuilder<>(&*FirstNewBlock, FirstNewBlock->begin())
David Blaikieff6409d2015-05-18 22:13:54 +00001886 .CreateCall(StackSave, {}, "savedstack");
Duncan Sands7c8fb1a2008-09-05 12:37:12 +00001887
Chris Lattner2be06072006-01-13 19:34:14 +00001888 // Insert a call to llvm.stackrestore before any return instructions in the
1889 // inlined function.
Reid Kleckner900d46f2014-05-15 21:10:46 +00001890 for (ReturnInst *RI : Returns) {
Sanjoy Dasf83ab6d2016-04-01 02:51:30 +00001891 // Don't insert llvm.stackrestore calls between a musttail or deoptimize
1892 // call and a return. The return will restore the stack pointer.
Reid Klecknere31acf22014-08-12 00:05:15 +00001893 if (InlinedMustTailCalls && RI->getParent()->getTerminatingMustTailCall())
Reid Kleckner900d46f2014-05-15 21:10:46 +00001894 continue;
Sanjoy Dasf83ab6d2016-04-01 02:51:30 +00001895 if (InlinedDeoptimizeCalls && RI->getParent()->getTerminatingDeoptimizeCall())
1896 continue;
Reid Klecknerf0915aa2014-05-15 20:11:28 +00001897 IRBuilder<>(RI).CreateCall(StackRestore, SavedPtr);
Reid Kleckner900d46f2014-05-15 21:10:46 +00001898 }
Chris Lattner9f3dced2005-05-06 06:47:52 +00001899 }
1900
Joseph Tremouletb41632b2016-01-20 02:15:15 +00001901 // If we are inlining for an invoke instruction, we must make sure to rewrite
1902 // any call instructions into invoke instructions. This is sensitive to which
1903 // funclet pads were top-level in the inlinee, so must be done before
1904 // rewriting the "parent pad" links.
1905 if (auto *II = dyn_cast<InvokeInst>(TheCall)) {
1906 BasicBlock *UnwindDest = II->getUnwindDest();
1907 Instruction *FirstNonPHI = UnwindDest->getFirstNonPHI();
1908 if (isa<LandingPadInst>(FirstNonPHI)) {
1909 HandleInlinedLandingPad(II, &*FirstNewBlock, InlinedFunctionInfo);
1910 } else {
1911 HandleInlinedEHPad(II, &*FirstNewBlock, InlinedFunctionInfo);
1912 }
1913 }
1914
David Majnemer3bb88c02015-12-15 21:27:27 +00001915 // Update the lexical scopes of the new funclets and callsites.
1916 // Anything that had 'none' as its parent is now nested inside the callsite's
1917 // EHPad.
1918
David Majnemer8a1c45d2015-12-12 05:38:55 +00001919 if (CallSiteEHPad) {
1920 for (Function::iterator BB = FirstNewBlock->getIterator(),
1921 E = Caller->end();
1922 BB != E; ++BB) {
David Majnemer3bb88c02015-12-15 21:27:27 +00001923 // Add bundle operands to any top-level call sites.
1924 SmallVector<OperandBundleDef, 1> OpBundles;
1925 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E;) {
1926 Instruction *I = &*BBI++;
1927 CallSite CS(I);
1928 if (!CS)
1929 continue;
1930
1931 // Skip call sites which are nounwind intrinsics.
1932 auto *CalledFn =
1933 dyn_cast<Function>(CS.getCalledValue()->stripPointerCasts());
1934 if (CalledFn && CalledFn->isIntrinsic() && CS.doesNotThrow())
1935 continue;
1936
1937 // Skip call sites which already have a "funclet" bundle.
1938 if (CS.getOperandBundle(LLVMContext::OB_funclet))
1939 continue;
1940
1941 CS.getOperandBundlesAsDefs(OpBundles);
1942 OpBundles.emplace_back("funclet", CallSiteEHPad);
1943
1944 Instruction *NewInst;
1945 if (CS.isCall())
1946 NewInst = CallInst::Create(cast<CallInst>(I), OpBundles, I);
1947 else
1948 NewInst = InvokeInst::Create(cast<InvokeInst>(I), OpBundles, I);
David Majnemer3bb88c02015-12-15 21:27:27 +00001949 NewInst->takeName(I);
1950 I->replaceAllUsesWith(NewInst);
1951 I->eraseFromParent();
1952
1953 OpBundles.clear();
1954 }
1955
David Majnemer223538f2016-02-23 17:11:04 +00001956 // It is problematic if the inlinee has a cleanupret which unwinds to
1957 // caller and we inline it into a call site which doesn't unwind but into
1958 // an EH pad that does. Such an edge must be dynamically unreachable.
1959 // As such, we replace the cleanupret with unreachable.
1960 if (auto *CleanupRet = dyn_cast<CleanupReturnInst>(BB->getTerminator()))
1961 if (CleanupRet->unwindsToCaller() && EHPadForCallUnwindsLocally)
David Majnemere14e7bc2016-06-25 08:19:55 +00001962 changeToUnreachable(CleanupRet, /*UseLLVMTrap=*/false);
David Majnemer223538f2016-02-23 17:11:04 +00001963
David Majnemer8a1c45d2015-12-12 05:38:55 +00001964 Instruction *I = BB->getFirstNonPHI();
1965 if (!I->isEHPad())
1966 continue;
1967
David Majnemerbbfc7212015-12-14 18:34:23 +00001968 if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(I)) {
David Majnemer8a1c45d2015-12-12 05:38:55 +00001969 if (isa<ConstantTokenNone>(CatchSwitch->getParentPad()))
1970 CatchSwitch->setParentPad(CallSiteEHPad);
1971 } else {
1972 auto *FPI = cast<FuncletPadInst>(I);
1973 if (isa<ConstantTokenNone>(FPI->getParentPad()))
1974 FPI->setParentPad(CallSiteEHPad);
1975 }
1976 }
1977 }
1978
Sanjoy Dasb51325d2016-03-11 19:08:34 +00001979 if (InlinedDeoptimizeCalls) {
1980 // We need to at least remove the deoptimizing returns from the Return set,
1981 // so that the control flow from those returns does not get merged into the
1982 // caller (but terminate it instead). If the caller's return type does not
1983 // match the callee's return type, we also need to change the return type of
1984 // the intrinsic.
1985 if (Caller->getReturnType() == TheCall->getType()) {
1986 auto NewEnd = remove_if(Returns, [](ReturnInst *RI) {
1987 return RI->getParent()->getTerminatingDeoptimizeCall() != nullptr;
1988 });
1989 Returns.erase(NewEnd, Returns.end());
1990 } else {
1991 SmallVector<ReturnInst *, 8> NormalReturns;
1992 Function *NewDeoptIntrinsic = Intrinsic::getDeclaration(
1993 Caller->getParent(), Intrinsic::experimental_deoptimize,
1994 {Caller->getReturnType()});
1995
1996 for (ReturnInst *RI : Returns) {
1997 CallInst *DeoptCall = RI->getParent()->getTerminatingDeoptimizeCall();
1998 if (!DeoptCall) {
1999 NormalReturns.push_back(RI);
2000 continue;
2001 }
2002
Sanjoy Dase0aa4142016-05-12 01:17:38 +00002003 // The calling convention on the deoptimize call itself may be bogus,
2004 // since the code we're inlining may have undefined behavior (and may
2005 // never actually execute at runtime); but all
2006 // @llvm.experimental.deoptimize declarations have to have the same
2007 // calling convention in a well-formed module.
2008 auto CallingConv = DeoptCall->getCalledFunction()->getCallingConv();
2009 NewDeoptIntrinsic->setCallingConv(CallingConv);
Sanjoy Dasb51325d2016-03-11 19:08:34 +00002010 auto *CurBB = RI->getParent();
2011 RI->eraseFromParent();
2012
2013 SmallVector<Value *, 4> CallArgs(DeoptCall->arg_begin(),
2014 DeoptCall->arg_end());
2015
2016 SmallVector<OperandBundleDef, 1> OpBundles;
2017 DeoptCall->getOperandBundlesAsDefs(OpBundles);
2018 DeoptCall->eraseFromParent();
2019 assert(!OpBundles.empty() &&
2020 "Expected at least the deopt operand bundle");
2021
2022 IRBuilder<> Builder(CurBB);
Sanjoy Dasdd77e1e2016-04-09 00:22:59 +00002023 CallInst *NewDeoptCall =
Sanjoy Dasb51325d2016-03-11 19:08:34 +00002024 Builder.CreateCall(NewDeoptIntrinsic, CallArgs, OpBundles);
Sanjoy Dasdd77e1e2016-04-09 00:22:59 +00002025 NewDeoptCall->setCallingConv(CallingConv);
Sanjoy Dasb51325d2016-03-11 19:08:34 +00002026 if (NewDeoptCall->getType()->isVoidTy())
2027 Builder.CreateRetVoid();
2028 else
2029 Builder.CreateRet(NewDeoptCall);
2030 }
2031
2032 // Leave behind the normal returns so we can merge control flow.
2033 std::swap(Returns, NormalReturns);
2034 }
2035 }
2036
Reid Klecknerf0915aa2014-05-15 20:11:28 +00002037 // Handle any inlined musttail call sites. In order for a new call site to be
2038 // musttail, the source of the clone and the inlined call site must have been
2039 // musttail. Therefore it's safe to return without merging control into the
2040 // phi below.
2041 if (InlinedMustTailCalls) {
2042 // Check if we need to bitcast the result of any musttail calls.
2043 Type *NewRetTy = Caller->getReturnType();
2044 bool NeedBitCast = !TheCall->use_empty() && TheCall->getType() != NewRetTy;
2045
2046 // Handle the returns preceded by musttail calls separately.
2047 SmallVector<ReturnInst *, 8> NormalReturns;
2048 for (ReturnInst *RI : Returns) {
Reid Klecknere31acf22014-08-12 00:05:15 +00002049 CallInst *ReturnedMustTail =
2050 RI->getParent()->getTerminatingMustTailCall();
Reid Klecknerf0915aa2014-05-15 20:11:28 +00002051 if (!ReturnedMustTail) {
2052 NormalReturns.push_back(RI);
2053 continue;
2054 }
2055 if (!NeedBitCast)
2056 continue;
2057
2058 // Delete the old return and any preceding bitcast.
2059 BasicBlock *CurBB = RI->getParent();
2060 auto *OldCast = dyn_cast_or_null<BitCastInst>(RI->getReturnValue());
2061 RI->eraseFromParent();
2062 if (OldCast)
2063 OldCast->eraseFromParent();
2064
2065 // Insert a new bitcast and return with the right type.
2066 IRBuilder<> Builder(CurBB);
2067 Builder.CreateRet(Builder.CreateBitCast(ReturnedMustTail, NewRetTy));
2068 }
2069
2070 // Leave behind the normal returns so we can merge control flow.
2071 std::swap(Returns, NormalReturns);
2072 }
2073
Chandler Carruth0ee8bb12016-12-27 01:24:50 +00002074 // Now that all of the transforms on the inlined code have taken place but
2075 // before we splice the inlined code into the CFG and lose track of which
2076 // blocks were actually inlined, collect the call sites. We only do this if
2077 // call graph updates weren't requested, as those provide value handle based
2078 // tracking of inlined call sites instead.
2079 if (InlinedFunctionInfo.ContainsCalls && !IFI.CG) {
2080 // Otherwise just collect the raw call sites that were inlined.
2081 for (BasicBlock &NewBB :
2082 make_range(FirstNewBlock->getIterator(), Caller->end()))
2083 for (Instruction &I : NewBB)
2084 if (auto CS = CallSite(&I))
2085 IFI.InlinedCallSites.push_back(CS);
2086 }
2087
Chris Lattner0fa8c7c2004-02-04 04:17:06 +00002088 // If we cloned in _exactly one_ basic block, and if that block ends in a
2089 // return instruction, we splice the body of the inlined callee directly into
2090 // the calling basic block.
2091 if (Returns.size() == 1 && std::distance(FirstNewBlock, Caller->end()) == 1) {
2092 // Move all of the instructions right before the call.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002093 OrigBB->getInstList().splice(TheCall->getIterator(),
2094 FirstNewBlock->getInstList(),
Chris Lattner0fa8c7c2004-02-04 04:17:06 +00002095 FirstNewBlock->begin(), FirstNewBlock->end());
2096 // Remove the cloned basic block.
2097 Caller->getBasicBlockList().pop_back();
Misha Brukmanb1c93172005-04-21 23:48:37 +00002098
Chris Lattner0fa8c7c2004-02-04 04:17:06 +00002099 // If the call site was an invoke instruction, add a branch to the normal
2100 // destination.
Adrian Prantl15db52b2013-04-23 19:56:03 +00002101 if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall)) {
2102 BranchInst *NewBr = BranchInst::Create(II->getNormalDest(), TheCall);
2103 NewBr->setDebugLoc(Returns[0]->getDebugLoc());
2104 }
Chris Lattner0fa8c7c2004-02-04 04:17:06 +00002105
2106 // If the return instruction returned a value, replace uses of the call with
2107 // uses of the returned value.
Devang Patel841322b2008-03-04 21:15:15 +00002108 if (!TheCall->use_empty()) {
2109 ReturnInst *R = Returns[0];
Eli Friedman36b90262009-05-08 00:22:04 +00002110 if (TheCall == R->getReturnValue())
Owen Andersonb292b8c2009-07-30 23:03:37 +00002111 TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
Eli Friedman36b90262009-05-08 00:22:04 +00002112 else
2113 TheCall->replaceAllUsesWith(R->getReturnValue());
Devang Patel841322b2008-03-04 21:15:15 +00002114 }
Chris Lattner0fa8c7c2004-02-04 04:17:06 +00002115 // Since we are now done with the Call/Invoke, we can delete it.
Dan Gohman158ff2c2008-06-21 22:08:46 +00002116 TheCall->eraseFromParent();
Chris Lattner0fa8c7c2004-02-04 04:17:06 +00002117
2118 // Since we are now done with the return instruction, delete it also.
Dan Gohman158ff2c2008-06-21 22:08:46 +00002119 Returns[0]->eraseFromParent();
Chris Lattner0fa8c7c2004-02-04 04:17:06 +00002120
2121 // We are now done with the inlining.
2122 return true;
2123 }
2124
2125 // Otherwise, we have the normal case, of more than one block to inline or
2126 // multiple return sites.
2127
Chris Lattner18ef3fd2004-02-04 02:51:48 +00002128 // We want to clone the entire callee function into the hole between the
2129 // "starter" and "ender" blocks. How we accomplish this depends on whether
2130 // this is an invoke instruction or a call instruction.
2131 BasicBlock *AfterCallBB;
Craig Topperf40110f2014-04-25 05:29:35 +00002132 BranchInst *CreatedBranchToNormalDest = nullptr;
Chris Lattner18ef3fd2004-02-04 02:51:48 +00002133 if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall)) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00002134
Chris Lattner18ef3fd2004-02-04 02:51:48 +00002135 // Add an unconditional branch to make this look like the CallInst case...
Adrian Prantl15db52b2013-04-23 19:56:03 +00002136 CreatedBranchToNormalDest = BranchInst::Create(II->getNormalDest(), TheCall);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002137
Chris Lattner18ef3fd2004-02-04 02:51:48 +00002138 // Split the basic block. This guarantees that no PHI nodes will have to be
2139 // updated due to new incoming edges, and make the invoke case more
2140 // symmetric to the call case.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002141 AfterCallBB =
2142 OrigBB->splitBasicBlock(CreatedBranchToNormalDest->getIterator(),
2143 CalledFunc->getName() + ".exit");
Misha Brukmanb1c93172005-04-21 23:48:37 +00002144
Chris Lattner18ef3fd2004-02-04 02:51:48 +00002145 } else { // It's a call
Chris Lattner0fa8c7c2004-02-04 04:17:06 +00002146 // If this is a call instruction, we need to split the basic block that
2147 // the call lives in.
Chris Lattner18ef3fd2004-02-04 02:51:48 +00002148 //
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002149 AfterCallBB = OrigBB->splitBasicBlock(TheCall->getIterator(),
2150 CalledFunc->getName() + ".exit");
Chris Lattner18ef3fd2004-02-04 02:51:48 +00002151 }
2152
Easwaran Raman12585b02017-01-20 22:44:04 +00002153 if (IFI.CallerBFI) {
2154 // Copy original BB's block frequency to AfterCallBB
2155 IFI.CallerBFI->setBlockFreq(
2156 AfterCallBB, IFI.CallerBFI->getBlockFreq(OrigBB).getFrequency());
2157 }
2158
Chris Lattner0fa8c7c2004-02-04 04:17:06 +00002159 // Change the branch that used to go to AfterCallBB to branch to the first
2160 // basic block of the inlined function.
2161 //
2162 TerminatorInst *Br = OrigBB->getTerminator();
Misha Brukmanb1c93172005-04-21 23:48:37 +00002163 assert(Br && Br->getOpcode() == Instruction::Br &&
Chris Lattner0fa8c7c2004-02-04 04:17:06 +00002164 "splitBasicBlock broken!");
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002165 Br->setOperand(0, &*FirstNewBlock);
Chris Lattner0fa8c7c2004-02-04 04:17:06 +00002166
2167 // Now that the function is correct, make it a little bit nicer. In
2168 // particular, move the basic blocks inserted from the end of the function
2169 // into the space made by splitting the source basic block.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002170 Caller->getBasicBlockList().splice(AfterCallBB->getIterator(),
2171 Caller->getBasicBlockList(), FirstNewBlock,
2172 Caller->end());
Chris Lattner0fa8c7c2004-02-04 04:17:06 +00002173
Chris Lattner18ef3fd2004-02-04 02:51:48 +00002174 // Handle all of the return instructions that we just cloned in, and eliminate
2175 // any users of the original call/invoke instruction.
Chris Lattner229907c2011-07-18 04:54:35 +00002176 Type *RTy = CalledFunc->getReturnType();
Dan Gohman3b18fd72008-06-20 01:03:44 +00002177
Craig Topperf40110f2014-04-25 05:29:35 +00002178 PHINode *PHI = nullptr;
Dan Gohmanfa1211f2008-07-23 00:34:11 +00002179 if (Returns.size() > 1) {
Chris Lattner18ef3fd2004-02-04 02:51:48 +00002180 // The PHI node should go at the front of the new basic block to merge all
2181 // possible incoming values.
Chris Lattner18ef3fd2004-02-04 02:51:48 +00002182 if (!TheCall->use_empty()) {
Jay Foad52131342011-03-30 11:28:46 +00002183 PHI = PHINode::Create(RTy, Returns.size(), TheCall->getName(),
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002184 &AfterCallBB->front());
Dan Gohmanfa1211f2008-07-23 00:34:11 +00002185 // Anything that used the result of the function call should now use the
2186 // PHI node as their operand.
Duncan Sands7c8fb1a2008-09-05 12:37:12 +00002187 TheCall->replaceAllUsesWith(PHI);
Chris Lattner18ef3fd2004-02-04 02:51:48 +00002188 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002189
Gabor Greif5aa19222009-01-15 18:40:09 +00002190 // Loop over all of the return instructions adding entries to the PHI node
2191 // as appropriate.
Dan Gohmanfa1211f2008-07-23 00:34:11 +00002192 if (PHI) {
2193 for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
2194 ReturnInst *RI = Returns[i];
2195 assert(RI->getReturnValue()->getType() == PHI->getType() &&
2196 "Ret value not consistent in function!");
2197 PHI->addIncoming(RI->getReturnValue(), RI->getParent());
Devang Patel780b3ca62008-03-07 20:06:16 +00002198 }
2199 }
2200
Gabor Greif8c573f72009-01-16 23:08:50 +00002201 // Add a branch to the merge points and remove return instructions.
Richard Trieu624c2eb2013-04-30 22:45:10 +00002202 DebugLoc Loc;
Chris Lattner18ef3fd2004-02-04 02:51:48 +00002203 for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
Richard Trieu624c2eb2013-04-30 22:45:10 +00002204 ReturnInst *RI = Returns[i];
Adrian Prantl09416382013-04-30 17:08:16 +00002205 BranchInst* BI = BranchInst::Create(AfterCallBB, RI);
Richard Trieu624c2eb2013-04-30 22:45:10 +00002206 Loc = RI->getDebugLoc();
2207 BI->setDebugLoc(Loc);
Devang Patel64d0f072008-03-10 18:34:00 +00002208 RI->eraseFromParent();
Chris Lattner18ef3fd2004-02-04 02:51:48 +00002209 }
Adrian Prantl09416382013-04-30 17:08:16 +00002210 // We need to set the debug location to *somewhere* inside the
Adrian Prantl8beccf92013-04-30 17:33:32 +00002211 // inlined function. The line number may be nonsensical, but the
Adrian Prantl09416382013-04-30 17:08:16 +00002212 // instruction will at least be associated with the right
2213 // function.
2214 if (CreatedBranchToNormalDest)
Richard Trieu624c2eb2013-04-30 22:45:10 +00002215 CreatedBranchToNormalDest->setDebugLoc(Loc);
Devang Patel64d0f072008-03-10 18:34:00 +00002216 } else if (!Returns.empty()) {
2217 // Otherwise, if there is exactly one return value, just replace anything
2218 // using the return value of the call with the computed value.
Eli Friedman36b90262009-05-08 00:22:04 +00002219 if (!TheCall->use_empty()) {
2220 if (TheCall == Returns[0]->getReturnValue())
Owen Andersonb292b8c2009-07-30 23:03:37 +00002221 TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
Eli Friedman36b90262009-05-08 00:22:04 +00002222 else
2223 TheCall->replaceAllUsesWith(Returns[0]->getReturnValue());
2224 }
Duncan Sands7c8fb1a2008-09-05 12:37:12 +00002225
Jay Foad61ea0e42011-06-23 09:09:15 +00002226 // Update PHI nodes that use the ReturnBB to use the AfterCallBB.
2227 BasicBlock *ReturnBB = Returns[0]->getParent();
2228 ReturnBB->replaceAllUsesWith(AfterCallBB);
2229
Devang Patel64d0f072008-03-10 18:34:00 +00002230 // Splice the code from the return block into the block that it will return
2231 // to, which contains the code that was after the call.
Devang Patel64d0f072008-03-10 18:34:00 +00002232 AfterCallBB->getInstList().splice(AfterCallBB->begin(),
2233 ReturnBB->getInstList());
Duncan Sands7c8fb1a2008-09-05 12:37:12 +00002234
Adrian Prantl15db52b2013-04-23 19:56:03 +00002235 if (CreatedBranchToNormalDest)
2236 CreatedBranchToNormalDest->setDebugLoc(Returns[0]->getDebugLoc());
2237
Devang Patel64d0f072008-03-10 18:34:00 +00002238 // Delete the return instruction now and empty ReturnBB now.
2239 Returns[0]->eraseFromParent();
2240 ReturnBB->eraseFromParent();
Chris Lattner6e79e552004-10-17 23:21:07 +00002241 } else if (!TheCall->use_empty()) {
2242 // No returns, but something is using the return value of the call. Just
2243 // nuke the result.
Owen Andersonb292b8c2009-07-30 23:03:37 +00002244 TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
Chris Lattner18ef3fd2004-02-04 02:51:48 +00002245 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002246
Chris Lattner18ef3fd2004-02-04 02:51:48 +00002247 // Since we are now done with the Call/Invoke, we can delete it.
Chris Lattner6e79e552004-10-17 23:21:07 +00002248 TheCall->eraseFromParent();
Chris Lattner530d4bf2003-05-29 15:11:31 +00002249
Reid Klecknerf0915aa2014-05-15 20:11:28 +00002250 // If we inlined any musttail calls and the original return is now
2251 // unreachable, delete it. It can only contain a bitcast and ret.
Easwaran Ramanb1bd3982016-03-08 00:36:35 +00002252 if (InlinedMustTailCalls && pred_begin(AfterCallBB) == pred_end(AfterCallBB))
Reid Klecknerf0915aa2014-05-15 20:11:28 +00002253 AfterCallBB->eraseFromParent();
2254
Chris Lattnerfc3fe5c2003-08-24 04:06:56 +00002255 // We should always be able to fold the entry block of the function into the
2256 // single predecessor of the block...
Chris Lattner0328d752004-04-16 05:17:59 +00002257 assert(cast<BranchInst>(Br)->isUnconditional() && "splitBasicBlock broken!");
Chris Lattnerfc3fe5c2003-08-24 04:06:56 +00002258 BasicBlock *CalleeEntry = cast<BranchInst>(Br)->getSuccessor(0);
Chris Lattner0fa8c7c2004-02-04 04:17:06 +00002259
Chris Lattner0328d752004-04-16 05:17:59 +00002260 // Splice the code entry block into calling block, right before the
2261 // unconditional branch.
Eric Christopher96513122011-06-23 06:24:52 +00002262 CalleeEntry->replaceAllUsesWith(OrigBB); // Update PHI nodes
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002263 OrigBB->getInstList().splice(Br->getIterator(), CalleeEntry->getInstList());
Chris Lattner0328d752004-04-16 05:17:59 +00002264
2265 // Remove the unconditional branch.
2266 OrigBB->getInstList().erase(Br);
2267
2268 // Now we can remove the CalleeEntry block, which is now empty.
2269 Caller->getBasicBlockList().erase(CalleeEntry);
Duncan Sands7c8fb1a2008-09-05 12:37:12 +00002270
Duncan Sands9d9a4e22010-11-17 11:16:23 +00002271 // If we inserted a phi node, check to see if it has a single value (e.g. all
2272 // the entries are the same or undef). If so, remove the PHI so it doesn't
2273 // block other optimizations.
Bill Wendlingce0c2292012-01-31 01:01:16 +00002274 if (PHI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002275 AssumptionCache *AC =
2276 IFI.GetAssumptionCache ? &(*IFI.GetAssumptionCache)(*Caller) : nullptr;
Mehdi Amini46a43552015-03-04 18:43:29 +00002277 auto &DL = Caller->getParent()->getDataLayout();
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002278 if (Value *V = SimplifyInstruction(PHI, DL, nullptr, nullptr, AC)) {
Duncan Sands9d9a4e22010-11-17 11:16:23 +00002279 PHI->replaceAllUsesWith(V);
2280 PHI->eraseFromParent();
2281 }
Bill Wendlingce0c2292012-01-31 01:01:16 +00002282 }
Duncan Sands9d9a4e22010-11-17 11:16:23 +00002283
Chris Lattner530d4bf2003-05-29 15:11:31 +00002284 return true;
2285}