blob: 0315aac1cf840409a797181843131b36a9079309 [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
Eugene Zelenko6cadde72017-10-17 21:27:42 +000015#include "llvm/ADT/DenseMap.h"
16#include "llvm/ADT/None.h"
17#include "llvm/ADT/Optional.h"
18#include "llvm/ADT/STLExtras.h"
Weiming Zhao45d4cb92015-11-24 18:57:06 +000019#include "llvm/ADT/SetVector.h"
Joseph Tremoulete92e0a92016-09-04 01:23:20 +000020#include "llvm/ADT/SmallPtrSet.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000021#include "llvm/ADT/SmallVector.h"
22#include "llvm/ADT/StringExtras.h"
Eugene Zelenko6cadde72017-10-17 21:27:42 +000023#include "llvm/ADT/iterator_range.h"
Hal Finkelff0bcb62014-07-25 15:50:08 +000024#include "llvm/Analysis/AliasAnalysis.h"
Daniel Jasperaec2fa32016-12-19 08:22:17 +000025#include "llvm/Analysis/AssumptionCache.h"
Easwaran Raman12585b02017-01-20 22:44:04 +000026#include "llvm/Analysis/BlockFrequencyInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000027#include "llvm/Analysis/CallGraph.h"
Hal Finkelff0bcb62014-07-25 15:50:08 +000028#include "llvm/Analysis/CaptureTracking.h"
David Majnemer8a1c45d2015-12-12 05:38:55 +000029#include "llvm/Analysis/EHPersonalities.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000030#include "llvm/Analysis/InstructionSimplify.h"
Dehao Chene5930492017-03-20 16:40:44 +000031#include "llvm/Analysis/ProfileSummaryInfo.h"
David Blaikie31b98d22018-06-04 21:23:21 +000032#include "llvm/Transforms/Utils/Local.h"
Hal Finkel94146652014-07-24 14:25:39 +000033#include "llvm/Analysis/ValueTracking.h"
Eugene Zelenko6cadde72017-10-17 21:27:42 +000034#include "llvm/IR/Argument.h"
35#include "llvm/IR/BasicBlock.h"
Reid Klecknerf0915aa2014-05-15 20:11:28 +000036#include "llvm/IR/CFG.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000037#include "llvm/IR/CallSite.h"
Eugene Zelenko6cadde72017-10-17 21:27:42 +000038#include "llvm/IR/Constant.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000039#include "llvm/IR/Constants.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000040#include "llvm/IR/DIBuilder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000041#include "llvm/IR/DataLayout.h"
Eugene Zelenko6cadde72017-10-17 21:27:42 +000042#include "llvm/IR/DebugInfoMetadata.h"
43#include "llvm/IR/DebugLoc.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000044#include "llvm/IR/DerivedTypes.h"
Hal Finkelff0bcb62014-07-25 15:50:08 +000045#include "llvm/IR/Dominators.h"
Eugene Zelenko6cadde72017-10-17 21:27:42 +000046#include "llvm/IR/Function.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000047#include "llvm/IR/IRBuilder.h"
Eugene Zelenko6cadde72017-10-17 21:27:42 +000048#include "llvm/IR/InstrTypes.h"
49#include "llvm/IR/Instruction.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000050#include "llvm/IR/Instructions.h"
51#include "llvm/IR/IntrinsicInst.h"
52#include "llvm/IR/Intrinsics.h"
Eugene Zelenko6cadde72017-10-17 21:27:42 +000053#include "llvm/IR/LLVMContext.h"
Hal Finkel94146652014-07-24 14:25:39 +000054#include "llvm/IR/MDBuilder.h"
Eugene Zelenko6cadde72017-10-17 21:27:42 +000055#include "llvm/IR/Metadata.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000056#include "llvm/IR/Module.h"
Eugene Zelenko6cadde72017-10-17 21:27:42 +000057#include "llvm/IR/Type.h"
58#include "llvm/IR/User.h"
59#include "llvm/IR/Value.h"
60#include "llvm/Support/Casting.h"
Hal Finkelff0bcb62014-07-25 15:50:08 +000061#include "llvm/Support/CommandLine.h"
Eugene Zelenko6cadde72017-10-17 21:27:42 +000062#include "llvm/Support/ErrorHandling.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000063#include "llvm/Transforms/Utils/Cloning.h"
Eugene Zelenko6cadde72017-10-17 21:27:42 +000064#include "llvm/Transforms/Utils/ValueMapper.h"
Hal Finkelff0bcb62014-07-25 15:50:08 +000065#include <algorithm>
Eugene Zelenko6cadde72017-10-17 21:27:42 +000066#include <cassert>
67#include <cstdint>
68#include <iterator>
69#include <limits>
70#include <string>
71#include <utility>
72#include <vector>
Hans Wennborg083ca9b2015-10-06 23:24:35 +000073
Chris Lattnerdf3c3422004-01-09 06:12:26 +000074using namespace llvm;
Easwaran Ramane5b8de22018-01-17 22:24:23 +000075using ProfileCount = Function::ProfileCount;
Chris Lattner530d4bf2003-05-29 15:11:31 +000076
Hal Finkelff0bcb62014-07-25 15:50:08 +000077static cl::opt<bool>
James Molloy6b95d8e2014-09-04 13:23:08 +000078EnableNoAliasConversion("enable-noalias-to-md-conversion", cl::init(true),
Hal Finkelff0bcb62014-07-25 15:50:08 +000079 cl::Hidden,
80 cl::desc("Convert noalias attributes to metadata during inlining."));
81
Hal Finkel68dc3c72014-10-15 23:44:41 +000082static cl::opt<bool>
83PreserveAlignmentAssumptions("preserve-alignment-assumptions-during-inlining",
84 cl::init(true), cl::Hidden,
85 cl::desc("Convert align attributes to assumptions during inlining."));
86
Eric Christopherf16bee82012-03-26 19:09:38 +000087bool llvm::InlineFunction(CallInst *CI, InlineFunctionInfo &IFI,
Chandler Carruth7b560d42015-09-09 17:55:00 +000088 AAResults *CalleeAAR, bool InsertLifetime) {
89 return InlineFunction(CallSite(CI), IFI, CalleeAAR, InsertLifetime);
Chris Lattner0841fb12006-01-14 20:07:50 +000090}
Eugene Zelenko6cadde72017-10-17 21:27:42 +000091
Eric Christopherf16bee82012-03-26 19:09:38 +000092bool llvm::InlineFunction(InvokeInst *II, InlineFunctionInfo &IFI,
Chandler Carruth7b560d42015-09-09 17:55:00 +000093 AAResults *CalleeAAR, bool InsertLifetime) {
94 return InlineFunction(CallSite(II), IFI, CalleeAAR, InsertLifetime);
Chris Lattner0841fb12006-01-14 20:07:50 +000095}
Chris Lattner0cc265e2003-08-24 06:59:16 +000096
John McCallbd04b742011-05-27 18:34:38 +000097namespace {
Eugene Zelenko6cadde72017-10-17 21:27:42 +000098
David Majnemer654e1302015-07-31 17:58:14 +000099 /// A class for recording information about inlining a landing pad.
100 class LandingPadInliningInfo {
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000101 /// Destination of the invoke's unwind.
102 BasicBlock *OuterResumeDest;
103
104 /// Destination for the callee's resume.
105 BasicBlock *InnerResumeDest = nullptr;
106
107 /// LandingPadInst associated with the invoke.
108 LandingPadInst *CallerLPad = nullptr;
109
110 /// PHI for EH values from landingpad insts.
111 PHINode *InnerEHValuesPHI = nullptr;
112
Bill Wendling0c2d82b2012-01-31 01:22:03 +0000113 SmallVector<Value*, 8> UnwindDestPHIValues;
Bill Wendlingfa284402011-07-28 07:31:46 +0000114
Bill Wendling55421f02011-08-14 08:01:36 +0000115 public:
David Majnemer654e1302015-07-31 17:58:14 +0000116 LandingPadInliningInfo(InvokeInst *II)
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000117 : OuterResumeDest(II->getUnwindDest()) {
Bill Wendling55421f02011-08-14 08:01:36 +0000118 // If there are PHI nodes in the unwind destination block, we need to keep
119 // track of which values came into them from the invoke before removing
120 // the edge from this block.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000121 BasicBlock *InvokeBB = II->getParent();
Bill Wendlingea6e9352012-01-31 01:25:54 +0000122 BasicBlock::iterator I = OuterResumeDest->begin();
Bill Wendling55421f02011-08-14 08:01:36 +0000123 for (; isa<PHINode>(I); ++I) {
John McCallbd04b742011-05-27 18:34:38 +0000124 // Save the value to use for this edge.
Bill Wendling55421f02011-08-14 08:01:36 +0000125 PHINode *PHI = cast<PHINode>(I);
126 UnwindDestPHIValues.push_back(PHI->getIncomingValueForBlock(InvokeBB));
127 }
128
Bill Wendlingf3cae512012-01-31 00:56:53 +0000129 CallerLPad = cast<LandingPadInst>(I);
John McCallbd04b742011-05-27 18:34:38 +0000130 }
131
Sanjay Patel0fdb4372015-03-10 19:42:57 +0000132 /// The outer unwind destination is the target of
Bill Wendlingea6e9352012-01-31 01:25:54 +0000133 /// unwind edges introduced for calls within the inlined function.
Bill Wendling0c2d82b2012-01-31 01:22:03 +0000134 BasicBlock *getOuterResumeDest() const {
Bill Wendlingea6e9352012-01-31 01:25:54 +0000135 return OuterResumeDest;
John McCallbd04b742011-05-27 18:34:38 +0000136 }
137
Bill Wendling3fd879d2012-01-31 01:48:40 +0000138 BasicBlock *getInnerResumeDest();
Bill Wendling55421f02011-08-14 08:01:36 +0000139
140 LandingPadInst *getLandingPadInst() const { return CallerLPad; }
141
Sanjay Patel0fdb4372015-03-10 19:42:57 +0000142 /// Forward the 'resume' instruction to the caller's landing pad block.
143 /// When the landing pad block has only one predecessor, this is
Bill Wendling55421f02011-08-14 08:01:36 +0000144 /// a simple branch. When there is more than one predecessor, we need to
145 /// split the landing pad block after the landingpad instruction and jump
146 /// to there.
Bill Wendling56f15bf2013-03-22 20:31:05 +0000147 void forwardResume(ResumeInst *RI,
Craig Topper71b7b682014-08-21 05:55:13 +0000148 SmallPtrSetImpl<LandingPadInst*> &InlinedLPads);
Bill Wendling55421f02011-08-14 08:01:36 +0000149
Sanjay Patel0fdb4372015-03-10 19:42:57 +0000150 /// Add incoming-PHI values to the unwind destination block for the given
151 /// basic block, using the values for the original invoke's source block.
John McCallbd04b742011-05-27 18:34:38 +0000152 void addIncomingPHIValuesFor(BasicBlock *BB) const {
Bill Wendlingea6e9352012-01-31 01:25:54 +0000153 addIncomingPHIValuesForInto(BB, OuterResumeDest);
John McCall046c47e2011-05-28 07:45:59 +0000154 }
Bill Wendlingad088e62011-07-30 05:42:50 +0000155
John McCall046c47e2011-05-28 07:45:59 +0000156 void addIncomingPHIValuesForInto(BasicBlock *src, BasicBlock *dest) const {
157 BasicBlock::iterator I = dest->begin();
John McCallbd04b742011-05-27 18:34:38 +0000158 for (unsigned i = 0, e = UnwindDestPHIValues.size(); i != e; ++i, ++I) {
Bill Wendlingad088e62011-07-30 05:42:50 +0000159 PHINode *phi = cast<PHINode>(I);
160 phi->addIncoming(UnwindDestPHIValues[i], src);
John McCallbd04b742011-05-27 18:34:38 +0000161 }
162 }
163 };
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000164
165} // end anonymous namespace
John McCallbd04b742011-05-27 18:34:38 +0000166
Sanjay Patel0fdb4372015-03-10 19:42:57 +0000167/// Get or create a target for the branch from ResumeInsts.
David Majnemer654e1302015-07-31 17:58:14 +0000168BasicBlock *LandingPadInliningInfo::getInnerResumeDest() {
Bill Wendling55421f02011-08-14 08:01:36 +0000169 if (InnerResumeDest) return InnerResumeDest;
170
171 // Split the landing pad.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000172 BasicBlock::iterator SplitPoint = ++CallerLPad->getIterator();
Bill Wendling55421f02011-08-14 08:01:36 +0000173 InnerResumeDest =
174 OuterResumeDest->splitBasicBlock(SplitPoint,
175 OuterResumeDest->getName() + ".body");
176
177 // The number of incoming edges we expect to the inner landing pad.
178 const unsigned PHICapacity = 2;
179
180 // Create corresponding new PHIs for all the PHIs in the outer landing pad.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000181 Instruction *InsertPoint = &InnerResumeDest->front();
Bill Wendling55421f02011-08-14 08:01:36 +0000182 BasicBlock::iterator I = OuterResumeDest->begin();
183 for (unsigned i = 0, e = UnwindDestPHIValues.size(); i != e; ++i, ++I) {
184 PHINode *OuterPHI = cast<PHINode>(I);
185 PHINode *InnerPHI = PHINode::Create(OuterPHI->getType(), PHICapacity,
186 OuterPHI->getName() + ".lpad-body",
187 InsertPoint);
188 OuterPHI->replaceAllUsesWith(InnerPHI);
189 InnerPHI->addIncoming(OuterPHI, OuterResumeDest);
190 }
191
192 // Create a PHI for the exception values.
193 InnerEHValuesPHI = PHINode::Create(CallerLPad->getType(), PHICapacity,
194 "eh.lpad-body", InsertPoint);
195 CallerLPad->replaceAllUsesWith(InnerEHValuesPHI);
196 InnerEHValuesPHI->addIncoming(CallerLPad, OuterResumeDest);
197
198 // All done.
199 return InnerResumeDest;
200}
201
Sanjay Patel0fdb4372015-03-10 19:42:57 +0000202/// Forward the 'resume' instruction to the caller's landing pad block.
203/// When the landing pad block has only one predecessor, this is a simple
Bill Wendling55421f02011-08-14 08:01:36 +0000204/// branch. When there is more than one predecessor, we need to split the
205/// landing pad block after the landingpad instruction and jump to there.
David Majnemer654e1302015-07-31 17:58:14 +0000206void LandingPadInliningInfo::forwardResume(
207 ResumeInst *RI, SmallPtrSetImpl<LandingPadInst *> &InlinedLPads) {
Bill Wendling3fd879d2012-01-31 01:48:40 +0000208 BasicBlock *Dest = getInnerResumeDest();
Bill Wendling55421f02011-08-14 08:01:36 +0000209 BasicBlock *Src = RI->getParent();
210
211 BranchInst::Create(Dest, Src);
212
213 // Update the PHIs in the destination. They were inserted in an order which
214 // makes this work.
215 addIncomingPHIValuesForInto(Src, Dest);
216
217 InnerEHValuesPHI->addIncoming(RI->getOperand(0), Src);
218 RI->eraseFromParent();
219}
220
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000221/// Helper for getUnwindDestToken/getUnwindDestTokenHelper.
222static Value *getParentPad(Value *EHPad) {
223 if (auto *FPI = dyn_cast<FuncletPadInst>(EHPad))
224 return FPI->getParentPad();
225 return cast<CatchSwitchInst>(EHPad)->getParentPad();
226}
227
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000228using UnwindDestMemoTy = DenseMap<Instruction *, Value *>;
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000229
230/// Helper for getUnwindDestToken that does the descendant-ward part of
231/// the search.
232static Value *getUnwindDestTokenHelper(Instruction *EHPad,
233 UnwindDestMemoTy &MemoMap) {
234 SmallVector<Instruction *, 8> Worklist(1, EHPad);
235
236 while (!Worklist.empty()) {
237 Instruction *CurrentPad = Worklist.pop_back_val();
238 // We only put pads on the worklist that aren't in the MemoMap. When
239 // we find an unwind dest for a pad we may update its ancestors, but
240 // the queue only ever contains uncles/great-uncles/etc. of CurrentPad,
241 // so they should never get updated while queued on the worklist.
242 assert(!MemoMap.count(CurrentPad));
243 Value *UnwindDestToken = nullptr;
244 if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(CurrentPad)) {
245 if (CatchSwitch->hasUnwindDest()) {
246 UnwindDestToken = CatchSwitch->getUnwindDest()->getFirstNonPHI();
247 } else {
248 // Catchswitch doesn't have a 'nounwind' variant, and one might be
249 // annotated as "unwinds to caller" when really it's nounwind (see
250 // e.g. SimplifyCFGOpt::SimplifyUnreachable), so we can't infer the
251 // parent's unwind dest from this. We can check its catchpads'
252 // descendants, since they might include a cleanuppad with an
253 // "unwinds to caller" cleanupret, which can be trusted.
254 for (auto HI = CatchSwitch->handler_begin(),
255 HE = CatchSwitch->handler_end();
256 HI != HE && !UnwindDestToken; ++HI) {
257 BasicBlock *HandlerBlock = *HI;
258 auto *CatchPad = cast<CatchPadInst>(HandlerBlock->getFirstNonPHI());
259 for (User *Child : CatchPad->users()) {
260 // Intentionally ignore invokes here -- since the catchswitch is
261 // marked "unwind to caller", it would be a verifier error if it
262 // contained an invoke which unwinds out of it, so any invoke we'd
263 // encounter must unwind to some child of the catch.
264 if (!isa<CleanupPadInst>(Child) && !isa<CatchSwitchInst>(Child))
265 continue;
266
267 Instruction *ChildPad = cast<Instruction>(Child);
268 auto Memo = MemoMap.find(ChildPad);
269 if (Memo == MemoMap.end()) {
Joseph Tremoulete92e0a92016-09-04 01:23:20 +0000270 // Haven't figured out this child pad yet; queue it.
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000271 Worklist.push_back(ChildPad);
272 continue;
273 }
274 // We've already checked this child, but might have found that
275 // it offers no proof either way.
276 Value *ChildUnwindDestToken = Memo->second;
277 if (!ChildUnwindDestToken)
278 continue;
279 // We already know the child's unwind dest, which can either
280 // be ConstantTokenNone to indicate unwind to caller, or can
281 // be another child of the catchpad. Only the former indicates
282 // the unwind dest of the catchswitch.
283 if (isa<ConstantTokenNone>(ChildUnwindDestToken)) {
284 UnwindDestToken = ChildUnwindDestToken;
285 break;
286 }
287 assert(getParentPad(ChildUnwindDestToken) == CatchPad);
288 }
289 }
290 }
291 } else {
292 auto *CleanupPad = cast<CleanupPadInst>(CurrentPad);
293 for (User *U : CleanupPad->users()) {
294 if (auto *CleanupRet = dyn_cast<CleanupReturnInst>(U)) {
295 if (BasicBlock *RetUnwindDest = CleanupRet->getUnwindDest())
296 UnwindDestToken = RetUnwindDest->getFirstNonPHI();
297 else
298 UnwindDestToken = ConstantTokenNone::get(CleanupPad->getContext());
299 break;
300 }
301 Value *ChildUnwindDestToken;
302 if (auto *Invoke = dyn_cast<InvokeInst>(U)) {
303 ChildUnwindDestToken = Invoke->getUnwindDest()->getFirstNonPHI();
304 } else if (isa<CleanupPadInst>(U) || isa<CatchSwitchInst>(U)) {
305 Instruction *ChildPad = cast<Instruction>(U);
306 auto Memo = MemoMap.find(ChildPad);
307 if (Memo == MemoMap.end()) {
308 // Haven't resolved this child yet; queue it and keep searching.
309 Worklist.push_back(ChildPad);
310 continue;
311 }
312 // We've checked this child, but still need to ignore it if it
313 // had no proof either way.
314 ChildUnwindDestToken = Memo->second;
315 if (!ChildUnwindDestToken)
316 continue;
317 } else {
318 // Not a relevant user of the cleanuppad
319 continue;
320 }
321 // In a well-formed program, the child/invoke must either unwind to
322 // an(other) child of the cleanup, or exit the cleanup. In the
323 // first case, continue searching.
324 if (isa<Instruction>(ChildUnwindDestToken) &&
325 getParentPad(ChildUnwindDestToken) == CleanupPad)
326 continue;
327 UnwindDestToken = ChildUnwindDestToken;
328 break;
329 }
330 }
331 // If we haven't found an unwind dest for CurrentPad, we may have queued its
332 // children, so move on to the next in the worklist.
333 if (!UnwindDestToken)
334 continue;
335
336 // Now we know that CurrentPad unwinds to UnwindDestToken. It also exits
337 // any ancestors of CurrentPad up to but not including UnwindDestToken's
338 // parent pad. Record this in the memo map, and check to see if the
339 // original EHPad being queried is one of the ones exited.
340 Value *UnwindParent;
341 if (auto *UnwindPad = dyn_cast<Instruction>(UnwindDestToken))
342 UnwindParent = getParentPad(UnwindPad);
343 else
344 UnwindParent = nullptr;
345 bool ExitedOriginalPad = false;
346 for (Instruction *ExitedPad = CurrentPad;
347 ExitedPad && ExitedPad != UnwindParent;
348 ExitedPad = dyn_cast<Instruction>(getParentPad(ExitedPad))) {
349 // Skip over catchpads since they just follow their catchswitches.
350 if (isa<CatchPadInst>(ExitedPad))
351 continue;
352 MemoMap[ExitedPad] = UnwindDestToken;
353 ExitedOriginalPad |= (ExitedPad == EHPad);
354 }
355
356 if (ExitedOriginalPad)
357 return UnwindDestToken;
358
359 // Continue the search.
360 }
361
362 // No definitive information is contained within this funclet.
363 return nullptr;
364}
365
366/// Given an EH pad, find where it unwinds. If it unwinds to an EH pad,
367/// return that pad instruction. If it unwinds to caller, return
368/// ConstantTokenNone. If it does not have a definitive unwind destination,
369/// return nullptr.
370///
371/// This routine gets invoked for calls in funclets in inlinees when inlining
372/// an invoke. Since many funclets don't have calls inside them, it's queried
373/// on-demand rather than building a map of pads to unwind dests up front.
374/// Determining a funclet's unwind dest may require recursively searching its
375/// descendants, and also ancestors and cousins if the descendants don't provide
376/// an answer. Since most funclets will have their unwind dest immediately
377/// available as the unwind dest of a catchswitch or cleanupret, this routine
378/// searches top-down from the given pad and then up. To avoid worst-case
379/// quadratic run-time given that approach, it uses a memo map to avoid
380/// re-processing funclet trees. The callers that rewrite the IR as they go
381/// take advantage of this, for correctness, by checking/forcing rewritten
382/// pads' entries to match the original callee view.
383static Value *getUnwindDestToken(Instruction *EHPad,
384 UnwindDestMemoTy &MemoMap) {
385 // Catchpads unwind to the same place as their catchswitch;
386 // redirct any queries on catchpads so the code below can
387 // deal with just catchswitches and cleanuppads.
388 if (auto *CPI = dyn_cast<CatchPadInst>(EHPad))
389 EHPad = CPI->getCatchSwitch();
390
391 // Check if we've already determined the unwind dest for this pad.
392 auto Memo = MemoMap.find(EHPad);
393 if (Memo != MemoMap.end())
394 return Memo->second;
395
396 // Search EHPad and, if necessary, its descendants.
397 Value *UnwindDestToken = getUnwindDestTokenHelper(EHPad, MemoMap);
398 assert((UnwindDestToken == nullptr) != (MemoMap.count(EHPad) != 0));
399 if (UnwindDestToken)
400 return UnwindDestToken;
401
402 // No information is available for this EHPad from itself or any of its
403 // descendants. An unwind all the way out to a pad in the caller would
404 // need also to agree with the unwind dest of the parent funclet, so
405 // search up the chain to try to find a funclet with information. Put
406 // null entries in the memo map to avoid re-processing as we go up.
407 MemoMap[EHPad] = nullptr;
Joseph Tremoulete92e0a92016-09-04 01:23:20 +0000408#ifndef NDEBUG
409 SmallPtrSet<Instruction *, 4> TempMemos;
410 TempMemos.insert(EHPad);
411#endif
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000412 Instruction *LastUselessPad = EHPad;
413 Value *AncestorToken;
414 for (AncestorToken = getParentPad(EHPad);
415 auto *AncestorPad = dyn_cast<Instruction>(AncestorToken);
416 AncestorToken = getParentPad(AncestorToken)) {
417 // Skip over catchpads since they just follow their catchswitches.
418 if (isa<CatchPadInst>(AncestorPad))
419 continue;
Joseph Tremoulete92e0a92016-09-04 01:23:20 +0000420 // If the MemoMap had an entry mapping AncestorPad to nullptr, since we
421 // haven't yet called getUnwindDestTokenHelper for AncestorPad in this
422 // call to getUnwindDestToken, that would mean that AncestorPad had no
423 // information in itself, its descendants, or its ancestors. If that
424 // were the case, then we should also have recorded the lack of information
425 // for the descendant that we're coming from. So assert that we don't
426 // find a null entry in the MemoMap for AncestorPad.
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000427 assert(!MemoMap.count(AncestorPad) || MemoMap[AncestorPad]);
428 auto AncestorMemo = MemoMap.find(AncestorPad);
429 if (AncestorMemo == MemoMap.end()) {
430 UnwindDestToken = getUnwindDestTokenHelper(AncestorPad, MemoMap);
431 } else {
432 UnwindDestToken = AncestorMemo->second;
433 }
434 if (UnwindDestToken)
435 break;
436 LastUselessPad = AncestorPad;
Joseph Tremoulete92e0a92016-09-04 01:23:20 +0000437 MemoMap[LastUselessPad] = nullptr;
438#ifndef NDEBUG
439 TempMemos.insert(LastUselessPad);
440#endif
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000441 }
442
Joseph Tremoulete92e0a92016-09-04 01:23:20 +0000443 // We know that getUnwindDestTokenHelper was called on LastUselessPad and
444 // returned nullptr (and likewise for EHPad and any of its ancestors up to
445 // LastUselessPad), so LastUselessPad has no information from below. Since
446 // getUnwindDestTokenHelper must investigate all downward paths through
447 // no-information nodes to prove that a node has no information like this,
448 // and since any time it finds information it records it in the MemoMap for
449 // not just the immediately-containing funclet but also any ancestors also
450 // exited, it must be the case that, walking downward from LastUselessPad,
451 // visiting just those nodes which have not been mapped to an unwind dest
452 // by getUnwindDestTokenHelper (the nullptr TempMemos notwithstanding, since
453 // they are just used to keep getUnwindDestTokenHelper from repeating work),
454 // any node visited must have been exhaustively searched with no information
455 // for it found.
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000456 SmallVector<Instruction *, 8> Worklist(1, LastUselessPad);
457 while (!Worklist.empty()) {
458 Instruction *UselessPad = Worklist.pop_back_val();
Joseph Tremoulete92e0a92016-09-04 01:23:20 +0000459 auto Memo = MemoMap.find(UselessPad);
460 if (Memo != MemoMap.end() && Memo->second) {
461 // Here the name 'UselessPad' is a bit of a misnomer, because we've found
462 // that it is a funclet that does have information about unwinding to
463 // a particular destination; its parent was a useless pad.
464 // Since its parent has no information, the unwind edge must not escape
465 // the parent, and must target a sibling of this pad. This local unwind
466 // gives us no information about EHPad. Leave it and the subtree rooted
467 // at it alone.
468 assert(getParentPad(Memo->second) == getParentPad(UselessPad));
469 continue;
470 }
471 // We know we don't have information for UselesPad. If it has an entry in
472 // the MemoMap (mapping it to nullptr), it must be one of the TempMemos
473 // added on this invocation of getUnwindDestToken; if a previous invocation
474 // recorded nullptr, it would have had to prove that the ancestors of
475 // UselessPad, which include LastUselessPad, had no information, and that
476 // in turn would have required proving that the descendants of
477 // LastUselesPad, which include EHPad, have no information about
478 // LastUselessPad, which would imply that EHPad was mapped to nullptr in
479 // the MemoMap on that invocation, which isn't the case if we got here.
480 assert(!MemoMap.count(UselessPad) || TempMemos.count(UselessPad));
481 // Assert as we enumerate users that 'UselessPad' doesn't have any unwind
482 // information that we'd be contradicting by making a map entry for it
483 // (which is something that getUnwindDestTokenHelper must have proved for
484 // us to get here). Just assert on is direct users here; the checks in
485 // this downward walk at its descendants will verify that they don't have
486 // any unwind edges that exit 'UselessPad' either (i.e. they either have no
487 // unwind edges or unwind to a sibling).
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000488 MemoMap[UselessPad] = UnwindDestToken;
489 if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(UselessPad)) {
Joseph Tremoulete92e0a92016-09-04 01:23:20 +0000490 assert(CatchSwitch->getUnwindDest() == nullptr && "Expected useless pad");
491 for (BasicBlock *HandlerBlock : CatchSwitch->handlers()) {
492 auto *CatchPad = HandlerBlock->getFirstNonPHI();
493 for (User *U : CatchPad->users()) {
494 assert(
495 (!isa<InvokeInst>(U) ||
496 (getParentPad(
497 cast<InvokeInst>(U)->getUnwindDest()->getFirstNonPHI()) ==
498 CatchPad)) &&
499 "Expected useless pad");
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000500 if (isa<CatchSwitchInst>(U) || isa<CleanupPadInst>(U))
501 Worklist.push_back(cast<Instruction>(U));
Joseph Tremoulete92e0a92016-09-04 01:23:20 +0000502 }
503 }
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000504 } else {
505 assert(isa<CleanupPadInst>(UselessPad));
Joseph Tremoulete92e0a92016-09-04 01:23:20 +0000506 for (User *U : UselessPad->users()) {
507 assert(!isa<CleanupReturnInst>(U) && "Expected useless pad");
508 assert((!isa<InvokeInst>(U) ||
509 (getParentPad(
510 cast<InvokeInst>(U)->getUnwindDest()->getFirstNonPHI()) ==
511 UselessPad)) &&
512 "Expected useless pad");
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000513 if (isa<CatchSwitchInst>(U) || isa<CleanupPadInst>(U))
514 Worklist.push_back(cast<Instruction>(U));
Joseph Tremoulete92e0a92016-09-04 01:23:20 +0000515 }
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000516 }
517 }
518
519 return UnwindDestToken;
520}
521
Sanjay Patel0fdb4372015-03-10 19:42:57 +0000522/// When we inline a basic block into an invoke,
523/// we have to turn all of the calls that can throw into invokes.
524/// This function analyze BB to see if there are any calls, and if so,
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000525/// it rewrites them to be invokes that jump to InvokeDest and fills in the PHI
Chris Lattner8900f3e2009-09-01 18:44:06 +0000526/// nodes in that block with the values specified in InvokeDestPHIValues.
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000527static BasicBlock *HandleCallsInBlockInlinedThroughInvoke(
528 BasicBlock *BB, BasicBlock *UnwindEdge,
529 UnwindDestMemoTy *FuncletUnwindMap = nullptr) {
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000530 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000531 Instruction *I = &*BBI++;
Bill Wendling55421f02011-08-14 08:01:36 +0000532
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000533 // We only need to check for function calls: inlined invoke
534 // instructions require no special handling.
535 CallInst *CI = dyn_cast<CallInst>(I);
John McCallbd04b742011-05-27 18:34:38 +0000536
Manman Ren87a2adc2013-10-31 21:56:03 +0000537 if (!CI || CI->doesNotThrow() || isa<InlineAsm>(CI->getCalledValue()))
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000538 continue;
Bill Wendling518a2052012-01-31 01:05:20 +0000539
Sanjoy Dasb51325d2016-03-11 19:08:34 +0000540 // We do not need to (and in fact, cannot) convert possibly throwing calls
Sanjoy Das021de052016-03-31 00:18:46 +0000541 // to @llvm.experimental_deoptimize (resp. @llvm.experimental.guard) into
542 // invokes. The caller's "segment" of the deoptimization continuation
543 // attached to the newly inlined @llvm.experimental_deoptimize
544 // (resp. @llvm.experimental.guard) call should contain the exception
545 // handling logic, if any.
Sanjoy Dasb51325d2016-03-11 19:08:34 +0000546 if (auto *F = CI->getCalledFunction())
Sanjoy Das021de052016-03-31 00:18:46 +0000547 if (F->getIntrinsicID() == Intrinsic::experimental_deoptimize ||
548 F->getIntrinsicID() == Intrinsic::experimental_guard)
Sanjoy Dasb51325d2016-03-11 19:08:34 +0000549 continue;
550
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000551 if (auto FuncletBundle = CI->getOperandBundle(LLVMContext::OB_funclet)) {
552 // This call is nested inside a funclet. If that funclet has an unwind
553 // destination within the inlinee, then unwinding out of this call would
554 // be UB. Rewriting this call to an invoke which targets the inlined
555 // invoke's unwind dest would give the call's parent funclet multiple
556 // unwind destinations, which is something that subsequent EH table
557 // generation can't handle and that the veirifer rejects. So when we
558 // see such a call, leave it as a call.
559 auto *FuncletPad = cast<Instruction>(FuncletBundle->Inputs[0]);
560 Value *UnwindDestToken =
561 getUnwindDestToken(FuncletPad, *FuncletUnwindMap);
562 if (UnwindDestToken && !isa<ConstantTokenNone>(UnwindDestToken))
563 continue;
564#ifndef NDEBUG
565 Instruction *MemoKey;
566 if (auto *CatchPad = dyn_cast<CatchPadInst>(FuncletPad))
567 MemoKey = CatchPad->getCatchSwitch();
568 else
569 MemoKey = FuncletPad;
570 assert(FuncletUnwindMap->count(MemoKey) &&
571 (*FuncletUnwindMap)[MemoKey] == UnwindDestToken &&
572 "must get memoized to avoid confusing later searches");
573#endif // NDEBUG
574 }
575
Kuba Breckaddfdba32016-11-14 21:41:13 +0000576 changeToInvokeAndSplitBasicBlock(CI, UnwindEdge);
David Majnemer654e1302015-07-31 17:58:14 +0000577 return BB;
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000578 }
David Majnemer654e1302015-07-31 17:58:14 +0000579 return nullptr;
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000580}
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000581
Sanjay Patel0fdb4372015-03-10 19:42:57 +0000582/// If we inlined an invoke site, we need to convert calls
Bill Wendling0aef16a2012-02-06 21:44:22 +0000583/// in the body of the inlined function into invokes.
Chris Lattner908d7952006-01-13 19:05:59 +0000584///
Nick Lewycky12a130b2009-02-03 04:34:40 +0000585/// II is the invoke instruction being inlined. FirstNewBlock is the first
Chris Lattner908d7952006-01-13 19:05:59 +0000586/// block of the inlined code (the last block is the end of the function),
587/// and InlineCodeInfo is information about the code that got inlined.
David Majnemer654e1302015-07-31 17:58:14 +0000588static void HandleInlinedLandingPad(InvokeInst *II, BasicBlock *FirstNewBlock,
589 ClonedCodeInfo &InlinedCodeInfo) {
Chris Lattner908d7952006-01-13 19:05:59 +0000590 BasicBlock *InvokeDest = II->getUnwindDest();
Chris Lattner908d7952006-01-13 19:05:59 +0000591
592 Function *Caller = FirstNewBlock->getParent();
Duncan Sands7c8fb1a2008-09-05 12:37:12 +0000593
Chris Lattner908d7952006-01-13 19:05:59 +0000594 // The inlined code is currently at the end of the function, scan from the
595 // start of the inlined code to its end, checking for stuff we need to
Bill Wendling173c71f2013-03-21 23:30:12 +0000596 // rewrite.
David Majnemer654e1302015-07-31 17:58:14 +0000597 LandingPadInliningInfo Invoke(II);
Bill Wendling173c71f2013-03-21 23:30:12 +0000598
Bill Wendling56f15bf2013-03-22 20:31:05 +0000599 // Get all of the inlined landing pad instructions.
600 SmallPtrSet<LandingPadInst*, 16> InlinedLPads;
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000601 for (Function::iterator I = FirstNewBlock->getIterator(), E = Caller->end();
602 I != E; ++I)
Bill Wendling56f15bf2013-03-22 20:31:05 +0000603 if (InvokeInst *II = dyn_cast<InvokeInst>(I->getTerminator()))
604 InlinedLPads.insert(II->getLandingPadInst());
605
Mark Seabornef3dbb92013-12-08 00:50:58 +0000606 // Append the clauses from the outer landing pad instruction into the inlined
607 // landing pad instructions.
608 LandingPadInst *OuterLPad = Invoke.getLandingPadInst();
Craig Topper46276792014-08-24 23:23:06 +0000609 for (LandingPadInst *InlinedLPad : InlinedLPads) {
Mark Seabornef3dbb92013-12-08 00:50:58 +0000610 unsigned OuterNum = OuterLPad->getNumClauses();
611 InlinedLPad->reserveClauses(OuterNum);
612 for (unsigned OuterIdx = 0; OuterIdx != OuterNum; ++OuterIdx)
613 InlinedLPad->addClause(OuterLPad->getClause(OuterIdx));
Mark Seaborn1b3dd352013-12-08 00:51:21 +0000614 if (OuterLPad->isCleanup())
615 InlinedLPad->setCleanup(true);
Mark Seabornef3dbb92013-12-08 00:50:58 +0000616 }
617
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000618 for (Function::iterator BB = FirstNewBlock->getIterator(), E = Caller->end();
619 BB != E; ++BB) {
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000620 if (InlinedCodeInfo.ContainsCalls)
David Majnemer654e1302015-07-31 17:58:14 +0000621 if (BasicBlock *NewBB = HandleCallsInBlockInlinedThroughInvoke(
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000622 &*BB, Invoke.getOuterResumeDest()))
David Majnemer654e1302015-07-31 17:58:14 +0000623 // Update any PHI nodes in the exceptional block to indicate that there
624 // is now a new entry in them.
625 Invoke.addIncomingPHIValuesFor(NewBB);
Duncan Sands7c8fb1a2008-09-05 12:37:12 +0000626
Bill Wendling173c71f2013-03-21 23:30:12 +0000627 // Forward any resumes that are remaining here.
Bill Wendling621699d2012-01-31 01:14:49 +0000628 if (ResumeInst *RI = dyn_cast<ResumeInst>(BB->getTerminator()))
Bill Wendling56f15bf2013-03-22 20:31:05 +0000629 Invoke.forwardResume(RI, InlinedLPads);
Chris Lattner908d7952006-01-13 19:05:59 +0000630 }
631
632 // Now that everything is happy, we have one final detail. The PHI nodes in
633 // the exception destination block still have entries due to the original
Bill Wendling173c71f2013-03-21 23:30:12 +0000634 // invoke instruction. Eliminate these entries (which might even delete the
Chris Lattner908d7952006-01-13 19:05:59 +0000635 // PHI node) now.
636 InvokeDest->removePredecessor(II->getParent());
637}
638
David Majnemer654e1302015-07-31 17:58:14 +0000639/// If we inlined an invoke site, we need to convert calls
640/// in the body of the inlined function into invokes.
641///
642/// II is the invoke instruction being inlined. FirstNewBlock is the first
643/// block of the inlined code (the last block is the end of the function),
644/// and InlineCodeInfo is information about the code that got inlined.
645static void HandleInlinedEHPad(InvokeInst *II, BasicBlock *FirstNewBlock,
646 ClonedCodeInfo &InlinedCodeInfo) {
647 BasicBlock *UnwindDest = II->getUnwindDest();
648 Function *Caller = FirstNewBlock->getParent();
649
650 assert(UnwindDest->getFirstNonPHI()->isEHPad() && "unexpected BasicBlock!");
651
652 // If there are PHI nodes in the unwind destination block, we need to keep
653 // track of which values came into them from the invoke before removing the
654 // edge from this block.
655 SmallVector<Value *, 8> UnwindDestPHIValues;
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000656 BasicBlock *InvokeBB = II->getParent();
David Majnemer654e1302015-07-31 17:58:14 +0000657 for (Instruction &I : *UnwindDest) {
658 // Save the value to use for this edge.
659 PHINode *PHI = dyn_cast<PHINode>(&I);
660 if (!PHI)
661 break;
662 UnwindDestPHIValues.push_back(PHI->getIncomingValueForBlock(InvokeBB));
663 }
664
665 // Add incoming-PHI values to the unwind destination block for the given basic
666 // block, using the values for the original invoke's source block.
667 auto UpdatePHINodes = [&](BasicBlock *Src) {
668 BasicBlock::iterator I = UnwindDest->begin();
669 for (Value *V : UnwindDestPHIValues) {
670 PHINode *PHI = cast<PHINode>(I);
671 PHI->addIncoming(V, Src);
672 ++I;
673 }
674 };
675
David Majnemer8a1c45d2015-12-12 05:38:55 +0000676 // This connects all the instructions which 'unwind to caller' to the invoke
677 // destination.
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000678 UnwindDestMemoTy FuncletUnwindMap;
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000679 for (Function::iterator BB = FirstNewBlock->getIterator(), E = Caller->end();
680 BB != E; ++BB) {
David Majnemer654e1302015-07-31 17:58:14 +0000681 if (auto *CRI = dyn_cast<CleanupReturnInst>(BB->getTerminator())) {
682 if (CRI->unwindsToCaller()) {
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000683 auto *CleanupPad = CRI->getCleanupPad();
684 CleanupReturnInst::Create(CleanupPad, UnwindDest, CRI);
David Majnemer654e1302015-07-31 17:58:14 +0000685 CRI->eraseFromParent();
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000686 UpdatePHINodes(&*BB);
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000687 // Finding a cleanupret with an unwind destination would confuse
688 // subsequent calls to getUnwindDestToken, so map the cleanuppad
689 // to short-circuit any such calls and recognize this as an "unwind
690 // to caller" cleanup.
691 assert(!FuncletUnwindMap.count(CleanupPad) ||
692 isa<ConstantTokenNone>(FuncletUnwindMap[CleanupPad]));
693 FuncletUnwindMap[CleanupPad] =
694 ConstantTokenNone::get(Caller->getContext());
David Majnemer654e1302015-07-31 17:58:14 +0000695 }
696 }
David Majnemer8a1c45d2015-12-12 05:38:55 +0000697
698 Instruction *I = BB->getFirstNonPHI();
699 if (!I->isEHPad())
700 continue;
701
702 Instruction *Replacement = nullptr;
David Majnemerbbfc7212015-12-14 18:34:23 +0000703 if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(I)) {
David Majnemer8a1c45d2015-12-12 05:38:55 +0000704 if (CatchSwitch->unwindsToCaller()) {
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000705 Value *UnwindDestToken;
706 if (auto *ParentPad =
707 dyn_cast<Instruction>(CatchSwitch->getParentPad())) {
708 // This catchswitch is nested inside another funclet. If that
709 // funclet has an unwind destination within the inlinee, then
710 // unwinding out of this catchswitch would be UB. Rewriting this
711 // catchswitch to unwind to the inlined invoke's unwind dest would
712 // give the parent funclet multiple unwind destinations, which is
713 // something that subsequent EH table generation can't handle and
714 // that the veirifer rejects. So when we see such a call, leave it
715 // as "unwind to caller".
716 UnwindDestToken = getUnwindDestToken(ParentPad, FuncletUnwindMap);
717 if (UnwindDestToken && !isa<ConstantTokenNone>(UnwindDestToken))
718 continue;
719 } else {
720 // This catchswitch has no parent to inherit constraints from, and
721 // none of its descendants can have an unwind edge that exits it and
722 // targets another funclet in the inlinee. It may or may not have a
723 // descendant that definitively has an unwind to caller. In either
724 // case, we'll have to assume that any unwinds out of it may need to
725 // be routed to the caller, so treat it as though it has a definitive
726 // unwind to caller.
727 UnwindDestToken = ConstantTokenNone::get(Caller->getContext());
728 }
David Majnemer8a1c45d2015-12-12 05:38:55 +0000729 auto *NewCatchSwitch = CatchSwitchInst::Create(
730 CatchSwitch->getParentPad(), UnwindDest,
731 CatchSwitch->getNumHandlers(), CatchSwitch->getName(),
732 CatchSwitch);
733 for (BasicBlock *PadBB : CatchSwitch->handlers())
734 NewCatchSwitch->addHandler(PadBB);
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000735 // Propagate info for the old catchswitch over to the new one in
736 // the unwind map. This also serves to short-circuit any subsequent
737 // checks for the unwind dest of this catchswitch, which would get
738 // confused if they found the outer handler in the callee.
739 FuncletUnwindMap[NewCatchSwitch] = UnwindDestToken;
David Majnemer8a1c45d2015-12-12 05:38:55 +0000740 Replacement = NewCatchSwitch;
741 }
742 } else if (!isa<FuncletPadInst>(I)) {
743 llvm_unreachable("unexpected EHPad!");
744 }
745
746 if (Replacement) {
747 Replacement->takeName(I);
748 I->replaceAllUsesWith(Replacement);
749 I->eraseFromParent();
750 UpdatePHINodes(&*BB);
751 }
David Majnemer654e1302015-07-31 17:58:14 +0000752 }
753
754 if (InlinedCodeInfo.ContainsCalls)
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000755 for (Function::iterator BB = FirstNewBlock->getIterator(),
756 E = Caller->end();
757 BB != E; ++BB)
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000758 if (BasicBlock *NewBB = HandleCallsInBlockInlinedThroughInvoke(
759 &*BB, UnwindDest, &FuncletUnwindMap))
David Majnemer654e1302015-07-31 17:58:14 +0000760 // Update any PHI nodes in the exceptional block to indicate that there
761 // is now a new entry in them.
762 UpdatePHINodes(NewBB);
763
764 // Now that everything is happy, we have one final detail. The PHI nodes in
765 // the exception destination block still have entries due to the original
766 // invoke instruction. Eliminate these entries (which might even delete the
767 // PHI node) now.
768 UnwindDest->removePredecessor(InvokeBB);
769}
770
Hal Finkel50316d92016-04-28 23:00:04 +0000771/// When inlining a call site that has !llvm.mem.parallel_loop_access metadata,
772/// that metadata should be propagated to all memory-accessing cloned
773/// instructions.
774static void PropagateParallelLoopAccessMetadata(CallSite CS,
775 ValueToValueMapTy &VMap) {
776 MDNode *M =
777 CS.getInstruction()->getMetadata(LLVMContext::MD_mem_parallel_loop_access);
778 if (!M)
779 return;
780
781 for (ValueToValueMapTy::iterator VMI = VMap.begin(), VMIE = VMap.end();
782 VMI != VMIE; ++VMI) {
783 if (!VMI->second)
784 continue;
785
786 Instruction *NI = dyn_cast<Instruction>(VMI->second);
787 if (!NI)
788 continue;
789
790 if (MDNode *PM = NI->getMetadata(LLVMContext::MD_mem_parallel_loop_access)) {
791 M = MDNode::concatenate(PM, M);
792 NI->setMetadata(LLVMContext::MD_mem_parallel_loop_access, M);
793 } else if (NI->mayReadOrWriteMemory()) {
794 NI->setMetadata(LLVMContext::MD_mem_parallel_loop_access, M);
795 }
796 }
797}
798
Sanjay Patel0fdb4372015-03-10 19:42:57 +0000799/// When inlining a function that contains noalias scope metadata,
800/// this metadata needs to be cloned so that the inlined blocks
Sanjay Patel65d533c2017-01-02 19:05:11 +0000801/// have different "unique scopes" at every call site. Were this not done, then
Hal Finkel94146652014-07-24 14:25:39 +0000802/// aliasing scopes from a function inlined into a caller multiple times could
803/// not be differentiated (and this would lead to miscompiles because the
804/// non-aliasing property communicated by the metadata could have
805/// call-site-specific control dependencies).
806static void CloneAliasScopeMetadata(CallSite CS, ValueToValueMapTy &VMap) {
807 const Function *CalledFunc = CS.getCalledFunction();
808 SetVector<const MDNode *> MD;
809
810 // Note: We could only clone the metadata if it is already used in the
811 // caller. I'm omitting that check here because it might confuse
812 // inter-procedural alias analysis passes. We can revisit this if it becomes
813 // an efficiency or overhead problem.
814
Benjamin Kramer135f7352016-06-26 12:28:59 +0000815 for (const BasicBlock &I : *CalledFunc)
816 for (const Instruction &J : I) {
817 if (const MDNode *M = J.getMetadata(LLVMContext::MD_alias_scope))
Hal Finkel94146652014-07-24 14:25:39 +0000818 MD.insert(M);
Benjamin Kramer135f7352016-06-26 12:28:59 +0000819 if (const MDNode *M = J.getMetadata(LLVMContext::MD_noalias))
Hal Finkel94146652014-07-24 14:25:39 +0000820 MD.insert(M);
821 }
822
823 if (MD.empty())
824 return;
825
826 // Walk the existing metadata, adding the complete (perhaps cyclic) chain to
827 // the set.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000828 SmallVector<const Metadata *, 16> Queue(MD.begin(), MD.end());
Hal Finkel94146652014-07-24 14:25:39 +0000829 while (!Queue.empty()) {
830 const MDNode *M = cast<MDNode>(Queue.pop_back_val());
831 for (unsigned i = 0, ie = M->getNumOperands(); i != ie; ++i)
832 if (const MDNode *M1 = dyn_cast<MDNode>(M->getOperand(i)))
833 if (MD.insert(M1))
834 Queue.push_back(M1);
835 }
836
837 // Now we have a complete set of all metadata in the chains used to specify
838 // the noalias scopes and the lists of those scopes.
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000839 SmallVector<TempMDTuple, 16> DummyNodes;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000840 DenseMap<const MDNode *, TrackingMDNodeRef> MDMap;
Benjamin Kramer135f7352016-06-26 12:28:59 +0000841 for (const MDNode *I : MD) {
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000842 DummyNodes.push_back(MDTuple::getTemporary(CalledFunc->getContext(), None));
Benjamin Kramer135f7352016-06-26 12:28:59 +0000843 MDMap[I].reset(DummyNodes.back().get());
Hal Finkel94146652014-07-24 14:25:39 +0000844 }
845
846 // Create new metadata nodes to replace the dummy nodes, replacing old
847 // metadata references with either a dummy node or an already-created new
848 // node.
Benjamin Kramer135f7352016-06-26 12:28:59 +0000849 for (const MDNode *I : MD) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000850 SmallVector<Metadata *, 4> NewOps;
Benjamin Kramer135f7352016-06-26 12:28:59 +0000851 for (unsigned i = 0, ie = I->getNumOperands(); i != ie; ++i) {
852 const Metadata *V = I->getOperand(i);
Hal Finkel94146652014-07-24 14:25:39 +0000853 if (const MDNode *M = dyn_cast<MDNode>(V))
854 NewOps.push_back(MDMap[M]);
855 else
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000856 NewOps.push_back(const_cast<Metadata *>(V));
Hal Finkel94146652014-07-24 14:25:39 +0000857 }
858
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000859 MDNode *NewM = MDNode::get(CalledFunc->getContext(), NewOps);
Benjamin Kramer135f7352016-06-26 12:28:59 +0000860 MDTuple *TempM = cast<MDTuple>(MDMap[I]);
Duncan P. N. Exon Smith946fdcc2015-01-19 20:36:39 +0000861 assert(TempM->isTemporary() && "Expected temporary node");
Hal Finkel94146652014-07-24 14:25:39 +0000862
863 TempM->replaceAllUsesWith(NewM);
864 }
865
866 // Now replace the metadata in the new inlined instructions with the
867 // repacements from the map.
868 for (ValueToValueMapTy::iterator VMI = VMap.begin(), VMIE = VMap.end();
869 VMI != VMIE; ++VMI) {
870 if (!VMI->second)
871 continue;
872
873 Instruction *NI = dyn_cast<Instruction>(VMI->second);
874 if (!NI)
875 continue;
876
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000877 if (MDNode *M = NI->getMetadata(LLVMContext::MD_alias_scope)) {
Hal Finkel61c38612014-08-14 21:09:37 +0000878 MDNode *NewMD = MDMap[M];
879 // If the call site also had alias scope metadata (a list of scopes to
880 // which instructions inside it might belong), propagate those scopes to
881 // the inlined instructions.
882 if (MDNode *CSM =
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000883 CS.getInstruction()->getMetadata(LLVMContext::MD_alias_scope))
Hal Finkel61c38612014-08-14 21:09:37 +0000884 NewMD = MDNode::concatenate(NewMD, CSM);
885 NI->setMetadata(LLVMContext::MD_alias_scope, NewMD);
886 } else if (NI->mayReadOrWriteMemory()) {
887 if (MDNode *M =
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000888 CS.getInstruction()->getMetadata(LLVMContext::MD_alias_scope))
Hal Finkel61c38612014-08-14 21:09:37 +0000889 NI->setMetadata(LLVMContext::MD_alias_scope, M);
890 }
Hal Finkel94146652014-07-24 14:25:39 +0000891
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000892 if (MDNode *M = NI->getMetadata(LLVMContext::MD_noalias)) {
Hal Finkel61c38612014-08-14 21:09:37 +0000893 MDNode *NewMD = MDMap[M];
894 // If the call site also had noalias metadata (a list of scopes with
895 // which instructions inside it don't alias), propagate those scopes to
896 // the inlined instructions.
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000897 if (MDNode *CSM =
898 CS.getInstruction()->getMetadata(LLVMContext::MD_noalias))
Hal Finkel61c38612014-08-14 21:09:37 +0000899 NewMD = MDNode::concatenate(NewMD, CSM);
900 NI->setMetadata(LLVMContext::MD_noalias, NewMD);
901 } else if (NI->mayReadOrWriteMemory()) {
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000902 if (MDNode *M = CS.getInstruction()->getMetadata(LLVMContext::MD_noalias))
Hal Finkel61c38612014-08-14 21:09:37 +0000903 NI->setMetadata(LLVMContext::MD_noalias, M);
904 }
Hal Finkel94146652014-07-24 14:25:39 +0000905 }
Hal Finkel94146652014-07-24 14:25:39 +0000906}
907
Sanjay Patel0fdb4372015-03-10 19:42:57 +0000908/// If the inlined function has noalias arguments,
909/// then add new alias scopes for each noalias argument, tag the mapped noalias
Hal Finkelff0bcb62014-07-25 15:50:08 +0000910/// parameters with noalias metadata specifying the new scope, and tag all
911/// non-derived loads, stores and memory intrinsics with the new alias scopes.
912static void AddAliasScopeMetadata(CallSite CS, ValueToValueMapTy &VMap,
Chandler Carruth7b560d42015-09-09 17:55:00 +0000913 const DataLayout &DL, AAResults *CalleeAAR) {
Hal Finkelff0bcb62014-07-25 15:50:08 +0000914 if (!EnableNoAliasConversion)
915 return;
916
917 const Function *CalledFunc = CS.getCalledFunction();
918 SmallVector<const Argument *, 4> NoAliasArgs;
919
Sanjay Patel42c73552016-01-13 22:16:48 +0000920 for (const Argument &Arg : CalledFunc->args())
921 if (Arg.hasNoAliasAttr() && !Arg.use_empty())
922 NoAliasArgs.push_back(&Arg);
Hal Finkelff0bcb62014-07-25 15:50:08 +0000923
924 if (NoAliasArgs.empty())
925 return;
926
927 // To do a good job, if a noalias variable is captured, we need to know if
928 // the capture point dominates the particular use we're considering.
929 DominatorTree DT;
930 DT.recalculate(const_cast<Function&>(*CalledFunc));
931
932 // noalias indicates that pointer values based on the argument do not alias
933 // pointer values which are not based on it. So we add a new "scope" for each
934 // noalias function argument. Accesses using pointers based on that argument
935 // become part of that alias scope, accesses using pointers not based on that
936 // argument are tagged as noalias with that scope.
937
938 DenseMap<const Argument *, MDNode *> NewScopes;
939 MDBuilder MDB(CalledFunc->getContext());
940
941 // Create a new scope domain for this function.
942 MDNode *NewDomain =
943 MDB.createAnonymousAliasScopeDomain(CalledFunc->getName());
944 for (unsigned i = 0, e = NoAliasArgs.size(); i != e; ++i) {
945 const Argument *A = NoAliasArgs[i];
946
947 std::string Name = CalledFunc->getName();
948 if (A->hasName()) {
949 Name += ": %";
950 Name += A->getName();
951 } else {
952 Name += ": argument ";
953 Name += utostr(i);
954 }
955
956 // Note: We always create a new anonymous root here. This is true regardless
957 // of the linkage of the callee because the aliasing "scope" is not just a
958 // property of the callee, but also all control dependencies in the caller.
959 MDNode *NewScope = MDB.createAnonymousAliasScope(NewDomain, Name);
960 NewScopes.insert(std::make_pair(A, NewScope));
961 }
962
963 // Iterate over all new instructions in the map; for all memory-access
964 // instructions, add the alias scope metadata.
965 for (ValueToValueMapTy::iterator VMI = VMap.begin(), VMIE = VMap.end();
966 VMI != VMIE; ++VMI) {
967 if (const Instruction *I = dyn_cast<Instruction>(VMI->first)) {
968 if (!VMI->second)
969 continue;
970
971 Instruction *NI = dyn_cast<Instruction>(VMI->second);
972 if (!NI)
973 continue;
974
Hal Finkel0c083022014-09-01 09:01:39 +0000975 bool IsArgMemOnlyCall = false, IsFuncCall = false;
Hal Finkelff0bcb62014-07-25 15:50:08 +0000976 SmallVector<const Value *, 2> PtrArgs;
977
978 if (const LoadInst *LI = dyn_cast<LoadInst>(I))
979 PtrArgs.push_back(LI->getPointerOperand());
980 else if (const StoreInst *SI = dyn_cast<StoreInst>(I))
981 PtrArgs.push_back(SI->getPointerOperand());
982 else if (const VAArgInst *VAAI = dyn_cast<VAArgInst>(I))
983 PtrArgs.push_back(VAAI->getPointerOperand());
984 else if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(I))
985 PtrArgs.push_back(CXI->getPointerOperand());
986 else if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(I))
987 PtrArgs.push_back(RMWI->getPointerOperand());
Hal Finkeld2dee162014-08-14 16:44:03 +0000988 else if (ImmutableCallSite ICS = ImmutableCallSite(I)) {
Hal Finkela3708df2014-08-30 12:48:33 +0000989 // If we know that the call does not access memory, then we'll still
990 // know that about the inlined clone of this call site, and we don't
991 // need to add metadata.
Hal Finkeld2dee162014-08-14 16:44:03 +0000992 if (ICS.doesNotAccessMemory())
993 continue;
994
Hal Finkel0c083022014-09-01 09:01:39 +0000995 IsFuncCall = true;
Chandler Carruth7b560d42015-09-09 17:55:00 +0000996 if (CalleeAAR) {
997 FunctionModRefBehavior MRB = CalleeAAR->getModRefBehavior(ICS);
Chandler Carruth194f59c2015-07-22 23:15:57 +0000998 if (MRB == FMRB_OnlyAccessesArgumentPointees ||
999 MRB == FMRB_OnlyReadsArgumentPointees)
Hal Finkel0c083022014-09-01 09:01:39 +00001000 IsArgMemOnlyCall = true;
1001 }
1002
Sanjay Patele01dcab2016-01-13 21:39:26 +00001003 for (Value *Arg : ICS.args()) {
Hal Finkela3708df2014-08-30 12:48:33 +00001004 // We need to check the underlying objects of all arguments, not just
1005 // the pointer arguments, because we might be passing pointers as
1006 // integers, etc.
Hal Finkel0c083022014-09-01 09:01:39 +00001007 // However, if we know that the call only accesses pointer arguments,
Hal Finkeld2dee162014-08-14 16:44:03 +00001008 // then we only need to check the pointer arguments.
Sanjay Patele01dcab2016-01-13 21:39:26 +00001009 if (IsArgMemOnlyCall && !Arg->getType()->isPointerTy())
Hal Finkel0c083022014-09-01 09:01:39 +00001010 continue;
Hal Finkelff0bcb62014-07-25 15:50:08 +00001011
Sanjay Patele01dcab2016-01-13 21:39:26 +00001012 PtrArgs.push_back(Arg);
Hal Finkel0c083022014-09-01 09:01:39 +00001013 }
1014 }
Hal Finkelcbb85f22014-09-01 04:26:40 +00001015
Hal Finkelff0bcb62014-07-25 15:50:08 +00001016 // If we found no pointers, then this instruction is not suitable for
1017 // pairing with an instruction to receive aliasing metadata.
Hal Finkeld2dee162014-08-14 16:44:03 +00001018 // However, if this is a call, this we might just alias with none of the
1019 // noalias arguments.
Hal Finkelcbb85f22014-09-01 04:26:40 +00001020 if (PtrArgs.empty() && !IsFuncCall)
Hal Finkelff0bcb62014-07-25 15:50:08 +00001021 continue;
1022
1023 // It is possible that there is only one underlying object, but you
1024 // need to go through several PHIs to see it, and thus could be
1025 // repeated in the Objects list.
1026 SmallPtrSet<const Value *, 4> ObjSet;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001027 SmallVector<Metadata *, 4> Scopes, NoAliases;
Hal Finkelff0bcb62014-07-25 15:50:08 +00001028
1029 SmallSetVector<const Argument *, 4> NAPtrArgs;
Sanjay Patele01dcab2016-01-13 21:39:26 +00001030 for (const Value *V : PtrArgs) {
Hal Finkelff0bcb62014-07-25 15:50:08 +00001031 SmallVector<Value *, 4> Objects;
Sanjay Patele01dcab2016-01-13 21:39:26 +00001032 GetUnderlyingObjects(const_cast<Value*>(V),
Hans Wennborg083ca9b2015-10-06 23:24:35 +00001033 Objects, DL, /* LI = */ nullptr);
Hal Finkelff0bcb62014-07-25 15:50:08 +00001034
1035 for (Value *O : Objects)
1036 ObjSet.insert(O);
1037 }
1038
Hal Finkel2d3d6da2014-08-29 16:33:41 +00001039 // Figure out if we're derived from anything that is not a noalias
Hal Finkelff0bcb62014-07-25 15:50:08 +00001040 // argument.
Hal Finkela3708df2014-08-30 12:48:33 +00001041 bool CanDeriveViaCapture = false, UsesAliasingPtr = false;
1042 for (const Value *V : ObjSet) {
1043 // Is this value a constant that cannot be derived from any pointer
1044 // value (we need to exclude constant expressions, for example, that
1045 // are formed from arithmetic on global symbols).
1046 bool IsNonPtrConst = isa<ConstantInt>(V) || isa<ConstantFP>(V) ||
1047 isa<ConstantPointerNull>(V) ||
1048 isa<ConstantDataVector>(V) || isa<UndefValue>(V);
Hal Finkelcbb85f22014-09-01 04:26:40 +00001049 if (IsNonPtrConst)
1050 continue;
1051
1052 // If this is anything other than a noalias argument, then we cannot
1053 // completely describe the aliasing properties using alias.scope
1054 // metadata (and, thus, won't add any).
1055 if (const Argument *A = dyn_cast<Argument>(V)) {
1056 if (!A->hasNoAliasAttr())
1057 UsesAliasingPtr = true;
1058 } else {
Hal Finkela3708df2014-08-30 12:48:33 +00001059 UsesAliasingPtr = true;
Hal Finkelff0bcb62014-07-25 15:50:08 +00001060 }
Hal Finkelcbb85f22014-09-01 04:26:40 +00001061
1062 // If this is not some identified function-local object (which cannot
1063 // directly alias a noalias argument), or some other argument (which,
1064 // by definition, also cannot alias a noalias argument), then we could
1065 // alias a noalias argument that has been captured).
1066 if (!isa<Argument>(V) &&
1067 !isIdentifiedFunctionLocal(const_cast<Value*>(V)))
1068 CanDeriveViaCapture = true;
Hal Finkela3708df2014-08-30 12:48:33 +00001069 }
Hal Finkelcbb85f22014-09-01 04:26:40 +00001070
1071 // A function call can always get captured noalias pointers (via other
1072 // parameters, globals, etc.).
1073 if (IsFuncCall && !IsArgMemOnlyCall)
1074 CanDeriveViaCapture = true;
1075
Hal Finkelff0bcb62014-07-25 15:50:08 +00001076 // First, we want to figure out all of the sets with which we definitely
1077 // don't alias. Iterate over all noalias set, and add those for which:
1078 // 1. The noalias argument is not in the set of objects from which we
1079 // definitely derive.
1080 // 2. The noalias argument has not yet been captured.
Hal Finkelcbb85f22014-09-01 04:26:40 +00001081 // An arbitrary function that might load pointers could see captured
1082 // noalias arguments via other noalias arguments or globals, and so we
1083 // must always check for prior capture.
Hal Finkelff0bcb62014-07-25 15:50:08 +00001084 for (const Argument *A : NoAliasArgs) {
1085 if (!ObjSet.count(A) && (!CanDeriveViaCapture ||
Hal Finkela3708df2014-08-30 12:48:33 +00001086 // It might be tempting to skip the
1087 // PointerMayBeCapturedBefore check if
1088 // A->hasNoCaptureAttr() is true, but this is
1089 // incorrect because nocapture only guarantees
1090 // that no copies outlive the function, not
1091 // that the value cannot be locally captured.
Hal Finkelff0bcb62014-07-25 15:50:08 +00001092 !PointerMayBeCapturedBefore(A,
1093 /* ReturnCaptures */ false,
1094 /* StoreCaptures */ false, I, &DT)))
1095 NoAliases.push_back(NewScopes[A]);
1096 }
1097
1098 if (!NoAliases.empty())
Duncan P. N. Exon Smith3872d002014-11-01 00:10:31 +00001099 NI->setMetadata(LLVMContext::MD_noalias,
1100 MDNode::concatenate(
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001101 NI->getMetadata(LLVMContext::MD_noalias),
Duncan P. N. Exon Smith3872d002014-11-01 00:10:31 +00001102 MDNode::get(CalledFunc->getContext(), NoAliases)));
Hal Finkela3708df2014-08-30 12:48:33 +00001103
Hal Finkelff0bcb62014-07-25 15:50:08 +00001104 // Next, we want to figure out all of the sets to which we might belong.
Hal Finkela3708df2014-08-30 12:48:33 +00001105 // We might belong to a set if the noalias argument is in the set of
1106 // underlying objects. If there is some non-noalias argument in our list
1107 // of underlying objects, then we cannot add a scope because the fact
1108 // that some access does not alias with any set of our noalias arguments
1109 // cannot itself guarantee that it does not alias with this access
1110 // (because there is some pointer of unknown origin involved and the
1111 // other access might also depend on this pointer). We also cannot add
1112 // scopes to arbitrary functions unless we know they don't access any
1113 // non-parameter pointer-values.
1114 bool CanAddScopes = !UsesAliasingPtr;
Hal Finkelcbb85f22014-09-01 04:26:40 +00001115 if (CanAddScopes && IsFuncCall)
1116 CanAddScopes = IsArgMemOnlyCall;
Hal Finkelff0bcb62014-07-25 15:50:08 +00001117
Hal Finkela3708df2014-08-30 12:48:33 +00001118 if (CanAddScopes)
1119 for (const Argument *A : NoAliasArgs) {
1120 if (ObjSet.count(A))
1121 Scopes.push_back(NewScopes[A]);
1122 }
1123
Hal Finkelff0bcb62014-07-25 15:50:08 +00001124 if (!Scopes.empty())
Duncan P. N. Exon Smith3872d002014-11-01 00:10:31 +00001125 NI->setMetadata(
1126 LLVMContext::MD_alias_scope,
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001127 MDNode::concatenate(NI->getMetadata(LLVMContext::MD_alias_scope),
Duncan P. N. Exon Smith3872d002014-11-01 00:10:31 +00001128 MDNode::get(CalledFunc->getContext(), Scopes)));
Hal Finkelff0bcb62014-07-25 15:50:08 +00001129 }
1130 }
1131}
1132
Hans Wennborg2d5841f2017-02-27 22:33:02 +00001133/// If the inlined function has non-byval align arguments, then
1134/// add @llvm.assume-based alignment assumptions to preserve this information.
1135static void AddAlignmentAssumptions(CallSite CS, InlineFunctionInfo &IFI) {
1136 if (!PreserveAlignmentAssumptions || !IFI.GetAssumptionCache)
Hal Finkel68dc3c72014-10-15 23:44:41 +00001137 return;
Sanjay Patelaea60842016-12-31 17:54:05 +00001138
1139 AssumptionCache *AC = &(*IFI.GetAssumptionCache)(*CS.getCaller());
Mehdi Amini46a43552015-03-04 18:43:29 +00001140 auto &DL = CS.getCaller()->getParent()->getDataLayout();
Hal Finkel68dc3c72014-10-15 23:44:41 +00001141
Hans Wennborg2d5841f2017-02-27 22:33:02 +00001142 // To avoid inserting redundant assumptions, we should check for assumptions
1143 // already in the caller. To do this, we might need a DT of the caller.
Hal Finkel68dc3c72014-10-15 23:44:41 +00001144 DominatorTree DT;
1145 bool DTCalculated = false;
1146
Chandler Carruth66b31302015-01-04 12:03:27 +00001147 Function *CalledFunc = CS.getCalledFunction();
Sanjay Patelada717e2017-02-15 14:56:11 +00001148 for (Argument &Arg : CalledFunc->args()) {
Sanjay Patel40975e02017-02-27 18:13:48 +00001149 unsigned Align = Arg.getType()->isPointerTy() ? Arg.getParamAlignment() : 0;
Hans Wennborg2d5841f2017-02-27 22:33:02 +00001150 if (Align && !Arg.hasByValOrInAllocaAttr() && !Arg.hasNUses(0)) {
1151 if (!DTCalculated) {
1152 DT.recalculate(*CS.getCaller());
1153 DTCalculated = true;
1154 }
1155
Hal Finkel68dc3c72014-10-15 23:44:41 +00001156 // If we can already prove the asserted alignment in the context of the
1157 // caller, then don't bother inserting the assumption.
Hans Wennborg2d5841f2017-02-27 22:33:02 +00001158 Value *ArgVal = CS.getArgument(Arg.getArgNo());
1159 if (getKnownAlignment(ArgVal, DL, CS.getInstruction(), AC, &DT) >= Align)
1160 continue;
Hal Finkel68dc3c72014-10-15 23:44:41 +00001161
Hans Wennborg2d5841f2017-02-27 22:33:02 +00001162 CallInst *NewAsmp = IRBuilder<>(CS.getInstruction())
1163 .CreateAlignmentAssumption(DL, ArgVal, Align);
1164 AC->registerAssumption(NewAsmp);
Hal Finkel68dc3c72014-10-15 23:44:41 +00001165 }
1166 }
1167}
1168
Sanjay Patel0fdb4372015-03-10 19:42:57 +00001169/// Once we have cloned code over from a callee into the caller,
1170/// update the specified callgraph to reflect the changes we made.
1171/// Note that it's possible that not all code was copied over, so only
Duncan Sands46911f12008-09-08 11:05:51 +00001172/// some edges of the callgraph may remain.
1173static void UpdateCallGraphAfterInlining(CallSite CS,
Chris Lattner5de3b8b2006-07-12 18:29:36 +00001174 Function::iterator FirstNewBlock,
Rafael Espindola229e38f2010-10-13 01:36:30 +00001175 ValueToValueMapTy &VMap,
Chris Lattner2eee5d32010-04-22 23:37:35 +00001176 InlineFunctionInfo &IFI) {
1177 CallGraph &CG = *IFI.CG;
Sanjay Patel32d753c2017-02-15 15:08:38 +00001178 const Function *Caller = CS.getCaller();
Duncan Sands46911f12008-09-08 11:05:51 +00001179 const Function *Callee = CS.getCalledFunction();
Chris Lattner0841fb12006-01-14 20:07:50 +00001180 CallGraphNode *CalleeNode = CG[Callee];
1181 CallGraphNode *CallerNode = CG[Caller];
Duncan Sands7c8fb1a2008-09-05 12:37:12 +00001182
Chris Lattner5de3b8b2006-07-12 18:29:36 +00001183 // Since we inlined some uninlined call sites in the callee into the caller,
Chris Lattner0841fb12006-01-14 20:07:50 +00001184 // add edges from the caller to all of the callees of the callee.
Gabor Greif5aa19222009-01-15 18:40:09 +00001185 CallGraphNode::iterator I = CalleeNode->begin(), E = CalleeNode->end();
1186
1187 // Consider the case where CalleeNode == CallerNode.
Gabor Greiff1abfdc2009-01-17 00:09:08 +00001188 CallGraphNode::CalledFunctionsVector CallCache;
Gabor Greif5aa19222009-01-15 18:40:09 +00001189 if (CalleeNode == CallerNode) {
1190 CallCache.assign(I, E);
1191 I = CallCache.begin();
1192 E = CallCache.end();
1193 }
1194
1195 for (; I != E; ++I) {
Chris Lattner063d0652009-09-01 06:31:31 +00001196 const Value *OrigCall = I->first;
Duncan Sands7c8fb1a2008-09-05 12:37:12 +00001197
Rafael Espindola229e38f2010-10-13 01:36:30 +00001198 ValueToValueMapTy::iterator VMI = VMap.find(OrigCall);
Chris Lattnerb3c64f72006-07-12 21:37:11 +00001199 // Only copy the edge if the call was inlined!
Craig Topperf40110f2014-04-25 05:29:35 +00001200 if (VMI == VMap.end() || VMI->second == nullptr)
Chris Lattner5eef6ad2009-08-27 03:51:50 +00001201 continue;
1202
1203 // If the call was inlined, but then constant folded, there is no edge to
1204 // add. Check for this case.
Chris Lattner016c00a2010-04-22 21:31:00 +00001205 Instruction *NewCall = dyn_cast<Instruction>(VMI->second);
Sanjay Patelc04b6f22015-03-11 15:12:32 +00001206 if (!NewCall)
1207 continue;
Chris Lattnerc2432b92010-05-01 01:26:13 +00001208
Sanjay Patelc04b6f22015-03-11 15:12:32 +00001209 // We do not treat intrinsic calls like real function calls because we
1210 // expect them to become inline code; do not add an edge for an intrinsic.
1211 CallSite CS = CallSite(NewCall);
1212 if (CS && CS.getCalledFunction() && CS.getCalledFunction()->isIntrinsic())
1213 continue;
1214
Chris Lattnerc2432b92010-05-01 01:26:13 +00001215 // Remember that this call site got inlined for the client of
1216 // InlineFunction.
1217 IFI.InlinedCalls.push_back(NewCall);
1218
Chris Lattner016c00a2010-04-22 21:31:00 +00001219 // It's possible that inlining the callsite will cause it to go from an
1220 // indirect to a direct call by resolving a function pointer. If this
1221 // happens, set the callee of the new call site to a more precise
1222 // destination. This can also happen if the call graph node of the caller
1223 // was just unnecessarily imprecise.
Craig Topperf40110f2014-04-25 05:29:35 +00001224 if (!I->second->getFunction())
Chris Lattner016c00a2010-04-22 21:31:00 +00001225 if (Function *F = CallSite(NewCall).getCalledFunction()) {
1226 // Indirect call site resolved to direct call.
Gabor Greif7b0a5fd2010-07-27 15:02:37 +00001227 CallerNode->addCalledFunction(CallSite(NewCall), CG[F]);
1228
Chris Lattner016c00a2010-04-22 21:31:00 +00001229 continue;
1230 }
Gabor Greif7b0a5fd2010-07-27 15:02:37 +00001231
1232 CallerNode->addCalledFunction(CallSite(NewCall), I->second);
Chris Lattner5de3b8b2006-07-12 18:29:36 +00001233 }
Chris Lattner5eef6ad2009-08-27 03:51:50 +00001234
Dale Johannesen0aeabdf2009-01-13 22:43:37 +00001235 // Update the call graph by deleting the edge from Callee to Caller. We must
1236 // do this after the loop above in case Caller and Callee are the same.
1237 CallerNode->removeCallEdgeFor(CS);
Chris Lattner0841fb12006-01-14 20:07:50 +00001238}
1239
Julien Lerouge957e91c2014-04-15 18:01:54 +00001240static void HandleByValArgumentInit(Value *Dst, Value *Src, Module *M,
1241 BasicBlock *InsertBlock,
1242 InlineFunctionInfo &IFI) {
Julien Lerouge957e91c2014-04-15 18:01:54 +00001243 Type *AggTy = cast<PointerType>(Src->getType())->getElementType();
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001244 IRBuilder<> Builder(InsertBlock, InsertBlock->begin());
Julien Lerouge957e91c2014-04-15 18:01:54 +00001245
Mehdi Amini46a43552015-03-04 18:43:29 +00001246 Value *Size = Builder.getInt64(M->getDataLayout().getTypeStoreSize(AggTy));
Julien Lerouge957e91c2014-04-15 18:01:54 +00001247
1248 // Always generate a memcpy of alignment 1 here because we don't know
1249 // the alignment of the src pointer. Other optimizations can infer
1250 // better alignment.
Daniel Neilsona8942012018-02-06 19:14:31 +00001251 Builder.CreateMemCpy(Dst, /*DstAlign*/1, Src, /*SrcAlign*/1, Size);
Julien Lerouge957e91c2014-04-15 18:01:54 +00001252}
1253
Sanjay Patel0fdb4372015-03-10 19:42:57 +00001254/// When inlining a call site that has a byval argument,
Chris Lattner0f114952010-12-20 08:10:40 +00001255/// we have to make the implicit memcpy explicit by adding it.
David Majnemer120f4a02013-11-03 12:22:13 +00001256static Value *HandleByValArgument(Value *Arg, Instruction *TheCall,
Chris Lattner00997442010-12-20 07:57:41 +00001257 const Function *CalledFunc,
1258 InlineFunctionInfo &IFI,
Reid Klecknerdd3f3ed2014-11-04 02:02:14 +00001259 unsigned ByValAlignment) {
Matt Arsenaultbe558882014-04-23 20:58:57 +00001260 PointerType *ArgTy = cast<PointerType>(Arg->getType());
1261 Type *AggTy = ArgTy->getElementType();
Chris Lattner0f114952010-12-20 08:10:40 +00001262
Sanjay Patel288f0752017-02-15 15:22:18 +00001263 Function *Caller = TheCall->getFunction();
Matt Arsenault3c1fc762017-04-10 22:27:50 +00001264 const DataLayout &DL = Caller->getParent()->getDataLayout();
Chandler Carruth66b31302015-01-04 12:03:27 +00001265
Chris Lattner0f114952010-12-20 08:10:40 +00001266 // If the called function is readonly, then it could not mutate the caller's
1267 // copy of the byval'd memory. In this case, it is safe to elide the copy and
1268 // temporary.
David Majnemer120f4a02013-11-03 12:22:13 +00001269 if (CalledFunc->onlyReadsMemory()) {
Chris Lattner0f114952010-12-20 08:10:40 +00001270 // If the byval argument has a specified alignment that is greater than the
1271 // passed in pointer, then we either have to round up the input pointer or
1272 // give up on this transformation.
1273 if (ByValAlignment <= 1) // 0 = unspecified, 1 = no particular alignment.
David Majnemer120f4a02013-11-03 12:22:13 +00001274 return Arg;
Chris Lattner0f114952010-12-20 08:10:40 +00001275
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001276 AssumptionCache *AC =
1277 IFI.GetAssumptionCache ? &(*IFI.GetAssumptionCache)(*Caller) : nullptr;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001278
Chris Lattner20fca482010-12-25 20:42:38 +00001279 // If the pointer is already known to be sufficiently aligned, or if we can
1280 // round it up to a larger alignment, then we don't need a temporary.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001281 if (getOrEnforceKnownAlignment(Arg, ByValAlignment, DL, TheCall, AC) >=
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001282 ByValAlignment)
David Majnemer120f4a02013-11-03 12:22:13 +00001283 return Arg;
Matt Arsenault3c1fc762017-04-10 22:27:50 +00001284
Chris Lattner20fca482010-12-25 20:42:38 +00001285 // Otherwise, we have to make a memcpy to get a safe alignment. This is bad
1286 // for code quality, but rarely happens and is required for correctness.
Chris Lattner0f114952010-12-20 08:10:40 +00001287 }
Chris Lattner00997442010-12-20 07:57:41 +00001288
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001289 // Create the alloca. If we have DataLayout, use nice alignment.
Matt Arsenault3c1fc762017-04-10 22:27:50 +00001290 unsigned Align = DL.getPrefTypeAlignment(AggTy);
Mehdi Amini46a43552015-03-04 18:43:29 +00001291
Chris Lattner00997442010-12-20 07:57:41 +00001292 // If the byval had an alignment specified, we *must* use at least that
1293 // alignment, as it is required by the byval argument (and uses of the
1294 // pointer inside the callee).
1295 Align = std::max(Align, ByValAlignment);
Matt Arsenault3c1fc762017-04-10 22:27:50 +00001296
1297 Value *NewAlloca = new AllocaInst(AggTy, DL.getAllocaAddrSpace(),
1298 nullptr, Align, Arg->getName(),
Chris Lattner00997442010-12-20 07:57:41 +00001299 &*Caller->begin()->begin());
Julien Lerougebe4fe322014-04-15 18:06:46 +00001300 IFI.StaticAllocas.push_back(cast<AllocaInst>(NewAlloca));
Matt Arsenault3c1fc762017-04-10 22:27:50 +00001301
Chris Lattner00997442010-12-20 07:57:41 +00001302 // Uses of the argument in the function should use our new alloca
1303 // instead.
1304 return NewAlloca;
1305}
1306
Sanjay Patel0fdb4372015-03-10 19:42:57 +00001307// Check whether this Value is used by a lifetime intrinsic.
Nick Lewyckya68ec832011-05-22 05:22:10 +00001308static bool isUsedByLifetimeMarker(Value *V) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001309 for (User *U : V->users()) {
1310 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U)) {
Nick Lewyckya68ec832011-05-22 05:22:10 +00001311 switch (II->getIntrinsicID()) {
1312 default: break;
1313 case Intrinsic::lifetime_start:
1314 case Intrinsic::lifetime_end:
1315 return true;
1316 }
1317 }
1318 }
1319 return false;
1320}
1321
Sanjay Patel0fdb4372015-03-10 19:42:57 +00001322// Check whether the given alloca already has
Nick Lewyckya68ec832011-05-22 05:22:10 +00001323// lifetime.start or lifetime.end intrinsics.
1324static bool hasLifetimeMarkers(AllocaInst *AI) {
Matt Arsenaultbe558882014-04-23 20:58:57 +00001325 Type *Ty = AI->getType();
1326 Type *Int8PtrTy = Type::getInt8PtrTy(Ty->getContext(),
1327 Ty->getPointerAddressSpace());
1328 if (Ty == Int8PtrTy)
Nick Lewyckya68ec832011-05-22 05:22:10 +00001329 return isUsedByLifetimeMarker(AI);
1330
Nick Lewycky9711b5c2011-06-14 00:59:24 +00001331 // Do a scan to find all the casts to i8*.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001332 for (User *U : AI->users()) {
1333 if (U->getType() != Int8PtrTy) continue;
1334 if (U->stripPointerCasts() != AI) continue;
1335 if (isUsedByLifetimeMarker(U))
Nick Lewyckya68ec832011-05-22 05:22:10 +00001336 return true;
1337 }
1338 return false;
1339}
1340
Reid Kleckner6ee00a22016-08-12 22:23:04 +00001341/// Return the result of AI->isStaticAlloca() if AI were moved to the entry
1342/// block. Allocas used in inalloca calls and allocas of dynamic array size
1343/// cannot be static.
1344static bool allocaWouldBeStaticInEntry(const AllocaInst *AI ) {
1345 return isa<Constant>(AI->getArraySize()) && !AI->isUsedWithInAlloca();
1346}
1347
Adrian Prantld4056502017-03-07 17:28:57 +00001348/// Update inlined instructions' line numbers to
1349/// to encode location where these instructions are inlined.
1350static void fixupLineNumbers(Function *Fn, Function::iterator FI,
1351 Instruction *TheCall, bool CalleeHasDebugInfo) {
Benjamin Kramer4ca41fd2016-06-12 17:30:47 +00001352 const DebugLoc &TheCallDL = TheCall->getDebugLoc();
Adrian Prantld4056502017-03-07 17:28:57 +00001353 if (!TheCallDL)
1354 return;
Devang Patel35797402011-07-08 18:01:31 +00001355
David Blaikiedf706282015-01-21 22:57:29 +00001356 auto &Ctx = Fn->getContext();
Adrian Prantld4056502017-03-07 17:28:57 +00001357 DILocation *InlinedAtNode = TheCallDL;
David Blaikiedf706282015-01-21 22:57:29 +00001358
1359 // Create a unique call site, not to be confused with any other call from the
1360 // same location.
Adrian Prantld4056502017-03-07 17:28:57 +00001361 InlinedAtNode = DILocation::getDistinct(
1362 Ctx, InlinedAtNode->getLine(), InlinedAtNode->getColumn(),
1363 InlinedAtNode->getScope(), InlinedAtNode->getInlinedAt());
David Blaikiedf706282015-01-21 22:57:29 +00001364
1365 // Cache the inlined-at nodes as they're built so they are reused, without
1366 // this every instruction's inlined-at chain would become distinct from each
1367 // other.
Adrian Prantlc10d0e52017-05-09 19:47:37 +00001368 DenseMap<const MDNode *, MDNode *> IANodes;
David Blaikiedf706282015-01-21 22:57:29 +00001369
Devang Patel35797402011-07-08 18:01:31 +00001370 for (; FI != Fn->end(); ++FI) {
1371 for (BasicBlock::iterator BI = FI->begin(), BE = FI->end();
1372 BI != BE; ++BI) {
Andrea Di Biagioeff22832016-12-07 12:01:45 +00001373 if (DebugLoc DL = BI->getDebugLoc()) {
Adrian Prantlc10d0e52017-05-09 19:47:37 +00001374 auto IA = DebugLoc::appendInlinedAt(DL, InlinedAtNode, BI->getContext(),
1375 IANodes);
1376 auto IDL = DebugLoc::get(DL.getLine(), DL.getCol(), DL.getScope(), IA);
1377 BI->setDebugLoc(IDL);
Andrea Di Biagioeff22832016-12-07 12:01:45 +00001378 continue;
Devang Patelbb23a4a2011-08-10 21:50:54 +00001379 }
Andrea Di Biagioeff22832016-12-07 12:01:45 +00001380
1381 if (CalleeHasDebugInfo)
1382 continue;
1383
1384 // If the inlined instruction has no line number, make it look as if it
1385 // originates from the call location. This is important for
1386 // ((__always_inline__, __nodebug__)) functions which must use caller
1387 // location for all instructions in their function body.
1388
1389 // Don't update static allocas, as they may get moved later.
1390 if (auto *AI = dyn_cast<AllocaInst>(BI))
1391 if (allocaWouldBeStaticInEntry(AI))
1392 continue;
1393
1394 BI->setDebugLoc(TheCallDL);
Devang Patel35797402011-07-08 18:01:31 +00001395 }
1396 }
1397}
Eugene Zelenko6cadde72017-10-17 21:27:42 +00001398
Easwaran Raman12585b02017-01-20 22:44:04 +00001399/// Update the block frequencies of the caller after a callee has been inlined.
1400///
1401/// Each block cloned into the caller has its block frequency scaled by the
1402/// ratio of CallSiteFreq/CalleeEntryFreq. This ensures that the cloned copy of
1403/// callee's entry block gets the same frequency as the callsite block and the
1404/// relative frequencies of all cloned blocks remain the same after cloning.
1405static void updateCallerBFI(BasicBlock *CallSiteBlock,
1406 const ValueToValueMapTy &VMap,
1407 BlockFrequencyInfo *CallerBFI,
1408 BlockFrequencyInfo *CalleeBFI,
1409 const BasicBlock &CalleeEntryBlock) {
1410 SmallPtrSet<BasicBlock *, 16> ClonedBBs;
1411 for (auto const &Entry : VMap) {
1412 if (!isa<BasicBlock>(Entry.first) || !Entry.second)
1413 continue;
1414 auto *OrigBB = cast<BasicBlock>(Entry.first);
1415 auto *ClonedBB = cast<BasicBlock>(Entry.second);
Easwaran Raman5a12f232017-02-14 22:49:28 +00001416 uint64_t Freq = CalleeBFI->getBlockFreq(OrigBB).getFrequency();
1417 if (!ClonedBBs.insert(ClonedBB).second) {
1418 // Multiple blocks in the callee might get mapped to one cloned block in
1419 // the caller since we prune the callee as we clone it. When that happens,
1420 // we want to use the maximum among the original blocks' frequencies.
1421 uint64_t NewFreq = CallerBFI->getBlockFreq(ClonedBB).getFrequency();
1422 if (NewFreq > Freq)
1423 Freq = NewFreq;
1424 }
1425 CallerBFI->setBlockFreq(ClonedBB, Freq);
Easwaran Raman12585b02017-01-20 22:44:04 +00001426 }
1427 BasicBlock *EntryClone = cast<BasicBlock>(VMap.lookup(&CalleeEntryBlock));
1428 CallerBFI->setBlockFreqAndScale(
1429 EntryClone, CallerBFI->getBlockFreq(CallSiteBlock).getFrequency(),
1430 ClonedBBs);
1431}
1432
Dehao Chene5930492017-03-20 16:40:44 +00001433/// Update the branch metadata for cloned call instructions.
1434static void updateCallProfile(Function *Callee, const ValueToValueMapTy &VMap,
Easwaran Ramane5b8de22018-01-17 22:24:23 +00001435 const ProfileCount &CalleeEntryCount,
Easwaran Ramanf5f91602017-05-09 23:21:10 +00001436 const Instruction *TheCall,
Teresa Johnson525dcb62017-05-22 20:28:18 +00001437 ProfileSummaryInfo *PSI,
1438 BlockFrequencyInfo *CallerBFI) {
Easwaran Ramane5b8de22018-01-17 22:24:23 +00001439 if (!CalleeEntryCount.hasValue() || CalleeEntryCount.isSynthetic() ||
1440 CalleeEntryCount.getCount() < 1)
Dehao Chene5930492017-03-20 16:40:44 +00001441 return;
Easwaran Ramane5b8de22018-01-17 22:24:23 +00001442 auto CallSiteCount = PSI ? PSI->getProfileCount(TheCall, CallerBFI) : None;
Dehao Chene5930492017-03-20 16:40:44 +00001443 uint64_t CallCount =
1444 std::min(CallSiteCount.hasValue() ? CallSiteCount.getValue() : 0,
Easwaran Ramane5b8de22018-01-17 22:24:23 +00001445 CalleeEntryCount.getCount());
Dehao Chene5930492017-03-20 16:40:44 +00001446
1447 for (auto const &Entry : VMap)
David Blaikie795dc942017-03-20 18:01:07 +00001448 if (isa<CallInst>(Entry.first))
1449 if (auto *CI = dyn_cast_or_null<CallInst>(Entry.second))
Easwaran Ramane5b8de22018-01-17 22:24:23 +00001450 CI->updateProfWeight(CallCount, CalleeEntryCount.getCount());
Dehao Chene5930492017-03-20 16:40:44 +00001451 for (BasicBlock &BB : *Callee)
1452 // No need to update the callsite if it is pruned during inlining.
1453 if (VMap.count(&BB))
1454 for (Instruction &I : BB)
1455 if (CallInst *CI = dyn_cast<CallInst>(&I))
Easwaran Ramane5b8de22018-01-17 22:24:23 +00001456 CI->updateProfWeight(CalleeEntryCount.getCount() - CallCount,
1457 CalleeEntryCount.getCount());
Dehao Chene5930492017-03-20 16:40:44 +00001458}
1459
Easwaran Raman12585b02017-01-20 22:44:04 +00001460/// Update the entry count of callee after inlining.
1461///
1462/// The callsite's block count is subtracted from the callee's function entry
1463/// count.
Dehao Chene5930492017-03-20 16:40:44 +00001464static void updateCalleeCount(BlockFrequencyInfo *CallerBFI, BasicBlock *CallBB,
Easwaran Ramanf5f91602017-05-09 23:21:10 +00001465 Instruction *CallInst, Function *Callee,
1466 ProfileSummaryInfo *PSI) {
Easwaran Raman12585b02017-01-20 22:44:04 +00001467 // If the callee has a original count of N, and the estimated count of
1468 // callsite is M, the new callee count is set to N - M. M is estimated from
1469 // the caller's entry count, its entry block frequency and the block frequency
1470 // of the callsite.
Easwaran Ramane5b8de22018-01-17 22:24:23 +00001471 auto CalleeCount = Callee->getEntryCount();
Easwaran Ramanf5f91602017-05-09 23:21:10 +00001472 if (!CalleeCount.hasValue() || !PSI)
Easwaran Raman12585b02017-01-20 22:44:04 +00001473 return;
Easwaran Ramane5b8de22018-01-17 22:24:23 +00001474 auto CallCount = PSI->getProfileCount(CallInst, CallerBFI);
Dehao Chene5930492017-03-20 16:40:44 +00001475 if (!CallCount.hasValue())
Easwaran Raman12585b02017-01-20 22:44:04 +00001476 return;
1477 // Since CallSiteCount is an estimate, it could exceed the original callee
1478 // count and has to be set to 0.
Easwaran Ramane5b8de22018-01-17 22:24:23 +00001479 if (CallCount.getValue() > CalleeCount.getCount())
1480 CalleeCount.setCount(0);
Easwaran Raman12585b02017-01-20 22:44:04 +00001481 else
Easwaran Ramane5b8de22018-01-17 22:24:23 +00001482 CalleeCount.setCount(CalleeCount.getCount() - CallCount.getValue());
1483 Callee->setEntryCount(CalleeCount);
Easwaran Raman12585b02017-01-20 22:44:04 +00001484}
Devang Patel35797402011-07-08 18:01:31 +00001485
Sanjay Patel0fdb4372015-03-10 19:42:57 +00001486/// This function inlines the called function into the basic block of the
1487/// caller. This returns false if it is not possible to inline this call.
1488/// The program is still in a well defined state if this occurs though.
Bill Wendlingce0c2292012-01-31 01:01:16 +00001489///
1490/// Note that this only does one level of inlining. For example, if the
1491/// instruction 'call B' is inlined, and 'B' calls 'C', then the call to 'C' now
1492/// exists in the instruction stream. Similarly this will inline a recursive
1493/// function by one level.
Eric Christopherf16bee82012-03-26 19:09:38 +00001494bool llvm::InlineFunction(CallSite CS, InlineFunctionInfo &IFI,
Florian Hahn0e9dec62017-11-13 10:35:52 +00001495 AAResults *CalleeAAR, bool InsertLifetime,
1496 Function *ForwardVarArgsTo) {
Chris Lattner0cc265e2003-08-24 06:59:16 +00001497 Instruction *TheCall = CS.getInstruction();
Sanjay Patel288f0752017-02-15 15:22:18 +00001498 assert(TheCall->getParent() && TheCall->getFunction()
1499 && "Instruction not in function!");
Chris Lattner530d4bf2003-05-29 15:11:31 +00001500
Chris Lattner4ba01ec2010-04-22 23:07:58 +00001501 // If IFI has any state in it, zap it before we fill it in.
1502 IFI.reset();
Easwaran Raman12585b02017-01-20 22:44:04 +00001503
1504 Function *CalledFunc = CS.getCalledFunction();
Florian Hahn80788d82018-01-06 19:45:40 +00001505 if (!CalledFunc || // Can't inline external function or indirect
1506 CalledFunc->isDeclaration()) // call!
1507 return false;
Chris Lattner530d4bf2003-05-29 15:11:31 +00001508
Sanjoy Das2d161452015-11-18 06:23:38 +00001509 // The inliner does not know how to inline through calls with operand bundles
1510 // in general ...
1511 if (CS.hasOperandBundles()) {
David Majnemer3bb88c02015-12-15 21:27:27 +00001512 for (int i = 0, e = CS.getNumOperandBundles(); i != e; ++i) {
1513 uint32_t Tag = CS.getOperandBundleAt(i).getTagID();
1514 // ... but it knows how to inline through "deopt" operand bundles ...
1515 if (Tag == LLVMContext::OB_deopt)
1516 continue;
1517 // ... and "funclet" operand bundles.
1518 if (Tag == LLVMContext::OB_funclet)
1519 continue;
1520
Sanjoy Das2d161452015-11-18 06:23:38 +00001521 return false;
David Majnemer3bb88c02015-12-15 21:27:27 +00001522 }
Sanjoy Das2d161452015-11-18 06:23:38 +00001523 }
Sanjoy Das0a1bee82015-10-23 20:09:55 +00001524
Duncan Sandsaa31b922007-12-19 21:13:37 +00001525 // If the call to the callee cannot throw, set the 'nounwind' flag on any
1526 // calls that we inline.
1527 bool MarkNoUnwind = CS.doesNotThrow();
1528
Chris Lattner0cc265e2003-08-24 06:59:16 +00001529 BasicBlock *OrigBB = TheCall->getParent();
Chris Lattner530d4bf2003-05-29 15:11:31 +00001530 Function *Caller = OrigBB->getParent();
1531
Gordon Henriksenb969c592007-12-25 03:10:07 +00001532 // GC poses two hazards to inlining, which only occur when the callee has GC:
1533 // 1. If the caller has no GC, then the callee's GC must be propagated to the
1534 // caller.
1535 // 2. If the caller has a differing GC, it is invalid to inline.
Gordon Henriksend930f912008-08-17 18:44:35 +00001536 if (CalledFunc->hasGC()) {
1537 if (!Caller->hasGC())
1538 Caller->setGC(CalledFunc->getGC());
1539 else if (CalledFunc->getGC() != Caller->getGC())
Gordon Henriksenb969c592007-12-25 03:10:07 +00001540 return false;
1541 }
Duncan Sands7c8fb1a2008-09-05 12:37:12 +00001542
Benjamin Kramer4d2b8712011-12-02 18:37:31 +00001543 // Get the personality function from the callee if it contains a landing pad.
David Majnemer7fddecc2015-06-17 20:52:32 +00001544 Constant *CalledPersonality =
David Majnemereba62792015-10-13 22:08:17 +00001545 CalledFunc->hasPersonalityFn()
1546 ? CalledFunc->getPersonalityFn()->stripPointerCasts()
1547 : nullptr;
Benjamin Kramer4d2b8712011-12-02 18:37:31 +00001548
Bill Wendling55421f02011-08-14 08:01:36 +00001549 // Find the personality function used by the landing pads of the caller. If it
1550 // exists, then check to see that it matches the personality function used in
1551 // the callee.
David Majnemer7fddecc2015-06-17 20:52:32 +00001552 Constant *CallerPersonality =
David Majnemereba62792015-10-13 22:08:17 +00001553 Caller->hasPersonalityFn()
1554 ? Caller->getPersonalityFn()->stripPointerCasts()
1555 : nullptr;
David Majnemer7fddecc2015-06-17 20:52:32 +00001556 if (CalledPersonality) {
1557 if (!CallerPersonality)
1558 Caller->setPersonalityFn(CalledPersonality);
1559 // If the personality functions match, then we can perform the
1560 // inlining. Otherwise, we can't inline.
1561 // TODO: This isn't 100% true. Some personality functions are proper
1562 // supersets of others and can be used in place of the other.
1563 else if (CalledPersonality != CallerPersonality)
1564 return false;
Bill Wendlingce0c2292012-01-31 01:01:16 +00001565 }
Bill Wendling55421f02011-08-14 08:01:36 +00001566
David Majnemer8a1c45d2015-12-12 05:38:55 +00001567 // We need to figure out which funclet the callsite was in so that we may
1568 // properly nest the callee.
1569 Instruction *CallSiteEHPad = nullptr;
David Majnemer3bb88c02015-12-15 21:27:27 +00001570 if (CallerPersonality) {
1571 EHPersonality Personality = classifyEHPersonality(CallerPersonality);
Heejin Ahnb4be38f2018-05-17 20:52:03 +00001572 if (isScopedEHPersonality(Personality)) {
David Majnemer3bb88c02015-12-15 21:27:27 +00001573 Optional<OperandBundleUse> ParentFunclet =
1574 CS.getOperandBundle(LLVMContext::OB_funclet);
1575 if (ParentFunclet)
1576 CallSiteEHPad = cast<FuncletPadInst>(ParentFunclet->Inputs.front());
David Majnemer8a1c45d2015-12-12 05:38:55 +00001577
1578 // OK, the inlining site is legal. What about the target function?
1579
1580 if (CallSiteEHPad) {
1581 if (Personality == EHPersonality::MSVC_CXX) {
1582 // The MSVC personality cannot tolerate catches getting inlined into
1583 // cleanup funclets.
1584 if (isa<CleanupPadInst>(CallSiteEHPad)) {
1585 // Ok, the call site is within a cleanuppad. Let's check the callee
1586 // for catchpads.
1587 for (const BasicBlock &CalledBB : *CalledFunc) {
David Majnemer3bb88c02015-12-15 21:27:27 +00001588 if (isa<CatchSwitchInst>(CalledBB.getFirstNonPHI()))
David Majnemer8a1c45d2015-12-12 05:38:55 +00001589 return false;
1590 }
1591 }
1592 } else if (isAsynchronousEHPersonality(Personality)) {
1593 // SEH is even less tolerant, there may not be any sort of exceptional
1594 // funclet in the callee.
1595 for (const BasicBlock &CalledBB : *CalledFunc) {
1596 if (CalledBB.isEHPad())
1597 return false;
1598 }
1599 }
1600 }
1601 }
1602 }
1603
David Majnemer223538f2016-02-23 17:11:04 +00001604 // Determine if we are dealing with a call in an EHPad which does not unwind
1605 // to caller.
1606 bool EHPadForCallUnwindsLocally = false;
1607 if (CallSiteEHPad && CS.isCall()) {
1608 UnwindDestMemoTy FuncletUnwindMap;
1609 Value *CallSiteUnwindDestToken =
1610 getUnwindDestToken(CallSiteEHPad, FuncletUnwindMap);
1611
1612 EHPadForCallUnwindsLocally =
1613 CallSiteUnwindDestToken &&
1614 !isa<ConstantTokenNone>(CallSiteUnwindDestToken);
1615 }
1616
Chris Lattner9fc977e2004-02-04 01:41:09 +00001617 // Get an iterator to the last basic block in the function, which will have
1618 // the new function inlined after it.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001619 Function::iterator LastBlock = --Caller->end();
Chris Lattner9fc977e2004-02-04 01:41:09 +00001620
Chris Lattner18ef3fd2004-02-04 02:51:48 +00001621 // Make sure to capture all of the return instructions from the cloned
Chris Lattner530d4bf2003-05-29 15:11:31 +00001622 // function.
Chris Lattnerd84dbb32009-08-27 04:02:30 +00001623 SmallVector<ReturnInst*, 8> Returns;
Chris Lattner908d7952006-01-13 19:05:59 +00001624 ClonedCodeInfo InlinedFunctionInfo;
Dale Johannesen845e5822009-03-04 02:09:48 +00001625 Function::iterator FirstNewBlock;
Duncan Sandsaa31b922007-12-19 21:13:37 +00001626
Devang Patelb8f11de2010-06-23 23:55:51 +00001627 { // Scope to destroy VMap after cloning.
Rafael Espindola229e38f2010-10-13 01:36:30 +00001628 ValueToValueMapTy VMap;
Julien Lerouge957e91c2014-04-15 18:01:54 +00001629 // Keep a list of pair (dst, src) to emit byval initializations.
1630 SmallVector<std::pair<Value*, Value*>, 4> ByValInit;
Chris Lattnerbe853d72006-05-27 01:28:04 +00001631
Mehdi Amini46a43552015-03-04 18:43:29 +00001632 auto &DL = Caller->getParent()->getDataLayout();
1633
Chris Lattner908117b2008-01-11 06:09:30 +00001634 // Calculate the vector of arguments to pass into the function cloner, which
1635 // matches up the formal to the actual argument values.
Chris Lattner18ef3fd2004-02-04 02:51:48 +00001636 CallSite::arg_iterator AI = CS.arg_begin();
Chris Lattner908117b2008-01-11 06:09:30 +00001637 unsigned ArgNo = 0;
Reid Kleckner45707d42017-03-16 22:59:15 +00001638 for (Function::arg_iterator I = CalledFunc->arg_begin(),
Chris Lattner908117b2008-01-11 06:09:30 +00001639 E = CalledFunc->arg_end(); I != E; ++I, ++AI, ++ArgNo) {
1640 Value *ActualArg = *AI;
Duncan Sands7c8fb1a2008-09-05 12:37:12 +00001641
Duncan Sands053c9872008-01-27 18:12:58 +00001642 // When byval arguments actually inlined, we need to make the copy implied
1643 // by them explicit. However, we don't do this if the callee is readonly
1644 // or readnone, because the copy would be unneeded: the callee doesn't
1645 // modify the struct.
Nick Lewycky612d70b2011-11-20 19:09:04 +00001646 if (CS.isByValArgument(ArgNo)) {
David Majnemer120f4a02013-11-03 12:22:13 +00001647 ActualArg = HandleByValArgument(ActualArg, TheCall, CalledFunc, IFI,
Reid Kleckner859f8b52017-04-28 20:34:27 +00001648 CalledFunc->getParamAlignment(ArgNo));
Reid Kleckner9b2cc642014-04-21 20:48:47 +00001649 if (ActualArg != *AI)
Julien Lerouge957e91c2014-04-15 18:01:54 +00001650 ByValInit.push_back(std::make_pair(ActualArg, (Value*) *AI));
Chris Lattner908117b2008-01-11 06:09:30 +00001651 }
Duncan Sands7c8fb1a2008-09-05 12:37:12 +00001652
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001653 VMap[&*I] = ActualArg;
Chris Lattner908117b2008-01-11 06:09:30 +00001654 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001655
Hans Wennborg2d5841f2017-02-27 22:33:02 +00001656 // Add alignment assumptions if necessary. We do this before the inlined
1657 // instructions are actually cloned into the caller so that we can easily
1658 // check what will be known at the start of the inlined code.
1659 AddAlignmentAssumptions(CS, IFI);
Hal Finkel68dc3c72014-10-15 23:44:41 +00001660
Chris Lattnerbe853d72006-05-27 01:28:04 +00001661 // We want the inliner to prune the code as it copies. We would LOVE to
1662 // have no dead or constant instructions leftover after inlining occurs
1663 // (which can happen, e.g., because an argument was constant), but we'll be
1664 // happy with whatever the cloner can do.
Mehdi Amini46a43552015-03-04 18:43:29 +00001665 CloneAndPruneFunctionInto(Caller, CalledFunc, VMap,
Dan Gohmanca26f792010-08-26 15:41:53 +00001666 /*ModuleLevelChanges=*/false, Returns, ".i",
Easwaran Ramanb1bd3982016-03-08 00:36:35 +00001667 &InlinedFunctionInfo, TheCall);
Chris Lattner5de3b8b2006-07-12 18:29:36 +00001668 // Remember the first block that is newly cloned over.
1669 FirstNewBlock = LastBlock; ++FirstNewBlock;
Duncan Sands7c8fb1a2008-09-05 12:37:12 +00001670
Dehao Chene5930492017-03-20 16:40:44 +00001671 if (IFI.CallerBFI != nullptr && IFI.CalleeBFI != nullptr)
Easwaran Raman12585b02017-01-20 22:44:04 +00001672 // Update the BFI of blocks cloned into the caller.
1673 updateCallerBFI(OrigBB, VMap, IFI.CallerBFI, IFI.CalleeBFI,
1674 CalledFunc->front());
Dehao Chene5930492017-03-20 16:40:44 +00001675
Easwaran Ramanf5f91602017-05-09 23:21:10 +00001676 updateCallProfile(CalledFunc, VMap, CalledFunc->getEntryCount(), TheCall,
Teresa Johnson525dcb62017-05-22 20:28:18 +00001677 IFI.PSI, IFI.CallerBFI);
Dehao Chene5930492017-03-20 16:40:44 +00001678 // Update the profile count of callee.
Easwaran Ramanf5f91602017-05-09 23:21:10 +00001679 updateCalleeCount(IFI.CallerBFI, OrigBB, TheCall, CalledFunc, IFI.PSI);
Easwaran Raman12585b02017-01-20 22:44:04 +00001680
Julien Lerouge957e91c2014-04-15 18:01:54 +00001681 // Inject byval arguments initialization.
1682 for (std::pair<Value*, Value*> &Init : ByValInit)
1683 HandleByValArgumentInit(Init.first, Init.second, Caller->getParent(),
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001684 &*FirstNewBlock, IFI);
Julien Lerouge957e91c2014-04-15 18:01:54 +00001685
David Majnemer3bb88c02015-12-15 21:27:27 +00001686 Optional<OperandBundleUse> ParentDeopt =
1687 CS.getOperandBundle(LLVMContext::OB_deopt);
1688 if (ParentDeopt) {
Sanjoy Das2d161452015-11-18 06:23:38 +00001689 SmallVector<OperandBundleDef, 2> OpDefs;
1690
1691 for (auto &VH : InlinedFunctionInfo.OperandBundleCallSites) {
Sanjoy Dasab0626e2015-12-19 22:40:28 +00001692 Instruction *I = dyn_cast_or_null<Instruction>(VH);
1693 if (!I) continue; // instruction was DCE'd or RAUW'ed to undef
Sanjoy Das2d161452015-11-18 06:23:38 +00001694
1695 OpDefs.clear();
1696
1697 CallSite ICS(I);
1698 OpDefs.reserve(ICS.getNumOperandBundles());
1699
1700 for (unsigned i = 0, e = ICS.getNumOperandBundles(); i < e; ++i) {
1701 auto ChildOB = ICS.getOperandBundleAt(i);
1702 if (ChildOB.getTagID() != LLVMContext::OB_deopt) {
1703 // If the inlined call has other operand bundles, let them be
1704 OpDefs.emplace_back(ChildOB);
1705 continue;
1706 }
1707
1708 // It may be useful to separate this logic (of handling operand
1709 // bundles) out to a separate "policy" component if this gets crowded.
1710 // Prepend the parent's deoptimization continuation to the newly
1711 // inlined call's deoptimization continuation.
1712 std::vector<Value *> MergedDeoptArgs;
David Majnemer3bb88c02015-12-15 21:27:27 +00001713 MergedDeoptArgs.reserve(ParentDeopt->Inputs.size() +
Sanjoy Das2d161452015-11-18 06:23:38 +00001714 ChildOB.Inputs.size());
1715
1716 MergedDeoptArgs.insert(MergedDeoptArgs.end(),
David Majnemer3bb88c02015-12-15 21:27:27 +00001717 ParentDeopt->Inputs.begin(),
1718 ParentDeopt->Inputs.end());
Sanjoy Das2d161452015-11-18 06:23:38 +00001719 MergedDeoptArgs.insert(MergedDeoptArgs.end(), ChildOB.Inputs.begin(),
1720 ChildOB.Inputs.end());
1721
Sanjoy Das8da1f952015-12-08 03:50:32 +00001722 OpDefs.emplace_back("deopt", std::move(MergedDeoptArgs));
Sanjoy Das2d161452015-11-18 06:23:38 +00001723 }
1724
1725 Instruction *NewI = nullptr;
1726 if (isa<CallInst>(I))
1727 NewI = CallInst::Create(cast<CallInst>(I), OpDefs, I);
1728 else
1729 NewI = InvokeInst::Create(cast<InvokeInst>(I), OpDefs, I);
1730
1731 // Note: the RAUW does the appropriate fixup in VMap, so we need to do
1732 // this even if the call returns void.
1733 I->replaceAllUsesWith(NewI);
1734
1735 VH = nullptr;
1736 I->eraseFromParent();
1737 }
1738 }
1739
Chris Lattner5de3b8b2006-07-12 18:29:36 +00001740 // Update the callgraph if requested.
Chandler Carruth0ee8bb12016-12-27 01:24:50 +00001741 if (IFI.CG)
Devang Patelb8f11de2010-06-23 23:55:51 +00001742 UpdateCallGraphAfterInlining(CS, FirstNewBlock, VMap, IFI);
Devang Patel35797402011-07-08 18:01:31 +00001743
Andrea Di Biagio32d5aed2016-12-07 10:37:26 +00001744 // For 'nodebug' functions, the associated DISubprogram is always null.
1745 // Conservatively avoid propagating the callsite debug location to
1746 // instructions inlined from a function whose DISubprogram is not null.
Adrian Prantld4056502017-03-07 17:28:57 +00001747 fixupLineNumbers(Caller, FirstNewBlock, TheCall,
1748 CalledFunc->getSubprogram() != nullptr);
Hal Finkel94146652014-07-24 14:25:39 +00001749
1750 // Clone existing noalias metadata if necessary.
1751 CloneAliasScopeMetadata(CS, VMap);
Hal Finkelff0bcb62014-07-25 15:50:08 +00001752
1753 // Add noalias metadata if necessary.
Chandler Carruth7b560d42015-09-09 17:55:00 +00001754 AddAliasScopeMetadata(CS, VMap, DL, CalleeAAR);
Hal Finkel74c2f352014-09-07 12:44:26 +00001755
Hal Finkel50316d92016-04-28 23:00:04 +00001756 // Propagate llvm.mem.parallel_loop_access if necessary.
1757 PropagateParallelLoopAccessMetadata(CS, VMap);
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001758
1759 // Register any cloned assumptions.
1760 if (IFI.GetAssumptionCache)
1761 for (BasicBlock &NewBlock :
1762 make_range(FirstNewBlock->getIterator(), Caller->end()))
1763 for (Instruction &I : NewBlock) {
1764 if (auto *II = dyn_cast<IntrinsicInst>(&I))
1765 if (II->getIntrinsicID() == Intrinsic::assume)
1766 (*IFI.GetAssumptionCache)(*Caller).registerAssumption(II);
1767 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001768 }
Duncan Sands7c8fb1a2008-09-05 12:37:12 +00001769
Chris Lattner530d4bf2003-05-29 15:11:31 +00001770 // If there are any alloca instructions in the block that used to be the entry
1771 // block for the callee, move them to the entry block of the caller. First
1772 // calculate which instruction they should be inserted before. We insert the
1773 // instructions at the end of the current alloca list.
Chris Lattner257492c2006-01-13 18:16:48 +00001774 {
Chris Lattner0cc265e2003-08-24 06:59:16 +00001775 BasicBlock::iterator InsertPoint = Caller->begin()->begin();
Chris Lattner18ef3fd2004-02-04 02:51:48 +00001776 for (BasicBlock::iterator I = FirstNewBlock->begin(),
Chris Lattner5eef6ad2009-08-27 03:51:50 +00001777 E = FirstNewBlock->end(); I != E; ) {
1778 AllocaInst *AI = dyn_cast<AllocaInst>(I++);
Craig Topperf40110f2014-04-25 05:29:35 +00001779 if (!AI) continue;
Chris Lattner5eef6ad2009-08-27 03:51:50 +00001780
1781 // If the alloca is now dead, remove it. This often occurs due to code
1782 // specialization.
1783 if (AI->use_empty()) {
1784 AI->eraseFromParent();
1785 continue;
Chris Lattner6ef6d062006-09-13 19:23:57 +00001786 }
Chris Lattner5eef6ad2009-08-27 03:51:50 +00001787
Reid Kleckner6ee00a22016-08-12 22:23:04 +00001788 if (!allocaWouldBeStaticInEntry(AI))
Chris Lattner5eef6ad2009-08-27 03:51:50 +00001789 continue;
1790
Chris Lattnercd3af962010-12-06 07:43:04 +00001791 // Keep track of the static allocas that we inline into the caller.
Chris Lattner4ba01ec2010-04-22 23:07:58 +00001792 IFI.StaticAllocas.push_back(AI);
Chris Lattnerb1cba3f2009-08-27 04:20:52 +00001793
Chris Lattner5eef6ad2009-08-27 03:51:50 +00001794 // Scan for the block of allocas that we can move over, and move them
1795 // all at once.
1796 while (isa<AllocaInst>(I) &&
Reid Kleckner6ee00a22016-08-12 22:23:04 +00001797 allocaWouldBeStaticInEntry(cast<AllocaInst>(I))) {
Chris Lattner4ba01ec2010-04-22 23:07:58 +00001798 IFI.StaticAllocas.push_back(cast<AllocaInst>(I));
Chris Lattner5eef6ad2009-08-27 03:51:50 +00001799 ++I;
Chris Lattnerb1cba3f2009-08-27 04:20:52 +00001800 }
Chris Lattner5eef6ad2009-08-27 03:51:50 +00001801
1802 // Transfer all of the allocas over in a block. Using splice means
1803 // that the instructions aren't removed from the symbol table, then
1804 // reinserted.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001805 Caller->getEntryBlock().getInstList().splice(
1806 InsertPoint, FirstNewBlock->getInstList(), AI->getIterator(), I);
Chris Lattner5eef6ad2009-08-27 03:51:50 +00001807 }
Adrian Prantl4d365252015-01-30 01:55:25 +00001808 // Move any dbg.declares describing the allocas into the entry basic block.
Adrian Prantl3e2659e2015-01-30 19:37:48 +00001809 DIBuilder DIB(*Caller->getParent());
Adrian Prantl133e1022015-01-30 19:42:59 +00001810 for (auto &AI : IFI.StaticAllocas)
Adrian Prantld1317012017-12-08 21:58:18 +00001811 replaceDbgDeclareForAlloca(AI, AI, DIB, DIExpression::NoDeref, 0,
1812 DIExpression::NoDeref);
Chris Lattner0cc265e2003-08-24 06:59:16 +00001813 }
Chris Lattner530d4bf2003-05-29 15:11:31 +00001814
Florian Hahn0e9dec62017-11-13 10:35:52 +00001815 SmallVector<Value*,4> VarArgsToForward;
Florian Hahnde10e6e2018-01-06 20:46:00 +00001816 SmallVector<AttributeSet, 4> VarArgsAttrs;
Florian Hahn0e9dec62017-11-13 10:35:52 +00001817 for (unsigned i = CalledFunc->getFunctionType()->getNumParams();
Florian Hahnde10e6e2018-01-06 20:46:00 +00001818 i < CS.getNumArgOperands(); i++) {
Florian Hahn0e9dec62017-11-13 10:35:52 +00001819 VarArgsToForward.push_back(CS.getArgOperand(i));
Florian Hahnde10e6e2018-01-06 20:46:00 +00001820 VarArgsAttrs.push_back(CS.getAttributes().getParamAttributes(i));
1821 }
Florian Hahn0e9dec62017-11-13 10:35:52 +00001822
Sanjoy Dasb51325d2016-03-11 19:08:34 +00001823 bool InlinedMustTailCalls = false, InlinedDeoptimizeCalls = false;
Reid Klecknerf0915aa2014-05-15 20:11:28 +00001824 if (InlinedFunctionInfo.ContainsCalls) {
Reid Kleckner6af21242014-05-15 20:39:42 +00001825 CallInst::TailCallKind CallSiteTailKind = CallInst::TCK_None;
1826 if (CallInst *CI = dyn_cast<CallInst>(TheCall))
1827 CallSiteTailKind = CI->getTailCallKind();
1828
Reid Klecknera9e99182018-04-02 21:23:16 +00001829 // For inlining purposes, the "notail" marker is the same as no marker.
1830 if (CallSiteTailKind == CallInst::TCK_NoTail)
1831 CallSiteTailKind = CallInst::TCK_None;
1832
Reid Klecknerf0915aa2014-05-15 20:11:28 +00001833 for (Function::iterator BB = FirstNewBlock, E = Caller->end(); BB != E;
1834 ++BB) {
Florian Hahn0e9dec62017-11-13 10:35:52 +00001835 for (auto II = BB->begin(); II != BB->end();) {
1836 Instruction &I = *II++;
Reid Klecknerf0915aa2014-05-15 20:11:28 +00001837 CallInst *CI = dyn_cast<CallInst>(&I);
1838 if (!CI)
1839 continue;
1840
Florian Hahn80788d82018-01-06 19:45:40 +00001841 // Forward varargs from inlined call site to calls to the
1842 // ForwardVarArgsTo function, if requested, and to musttail calls.
1843 if (!VarArgsToForward.empty() &&
1844 ((ForwardVarArgsTo &&
1845 CI->getCalledFunction() == ForwardVarArgsTo) ||
1846 CI->isMustTailCall())) {
Florian Hahnde10e6e2018-01-06 20:46:00 +00001847 // Collect attributes for non-vararg parameters.
1848 AttributeList Attrs = CI->getAttributes();
1849 SmallVector<AttributeSet, 8> ArgAttrs;
Florian Hahn8f804fc2018-02-04 18:27:47 +00001850 if (!Attrs.isEmpty() || !VarArgsAttrs.empty()) {
Florian Hahnde10e6e2018-01-06 20:46:00 +00001851 for (unsigned ArgNo = 0;
1852 ArgNo < CI->getFunctionType()->getNumParams(); ++ArgNo)
1853 ArgAttrs.push_back(Attrs.getParamAttributes(ArgNo));
1854 }
1855
1856 // Add VarArg attributes.
1857 ArgAttrs.append(VarArgsAttrs.begin(), VarArgsAttrs.end());
1858 Attrs = AttributeList::get(CI->getContext(), Attrs.getFnAttributes(),
1859 Attrs.getRetAttributes(), ArgAttrs);
1860 // Add VarArgs to existing parameters.
Florian Hahn80788d82018-01-06 19:45:40 +00001861 SmallVector<Value *, 6> Params(CI->arg_operands());
1862 Params.append(VarArgsToForward.begin(), VarArgsToForward.end());
Florian Hahnde10e6e2018-01-06 20:46:00 +00001863 CallInst *NewCI =
Florian Hahn80788d82018-01-06 19:45:40 +00001864 CallInst::Create(CI->getCalledFunction() ? CI->getCalledFunction()
1865 : CI->getCalledValue(),
1866 Params, "", CI);
Florian Hahnde10e6e2018-01-06 20:46:00 +00001867 NewCI->setDebugLoc(CI->getDebugLoc());
1868 NewCI->setAttributes(Attrs);
Florian Hahna82eef22018-01-06 20:56:27 +00001869 NewCI->setCallingConv(CI->getCallingConv());
Florian Hahnde10e6e2018-01-06 20:46:00 +00001870 CI->replaceAllUsesWith(NewCI);
Florian Hahn80788d82018-01-06 19:45:40 +00001871 CI->eraseFromParent();
Florian Hahnde10e6e2018-01-06 20:46:00 +00001872 CI = NewCI;
Florian Hahn80788d82018-01-06 19:45:40 +00001873 }
1874
Sanjoy Dasb51325d2016-03-11 19:08:34 +00001875 if (Function *F = CI->getCalledFunction())
1876 InlinedDeoptimizeCalls |=
1877 F->getIntrinsicID() == Intrinsic::experimental_deoptimize;
1878
Reid Klecknerf0915aa2014-05-15 20:11:28 +00001879 // We need to reduce the strength of any inlined tail calls. For
1880 // musttail, we have to avoid introducing potential unbounded stack
1881 // growth. For example, if functions 'f' and 'g' are mutually recursive
1882 // with musttail, we can inline 'g' into 'f' so long as we preserve
1883 // musttail on the cloned call to 'f'. If either the inlined call site
1884 // or the cloned call site is *not* musttail, the program already has
1885 // one frame of stack growth, so it's safe to remove musttail. Here is
1886 // a table of example transformations:
1887 //
1888 // f -> musttail g -> musttail f ==> f -> musttail f
1889 // f -> musttail g -> tail f ==> f -> tail f
1890 // f -> g -> musttail f ==> f -> f
1891 // f -> g -> tail f ==> f -> f
Reid Klecknera9e99182018-04-02 21:23:16 +00001892 //
1893 // Inlined notail calls should remain notail calls.
Reid Klecknerf0915aa2014-05-15 20:11:28 +00001894 CallInst::TailCallKind ChildTCK = CI->getTailCallKind();
Arnold Schwaighoferd9e71092017-11-27 19:03:40 +00001895 if (ChildTCK != CallInst::TCK_NoTail)
1896 ChildTCK = std::min(CallSiteTailKind, ChildTCK);
Reid Klecknerdd3f3ed2014-11-04 02:02:14 +00001897 CI->setTailCallKind(ChildTCK);
Reid Klecknerf0915aa2014-05-15 20:11:28 +00001898 InlinedMustTailCalls |= CI->isMustTailCall();
1899
1900 // Calls inlined through a 'nounwind' call site should be marked
1901 // 'nounwind'.
1902 if (MarkNoUnwind)
1903 CI->setDoesNotThrow();
1904 }
1905 }
1906 }
1907
Nick Lewyckya68ec832011-05-22 05:22:10 +00001908 // Leave lifetime markers for the static alloca's, scoping them to the
1909 // function we just inlined.
Chad Rosier07d37bc2012-02-25 02:56:01 +00001910 if (InsertLifetime && !IFI.StaticAllocas.empty()) {
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001911 IRBuilder<> builder(&FirstNewBlock->front());
Nick Lewyckya68ec832011-05-22 05:22:10 +00001912 for (unsigned ai = 0, ae = IFI.StaticAllocas.size(); ai != ae; ++ai) {
1913 AllocaInst *AI = IFI.StaticAllocas[ai];
Arnold Schwaighoferc9277f42016-09-09 22:40:27 +00001914 // Don't mark swifterror allocas. They can't have bitcast uses.
1915 if (AI->isSwiftError())
1916 continue;
Nick Lewyckya68ec832011-05-22 05:22:10 +00001917
1918 // If the alloca is already scoped to something smaller than the whole
1919 // function then there's no need to add redundant, less accurate markers.
1920 if (hasLifetimeMarkers(AI))
1921 continue;
1922
Alexey Samsonovcfd662f2012-11-13 07:15:32 +00001923 // Try to determine the size of the allocation.
Craig Topperf40110f2014-04-25 05:29:35 +00001924 ConstantInt *AllocaSize = nullptr;
Alexey Samsonovcfd662f2012-11-13 07:15:32 +00001925 if (ConstantInt *AIArraySize =
1926 dyn_cast<ConstantInt>(AI->getArraySize())) {
Mehdi Amini46a43552015-03-04 18:43:29 +00001927 auto &DL = Caller->getParent()->getDataLayout();
1928 Type *AllocaType = AI->getAllocatedType();
1929 uint64_t AllocaTypeSize = DL.getTypeAllocSize(AllocaType);
1930 uint64_t AllocaArraySize = AIArraySize->getLimitedValue();
Akira Hatanaka2cc2b632015-04-20 16:11:05 +00001931
1932 // Don't add markers for zero-sized allocas.
1933 if (AllocaArraySize == 0)
1934 continue;
1935
Mehdi Amini46a43552015-03-04 18:43:29 +00001936 // Check that array size doesn't saturate uint64_t and doesn't
1937 // overflow when it's multiplied by type size.
Eugene Zelenko6cadde72017-10-17 21:27:42 +00001938 if (AllocaArraySize != std::numeric_limits<uint64_t>::max() &&
1939 std::numeric_limits<uint64_t>::max() / AllocaArraySize >=
1940 AllocaTypeSize) {
Mehdi Amini46a43552015-03-04 18:43:29 +00001941 AllocaSize = ConstantInt::get(Type::getInt64Ty(AI->getContext()),
1942 AllocaArraySize * AllocaTypeSize);
Alexey Samsonovcfd662f2012-11-13 07:15:32 +00001943 }
1944 }
1945
1946 builder.CreateLifetimeStart(AI, AllocaSize);
Reid Kleckner900d46f2014-05-15 21:10:46 +00001947 for (ReturnInst *RI : Returns) {
Sanjoy Das18b92962016-04-01 02:51:26 +00001948 // Don't insert llvm.lifetime.end calls between a musttail or deoptimize
1949 // call and a return. The return kills all local allocas.
Reid Klecknere31acf22014-08-12 00:05:15 +00001950 if (InlinedMustTailCalls &&
1951 RI->getParent()->getTerminatingMustTailCall())
Reid Kleckner900d46f2014-05-15 21:10:46 +00001952 continue;
Sanjoy Das18b92962016-04-01 02:51:26 +00001953 if (InlinedDeoptimizeCalls &&
1954 RI->getParent()->getTerminatingDeoptimizeCall())
1955 continue;
Reid Klecknerf0915aa2014-05-15 20:11:28 +00001956 IRBuilder<>(RI).CreateLifetimeEnd(AI, AllocaSize);
Reid Kleckner900d46f2014-05-15 21:10:46 +00001957 }
Nick Lewyckya68ec832011-05-22 05:22:10 +00001958 }
1959 }
1960
Chris Lattner2be06072006-01-13 19:34:14 +00001961 // If the inlined code contained dynamic alloca instructions, wrap the inlined
1962 // code with llvm.stacksave/llvm.stackrestore intrinsics.
1963 if (InlinedFunctionInfo.ContainsDynamicAllocas) {
1964 Module *M = Caller->getParent();
Chris Lattner2be06072006-01-13 19:34:14 +00001965 // Get the two intrinsics we care about.
Chris Lattner88b36f12009-10-17 05:39:39 +00001966 Function *StackSave = Intrinsic::getDeclaration(M, Intrinsic::stacksave);
1967 Function *StackRestore=Intrinsic::getDeclaration(M,Intrinsic::stackrestore);
Chris Lattner5de3b8b2006-07-12 18:29:36 +00001968
Chris Lattner2be06072006-01-13 19:34:14 +00001969 // Insert the llvm.stacksave.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001970 CallInst *SavedPtr = IRBuilder<>(&*FirstNewBlock, FirstNewBlock->begin())
David Blaikieff6409d2015-05-18 22:13:54 +00001971 .CreateCall(StackSave, {}, "savedstack");
Duncan Sands7c8fb1a2008-09-05 12:37:12 +00001972
Chris Lattner2be06072006-01-13 19:34:14 +00001973 // Insert a call to llvm.stackrestore before any return instructions in the
1974 // inlined function.
Reid Kleckner900d46f2014-05-15 21:10:46 +00001975 for (ReturnInst *RI : Returns) {
Sanjoy Dasf83ab6d2016-04-01 02:51:30 +00001976 // Don't insert llvm.stackrestore calls between a musttail or deoptimize
1977 // call and a return. The return will restore the stack pointer.
Reid Klecknere31acf22014-08-12 00:05:15 +00001978 if (InlinedMustTailCalls && RI->getParent()->getTerminatingMustTailCall())
Reid Kleckner900d46f2014-05-15 21:10:46 +00001979 continue;
Sanjoy Dasf83ab6d2016-04-01 02:51:30 +00001980 if (InlinedDeoptimizeCalls && RI->getParent()->getTerminatingDeoptimizeCall())
1981 continue;
Reid Klecknerf0915aa2014-05-15 20:11:28 +00001982 IRBuilder<>(RI).CreateCall(StackRestore, SavedPtr);
Reid Kleckner900d46f2014-05-15 21:10:46 +00001983 }
Chris Lattner9f3dced2005-05-06 06:47:52 +00001984 }
1985
Joseph Tremouletb41632b2016-01-20 02:15:15 +00001986 // If we are inlining for an invoke instruction, we must make sure to rewrite
1987 // any call instructions into invoke instructions. This is sensitive to which
1988 // funclet pads were top-level in the inlinee, so must be done before
1989 // rewriting the "parent pad" links.
1990 if (auto *II = dyn_cast<InvokeInst>(TheCall)) {
1991 BasicBlock *UnwindDest = II->getUnwindDest();
1992 Instruction *FirstNonPHI = UnwindDest->getFirstNonPHI();
1993 if (isa<LandingPadInst>(FirstNonPHI)) {
1994 HandleInlinedLandingPad(II, &*FirstNewBlock, InlinedFunctionInfo);
1995 } else {
1996 HandleInlinedEHPad(II, &*FirstNewBlock, InlinedFunctionInfo);
1997 }
1998 }
1999
David Majnemer3bb88c02015-12-15 21:27:27 +00002000 // Update the lexical scopes of the new funclets and callsites.
2001 // Anything that had 'none' as its parent is now nested inside the callsite's
2002 // EHPad.
2003
David Majnemer8a1c45d2015-12-12 05:38:55 +00002004 if (CallSiteEHPad) {
2005 for (Function::iterator BB = FirstNewBlock->getIterator(),
2006 E = Caller->end();
2007 BB != E; ++BB) {
David Majnemer3bb88c02015-12-15 21:27:27 +00002008 // Add bundle operands to any top-level call sites.
2009 SmallVector<OperandBundleDef, 1> OpBundles;
2010 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E;) {
2011 Instruction *I = &*BBI++;
2012 CallSite CS(I);
2013 if (!CS)
2014 continue;
2015
2016 // Skip call sites which are nounwind intrinsics.
2017 auto *CalledFn =
2018 dyn_cast<Function>(CS.getCalledValue()->stripPointerCasts());
2019 if (CalledFn && CalledFn->isIntrinsic() && CS.doesNotThrow())
2020 continue;
2021
2022 // Skip call sites which already have a "funclet" bundle.
2023 if (CS.getOperandBundle(LLVMContext::OB_funclet))
2024 continue;
2025
2026 CS.getOperandBundlesAsDefs(OpBundles);
2027 OpBundles.emplace_back("funclet", CallSiteEHPad);
2028
2029 Instruction *NewInst;
2030 if (CS.isCall())
2031 NewInst = CallInst::Create(cast<CallInst>(I), OpBundles, I);
2032 else
2033 NewInst = InvokeInst::Create(cast<InvokeInst>(I), OpBundles, I);
David Majnemer3bb88c02015-12-15 21:27:27 +00002034 NewInst->takeName(I);
2035 I->replaceAllUsesWith(NewInst);
2036 I->eraseFromParent();
2037
2038 OpBundles.clear();
2039 }
2040
David Majnemer223538f2016-02-23 17:11:04 +00002041 // It is problematic if the inlinee has a cleanupret which unwinds to
2042 // caller and we inline it into a call site which doesn't unwind but into
2043 // an EH pad that does. Such an edge must be dynamically unreachable.
2044 // As such, we replace the cleanupret with unreachable.
2045 if (auto *CleanupRet = dyn_cast<CleanupReturnInst>(BB->getTerminator()))
2046 if (CleanupRet->unwindsToCaller() && EHPadForCallUnwindsLocally)
David Majnemere14e7bc2016-06-25 08:19:55 +00002047 changeToUnreachable(CleanupRet, /*UseLLVMTrap=*/false);
David Majnemer223538f2016-02-23 17:11:04 +00002048
David Majnemer8a1c45d2015-12-12 05:38:55 +00002049 Instruction *I = BB->getFirstNonPHI();
2050 if (!I->isEHPad())
2051 continue;
2052
David Majnemerbbfc7212015-12-14 18:34:23 +00002053 if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(I)) {
David Majnemer8a1c45d2015-12-12 05:38:55 +00002054 if (isa<ConstantTokenNone>(CatchSwitch->getParentPad()))
2055 CatchSwitch->setParentPad(CallSiteEHPad);
2056 } else {
2057 auto *FPI = cast<FuncletPadInst>(I);
2058 if (isa<ConstantTokenNone>(FPI->getParentPad()))
2059 FPI->setParentPad(CallSiteEHPad);
2060 }
2061 }
2062 }
2063
Sanjoy Dasb51325d2016-03-11 19:08:34 +00002064 if (InlinedDeoptimizeCalls) {
2065 // We need to at least remove the deoptimizing returns from the Return set,
2066 // so that the control flow from those returns does not get merged into the
2067 // caller (but terminate it instead). If the caller's return type does not
2068 // match the callee's return type, we also need to change the return type of
2069 // the intrinsic.
2070 if (Caller->getReturnType() == TheCall->getType()) {
Eugene Zelenko6cadde72017-10-17 21:27:42 +00002071 auto NewEnd = llvm::remove_if(Returns, [](ReturnInst *RI) {
Sanjoy Dasb51325d2016-03-11 19:08:34 +00002072 return RI->getParent()->getTerminatingDeoptimizeCall() != nullptr;
2073 });
2074 Returns.erase(NewEnd, Returns.end());
2075 } else {
2076 SmallVector<ReturnInst *, 8> NormalReturns;
2077 Function *NewDeoptIntrinsic = Intrinsic::getDeclaration(
2078 Caller->getParent(), Intrinsic::experimental_deoptimize,
2079 {Caller->getReturnType()});
2080
2081 for (ReturnInst *RI : Returns) {
2082 CallInst *DeoptCall = RI->getParent()->getTerminatingDeoptimizeCall();
2083 if (!DeoptCall) {
2084 NormalReturns.push_back(RI);
2085 continue;
2086 }
2087
Sanjoy Dase0aa4142016-05-12 01:17:38 +00002088 // The calling convention on the deoptimize call itself may be bogus,
2089 // since the code we're inlining may have undefined behavior (and may
2090 // never actually execute at runtime); but all
2091 // @llvm.experimental.deoptimize declarations have to have the same
2092 // calling convention in a well-formed module.
2093 auto CallingConv = DeoptCall->getCalledFunction()->getCallingConv();
2094 NewDeoptIntrinsic->setCallingConv(CallingConv);
Sanjoy Dasb51325d2016-03-11 19:08:34 +00002095 auto *CurBB = RI->getParent();
2096 RI->eraseFromParent();
2097
2098 SmallVector<Value *, 4> CallArgs(DeoptCall->arg_begin(),
2099 DeoptCall->arg_end());
2100
2101 SmallVector<OperandBundleDef, 1> OpBundles;
2102 DeoptCall->getOperandBundlesAsDefs(OpBundles);
2103 DeoptCall->eraseFromParent();
2104 assert(!OpBundles.empty() &&
2105 "Expected at least the deopt operand bundle");
2106
2107 IRBuilder<> Builder(CurBB);
Sanjoy Dasdd77e1e2016-04-09 00:22:59 +00002108 CallInst *NewDeoptCall =
Sanjoy Dasb51325d2016-03-11 19:08:34 +00002109 Builder.CreateCall(NewDeoptIntrinsic, CallArgs, OpBundles);
Sanjoy Dasdd77e1e2016-04-09 00:22:59 +00002110 NewDeoptCall->setCallingConv(CallingConv);
Sanjoy Dasb51325d2016-03-11 19:08:34 +00002111 if (NewDeoptCall->getType()->isVoidTy())
2112 Builder.CreateRetVoid();
2113 else
2114 Builder.CreateRet(NewDeoptCall);
2115 }
2116
2117 // Leave behind the normal returns so we can merge control flow.
2118 std::swap(Returns, NormalReturns);
2119 }
2120 }
2121
Reid Klecknerf0915aa2014-05-15 20:11:28 +00002122 // Handle any inlined musttail call sites. In order for a new call site to be
2123 // musttail, the source of the clone and the inlined call site must have been
2124 // musttail. Therefore it's safe to return without merging control into the
2125 // phi below.
2126 if (InlinedMustTailCalls) {
2127 // Check if we need to bitcast the result of any musttail calls.
2128 Type *NewRetTy = Caller->getReturnType();
2129 bool NeedBitCast = !TheCall->use_empty() && TheCall->getType() != NewRetTy;
2130
2131 // Handle the returns preceded by musttail calls separately.
2132 SmallVector<ReturnInst *, 8> NormalReturns;
2133 for (ReturnInst *RI : Returns) {
Reid Klecknere31acf22014-08-12 00:05:15 +00002134 CallInst *ReturnedMustTail =
2135 RI->getParent()->getTerminatingMustTailCall();
Reid Klecknerf0915aa2014-05-15 20:11:28 +00002136 if (!ReturnedMustTail) {
2137 NormalReturns.push_back(RI);
2138 continue;
2139 }
2140 if (!NeedBitCast)
2141 continue;
2142
2143 // Delete the old return and any preceding bitcast.
2144 BasicBlock *CurBB = RI->getParent();
2145 auto *OldCast = dyn_cast_or_null<BitCastInst>(RI->getReturnValue());
2146 RI->eraseFromParent();
2147 if (OldCast)
2148 OldCast->eraseFromParent();
2149
2150 // Insert a new bitcast and return with the right type.
2151 IRBuilder<> Builder(CurBB);
2152 Builder.CreateRet(Builder.CreateBitCast(ReturnedMustTail, NewRetTy));
2153 }
2154
2155 // Leave behind the normal returns so we can merge control flow.
2156 std::swap(Returns, NormalReturns);
2157 }
2158
Chandler Carruth0ee8bb12016-12-27 01:24:50 +00002159 // Now that all of the transforms on the inlined code have taken place but
2160 // before we splice the inlined code into the CFG and lose track of which
2161 // blocks were actually inlined, collect the call sites. We only do this if
2162 // call graph updates weren't requested, as those provide value handle based
2163 // tracking of inlined call sites instead.
2164 if (InlinedFunctionInfo.ContainsCalls && !IFI.CG) {
2165 // Otherwise just collect the raw call sites that were inlined.
2166 for (BasicBlock &NewBB :
2167 make_range(FirstNewBlock->getIterator(), Caller->end()))
2168 for (Instruction &I : NewBB)
2169 if (auto CS = CallSite(&I))
2170 IFI.InlinedCallSites.push_back(CS);
2171 }
2172
Chris Lattner0fa8c7c2004-02-04 04:17:06 +00002173 // If we cloned in _exactly one_ basic block, and if that block ends in a
2174 // return instruction, we splice the body of the inlined callee directly into
2175 // the calling basic block.
2176 if (Returns.size() == 1 && std::distance(FirstNewBlock, Caller->end()) == 1) {
2177 // Move all of the instructions right before the call.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002178 OrigBB->getInstList().splice(TheCall->getIterator(),
2179 FirstNewBlock->getInstList(),
Chris Lattner0fa8c7c2004-02-04 04:17:06 +00002180 FirstNewBlock->begin(), FirstNewBlock->end());
2181 // Remove the cloned basic block.
2182 Caller->getBasicBlockList().pop_back();
Misha Brukmanb1c93172005-04-21 23:48:37 +00002183
Chris Lattner0fa8c7c2004-02-04 04:17:06 +00002184 // If the call site was an invoke instruction, add a branch to the normal
2185 // destination.
Adrian Prantl15db52b2013-04-23 19:56:03 +00002186 if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall)) {
2187 BranchInst *NewBr = BranchInst::Create(II->getNormalDest(), TheCall);
2188 NewBr->setDebugLoc(Returns[0]->getDebugLoc());
2189 }
Chris Lattner0fa8c7c2004-02-04 04:17:06 +00002190
2191 // If the return instruction returned a value, replace uses of the call with
2192 // uses of the returned value.
Devang Patel841322b2008-03-04 21:15:15 +00002193 if (!TheCall->use_empty()) {
2194 ReturnInst *R = Returns[0];
Eli Friedman36b90262009-05-08 00:22:04 +00002195 if (TheCall == R->getReturnValue())
Owen Andersonb292b8c2009-07-30 23:03:37 +00002196 TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
Eli Friedman36b90262009-05-08 00:22:04 +00002197 else
2198 TheCall->replaceAllUsesWith(R->getReturnValue());
Devang Patel841322b2008-03-04 21:15:15 +00002199 }
Chris Lattner0fa8c7c2004-02-04 04:17:06 +00002200 // Since we are now done with the Call/Invoke, we can delete it.
Dan Gohman158ff2c2008-06-21 22:08:46 +00002201 TheCall->eraseFromParent();
Chris Lattner0fa8c7c2004-02-04 04:17:06 +00002202
2203 // Since we are now done with the return instruction, delete it also.
Dan Gohman158ff2c2008-06-21 22:08:46 +00002204 Returns[0]->eraseFromParent();
Chris Lattner0fa8c7c2004-02-04 04:17:06 +00002205
2206 // We are now done with the inlining.
2207 return true;
2208 }
2209
2210 // Otherwise, we have the normal case, of more than one block to inline or
2211 // multiple return sites.
2212
Chris Lattner18ef3fd2004-02-04 02:51:48 +00002213 // We want to clone the entire callee function into the hole between the
2214 // "starter" and "ender" blocks. How we accomplish this depends on whether
2215 // this is an invoke instruction or a call instruction.
2216 BasicBlock *AfterCallBB;
Craig Topperf40110f2014-04-25 05:29:35 +00002217 BranchInst *CreatedBranchToNormalDest = nullptr;
Chris Lattner18ef3fd2004-02-04 02:51:48 +00002218 if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall)) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00002219
Chris Lattner18ef3fd2004-02-04 02:51:48 +00002220 // Add an unconditional branch to make this look like the CallInst case...
Adrian Prantl15db52b2013-04-23 19:56:03 +00002221 CreatedBranchToNormalDest = BranchInst::Create(II->getNormalDest(), TheCall);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002222
Chris Lattner18ef3fd2004-02-04 02:51:48 +00002223 // Split the basic block. This guarantees that no PHI nodes will have to be
2224 // updated due to new incoming edges, and make the invoke case more
2225 // symmetric to the call case.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002226 AfterCallBB =
2227 OrigBB->splitBasicBlock(CreatedBranchToNormalDest->getIterator(),
2228 CalledFunc->getName() + ".exit");
Misha Brukmanb1c93172005-04-21 23:48:37 +00002229
Chris Lattner18ef3fd2004-02-04 02:51:48 +00002230 } else { // It's a call
Chris Lattner0fa8c7c2004-02-04 04:17:06 +00002231 // If this is a call instruction, we need to split the basic block that
2232 // the call lives in.
Chris Lattner18ef3fd2004-02-04 02:51:48 +00002233 //
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002234 AfterCallBB = OrigBB->splitBasicBlock(TheCall->getIterator(),
2235 CalledFunc->getName() + ".exit");
Chris Lattner18ef3fd2004-02-04 02:51:48 +00002236 }
2237
Easwaran Raman12585b02017-01-20 22:44:04 +00002238 if (IFI.CallerBFI) {
2239 // Copy original BB's block frequency to AfterCallBB
2240 IFI.CallerBFI->setBlockFreq(
2241 AfterCallBB, IFI.CallerBFI->getBlockFreq(OrigBB).getFrequency());
2242 }
2243
Chris Lattner0fa8c7c2004-02-04 04:17:06 +00002244 // Change the branch that used to go to AfterCallBB to branch to the first
2245 // basic block of the inlined function.
2246 //
2247 TerminatorInst *Br = OrigBB->getTerminator();
Misha Brukmanb1c93172005-04-21 23:48:37 +00002248 assert(Br && Br->getOpcode() == Instruction::Br &&
Chris Lattner0fa8c7c2004-02-04 04:17:06 +00002249 "splitBasicBlock broken!");
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002250 Br->setOperand(0, &*FirstNewBlock);
Chris Lattner0fa8c7c2004-02-04 04:17:06 +00002251
2252 // Now that the function is correct, make it a little bit nicer. In
2253 // particular, move the basic blocks inserted from the end of the function
2254 // into the space made by splitting the source basic block.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002255 Caller->getBasicBlockList().splice(AfterCallBB->getIterator(),
2256 Caller->getBasicBlockList(), FirstNewBlock,
2257 Caller->end());
Chris Lattner0fa8c7c2004-02-04 04:17:06 +00002258
Chris Lattner18ef3fd2004-02-04 02:51:48 +00002259 // Handle all of the return instructions that we just cloned in, and eliminate
2260 // any users of the original call/invoke instruction.
Chris Lattner229907c2011-07-18 04:54:35 +00002261 Type *RTy = CalledFunc->getReturnType();
Dan Gohman3b18fd72008-06-20 01:03:44 +00002262
Craig Topperf40110f2014-04-25 05:29:35 +00002263 PHINode *PHI = nullptr;
Dan Gohmanfa1211f2008-07-23 00:34:11 +00002264 if (Returns.size() > 1) {
Chris Lattner18ef3fd2004-02-04 02:51:48 +00002265 // The PHI node should go at the front of the new basic block to merge all
2266 // possible incoming values.
Chris Lattner18ef3fd2004-02-04 02:51:48 +00002267 if (!TheCall->use_empty()) {
Jay Foad52131342011-03-30 11:28:46 +00002268 PHI = PHINode::Create(RTy, Returns.size(), TheCall->getName(),
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002269 &AfterCallBB->front());
Dan Gohmanfa1211f2008-07-23 00:34:11 +00002270 // Anything that used the result of the function call should now use the
2271 // PHI node as their operand.
Duncan Sands7c8fb1a2008-09-05 12:37:12 +00002272 TheCall->replaceAllUsesWith(PHI);
Chris Lattner18ef3fd2004-02-04 02:51:48 +00002273 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002274
Gabor Greif5aa19222009-01-15 18:40:09 +00002275 // Loop over all of the return instructions adding entries to the PHI node
2276 // as appropriate.
Dan Gohmanfa1211f2008-07-23 00:34:11 +00002277 if (PHI) {
2278 for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
2279 ReturnInst *RI = Returns[i];
2280 assert(RI->getReturnValue()->getType() == PHI->getType() &&
2281 "Ret value not consistent in function!");
2282 PHI->addIncoming(RI->getReturnValue(), RI->getParent());
Devang Patel780b3ca62008-03-07 20:06:16 +00002283 }
2284 }
2285
Gabor Greif8c573f72009-01-16 23:08:50 +00002286 // Add a branch to the merge points and remove return instructions.
Richard Trieu624c2eb2013-04-30 22:45:10 +00002287 DebugLoc Loc;
Chris Lattner18ef3fd2004-02-04 02:51:48 +00002288 for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
Richard Trieu624c2eb2013-04-30 22:45:10 +00002289 ReturnInst *RI = Returns[i];
Adrian Prantl09416382013-04-30 17:08:16 +00002290 BranchInst* BI = BranchInst::Create(AfterCallBB, RI);
Richard Trieu624c2eb2013-04-30 22:45:10 +00002291 Loc = RI->getDebugLoc();
2292 BI->setDebugLoc(Loc);
Devang Patel64d0f072008-03-10 18:34:00 +00002293 RI->eraseFromParent();
Chris Lattner18ef3fd2004-02-04 02:51:48 +00002294 }
Adrian Prantl09416382013-04-30 17:08:16 +00002295 // We need to set the debug location to *somewhere* inside the
Adrian Prantl8beccf92013-04-30 17:33:32 +00002296 // inlined function. The line number may be nonsensical, but the
Adrian Prantl09416382013-04-30 17:08:16 +00002297 // instruction will at least be associated with the right
2298 // function.
2299 if (CreatedBranchToNormalDest)
Richard Trieu624c2eb2013-04-30 22:45:10 +00002300 CreatedBranchToNormalDest->setDebugLoc(Loc);
Devang Patel64d0f072008-03-10 18:34:00 +00002301 } else if (!Returns.empty()) {
2302 // Otherwise, if there is exactly one return value, just replace anything
2303 // using the return value of the call with the computed value.
Eli Friedman36b90262009-05-08 00:22:04 +00002304 if (!TheCall->use_empty()) {
2305 if (TheCall == Returns[0]->getReturnValue())
Owen Andersonb292b8c2009-07-30 23:03:37 +00002306 TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
Eli Friedman36b90262009-05-08 00:22:04 +00002307 else
2308 TheCall->replaceAllUsesWith(Returns[0]->getReturnValue());
2309 }
Duncan Sands7c8fb1a2008-09-05 12:37:12 +00002310
Jay Foad61ea0e42011-06-23 09:09:15 +00002311 // Update PHI nodes that use the ReturnBB to use the AfterCallBB.
2312 BasicBlock *ReturnBB = Returns[0]->getParent();
2313 ReturnBB->replaceAllUsesWith(AfterCallBB);
2314
Devang Patel64d0f072008-03-10 18:34:00 +00002315 // Splice the code from the return block into the block that it will return
2316 // to, which contains the code that was after the call.
Devang Patel64d0f072008-03-10 18:34:00 +00002317 AfterCallBB->getInstList().splice(AfterCallBB->begin(),
2318 ReturnBB->getInstList());
Duncan Sands7c8fb1a2008-09-05 12:37:12 +00002319
Adrian Prantl15db52b2013-04-23 19:56:03 +00002320 if (CreatedBranchToNormalDest)
2321 CreatedBranchToNormalDest->setDebugLoc(Returns[0]->getDebugLoc());
2322
Devang Patel64d0f072008-03-10 18:34:00 +00002323 // Delete the return instruction now and empty ReturnBB now.
2324 Returns[0]->eraseFromParent();
2325 ReturnBB->eraseFromParent();
Chris Lattner6e79e552004-10-17 23:21:07 +00002326 } else if (!TheCall->use_empty()) {
2327 // No returns, but something is using the return value of the call. Just
2328 // nuke the result.
Owen Andersonb292b8c2009-07-30 23:03:37 +00002329 TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
Chris Lattner18ef3fd2004-02-04 02:51:48 +00002330 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002331
Chris Lattner18ef3fd2004-02-04 02:51:48 +00002332 // Since we are now done with the Call/Invoke, we can delete it.
Chris Lattner6e79e552004-10-17 23:21:07 +00002333 TheCall->eraseFromParent();
Chris Lattner530d4bf2003-05-29 15:11:31 +00002334
Reid Klecknerf0915aa2014-05-15 20:11:28 +00002335 // If we inlined any musttail calls and the original return is now
2336 // unreachable, delete it. It can only contain a bitcast and ret.
Easwaran Ramanb1bd3982016-03-08 00:36:35 +00002337 if (InlinedMustTailCalls && pred_begin(AfterCallBB) == pred_end(AfterCallBB))
Reid Klecknerf0915aa2014-05-15 20:11:28 +00002338 AfterCallBB->eraseFromParent();
2339
Chris Lattnerfc3fe5c2003-08-24 04:06:56 +00002340 // We should always be able to fold the entry block of the function into the
2341 // single predecessor of the block...
Chris Lattner0328d752004-04-16 05:17:59 +00002342 assert(cast<BranchInst>(Br)->isUnconditional() && "splitBasicBlock broken!");
Chris Lattnerfc3fe5c2003-08-24 04:06:56 +00002343 BasicBlock *CalleeEntry = cast<BranchInst>(Br)->getSuccessor(0);
Chris Lattner0fa8c7c2004-02-04 04:17:06 +00002344
Chris Lattner0328d752004-04-16 05:17:59 +00002345 // Splice the code entry block into calling block, right before the
2346 // unconditional branch.
Eric Christopher96513122011-06-23 06:24:52 +00002347 CalleeEntry->replaceAllUsesWith(OrigBB); // Update PHI nodes
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002348 OrigBB->getInstList().splice(Br->getIterator(), CalleeEntry->getInstList());
Chris Lattner0328d752004-04-16 05:17:59 +00002349
2350 // Remove the unconditional branch.
2351 OrigBB->getInstList().erase(Br);
2352
2353 // Now we can remove the CalleeEntry block, which is now empty.
2354 Caller->getBasicBlockList().erase(CalleeEntry);
Duncan Sands7c8fb1a2008-09-05 12:37:12 +00002355
Duncan Sands9d9a4e22010-11-17 11:16:23 +00002356 // If we inserted a phi node, check to see if it has a single value (e.g. all
2357 // the entries are the same or undef). If so, remove the PHI so it doesn't
2358 // block other optimizations.
Bill Wendlingce0c2292012-01-31 01:01:16 +00002359 if (PHI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002360 AssumptionCache *AC =
2361 IFI.GetAssumptionCache ? &(*IFI.GetAssumptionCache)(*Caller) : nullptr;
Mehdi Amini46a43552015-03-04 18:43:29 +00002362 auto &DL = Caller->getParent()->getDataLayout();
Daniel Berlin4d0fe642017-04-28 19:55:38 +00002363 if (Value *V = SimplifyInstruction(PHI, {DL, nullptr, nullptr, AC})) {
Duncan Sands9d9a4e22010-11-17 11:16:23 +00002364 PHI->replaceAllUsesWith(V);
2365 PHI->eraseFromParent();
2366 }
Bill Wendlingce0c2292012-01-31 01:01:16 +00002367 }
Duncan Sands9d9a4e22010-11-17 11:16:23 +00002368
Chris Lattner530d4bf2003-05-29 15:11:31 +00002369 return true;
2370}