blob: 0b220828d16c48aeef29b58cf093c9bd0fa77fb4 [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"
Michael Kruse978ba612018-12-20 04:58:07 +000034#include "llvm/Analysis/VectorUtils.h"
Eugene Zelenko6cadde72017-10-17 21:27:42 +000035#include "llvm/IR/Argument.h"
36#include "llvm/IR/BasicBlock.h"
Reid Klecknerf0915aa2014-05-15 20:11:28 +000037#include "llvm/IR/CFG.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000038#include "llvm/IR/CallSite.h"
Eugene Zelenko6cadde72017-10-17 21:27:42 +000039#include "llvm/IR/Constant.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000040#include "llvm/IR/Constants.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000041#include "llvm/IR/DIBuilder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000042#include "llvm/IR/DataLayout.h"
Eugene Zelenko6cadde72017-10-17 21:27:42 +000043#include "llvm/IR/DebugInfoMetadata.h"
44#include "llvm/IR/DebugLoc.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000045#include "llvm/IR/DerivedTypes.h"
Hal Finkelff0bcb62014-07-25 15:50:08 +000046#include "llvm/IR/Dominators.h"
Eugene Zelenko6cadde72017-10-17 21:27:42 +000047#include "llvm/IR/Function.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000048#include "llvm/IR/IRBuilder.h"
Eugene Zelenko6cadde72017-10-17 21:27:42 +000049#include "llvm/IR/InstrTypes.h"
50#include "llvm/IR/Instruction.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000051#include "llvm/IR/Instructions.h"
52#include "llvm/IR/IntrinsicInst.h"
53#include "llvm/IR/Intrinsics.h"
Eugene Zelenko6cadde72017-10-17 21:27:42 +000054#include "llvm/IR/LLVMContext.h"
Hal Finkel94146652014-07-24 14:25:39 +000055#include "llvm/IR/MDBuilder.h"
Eugene Zelenko6cadde72017-10-17 21:27:42 +000056#include "llvm/IR/Metadata.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000057#include "llvm/IR/Module.h"
Eugene Zelenko6cadde72017-10-17 21:27:42 +000058#include "llvm/IR/Type.h"
59#include "llvm/IR/User.h"
60#include "llvm/IR/Value.h"
61#include "llvm/Support/Casting.h"
Hal Finkelff0bcb62014-07-25 15:50:08 +000062#include "llvm/Support/CommandLine.h"
Eugene Zelenko6cadde72017-10-17 21:27:42 +000063#include "llvm/Support/ErrorHandling.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000064#include "llvm/Transforms/Utils/Cloning.h"
Eugene Zelenko6cadde72017-10-17 21:27:42 +000065#include "llvm/Transforms/Utils/ValueMapper.h"
Hal Finkelff0bcb62014-07-25 15:50:08 +000066#include <algorithm>
Eugene Zelenko6cadde72017-10-17 21:27:42 +000067#include <cassert>
68#include <cstdint>
69#include <iterator>
70#include <limits>
71#include <string>
72#include <utility>
73#include <vector>
Hans Wennborg083ca9b2015-10-06 23:24:35 +000074
Chris Lattnerdf3c3422004-01-09 06:12:26 +000075using namespace llvm;
Easwaran Ramane5b8de22018-01-17 22:24:23 +000076using ProfileCount = Function::ProfileCount;
Chris Lattner530d4bf2003-05-29 15:11:31 +000077
Hal Finkelff0bcb62014-07-25 15:50:08 +000078static cl::opt<bool>
James Molloy6b95d8e2014-09-04 13:23:08 +000079EnableNoAliasConversion("enable-noalias-to-md-conversion", cl::init(true),
Hal Finkelff0bcb62014-07-25 15:50:08 +000080 cl::Hidden,
81 cl::desc("Convert noalias attributes to metadata during inlining."));
82
Hal Finkel68dc3c72014-10-15 23:44:41 +000083static cl::opt<bool>
84PreserveAlignmentAssumptions("preserve-alignment-assumptions-during-inlining",
85 cl::init(true), cl::Hidden,
86 cl::desc("Convert align attributes to assumptions during inlining."));
87
David Bolvanskyc0aa4b72018-08-05 14:53:08 +000088llvm::InlineResult llvm::InlineFunction(CallInst *CI, InlineFunctionInfo &IFI,
89 AAResults *CalleeAAR,
90 bool InsertLifetime) {
Chandler Carruth7b560d42015-09-09 17:55:00 +000091 return InlineFunction(CallSite(CI), IFI, CalleeAAR, InsertLifetime);
Chris Lattner0841fb12006-01-14 20:07:50 +000092}
Eugene Zelenko6cadde72017-10-17 21:27:42 +000093
David Bolvanskyc0aa4b72018-08-05 14:53:08 +000094llvm::InlineResult llvm::InlineFunction(InvokeInst *II, InlineFunctionInfo &IFI,
95 AAResults *CalleeAAR,
96 bool InsertLifetime) {
Chandler Carruth7b560d42015-09-09 17:55:00 +000097 return InlineFunction(CallSite(II), IFI, CalleeAAR, InsertLifetime);
Chris Lattner0841fb12006-01-14 20:07:50 +000098}
Chris Lattner0cc265e2003-08-24 06:59:16 +000099
John McCallbd04b742011-05-27 18:34:38 +0000100namespace {
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000101
David Majnemer654e1302015-07-31 17:58:14 +0000102 /// A class for recording information about inlining a landing pad.
103 class LandingPadInliningInfo {
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000104 /// Destination of the invoke's unwind.
105 BasicBlock *OuterResumeDest;
106
107 /// Destination for the callee's resume.
108 BasicBlock *InnerResumeDest = nullptr;
109
110 /// LandingPadInst associated with the invoke.
111 LandingPadInst *CallerLPad = nullptr;
112
113 /// PHI for EH values from landingpad insts.
114 PHINode *InnerEHValuesPHI = nullptr;
115
Bill Wendling0c2d82b2012-01-31 01:22:03 +0000116 SmallVector<Value*, 8> UnwindDestPHIValues;
Bill Wendlingfa284402011-07-28 07:31:46 +0000117
Bill Wendling55421f02011-08-14 08:01:36 +0000118 public:
David Majnemer654e1302015-07-31 17:58:14 +0000119 LandingPadInliningInfo(InvokeInst *II)
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000120 : OuterResumeDest(II->getUnwindDest()) {
Bill Wendling55421f02011-08-14 08:01:36 +0000121 // If there are PHI nodes in the unwind destination block, we need to keep
122 // track of which values came into them from the invoke before removing
123 // the edge from this block.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000124 BasicBlock *InvokeBB = II->getParent();
Bill Wendlingea6e9352012-01-31 01:25:54 +0000125 BasicBlock::iterator I = OuterResumeDest->begin();
Bill Wendling55421f02011-08-14 08:01:36 +0000126 for (; isa<PHINode>(I); ++I) {
John McCallbd04b742011-05-27 18:34:38 +0000127 // Save the value to use for this edge.
Bill Wendling55421f02011-08-14 08:01:36 +0000128 PHINode *PHI = cast<PHINode>(I);
129 UnwindDestPHIValues.push_back(PHI->getIncomingValueForBlock(InvokeBB));
130 }
131
Bill Wendlingf3cae512012-01-31 00:56:53 +0000132 CallerLPad = cast<LandingPadInst>(I);
John McCallbd04b742011-05-27 18:34:38 +0000133 }
134
Sanjay Patel0fdb4372015-03-10 19:42:57 +0000135 /// The outer unwind destination is the target of
Bill Wendlingea6e9352012-01-31 01:25:54 +0000136 /// unwind edges introduced for calls within the inlined function.
Bill Wendling0c2d82b2012-01-31 01:22:03 +0000137 BasicBlock *getOuterResumeDest() const {
Bill Wendlingea6e9352012-01-31 01:25:54 +0000138 return OuterResumeDest;
John McCallbd04b742011-05-27 18:34:38 +0000139 }
140
Bill Wendling3fd879d2012-01-31 01:48:40 +0000141 BasicBlock *getInnerResumeDest();
Bill Wendling55421f02011-08-14 08:01:36 +0000142
143 LandingPadInst *getLandingPadInst() const { return CallerLPad; }
144
Sanjay Patel0fdb4372015-03-10 19:42:57 +0000145 /// Forward the 'resume' instruction to the caller's landing pad block.
146 /// When the landing pad block has only one predecessor, this is
Bill Wendling55421f02011-08-14 08:01:36 +0000147 /// a simple branch. When there is more than one predecessor, we need to
148 /// split the landing pad block after the landingpad instruction and jump
149 /// to there.
Bill Wendling56f15bf2013-03-22 20:31:05 +0000150 void forwardResume(ResumeInst *RI,
Craig Topper71b7b682014-08-21 05:55:13 +0000151 SmallPtrSetImpl<LandingPadInst*> &InlinedLPads);
Bill Wendling55421f02011-08-14 08:01:36 +0000152
Sanjay Patel0fdb4372015-03-10 19:42:57 +0000153 /// Add incoming-PHI values to the unwind destination block for the given
154 /// basic block, using the values for the original invoke's source block.
John McCallbd04b742011-05-27 18:34:38 +0000155 void addIncomingPHIValuesFor(BasicBlock *BB) const {
Bill Wendlingea6e9352012-01-31 01:25:54 +0000156 addIncomingPHIValuesForInto(BB, OuterResumeDest);
John McCall046c47e2011-05-28 07:45:59 +0000157 }
Bill Wendlingad088e62011-07-30 05:42:50 +0000158
John McCall046c47e2011-05-28 07:45:59 +0000159 void addIncomingPHIValuesForInto(BasicBlock *src, BasicBlock *dest) const {
160 BasicBlock::iterator I = dest->begin();
John McCallbd04b742011-05-27 18:34:38 +0000161 for (unsigned i = 0, e = UnwindDestPHIValues.size(); i != e; ++i, ++I) {
Bill Wendlingad088e62011-07-30 05:42:50 +0000162 PHINode *phi = cast<PHINode>(I);
163 phi->addIncoming(UnwindDestPHIValues[i], src);
John McCallbd04b742011-05-27 18:34:38 +0000164 }
165 }
166 };
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000167
168} // end anonymous namespace
John McCallbd04b742011-05-27 18:34:38 +0000169
Sanjay Patel0fdb4372015-03-10 19:42:57 +0000170/// Get or create a target for the branch from ResumeInsts.
David Majnemer654e1302015-07-31 17:58:14 +0000171BasicBlock *LandingPadInliningInfo::getInnerResumeDest() {
Bill Wendling55421f02011-08-14 08:01:36 +0000172 if (InnerResumeDest) return InnerResumeDest;
173
174 // Split the landing pad.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000175 BasicBlock::iterator SplitPoint = ++CallerLPad->getIterator();
Bill Wendling55421f02011-08-14 08:01:36 +0000176 InnerResumeDest =
177 OuterResumeDest->splitBasicBlock(SplitPoint,
178 OuterResumeDest->getName() + ".body");
179
180 // The number of incoming edges we expect to the inner landing pad.
181 const unsigned PHICapacity = 2;
182
183 // Create corresponding new PHIs for all the PHIs in the outer landing pad.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000184 Instruction *InsertPoint = &InnerResumeDest->front();
Bill Wendling55421f02011-08-14 08:01:36 +0000185 BasicBlock::iterator I = OuterResumeDest->begin();
186 for (unsigned i = 0, e = UnwindDestPHIValues.size(); i != e; ++i, ++I) {
187 PHINode *OuterPHI = cast<PHINode>(I);
188 PHINode *InnerPHI = PHINode::Create(OuterPHI->getType(), PHICapacity,
189 OuterPHI->getName() + ".lpad-body",
190 InsertPoint);
191 OuterPHI->replaceAllUsesWith(InnerPHI);
192 InnerPHI->addIncoming(OuterPHI, OuterResumeDest);
193 }
194
195 // Create a PHI for the exception values.
196 InnerEHValuesPHI = PHINode::Create(CallerLPad->getType(), PHICapacity,
197 "eh.lpad-body", InsertPoint);
198 CallerLPad->replaceAllUsesWith(InnerEHValuesPHI);
199 InnerEHValuesPHI->addIncoming(CallerLPad, OuterResumeDest);
200
201 // All done.
202 return InnerResumeDest;
203}
204
Sanjay Patel0fdb4372015-03-10 19:42:57 +0000205/// Forward the 'resume' instruction to the caller's landing pad block.
206/// When the landing pad block has only one predecessor, this is a simple
Bill Wendling55421f02011-08-14 08:01:36 +0000207/// branch. When there is more than one predecessor, we need to split the
208/// landing pad block after the landingpad instruction and jump to there.
David Majnemer654e1302015-07-31 17:58:14 +0000209void LandingPadInliningInfo::forwardResume(
210 ResumeInst *RI, SmallPtrSetImpl<LandingPadInst *> &InlinedLPads) {
Bill Wendling3fd879d2012-01-31 01:48:40 +0000211 BasicBlock *Dest = getInnerResumeDest();
Bill Wendling55421f02011-08-14 08:01:36 +0000212 BasicBlock *Src = RI->getParent();
213
214 BranchInst::Create(Dest, Src);
215
216 // Update the PHIs in the destination. They were inserted in an order which
217 // makes this work.
218 addIncomingPHIValuesForInto(Src, Dest);
219
220 InnerEHValuesPHI->addIncoming(RI->getOperand(0), Src);
221 RI->eraseFromParent();
222}
223
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000224/// Helper for getUnwindDestToken/getUnwindDestTokenHelper.
225static Value *getParentPad(Value *EHPad) {
226 if (auto *FPI = dyn_cast<FuncletPadInst>(EHPad))
227 return FPI->getParentPad();
228 return cast<CatchSwitchInst>(EHPad)->getParentPad();
229}
230
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000231using UnwindDestMemoTy = DenseMap<Instruction *, Value *>;
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000232
233/// Helper for getUnwindDestToken that does the descendant-ward part of
234/// the search.
235static Value *getUnwindDestTokenHelper(Instruction *EHPad,
236 UnwindDestMemoTy &MemoMap) {
237 SmallVector<Instruction *, 8> Worklist(1, EHPad);
238
239 while (!Worklist.empty()) {
240 Instruction *CurrentPad = Worklist.pop_back_val();
241 // We only put pads on the worklist that aren't in the MemoMap. When
242 // we find an unwind dest for a pad we may update its ancestors, but
243 // the queue only ever contains uncles/great-uncles/etc. of CurrentPad,
244 // so they should never get updated while queued on the worklist.
245 assert(!MemoMap.count(CurrentPad));
246 Value *UnwindDestToken = nullptr;
247 if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(CurrentPad)) {
248 if (CatchSwitch->hasUnwindDest()) {
249 UnwindDestToken = CatchSwitch->getUnwindDest()->getFirstNonPHI();
250 } else {
251 // Catchswitch doesn't have a 'nounwind' variant, and one might be
252 // annotated as "unwinds to caller" when really it's nounwind (see
253 // e.g. SimplifyCFGOpt::SimplifyUnreachable), so we can't infer the
254 // parent's unwind dest from this. We can check its catchpads'
255 // descendants, since they might include a cleanuppad with an
256 // "unwinds to caller" cleanupret, which can be trusted.
257 for (auto HI = CatchSwitch->handler_begin(),
258 HE = CatchSwitch->handler_end();
259 HI != HE && !UnwindDestToken; ++HI) {
260 BasicBlock *HandlerBlock = *HI;
261 auto *CatchPad = cast<CatchPadInst>(HandlerBlock->getFirstNonPHI());
262 for (User *Child : CatchPad->users()) {
263 // Intentionally ignore invokes here -- since the catchswitch is
264 // marked "unwind to caller", it would be a verifier error if it
265 // contained an invoke which unwinds out of it, so any invoke we'd
266 // encounter must unwind to some child of the catch.
267 if (!isa<CleanupPadInst>(Child) && !isa<CatchSwitchInst>(Child))
268 continue;
269
270 Instruction *ChildPad = cast<Instruction>(Child);
271 auto Memo = MemoMap.find(ChildPad);
272 if (Memo == MemoMap.end()) {
Joseph Tremoulete92e0a92016-09-04 01:23:20 +0000273 // Haven't figured out this child pad yet; queue it.
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000274 Worklist.push_back(ChildPad);
275 continue;
276 }
277 // We've already checked this child, but might have found that
278 // it offers no proof either way.
279 Value *ChildUnwindDestToken = Memo->second;
280 if (!ChildUnwindDestToken)
281 continue;
282 // We already know the child's unwind dest, which can either
283 // be ConstantTokenNone to indicate unwind to caller, or can
284 // be another child of the catchpad. Only the former indicates
285 // the unwind dest of the catchswitch.
286 if (isa<ConstantTokenNone>(ChildUnwindDestToken)) {
287 UnwindDestToken = ChildUnwindDestToken;
288 break;
289 }
290 assert(getParentPad(ChildUnwindDestToken) == CatchPad);
291 }
292 }
293 }
294 } else {
295 auto *CleanupPad = cast<CleanupPadInst>(CurrentPad);
296 for (User *U : CleanupPad->users()) {
297 if (auto *CleanupRet = dyn_cast<CleanupReturnInst>(U)) {
298 if (BasicBlock *RetUnwindDest = CleanupRet->getUnwindDest())
299 UnwindDestToken = RetUnwindDest->getFirstNonPHI();
300 else
301 UnwindDestToken = ConstantTokenNone::get(CleanupPad->getContext());
302 break;
303 }
304 Value *ChildUnwindDestToken;
305 if (auto *Invoke = dyn_cast<InvokeInst>(U)) {
306 ChildUnwindDestToken = Invoke->getUnwindDest()->getFirstNonPHI();
307 } else if (isa<CleanupPadInst>(U) || isa<CatchSwitchInst>(U)) {
308 Instruction *ChildPad = cast<Instruction>(U);
309 auto Memo = MemoMap.find(ChildPad);
310 if (Memo == MemoMap.end()) {
311 // Haven't resolved this child yet; queue it and keep searching.
312 Worklist.push_back(ChildPad);
313 continue;
314 }
315 // We've checked this child, but still need to ignore it if it
316 // had no proof either way.
317 ChildUnwindDestToken = Memo->second;
318 if (!ChildUnwindDestToken)
319 continue;
320 } else {
321 // Not a relevant user of the cleanuppad
322 continue;
323 }
324 // In a well-formed program, the child/invoke must either unwind to
325 // an(other) child of the cleanup, or exit the cleanup. In the
326 // first case, continue searching.
327 if (isa<Instruction>(ChildUnwindDestToken) &&
328 getParentPad(ChildUnwindDestToken) == CleanupPad)
329 continue;
330 UnwindDestToken = ChildUnwindDestToken;
331 break;
332 }
333 }
334 // If we haven't found an unwind dest for CurrentPad, we may have queued its
335 // children, so move on to the next in the worklist.
336 if (!UnwindDestToken)
337 continue;
338
339 // Now we know that CurrentPad unwinds to UnwindDestToken. It also exits
340 // any ancestors of CurrentPad up to but not including UnwindDestToken's
341 // parent pad. Record this in the memo map, and check to see if the
342 // original EHPad being queried is one of the ones exited.
343 Value *UnwindParent;
344 if (auto *UnwindPad = dyn_cast<Instruction>(UnwindDestToken))
345 UnwindParent = getParentPad(UnwindPad);
346 else
347 UnwindParent = nullptr;
348 bool ExitedOriginalPad = false;
349 for (Instruction *ExitedPad = CurrentPad;
350 ExitedPad && ExitedPad != UnwindParent;
351 ExitedPad = dyn_cast<Instruction>(getParentPad(ExitedPad))) {
352 // Skip over catchpads since they just follow their catchswitches.
353 if (isa<CatchPadInst>(ExitedPad))
354 continue;
355 MemoMap[ExitedPad] = UnwindDestToken;
356 ExitedOriginalPad |= (ExitedPad == EHPad);
357 }
358
359 if (ExitedOriginalPad)
360 return UnwindDestToken;
361
362 // Continue the search.
363 }
364
365 // No definitive information is contained within this funclet.
366 return nullptr;
367}
368
369/// Given an EH pad, find where it unwinds. If it unwinds to an EH pad,
370/// return that pad instruction. If it unwinds to caller, return
371/// ConstantTokenNone. If it does not have a definitive unwind destination,
372/// return nullptr.
373///
374/// This routine gets invoked for calls in funclets in inlinees when inlining
375/// an invoke. Since many funclets don't have calls inside them, it's queried
376/// on-demand rather than building a map of pads to unwind dests up front.
377/// Determining a funclet's unwind dest may require recursively searching its
378/// descendants, and also ancestors and cousins if the descendants don't provide
379/// an answer. Since most funclets will have their unwind dest immediately
380/// available as the unwind dest of a catchswitch or cleanupret, this routine
381/// searches top-down from the given pad and then up. To avoid worst-case
382/// quadratic run-time given that approach, it uses a memo map to avoid
383/// re-processing funclet trees. The callers that rewrite the IR as they go
384/// take advantage of this, for correctness, by checking/forcing rewritten
385/// pads' entries to match the original callee view.
386static Value *getUnwindDestToken(Instruction *EHPad,
387 UnwindDestMemoTy &MemoMap) {
388 // Catchpads unwind to the same place as their catchswitch;
389 // redirct any queries on catchpads so the code below can
390 // deal with just catchswitches and cleanuppads.
391 if (auto *CPI = dyn_cast<CatchPadInst>(EHPad))
392 EHPad = CPI->getCatchSwitch();
393
394 // Check if we've already determined the unwind dest for this pad.
395 auto Memo = MemoMap.find(EHPad);
396 if (Memo != MemoMap.end())
397 return Memo->second;
398
399 // Search EHPad and, if necessary, its descendants.
400 Value *UnwindDestToken = getUnwindDestTokenHelper(EHPad, MemoMap);
401 assert((UnwindDestToken == nullptr) != (MemoMap.count(EHPad) != 0));
402 if (UnwindDestToken)
403 return UnwindDestToken;
404
405 // No information is available for this EHPad from itself or any of its
406 // descendants. An unwind all the way out to a pad in the caller would
407 // need also to agree with the unwind dest of the parent funclet, so
408 // search up the chain to try to find a funclet with information. Put
409 // null entries in the memo map to avoid re-processing as we go up.
410 MemoMap[EHPad] = nullptr;
Joseph Tremoulete92e0a92016-09-04 01:23:20 +0000411#ifndef NDEBUG
412 SmallPtrSet<Instruction *, 4> TempMemos;
413 TempMemos.insert(EHPad);
414#endif
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000415 Instruction *LastUselessPad = EHPad;
416 Value *AncestorToken;
417 for (AncestorToken = getParentPad(EHPad);
418 auto *AncestorPad = dyn_cast<Instruction>(AncestorToken);
419 AncestorToken = getParentPad(AncestorToken)) {
420 // Skip over catchpads since they just follow their catchswitches.
421 if (isa<CatchPadInst>(AncestorPad))
422 continue;
Joseph Tremoulete92e0a92016-09-04 01:23:20 +0000423 // If the MemoMap had an entry mapping AncestorPad to nullptr, since we
424 // haven't yet called getUnwindDestTokenHelper for AncestorPad in this
425 // call to getUnwindDestToken, that would mean that AncestorPad had no
426 // information in itself, its descendants, or its ancestors. If that
427 // were the case, then we should also have recorded the lack of information
428 // for the descendant that we're coming from. So assert that we don't
429 // find a null entry in the MemoMap for AncestorPad.
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000430 assert(!MemoMap.count(AncestorPad) || MemoMap[AncestorPad]);
431 auto AncestorMemo = MemoMap.find(AncestorPad);
432 if (AncestorMemo == MemoMap.end()) {
433 UnwindDestToken = getUnwindDestTokenHelper(AncestorPad, MemoMap);
434 } else {
435 UnwindDestToken = AncestorMemo->second;
436 }
437 if (UnwindDestToken)
438 break;
439 LastUselessPad = AncestorPad;
Joseph Tremoulete92e0a92016-09-04 01:23:20 +0000440 MemoMap[LastUselessPad] = nullptr;
441#ifndef NDEBUG
442 TempMemos.insert(LastUselessPad);
443#endif
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000444 }
445
Joseph Tremoulete92e0a92016-09-04 01:23:20 +0000446 // We know that getUnwindDestTokenHelper was called on LastUselessPad and
447 // returned nullptr (and likewise for EHPad and any of its ancestors up to
448 // LastUselessPad), so LastUselessPad has no information from below. Since
449 // getUnwindDestTokenHelper must investigate all downward paths through
450 // no-information nodes to prove that a node has no information like this,
451 // and since any time it finds information it records it in the MemoMap for
452 // not just the immediately-containing funclet but also any ancestors also
453 // exited, it must be the case that, walking downward from LastUselessPad,
454 // visiting just those nodes which have not been mapped to an unwind dest
455 // by getUnwindDestTokenHelper (the nullptr TempMemos notwithstanding, since
456 // they are just used to keep getUnwindDestTokenHelper from repeating work),
457 // any node visited must have been exhaustively searched with no information
458 // for it found.
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000459 SmallVector<Instruction *, 8> Worklist(1, LastUselessPad);
460 while (!Worklist.empty()) {
461 Instruction *UselessPad = Worklist.pop_back_val();
Joseph Tremoulete92e0a92016-09-04 01:23:20 +0000462 auto Memo = MemoMap.find(UselessPad);
463 if (Memo != MemoMap.end() && Memo->second) {
464 // Here the name 'UselessPad' is a bit of a misnomer, because we've found
465 // that it is a funclet that does have information about unwinding to
466 // a particular destination; its parent was a useless pad.
467 // Since its parent has no information, the unwind edge must not escape
468 // the parent, and must target a sibling of this pad. This local unwind
469 // gives us no information about EHPad. Leave it and the subtree rooted
470 // at it alone.
471 assert(getParentPad(Memo->second) == getParentPad(UselessPad));
472 continue;
473 }
474 // We know we don't have information for UselesPad. If it has an entry in
475 // the MemoMap (mapping it to nullptr), it must be one of the TempMemos
476 // added on this invocation of getUnwindDestToken; if a previous invocation
477 // recorded nullptr, it would have had to prove that the ancestors of
478 // UselessPad, which include LastUselessPad, had no information, and that
479 // in turn would have required proving that the descendants of
480 // LastUselesPad, which include EHPad, have no information about
481 // LastUselessPad, which would imply that EHPad was mapped to nullptr in
482 // the MemoMap on that invocation, which isn't the case if we got here.
483 assert(!MemoMap.count(UselessPad) || TempMemos.count(UselessPad));
484 // Assert as we enumerate users that 'UselessPad' doesn't have any unwind
485 // information that we'd be contradicting by making a map entry for it
486 // (which is something that getUnwindDestTokenHelper must have proved for
487 // us to get here). Just assert on is direct users here; the checks in
488 // this downward walk at its descendants will verify that they don't have
489 // any unwind edges that exit 'UselessPad' either (i.e. they either have no
490 // unwind edges or unwind to a sibling).
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000491 MemoMap[UselessPad] = UnwindDestToken;
492 if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(UselessPad)) {
Joseph Tremoulete92e0a92016-09-04 01:23:20 +0000493 assert(CatchSwitch->getUnwindDest() == nullptr && "Expected useless pad");
494 for (BasicBlock *HandlerBlock : CatchSwitch->handlers()) {
495 auto *CatchPad = HandlerBlock->getFirstNonPHI();
496 for (User *U : CatchPad->users()) {
497 assert(
498 (!isa<InvokeInst>(U) ||
499 (getParentPad(
500 cast<InvokeInst>(U)->getUnwindDest()->getFirstNonPHI()) ==
501 CatchPad)) &&
502 "Expected useless pad");
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000503 if (isa<CatchSwitchInst>(U) || isa<CleanupPadInst>(U))
504 Worklist.push_back(cast<Instruction>(U));
Joseph Tremoulete92e0a92016-09-04 01:23:20 +0000505 }
506 }
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000507 } else {
508 assert(isa<CleanupPadInst>(UselessPad));
Joseph Tremoulete92e0a92016-09-04 01:23:20 +0000509 for (User *U : UselessPad->users()) {
510 assert(!isa<CleanupReturnInst>(U) && "Expected useless pad");
511 assert((!isa<InvokeInst>(U) ||
512 (getParentPad(
513 cast<InvokeInst>(U)->getUnwindDest()->getFirstNonPHI()) ==
514 UselessPad)) &&
515 "Expected useless pad");
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000516 if (isa<CatchSwitchInst>(U) || isa<CleanupPadInst>(U))
517 Worklist.push_back(cast<Instruction>(U));
Joseph Tremoulete92e0a92016-09-04 01:23:20 +0000518 }
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000519 }
520 }
521
522 return UnwindDestToken;
523}
524
Sanjay Patel0fdb4372015-03-10 19:42:57 +0000525/// When we inline a basic block into an invoke,
526/// we have to turn all of the calls that can throw into invokes.
527/// This function analyze BB to see if there are any calls, and if so,
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000528/// it rewrites them to be invokes that jump to InvokeDest and fills in the PHI
Chris Lattner8900f3e2009-09-01 18:44:06 +0000529/// nodes in that block with the values specified in InvokeDestPHIValues.
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000530static BasicBlock *HandleCallsInBlockInlinedThroughInvoke(
531 BasicBlock *BB, BasicBlock *UnwindEdge,
532 UnwindDestMemoTy *FuncletUnwindMap = nullptr) {
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000533 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000534 Instruction *I = &*BBI++;
Bill Wendling55421f02011-08-14 08:01:36 +0000535
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000536 // We only need to check for function calls: inlined invoke
537 // instructions require no special handling.
538 CallInst *CI = dyn_cast<CallInst>(I);
John McCallbd04b742011-05-27 18:34:38 +0000539
Manman Ren87a2adc2013-10-31 21:56:03 +0000540 if (!CI || CI->doesNotThrow() || isa<InlineAsm>(CI->getCalledValue()))
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000541 continue;
Bill Wendling518a2052012-01-31 01:05:20 +0000542
Sanjoy Dasb51325d2016-03-11 19:08:34 +0000543 // We do not need to (and in fact, cannot) convert possibly throwing calls
Sanjoy Das021de052016-03-31 00:18:46 +0000544 // to @llvm.experimental_deoptimize (resp. @llvm.experimental.guard) into
545 // invokes. The caller's "segment" of the deoptimization continuation
546 // attached to the newly inlined @llvm.experimental_deoptimize
547 // (resp. @llvm.experimental.guard) call should contain the exception
548 // handling logic, if any.
Sanjoy Dasb51325d2016-03-11 19:08:34 +0000549 if (auto *F = CI->getCalledFunction())
Sanjoy Das021de052016-03-31 00:18:46 +0000550 if (F->getIntrinsicID() == Intrinsic::experimental_deoptimize ||
551 F->getIntrinsicID() == Intrinsic::experimental_guard)
Sanjoy Dasb51325d2016-03-11 19:08:34 +0000552 continue;
553
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000554 if (auto FuncletBundle = CI->getOperandBundle(LLVMContext::OB_funclet)) {
555 // This call is nested inside a funclet. If that funclet has an unwind
556 // destination within the inlinee, then unwinding out of this call would
557 // be UB. Rewriting this call to an invoke which targets the inlined
558 // invoke's unwind dest would give the call's parent funclet multiple
559 // unwind destinations, which is something that subsequent EH table
560 // generation can't handle and that the veirifer rejects. So when we
561 // see such a call, leave it as a call.
562 auto *FuncletPad = cast<Instruction>(FuncletBundle->Inputs[0]);
563 Value *UnwindDestToken =
564 getUnwindDestToken(FuncletPad, *FuncletUnwindMap);
565 if (UnwindDestToken && !isa<ConstantTokenNone>(UnwindDestToken))
566 continue;
567#ifndef NDEBUG
568 Instruction *MemoKey;
569 if (auto *CatchPad = dyn_cast<CatchPadInst>(FuncletPad))
570 MemoKey = CatchPad->getCatchSwitch();
571 else
572 MemoKey = FuncletPad;
573 assert(FuncletUnwindMap->count(MemoKey) &&
574 (*FuncletUnwindMap)[MemoKey] == UnwindDestToken &&
575 "must get memoized to avoid confusing later searches");
576#endif // NDEBUG
577 }
578
Kuba Breckaddfdba32016-11-14 21:41:13 +0000579 changeToInvokeAndSplitBasicBlock(CI, UnwindEdge);
David Majnemer654e1302015-07-31 17:58:14 +0000580 return BB;
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000581 }
David Majnemer654e1302015-07-31 17:58:14 +0000582 return nullptr;
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000583}
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000584
Sanjay Patel0fdb4372015-03-10 19:42:57 +0000585/// If we inlined an invoke site, we need to convert calls
Bill Wendling0aef16a2012-02-06 21:44:22 +0000586/// in the body of the inlined function into invokes.
Chris Lattner908d7952006-01-13 19:05:59 +0000587///
Nick Lewycky12a130b2009-02-03 04:34:40 +0000588/// II is the invoke instruction being inlined. FirstNewBlock is the first
Chris Lattner908d7952006-01-13 19:05:59 +0000589/// block of the inlined code (the last block is the end of the function),
590/// and InlineCodeInfo is information about the code that got inlined.
David Majnemer654e1302015-07-31 17:58:14 +0000591static void HandleInlinedLandingPad(InvokeInst *II, BasicBlock *FirstNewBlock,
592 ClonedCodeInfo &InlinedCodeInfo) {
Chris Lattner908d7952006-01-13 19:05:59 +0000593 BasicBlock *InvokeDest = II->getUnwindDest();
Chris Lattner908d7952006-01-13 19:05:59 +0000594
595 Function *Caller = FirstNewBlock->getParent();
Duncan Sands7c8fb1a2008-09-05 12:37:12 +0000596
Chris Lattner908d7952006-01-13 19:05:59 +0000597 // The inlined code is currently at the end of the function, scan from the
598 // start of the inlined code to its end, checking for stuff we need to
Bill Wendling173c71f2013-03-21 23:30:12 +0000599 // rewrite.
David Majnemer654e1302015-07-31 17:58:14 +0000600 LandingPadInliningInfo Invoke(II);
Bill Wendling173c71f2013-03-21 23:30:12 +0000601
Bill Wendling56f15bf2013-03-22 20:31:05 +0000602 // Get all of the inlined landing pad instructions.
603 SmallPtrSet<LandingPadInst*, 16> InlinedLPads;
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000604 for (Function::iterator I = FirstNewBlock->getIterator(), E = Caller->end();
605 I != E; ++I)
Bill Wendling56f15bf2013-03-22 20:31:05 +0000606 if (InvokeInst *II = dyn_cast<InvokeInst>(I->getTerminator()))
607 InlinedLPads.insert(II->getLandingPadInst());
608
Mark Seabornef3dbb92013-12-08 00:50:58 +0000609 // Append the clauses from the outer landing pad instruction into the inlined
610 // landing pad instructions.
611 LandingPadInst *OuterLPad = Invoke.getLandingPadInst();
Craig Topper46276792014-08-24 23:23:06 +0000612 for (LandingPadInst *InlinedLPad : InlinedLPads) {
Mark Seabornef3dbb92013-12-08 00:50:58 +0000613 unsigned OuterNum = OuterLPad->getNumClauses();
614 InlinedLPad->reserveClauses(OuterNum);
615 for (unsigned OuterIdx = 0; OuterIdx != OuterNum; ++OuterIdx)
616 InlinedLPad->addClause(OuterLPad->getClause(OuterIdx));
Mark Seaborn1b3dd352013-12-08 00:51:21 +0000617 if (OuterLPad->isCleanup())
618 InlinedLPad->setCleanup(true);
Mark Seabornef3dbb92013-12-08 00:50:58 +0000619 }
620
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000621 for (Function::iterator BB = FirstNewBlock->getIterator(), E = Caller->end();
622 BB != E; ++BB) {
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000623 if (InlinedCodeInfo.ContainsCalls)
David Majnemer654e1302015-07-31 17:58:14 +0000624 if (BasicBlock *NewBB = HandleCallsInBlockInlinedThroughInvoke(
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000625 &*BB, Invoke.getOuterResumeDest()))
David Majnemer654e1302015-07-31 17:58:14 +0000626 // Update any PHI nodes in the exceptional block to indicate that there
627 // is now a new entry in them.
628 Invoke.addIncomingPHIValuesFor(NewBB);
Duncan Sands7c8fb1a2008-09-05 12:37:12 +0000629
Bill Wendling173c71f2013-03-21 23:30:12 +0000630 // Forward any resumes that are remaining here.
Bill Wendling621699d2012-01-31 01:14:49 +0000631 if (ResumeInst *RI = dyn_cast<ResumeInst>(BB->getTerminator()))
Bill Wendling56f15bf2013-03-22 20:31:05 +0000632 Invoke.forwardResume(RI, InlinedLPads);
Chris Lattner908d7952006-01-13 19:05:59 +0000633 }
634
635 // Now that everything is happy, we have one final detail. The PHI nodes in
636 // the exception destination block still have entries due to the original
Bill Wendling173c71f2013-03-21 23:30:12 +0000637 // invoke instruction. Eliminate these entries (which might even delete the
Chris Lattner908d7952006-01-13 19:05:59 +0000638 // PHI node) now.
639 InvokeDest->removePredecessor(II->getParent());
640}
641
David Majnemer654e1302015-07-31 17:58:14 +0000642/// If we inlined an invoke site, we need to convert calls
643/// in the body of the inlined function into invokes.
644///
645/// II is the invoke instruction being inlined. FirstNewBlock is the first
646/// block of the inlined code (the last block is the end of the function),
647/// and InlineCodeInfo is information about the code that got inlined.
648static void HandleInlinedEHPad(InvokeInst *II, BasicBlock *FirstNewBlock,
649 ClonedCodeInfo &InlinedCodeInfo) {
650 BasicBlock *UnwindDest = II->getUnwindDest();
651 Function *Caller = FirstNewBlock->getParent();
652
653 assert(UnwindDest->getFirstNonPHI()->isEHPad() && "unexpected BasicBlock!");
654
655 // If there are PHI nodes in the unwind destination block, we need to keep
656 // track of which values came into them from the invoke before removing the
657 // edge from this block.
658 SmallVector<Value *, 8> UnwindDestPHIValues;
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000659 BasicBlock *InvokeBB = II->getParent();
David Majnemer654e1302015-07-31 17:58:14 +0000660 for (Instruction &I : *UnwindDest) {
661 // Save the value to use for this edge.
662 PHINode *PHI = dyn_cast<PHINode>(&I);
663 if (!PHI)
664 break;
665 UnwindDestPHIValues.push_back(PHI->getIncomingValueForBlock(InvokeBB));
666 }
667
668 // Add incoming-PHI values to the unwind destination block for the given basic
669 // block, using the values for the original invoke's source block.
670 auto UpdatePHINodes = [&](BasicBlock *Src) {
671 BasicBlock::iterator I = UnwindDest->begin();
672 for (Value *V : UnwindDestPHIValues) {
673 PHINode *PHI = cast<PHINode>(I);
674 PHI->addIncoming(V, Src);
675 ++I;
676 }
677 };
678
David Majnemer8a1c45d2015-12-12 05:38:55 +0000679 // This connects all the instructions which 'unwind to caller' to the invoke
680 // destination.
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000681 UnwindDestMemoTy FuncletUnwindMap;
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000682 for (Function::iterator BB = FirstNewBlock->getIterator(), E = Caller->end();
683 BB != E; ++BB) {
David Majnemer654e1302015-07-31 17:58:14 +0000684 if (auto *CRI = dyn_cast<CleanupReturnInst>(BB->getTerminator())) {
685 if (CRI->unwindsToCaller()) {
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000686 auto *CleanupPad = CRI->getCleanupPad();
687 CleanupReturnInst::Create(CleanupPad, UnwindDest, CRI);
David Majnemer654e1302015-07-31 17:58:14 +0000688 CRI->eraseFromParent();
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000689 UpdatePHINodes(&*BB);
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000690 // Finding a cleanupret with an unwind destination would confuse
691 // subsequent calls to getUnwindDestToken, so map the cleanuppad
692 // to short-circuit any such calls and recognize this as an "unwind
693 // to caller" cleanup.
694 assert(!FuncletUnwindMap.count(CleanupPad) ||
695 isa<ConstantTokenNone>(FuncletUnwindMap[CleanupPad]));
696 FuncletUnwindMap[CleanupPad] =
697 ConstantTokenNone::get(Caller->getContext());
David Majnemer654e1302015-07-31 17:58:14 +0000698 }
699 }
David Majnemer8a1c45d2015-12-12 05:38:55 +0000700
701 Instruction *I = BB->getFirstNonPHI();
702 if (!I->isEHPad())
703 continue;
704
705 Instruction *Replacement = nullptr;
David Majnemerbbfc7212015-12-14 18:34:23 +0000706 if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(I)) {
David Majnemer8a1c45d2015-12-12 05:38:55 +0000707 if (CatchSwitch->unwindsToCaller()) {
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000708 Value *UnwindDestToken;
709 if (auto *ParentPad =
710 dyn_cast<Instruction>(CatchSwitch->getParentPad())) {
711 // This catchswitch is nested inside another funclet. If that
712 // funclet has an unwind destination within the inlinee, then
713 // unwinding out of this catchswitch would be UB. Rewriting this
714 // catchswitch to unwind to the inlined invoke's unwind dest would
715 // give the parent funclet multiple unwind destinations, which is
716 // something that subsequent EH table generation can't handle and
717 // that the veirifer rejects. So when we see such a call, leave it
718 // as "unwind to caller".
719 UnwindDestToken = getUnwindDestToken(ParentPad, FuncletUnwindMap);
720 if (UnwindDestToken && !isa<ConstantTokenNone>(UnwindDestToken))
721 continue;
722 } else {
723 // This catchswitch has no parent to inherit constraints from, and
724 // none of its descendants can have an unwind edge that exits it and
725 // targets another funclet in the inlinee. It may or may not have a
726 // descendant that definitively has an unwind to caller. In either
727 // case, we'll have to assume that any unwinds out of it may need to
728 // be routed to the caller, so treat it as though it has a definitive
729 // unwind to caller.
730 UnwindDestToken = ConstantTokenNone::get(Caller->getContext());
731 }
David Majnemer8a1c45d2015-12-12 05:38:55 +0000732 auto *NewCatchSwitch = CatchSwitchInst::Create(
733 CatchSwitch->getParentPad(), UnwindDest,
734 CatchSwitch->getNumHandlers(), CatchSwitch->getName(),
735 CatchSwitch);
736 for (BasicBlock *PadBB : CatchSwitch->handlers())
737 NewCatchSwitch->addHandler(PadBB);
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000738 // Propagate info for the old catchswitch over to the new one in
739 // the unwind map. This also serves to short-circuit any subsequent
740 // checks for the unwind dest of this catchswitch, which would get
741 // confused if they found the outer handler in the callee.
742 FuncletUnwindMap[NewCatchSwitch] = UnwindDestToken;
David Majnemer8a1c45d2015-12-12 05:38:55 +0000743 Replacement = NewCatchSwitch;
744 }
745 } else if (!isa<FuncletPadInst>(I)) {
746 llvm_unreachable("unexpected EHPad!");
747 }
748
749 if (Replacement) {
750 Replacement->takeName(I);
751 I->replaceAllUsesWith(Replacement);
752 I->eraseFromParent();
753 UpdatePHINodes(&*BB);
754 }
David Majnemer654e1302015-07-31 17:58:14 +0000755 }
756
757 if (InlinedCodeInfo.ContainsCalls)
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000758 for (Function::iterator BB = FirstNewBlock->getIterator(),
759 E = Caller->end();
760 BB != E; ++BB)
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000761 if (BasicBlock *NewBB = HandleCallsInBlockInlinedThroughInvoke(
762 &*BB, UnwindDest, &FuncletUnwindMap))
David Majnemer654e1302015-07-31 17:58:14 +0000763 // Update any PHI nodes in the exceptional block to indicate that there
764 // is now a new entry in them.
765 UpdatePHINodes(NewBB);
766
767 // Now that everything is happy, we have one final detail. The PHI nodes in
768 // the exception destination block still have entries due to the original
769 // invoke instruction. Eliminate these entries (which might even delete the
770 // PHI node) now.
771 UnwindDest->removePredecessor(InvokeBB);
772}
773
Michael Kruse978ba612018-12-20 04:58:07 +0000774/// When inlining a call site that has !llvm.mem.parallel_loop_access or
775/// llvm.access.group metadata, that metadata should be propagated to all
776/// memory-accessing cloned instructions.
Hal Finkel50316d92016-04-28 23:00:04 +0000777static void PropagateParallelLoopAccessMetadata(CallSite CS,
778 ValueToValueMapTy &VMap) {
779 MDNode *M =
780 CS.getInstruction()->getMetadata(LLVMContext::MD_mem_parallel_loop_access);
Michael Kruse978ba612018-12-20 04:58:07 +0000781 MDNode *CallAccessGroup =
782 CS.getInstruction()->getMetadata(LLVMContext::MD_access_group);
783 if (!M && !CallAccessGroup)
Hal Finkel50316d92016-04-28 23:00:04 +0000784 return;
785
786 for (ValueToValueMapTy::iterator VMI = VMap.begin(), VMIE = VMap.end();
787 VMI != VMIE; ++VMI) {
788 if (!VMI->second)
789 continue;
790
791 Instruction *NI = dyn_cast<Instruction>(VMI->second);
792 if (!NI)
793 continue;
794
Michael Kruse978ba612018-12-20 04:58:07 +0000795 if (M) {
796 if (MDNode *PM =
797 NI->getMetadata(LLVMContext::MD_mem_parallel_loop_access)) {
Hal Finkel50316d92016-04-28 23:00:04 +0000798 M = MDNode::concatenate(PM, M);
799 NI->setMetadata(LLVMContext::MD_mem_parallel_loop_access, M);
Michael Kruse978ba612018-12-20 04:58:07 +0000800 } else if (NI->mayReadOrWriteMemory()) {
801 NI->setMetadata(LLVMContext::MD_mem_parallel_loop_access, M);
802 }
803 }
804
805 if (NI->mayReadOrWriteMemory()) {
806 MDNode *UnitedAccGroups = uniteAccessGroups(
807 NI->getMetadata(LLVMContext::MD_access_group), CallAccessGroup);
808 NI->setMetadata(LLVMContext::MD_access_group, UnitedAccGroups);
Hal Finkel50316d92016-04-28 23:00:04 +0000809 }
810 }
811}
812
Sanjay Patel0fdb4372015-03-10 19:42:57 +0000813/// When inlining a function that contains noalias scope metadata,
814/// this metadata needs to be cloned so that the inlined blocks
Sanjay Patel65d533c2017-01-02 19:05:11 +0000815/// have different "unique scopes" at every call site. Were this not done, then
Hal Finkel94146652014-07-24 14:25:39 +0000816/// aliasing scopes from a function inlined into a caller multiple times could
817/// not be differentiated (and this would lead to miscompiles because the
818/// non-aliasing property communicated by the metadata could have
819/// call-site-specific control dependencies).
820static void CloneAliasScopeMetadata(CallSite CS, ValueToValueMapTy &VMap) {
821 const Function *CalledFunc = CS.getCalledFunction();
822 SetVector<const MDNode *> MD;
823
824 // Note: We could only clone the metadata if it is already used in the
825 // caller. I'm omitting that check here because it might confuse
826 // inter-procedural alias analysis passes. We can revisit this if it becomes
827 // an efficiency or overhead problem.
828
Benjamin Kramer135f7352016-06-26 12:28:59 +0000829 for (const BasicBlock &I : *CalledFunc)
830 for (const Instruction &J : I) {
831 if (const MDNode *M = J.getMetadata(LLVMContext::MD_alias_scope))
Hal Finkel94146652014-07-24 14:25:39 +0000832 MD.insert(M);
Benjamin Kramer135f7352016-06-26 12:28:59 +0000833 if (const MDNode *M = J.getMetadata(LLVMContext::MD_noalias))
Hal Finkel94146652014-07-24 14:25:39 +0000834 MD.insert(M);
835 }
836
837 if (MD.empty())
838 return;
839
840 // Walk the existing metadata, adding the complete (perhaps cyclic) chain to
841 // the set.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000842 SmallVector<const Metadata *, 16> Queue(MD.begin(), MD.end());
Hal Finkel94146652014-07-24 14:25:39 +0000843 while (!Queue.empty()) {
844 const MDNode *M = cast<MDNode>(Queue.pop_back_val());
845 for (unsigned i = 0, ie = M->getNumOperands(); i != ie; ++i)
846 if (const MDNode *M1 = dyn_cast<MDNode>(M->getOperand(i)))
847 if (MD.insert(M1))
848 Queue.push_back(M1);
849 }
850
851 // Now we have a complete set of all metadata in the chains used to specify
852 // the noalias scopes and the lists of those scopes.
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000853 SmallVector<TempMDTuple, 16> DummyNodes;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000854 DenseMap<const MDNode *, TrackingMDNodeRef> MDMap;
Benjamin Kramer135f7352016-06-26 12:28:59 +0000855 for (const MDNode *I : MD) {
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000856 DummyNodes.push_back(MDTuple::getTemporary(CalledFunc->getContext(), None));
Benjamin Kramer135f7352016-06-26 12:28:59 +0000857 MDMap[I].reset(DummyNodes.back().get());
Hal Finkel94146652014-07-24 14:25:39 +0000858 }
859
860 // Create new metadata nodes to replace the dummy nodes, replacing old
861 // metadata references with either a dummy node or an already-created new
862 // node.
Benjamin Kramer135f7352016-06-26 12:28:59 +0000863 for (const MDNode *I : MD) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000864 SmallVector<Metadata *, 4> NewOps;
Benjamin Kramer135f7352016-06-26 12:28:59 +0000865 for (unsigned i = 0, ie = I->getNumOperands(); i != ie; ++i) {
866 const Metadata *V = I->getOperand(i);
Hal Finkel94146652014-07-24 14:25:39 +0000867 if (const MDNode *M = dyn_cast<MDNode>(V))
868 NewOps.push_back(MDMap[M]);
869 else
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000870 NewOps.push_back(const_cast<Metadata *>(V));
Hal Finkel94146652014-07-24 14:25:39 +0000871 }
872
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000873 MDNode *NewM = MDNode::get(CalledFunc->getContext(), NewOps);
Benjamin Kramer135f7352016-06-26 12:28:59 +0000874 MDTuple *TempM = cast<MDTuple>(MDMap[I]);
Duncan P. N. Exon Smith946fdcc2015-01-19 20:36:39 +0000875 assert(TempM->isTemporary() && "Expected temporary node");
Hal Finkel94146652014-07-24 14:25:39 +0000876
877 TempM->replaceAllUsesWith(NewM);
878 }
879
880 // Now replace the metadata in the new inlined instructions with the
881 // repacements from the map.
882 for (ValueToValueMapTy::iterator VMI = VMap.begin(), VMIE = VMap.end();
883 VMI != VMIE; ++VMI) {
884 if (!VMI->second)
885 continue;
886
887 Instruction *NI = dyn_cast<Instruction>(VMI->second);
888 if (!NI)
889 continue;
890
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000891 if (MDNode *M = NI->getMetadata(LLVMContext::MD_alias_scope)) {
Hal Finkel61c38612014-08-14 21:09:37 +0000892 MDNode *NewMD = MDMap[M];
893 // If the call site also had alias scope metadata (a list of scopes to
894 // which instructions inside it might belong), propagate those scopes to
895 // the inlined instructions.
896 if (MDNode *CSM =
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000897 CS.getInstruction()->getMetadata(LLVMContext::MD_alias_scope))
Hal Finkel61c38612014-08-14 21:09:37 +0000898 NewMD = MDNode::concatenate(NewMD, CSM);
899 NI->setMetadata(LLVMContext::MD_alias_scope, NewMD);
900 } else if (NI->mayReadOrWriteMemory()) {
901 if (MDNode *M =
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000902 CS.getInstruction()->getMetadata(LLVMContext::MD_alias_scope))
Hal Finkel61c38612014-08-14 21:09:37 +0000903 NI->setMetadata(LLVMContext::MD_alias_scope, M);
904 }
Hal Finkel94146652014-07-24 14:25:39 +0000905
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000906 if (MDNode *M = NI->getMetadata(LLVMContext::MD_noalias)) {
Hal Finkel61c38612014-08-14 21:09:37 +0000907 MDNode *NewMD = MDMap[M];
908 // If the call site also had noalias metadata (a list of scopes with
909 // which instructions inside it don't alias), propagate those scopes to
910 // the inlined instructions.
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000911 if (MDNode *CSM =
912 CS.getInstruction()->getMetadata(LLVMContext::MD_noalias))
Hal Finkel61c38612014-08-14 21:09:37 +0000913 NewMD = MDNode::concatenate(NewMD, CSM);
914 NI->setMetadata(LLVMContext::MD_noalias, NewMD);
915 } else if (NI->mayReadOrWriteMemory()) {
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000916 if (MDNode *M = CS.getInstruction()->getMetadata(LLVMContext::MD_noalias))
Hal Finkel61c38612014-08-14 21:09:37 +0000917 NI->setMetadata(LLVMContext::MD_noalias, M);
918 }
Hal Finkel94146652014-07-24 14:25:39 +0000919 }
Hal Finkel94146652014-07-24 14:25:39 +0000920}
921
Sanjay Patel0fdb4372015-03-10 19:42:57 +0000922/// If the inlined function has noalias arguments,
923/// then add new alias scopes for each noalias argument, tag the mapped noalias
Hal Finkelff0bcb62014-07-25 15:50:08 +0000924/// parameters with noalias metadata specifying the new scope, and tag all
925/// non-derived loads, stores and memory intrinsics with the new alias scopes.
926static void AddAliasScopeMetadata(CallSite CS, ValueToValueMapTy &VMap,
Chandler Carruth7b560d42015-09-09 17:55:00 +0000927 const DataLayout &DL, AAResults *CalleeAAR) {
Hal Finkelff0bcb62014-07-25 15:50:08 +0000928 if (!EnableNoAliasConversion)
929 return;
930
931 const Function *CalledFunc = CS.getCalledFunction();
932 SmallVector<const Argument *, 4> NoAliasArgs;
933
Sanjay Patel42c73552016-01-13 22:16:48 +0000934 for (const Argument &Arg : CalledFunc->args())
935 if (Arg.hasNoAliasAttr() && !Arg.use_empty())
936 NoAliasArgs.push_back(&Arg);
Hal Finkelff0bcb62014-07-25 15:50:08 +0000937
938 if (NoAliasArgs.empty())
939 return;
940
941 // To do a good job, if a noalias variable is captured, we need to know if
942 // the capture point dominates the particular use we're considering.
943 DominatorTree DT;
944 DT.recalculate(const_cast<Function&>(*CalledFunc));
945
946 // noalias indicates that pointer values based on the argument do not alias
947 // pointer values which are not based on it. So we add a new "scope" for each
948 // noalias function argument. Accesses using pointers based on that argument
949 // become part of that alias scope, accesses using pointers not based on that
950 // argument are tagged as noalias with that scope.
951
952 DenseMap<const Argument *, MDNode *> NewScopes;
953 MDBuilder MDB(CalledFunc->getContext());
954
955 // Create a new scope domain for this function.
956 MDNode *NewDomain =
957 MDB.createAnonymousAliasScopeDomain(CalledFunc->getName());
958 for (unsigned i = 0, e = NoAliasArgs.size(); i != e; ++i) {
959 const Argument *A = NoAliasArgs[i];
960
961 std::string Name = CalledFunc->getName();
962 if (A->hasName()) {
963 Name += ": %";
964 Name += A->getName();
965 } else {
966 Name += ": argument ";
967 Name += utostr(i);
968 }
969
970 // Note: We always create a new anonymous root here. This is true regardless
971 // of the linkage of the callee because the aliasing "scope" is not just a
972 // property of the callee, but also all control dependencies in the caller.
973 MDNode *NewScope = MDB.createAnonymousAliasScope(NewDomain, Name);
974 NewScopes.insert(std::make_pair(A, NewScope));
975 }
976
977 // Iterate over all new instructions in the map; for all memory-access
978 // instructions, add the alias scope metadata.
979 for (ValueToValueMapTy::iterator VMI = VMap.begin(), VMIE = VMap.end();
980 VMI != VMIE; ++VMI) {
981 if (const Instruction *I = dyn_cast<Instruction>(VMI->first)) {
982 if (!VMI->second)
983 continue;
984
985 Instruction *NI = dyn_cast<Instruction>(VMI->second);
986 if (!NI)
987 continue;
988
Hal Finkel0c083022014-09-01 09:01:39 +0000989 bool IsArgMemOnlyCall = false, IsFuncCall = false;
Hal Finkelff0bcb62014-07-25 15:50:08 +0000990 SmallVector<const Value *, 2> PtrArgs;
991
992 if (const LoadInst *LI = dyn_cast<LoadInst>(I))
993 PtrArgs.push_back(LI->getPointerOperand());
994 else if (const StoreInst *SI = dyn_cast<StoreInst>(I))
995 PtrArgs.push_back(SI->getPointerOperand());
996 else if (const VAArgInst *VAAI = dyn_cast<VAArgInst>(I))
997 PtrArgs.push_back(VAAI->getPointerOperand());
998 else if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(I))
999 PtrArgs.push_back(CXI->getPointerOperand());
1000 else if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(I))
1001 PtrArgs.push_back(RMWI->getPointerOperand());
Hal Finkeld2dee162014-08-14 16:44:03 +00001002 else if (ImmutableCallSite ICS = ImmutableCallSite(I)) {
Hal Finkela3708df2014-08-30 12:48:33 +00001003 // If we know that the call does not access memory, then we'll still
1004 // know that about the inlined clone of this call site, and we don't
1005 // need to add metadata.
Hal Finkeld2dee162014-08-14 16:44:03 +00001006 if (ICS.doesNotAccessMemory())
1007 continue;
1008
Hal Finkel0c083022014-09-01 09:01:39 +00001009 IsFuncCall = true;
Chandler Carruth7b560d42015-09-09 17:55:00 +00001010 if (CalleeAAR) {
1011 FunctionModRefBehavior MRB = CalleeAAR->getModRefBehavior(ICS);
Chandler Carruth194f59c2015-07-22 23:15:57 +00001012 if (MRB == FMRB_OnlyAccessesArgumentPointees ||
1013 MRB == FMRB_OnlyReadsArgumentPointees)
Hal Finkel0c083022014-09-01 09:01:39 +00001014 IsArgMemOnlyCall = true;
1015 }
1016
Sanjay Patele01dcab2016-01-13 21:39:26 +00001017 for (Value *Arg : ICS.args()) {
Hal Finkela3708df2014-08-30 12:48:33 +00001018 // We need to check the underlying objects of all arguments, not just
1019 // the pointer arguments, because we might be passing pointers as
1020 // integers, etc.
Hal Finkel0c083022014-09-01 09:01:39 +00001021 // However, if we know that the call only accesses pointer arguments,
Hal Finkeld2dee162014-08-14 16:44:03 +00001022 // then we only need to check the pointer arguments.
Sanjay Patele01dcab2016-01-13 21:39:26 +00001023 if (IsArgMemOnlyCall && !Arg->getType()->isPointerTy())
Hal Finkel0c083022014-09-01 09:01:39 +00001024 continue;
Hal Finkelff0bcb62014-07-25 15:50:08 +00001025
Sanjay Patele01dcab2016-01-13 21:39:26 +00001026 PtrArgs.push_back(Arg);
Hal Finkel0c083022014-09-01 09:01:39 +00001027 }
1028 }
Hal Finkelcbb85f22014-09-01 04:26:40 +00001029
Hal Finkelff0bcb62014-07-25 15:50:08 +00001030 // If we found no pointers, then this instruction is not suitable for
1031 // pairing with an instruction to receive aliasing metadata.
Hal Finkeld2dee162014-08-14 16:44:03 +00001032 // However, if this is a call, this we might just alias with none of the
1033 // noalias arguments.
Hal Finkelcbb85f22014-09-01 04:26:40 +00001034 if (PtrArgs.empty() && !IsFuncCall)
Hal Finkelff0bcb62014-07-25 15:50:08 +00001035 continue;
1036
1037 // It is possible that there is only one underlying object, but you
1038 // need to go through several PHIs to see it, and thus could be
1039 // repeated in the Objects list.
1040 SmallPtrSet<const Value *, 4> ObjSet;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001041 SmallVector<Metadata *, 4> Scopes, NoAliases;
Hal Finkelff0bcb62014-07-25 15:50:08 +00001042
1043 SmallSetVector<const Argument *, 4> NAPtrArgs;
Sanjay Patele01dcab2016-01-13 21:39:26 +00001044 for (const Value *V : PtrArgs) {
Hal Finkelff0bcb62014-07-25 15:50:08 +00001045 SmallVector<Value *, 4> Objects;
Sanjay Patele01dcab2016-01-13 21:39:26 +00001046 GetUnderlyingObjects(const_cast<Value*>(V),
Hans Wennborg083ca9b2015-10-06 23:24:35 +00001047 Objects, DL, /* LI = */ nullptr);
Hal Finkelff0bcb62014-07-25 15:50:08 +00001048
1049 for (Value *O : Objects)
1050 ObjSet.insert(O);
1051 }
1052
Hal Finkel2d3d6da2014-08-29 16:33:41 +00001053 // Figure out if we're derived from anything that is not a noalias
Hal Finkelff0bcb62014-07-25 15:50:08 +00001054 // argument.
Hal Finkela3708df2014-08-30 12:48:33 +00001055 bool CanDeriveViaCapture = false, UsesAliasingPtr = false;
1056 for (const Value *V : ObjSet) {
1057 // Is this value a constant that cannot be derived from any pointer
1058 // value (we need to exclude constant expressions, for example, that
1059 // are formed from arithmetic on global symbols).
1060 bool IsNonPtrConst = isa<ConstantInt>(V) || isa<ConstantFP>(V) ||
1061 isa<ConstantPointerNull>(V) ||
1062 isa<ConstantDataVector>(V) || isa<UndefValue>(V);
Hal Finkelcbb85f22014-09-01 04:26:40 +00001063 if (IsNonPtrConst)
1064 continue;
1065
1066 // If this is anything other than a noalias argument, then we cannot
1067 // completely describe the aliasing properties using alias.scope
1068 // metadata (and, thus, won't add any).
1069 if (const Argument *A = dyn_cast<Argument>(V)) {
1070 if (!A->hasNoAliasAttr())
1071 UsesAliasingPtr = true;
1072 } else {
Hal Finkela3708df2014-08-30 12:48:33 +00001073 UsesAliasingPtr = true;
Hal Finkelff0bcb62014-07-25 15:50:08 +00001074 }
Hal Finkelcbb85f22014-09-01 04:26:40 +00001075
1076 // If this is not some identified function-local object (which cannot
1077 // directly alias a noalias argument), or some other argument (which,
1078 // by definition, also cannot alias a noalias argument), then we could
1079 // alias a noalias argument that has been captured).
1080 if (!isa<Argument>(V) &&
1081 !isIdentifiedFunctionLocal(const_cast<Value*>(V)))
1082 CanDeriveViaCapture = true;
Hal Finkela3708df2014-08-30 12:48:33 +00001083 }
Hal Finkelcbb85f22014-09-01 04:26:40 +00001084
1085 // A function call can always get captured noalias pointers (via other
1086 // parameters, globals, etc.).
1087 if (IsFuncCall && !IsArgMemOnlyCall)
1088 CanDeriveViaCapture = true;
1089
Hal Finkelff0bcb62014-07-25 15:50:08 +00001090 // First, we want to figure out all of the sets with which we definitely
1091 // don't alias. Iterate over all noalias set, and add those for which:
1092 // 1. The noalias argument is not in the set of objects from which we
1093 // definitely derive.
1094 // 2. The noalias argument has not yet been captured.
Hal Finkelcbb85f22014-09-01 04:26:40 +00001095 // An arbitrary function that might load pointers could see captured
1096 // noalias arguments via other noalias arguments or globals, and so we
1097 // must always check for prior capture.
Hal Finkelff0bcb62014-07-25 15:50:08 +00001098 for (const Argument *A : NoAliasArgs) {
1099 if (!ObjSet.count(A) && (!CanDeriveViaCapture ||
Hal Finkela3708df2014-08-30 12:48:33 +00001100 // It might be tempting to skip the
1101 // PointerMayBeCapturedBefore check if
1102 // A->hasNoCaptureAttr() is true, but this is
1103 // incorrect because nocapture only guarantees
1104 // that no copies outlive the function, not
1105 // that the value cannot be locally captured.
Hal Finkelff0bcb62014-07-25 15:50:08 +00001106 !PointerMayBeCapturedBefore(A,
1107 /* ReturnCaptures */ false,
1108 /* StoreCaptures */ false, I, &DT)))
1109 NoAliases.push_back(NewScopes[A]);
1110 }
1111
1112 if (!NoAliases.empty())
Duncan P. N. Exon Smith3872d002014-11-01 00:10:31 +00001113 NI->setMetadata(LLVMContext::MD_noalias,
1114 MDNode::concatenate(
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001115 NI->getMetadata(LLVMContext::MD_noalias),
Duncan P. N. Exon Smith3872d002014-11-01 00:10:31 +00001116 MDNode::get(CalledFunc->getContext(), NoAliases)));
Hal Finkela3708df2014-08-30 12:48:33 +00001117
Hal Finkelff0bcb62014-07-25 15:50:08 +00001118 // Next, we want to figure out all of the sets to which we might belong.
Hal Finkela3708df2014-08-30 12:48:33 +00001119 // We might belong to a set if the noalias argument is in the set of
1120 // underlying objects. If there is some non-noalias argument in our list
1121 // of underlying objects, then we cannot add a scope because the fact
1122 // that some access does not alias with any set of our noalias arguments
1123 // cannot itself guarantee that it does not alias with this access
1124 // (because there is some pointer of unknown origin involved and the
1125 // other access might also depend on this pointer). We also cannot add
1126 // scopes to arbitrary functions unless we know they don't access any
1127 // non-parameter pointer-values.
1128 bool CanAddScopes = !UsesAliasingPtr;
Hal Finkelcbb85f22014-09-01 04:26:40 +00001129 if (CanAddScopes && IsFuncCall)
1130 CanAddScopes = IsArgMemOnlyCall;
Hal Finkelff0bcb62014-07-25 15:50:08 +00001131
Hal Finkela3708df2014-08-30 12:48:33 +00001132 if (CanAddScopes)
1133 for (const Argument *A : NoAliasArgs) {
1134 if (ObjSet.count(A))
1135 Scopes.push_back(NewScopes[A]);
1136 }
1137
Hal Finkelff0bcb62014-07-25 15:50:08 +00001138 if (!Scopes.empty())
Duncan P. N. Exon Smith3872d002014-11-01 00:10:31 +00001139 NI->setMetadata(
1140 LLVMContext::MD_alias_scope,
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001141 MDNode::concatenate(NI->getMetadata(LLVMContext::MD_alias_scope),
Duncan P. N. Exon Smith3872d002014-11-01 00:10:31 +00001142 MDNode::get(CalledFunc->getContext(), Scopes)));
Hal Finkelff0bcb62014-07-25 15:50:08 +00001143 }
1144 }
1145}
1146
Hans Wennborg2d5841f2017-02-27 22:33:02 +00001147/// If the inlined function has non-byval align arguments, then
1148/// add @llvm.assume-based alignment assumptions to preserve this information.
1149static void AddAlignmentAssumptions(CallSite CS, InlineFunctionInfo &IFI) {
1150 if (!PreserveAlignmentAssumptions || !IFI.GetAssumptionCache)
Hal Finkel68dc3c72014-10-15 23:44:41 +00001151 return;
Sanjay Patelaea60842016-12-31 17:54:05 +00001152
1153 AssumptionCache *AC = &(*IFI.GetAssumptionCache)(*CS.getCaller());
Mehdi Amini46a43552015-03-04 18:43:29 +00001154 auto &DL = CS.getCaller()->getParent()->getDataLayout();
Hal Finkel68dc3c72014-10-15 23:44:41 +00001155
Hans Wennborg2d5841f2017-02-27 22:33:02 +00001156 // To avoid inserting redundant assumptions, we should check for assumptions
1157 // already in the caller. To do this, we might need a DT of the caller.
Hal Finkel68dc3c72014-10-15 23:44:41 +00001158 DominatorTree DT;
1159 bool DTCalculated = false;
1160
Chandler Carruth66b31302015-01-04 12:03:27 +00001161 Function *CalledFunc = CS.getCalledFunction();
Sanjay Patelada717e2017-02-15 14:56:11 +00001162 for (Argument &Arg : CalledFunc->args()) {
Sanjay Patel40975e02017-02-27 18:13:48 +00001163 unsigned Align = Arg.getType()->isPointerTy() ? Arg.getParamAlignment() : 0;
Hans Wennborg2d5841f2017-02-27 22:33:02 +00001164 if (Align && !Arg.hasByValOrInAllocaAttr() && !Arg.hasNUses(0)) {
1165 if (!DTCalculated) {
1166 DT.recalculate(*CS.getCaller());
1167 DTCalculated = true;
1168 }
1169
Hal Finkel68dc3c72014-10-15 23:44:41 +00001170 // If we can already prove the asserted alignment in the context of the
1171 // caller, then don't bother inserting the assumption.
Hans Wennborg2d5841f2017-02-27 22:33:02 +00001172 Value *ArgVal = CS.getArgument(Arg.getArgNo());
1173 if (getKnownAlignment(ArgVal, DL, CS.getInstruction(), AC, &DT) >= Align)
1174 continue;
Hal Finkel68dc3c72014-10-15 23:44:41 +00001175
Hans Wennborg2d5841f2017-02-27 22:33:02 +00001176 CallInst *NewAsmp = IRBuilder<>(CS.getInstruction())
1177 .CreateAlignmentAssumption(DL, ArgVal, Align);
1178 AC->registerAssumption(NewAsmp);
Hal Finkel68dc3c72014-10-15 23:44:41 +00001179 }
1180 }
1181}
1182
Sanjay Patel0fdb4372015-03-10 19:42:57 +00001183/// Once we have cloned code over from a callee into the caller,
1184/// update the specified callgraph to reflect the changes we made.
1185/// Note that it's possible that not all code was copied over, so only
Duncan Sands46911f12008-09-08 11:05:51 +00001186/// some edges of the callgraph may remain.
1187static void UpdateCallGraphAfterInlining(CallSite CS,
Chris Lattner5de3b8b2006-07-12 18:29:36 +00001188 Function::iterator FirstNewBlock,
Rafael Espindola229e38f2010-10-13 01:36:30 +00001189 ValueToValueMapTy &VMap,
Chris Lattner2eee5d32010-04-22 23:37:35 +00001190 InlineFunctionInfo &IFI) {
1191 CallGraph &CG = *IFI.CG;
Sanjay Patel32d753c2017-02-15 15:08:38 +00001192 const Function *Caller = CS.getCaller();
Duncan Sands46911f12008-09-08 11:05:51 +00001193 const Function *Callee = CS.getCalledFunction();
Chris Lattner0841fb12006-01-14 20:07:50 +00001194 CallGraphNode *CalleeNode = CG[Callee];
1195 CallGraphNode *CallerNode = CG[Caller];
Duncan Sands7c8fb1a2008-09-05 12:37:12 +00001196
Chris Lattner5de3b8b2006-07-12 18:29:36 +00001197 // Since we inlined some uninlined call sites in the callee into the caller,
Chris Lattner0841fb12006-01-14 20:07:50 +00001198 // add edges from the caller to all of the callees of the callee.
Gabor Greif5aa19222009-01-15 18:40:09 +00001199 CallGraphNode::iterator I = CalleeNode->begin(), E = CalleeNode->end();
1200
1201 // Consider the case where CalleeNode == CallerNode.
Gabor Greiff1abfdc2009-01-17 00:09:08 +00001202 CallGraphNode::CalledFunctionsVector CallCache;
Gabor Greif5aa19222009-01-15 18:40:09 +00001203 if (CalleeNode == CallerNode) {
1204 CallCache.assign(I, E);
1205 I = CallCache.begin();
1206 E = CallCache.end();
1207 }
1208
1209 for (; I != E; ++I) {
Chris Lattner063d0652009-09-01 06:31:31 +00001210 const Value *OrigCall = I->first;
Duncan Sands7c8fb1a2008-09-05 12:37:12 +00001211
Rafael Espindola229e38f2010-10-13 01:36:30 +00001212 ValueToValueMapTy::iterator VMI = VMap.find(OrigCall);
Chris Lattnerb3c64f72006-07-12 21:37:11 +00001213 // Only copy the edge if the call was inlined!
Craig Topperf40110f2014-04-25 05:29:35 +00001214 if (VMI == VMap.end() || VMI->second == nullptr)
Chris Lattner5eef6ad2009-08-27 03:51:50 +00001215 continue;
Fangrui Songf78650a2018-07-30 19:41:25 +00001216
Chris Lattner5eef6ad2009-08-27 03:51:50 +00001217 // If the call was inlined, but then constant folded, there is no edge to
1218 // add. Check for this case.
Chris Lattner016c00a2010-04-22 21:31:00 +00001219 Instruction *NewCall = dyn_cast<Instruction>(VMI->second);
Sanjay Patelc04b6f22015-03-11 15:12:32 +00001220 if (!NewCall)
1221 continue;
Chris Lattnerc2432b92010-05-01 01:26:13 +00001222
Sanjay Patelc04b6f22015-03-11 15:12:32 +00001223 // We do not treat intrinsic calls like real function calls because we
1224 // expect them to become inline code; do not add an edge for an intrinsic.
1225 CallSite CS = CallSite(NewCall);
1226 if (CS && CS.getCalledFunction() && CS.getCalledFunction()->isIntrinsic())
1227 continue;
Fangrui Songf78650a2018-07-30 19:41:25 +00001228
Chris Lattnerc2432b92010-05-01 01:26:13 +00001229 // Remember that this call site got inlined for the client of
1230 // InlineFunction.
1231 IFI.InlinedCalls.push_back(NewCall);
1232
Chris Lattner016c00a2010-04-22 21:31:00 +00001233 // It's possible that inlining the callsite will cause it to go from an
1234 // indirect to a direct call by resolving a function pointer. If this
1235 // happens, set the callee of the new call site to a more precise
1236 // destination. This can also happen if the call graph node of the caller
1237 // was just unnecessarily imprecise.
Craig Topperf40110f2014-04-25 05:29:35 +00001238 if (!I->second->getFunction())
Chris Lattner016c00a2010-04-22 21:31:00 +00001239 if (Function *F = CallSite(NewCall).getCalledFunction()) {
1240 // Indirect call site resolved to direct call.
Gabor Greif7b0a5fd2010-07-27 15:02:37 +00001241 CallerNode->addCalledFunction(CallSite(NewCall), CG[F]);
1242
Chris Lattner016c00a2010-04-22 21:31:00 +00001243 continue;
1244 }
Gabor Greif7b0a5fd2010-07-27 15:02:37 +00001245
1246 CallerNode->addCalledFunction(CallSite(NewCall), I->second);
Chris Lattner5de3b8b2006-07-12 18:29:36 +00001247 }
Fangrui Songf78650a2018-07-30 19:41:25 +00001248
Dale Johannesen0aeabdf2009-01-13 22:43:37 +00001249 // Update the call graph by deleting the edge from Callee to Caller. We must
1250 // do this after the loop above in case Caller and Callee are the same.
1251 CallerNode->removeCallEdgeFor(CS);
Chris Lattner0841fb12006-01-14 20:07:50 +00001252}
1253
Julien Lerouge957e91c2014-04-15 18:01:54 +00001254static void HandleByValArgumentInit(Value *Dst, Value *Src, Module *M,
1255 BasicBlock *InsertBlock,
1256 InlineFunctionInfo &IFI) {
Julien Lerouge957e91c2014-04-15 18:01:54 +00001257 Type *AggTy = cast<PointerType>(Src->getType())->getElementType();
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001258 IRBuilder<> Builder(InsertBlock, InsertBlock->begin());
Julien Lerouge957e91c2014-04-15 18:01:54 +00001259
Mehdi Amini46a43552015-03-04 18:43:29 +00001260 Value *Size = Builder.getInt64(M->getDataLayout().getTypeStoreSize(AggTy));
Julien Lerouge957e91c2014-04-15 18:01:54 +00001261
1262 // Always generate a memcpy of alignment 1 here because we don't know
1263 // the alignment of the src pointer. Other optimizations can infer
1264 // better alignment.
Daniel Neilsona8942012018-02-06 19:14:31 +00001265 Builder.CreateMemCpy(Dst, /*DstAlign*/1, Src, /*SrcAlign*/1, Size);
Julien Lerouge957e91c2014-04-15 18:01:54 +00001266}
1267
Sanjay Patel0fdb4372015-03-10 19:42:57 +00001268/// When inlining a call site that has a byval argument,
Chris Lattner0f114952010-12-20 08:10:40 +00001269/// we have to make the implicit memcpy explicit by adding it.
David Majnemer120f4a02013-11-03 12:22:13 +00001270static Value *HandleByValArgument(Value *Arg, Instruction *TheCall,
Chris Lattner00997442010-12-20 07:57:41 +00001271 const Function *CalledFunc,
1272 InlineFunctionInfo &IFI,
Reid Klecknerdd3f3ed2014-11-04 02:02:14 +00001273 unsigned ByValAlignment) {
Matt Arsenaultbe558882014-04-23 20:58:57 +00001274 PointerType *ArgTy = cast<PointerType>(Arg->getType());
1275 Type *AggTy = ArgTy->getElementType();
Chris Lattner0f114952010-12-20 08:10:40 +00001276
Sanjay Patel288f0752017-02-15 15:22:18 +00001277 Function *Caller = TheCall->getFunction();
Matt Arsenault3c1fc762017-04-10 22:27:50 +00001278 const DataLayout &DL = Caller->getParent()->getDataLayout();
Chandler Carruth66b31302015-01-04 12:03:27 +00001279
Chris Lattner0f114952010-12-20 08:10:40 +00001280 // If the called function is readonly, then it could not mutate the caller's
1281 // copy of the byval'd memory. In this case, it is safe to elide the copy and
1282 // temporary.
David Majnemer120f4a02013-11-03 12:22:13 +00001283 if (CalledFunc->onlyReadsMemory()) {
Chris Lattner0f114952010-12-20 08:10:40 +00001284 // If the byval argument has a specified alignment that is greater than the
1285 // passed in pointer, then we either have to round up the input pointer or
1286 // give up on this transformation.
1287 if (ByValAlignment <= 1) // 0 = unspecified, 1 = no particular alignment.
David Majnemer120f4a02013-11-03 12:22:13 +00001288 return Arg;
Chris Lattner0f114952010-12-20 08:10:40 +00001289
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001290 AssumptionCache *AC =
1291 IFI.GetAssumptionCache ? &(*IFI.GetAssumptionCache)(*Caller) : nullptr;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001292
Chris Lattner20fca482010-12-25 20:42:38 +00001293 // If the pointer is already known to be sufficiently aligned, or if we can
1294 // round it up to a larger alignment, then we don't need a temporary.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001295 if (getOrEnforceKnownAlignment(Arg, ByValAlignment, DL, TheCall, AC) >=
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001296 ByValAlignment)
David Majnemer120f4a02013-11-03 12:22:13 +00001297 return Arg;
Matt Arsenault3c1fc762017-04-10 22:27:50 +00001298
Chris Lattner20fca482010-12-25 20:42:38 +00001299 // Otherwise, we have to make a memcpy to get a safe alignment. This is bad
1300 // for code quality, but rarely happens and is required for correctness.
Chris Lattner0f114952010-12-20 08:10:40 +00001301 }
Chris Lattner00997442010-12-20 07:57:41 +00001302
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001303 // Create the alloca. If we have DataLayout, use nice alignment.
Matt Arsenault3c1fc762017-04-10 22:27:50 +00001304 unsigned Align = DL.getPrefTypeAlignment(AggTy);
Mehdi Amini46a43552015-03-04 18:43:29 +00001305
Chris Lattner00997442010-12-20 07:57:41 +00001306 // If the byval had an alignment specified, we *must* use at least that
1307 // alignment, as it is required by the byval argument (and uses of the
1308 // pointer inside the callee).
1309 Align = std::max(Align, ByValAlignment);
Matt Arsenault3c1fc762017-04-10 22:27:50 +00001310
1311 Value *NewAlloca = new AllocaInst(AggTy, DL.getAllocaAddrSpace(),
1312 nullptr, Align, Arg->getName(),
Chris Lattner00997442010-12-20 07:57:41 +00001313 &*Caller->begin()->begin());
Julien Lerougebe4fe322014-04-15 18:06:46 +00001314 IFI.StaticAllocas.push_back(cast<AllocaInst>(NewAlloca));
Matt Arsenault3c1fc762017-04-10 22:27:50 +00001315
Chris Lattner00997442010-12-20 07:57:41 +00001316 // Uses of the argument in the function should use our new alloca
1317 // instead.
1318 return NewAlloca;
1319}
1320
Sanjay Patel0fdb4372015-03-10 19:42:57 +00001321// Check whether this Value is used by a lifetime intrinsic.
Nick Lewyckya68ec832011-05-22 05:22:10 +00001322static bool isUsedByLifetimeMarker(Value *V) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001323 for (User *U : V->users()) {
1324 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U)) {
Nick Lewyckya68ec832011-05-22 05:22:10 +00001325 switch (II->getIntrinsicID()) {
1326 default: break;
1327 case Intrinsic::lifetime_start:
1328 case Intrinsic::lifetime_end:
1329 return true;
1330 }
1331 }
1332 }
1333 return false;
1334}
1335
Sanjay Patel0fdb4372015-03-10 19:42:57 +00001336// Check whether the given alloca already has
Nick Lewyckya68ec832011-05-22 05:22:10 +00001337// lifetime.start or lifetime.end intrinsics.
1338static bool hasLifetimeMarkers(AllocaInst *AI) {
Matt Arsenaultbe558882014-04-23 20:58:57 +00001339 Type *Ty = AI->getType();
1340 Type *Int8PtrTy = Type::getInt8PtrTy(Ty->getContext(),
1341 Ty->getPointerAddressSpace());
1342 if (Ty == Int8PtrTy)
Nick Lewyckya68ec832011-05-22 05:22:10 +00001343 return isUsedByLifetimeMarker(AI);
1344
Nick Lewycky9711b5c2011-06-14 00:59:24 +00001345 // Do a scan to find all the casts to i8*.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001346 for (User *U : AI->users()) {
1347 if (U->getType() != Int8PtrTy) continue;
1348 if (U->stripPointerCasts() != AI) continue;
1349 if (isUsedByLifetimeMarker(U))
Nick Lewyckya68ec832011-05-22 05:22:10 +00001350 return true;
1351 }
1352 return false;
1353}
1354
Reid Kleckner6ee00a22016-08-12 22:23:04 +00001355/// Return the result of AI->isStaticAlloca() if AI were moved to the entry
1356/// block. Allocas used in inalloca calls and allocas of dynamic array size
1357/// cannot be static.
1358static bool allocaWouldBeStaticInEntry(const AllocaInst *AI ) {
1359 return isa<Constant>(AI->getArraySize()) && !AI->isUsedWithInAlloca();
1360}
1361
Adrian Prantld4056502017-03-07 17:28:57 +00001362/// Update inlined instructions' line numbers to
1363/// to encode location where these instructions are inlined.
1364static void fixupLineNumbers(Function *Fn, Function::iterator FI,
1365 Instruction *TheCall, bool CalleeHasDebugInfo) {
Benjamin Kramer4ca41fd2016-06-12 17:30:47 +00001366 const DebugLoc &TheCallDL = TheCall->getDebugLoc();
Adrian Prantld4056502017-03-07 17:28:57 +00001367 if (!TheCallDL)
1368 return;
Devang Patel35797402011-07-08 18:01:31 +00001369
David Blaikiedf706282015-01-21 22:57:29 +00001370 auto &Ctx = Fn->getContext();
Adrian Prantld4056502017-03-07 17:28:57 +00001371 DILocation *InlinedAtNode = TheCallDL;
David Blaikiedf706282015-01-21 22:57:29 +00001372
1373 // Create a unique call site, not to be confused with any other call from the
1374 // same location.
Adrian Prantld4056502017-03-07 17:28:57 +00001375 InlinedAtNode = DILocation::getDistinct(
1376 Ctx, InlinedAtNode->getLine(), InlinedAtNode->getColumn(),
1377 InlinedAtNode->getScope(), InlinedAtNode->getInlinedAt());
David Blaikiedf706282015-01-21 22:57:29 +00001378
1379 // Cache the inlined-at nodes as they're built so they are reused, without
1380 // this every instruction's inlined-at chain would become distinct from each
1381 // other.
Adrian Prantlc10d0e52017-05-09 19:47:37 +00001382 DenseMap<const MDNode *, MDNode *> IANodes;
David Blaikiedf706282015-01-21 22:57:29 +00001383
Devang Patel35797402011-07-08 18:01:31 +00001384 for (; FI != Fn->end(); ++FI) {
1385 for (BasicBlock::iterator BI = FI->begin(), BE = FI->end();
1386 BI != BE; ++BI) {
Andrea Di Biagioeff22832016-12-07 12:01:45 +00001387 if (DebugLoc DL = BI->getDebugLoc()) {
Adrian Prantlc10d0e52017-05-09 19:47:37 +00001388 auto IA = DebugLoc::appendInlinedAt(DL, InlinedAtNode, BI->getContext(),
1389 IANodes);
1390 auto IDL = DebugLoc::get(DL.getLine(), DL.getCol(), DL.getScope(), IA);
1391 BI->setDebugLoc(IDL);
Andrea Di Biagioeff22832016-12-07 12:01:45 +00001392 continue;
Devang Patelbb23a4a2011-08-10 21:50:54 +00001393 }
Andrea Di Biagioeff22832016-12-07 12:01:45 +00001394
1395 if (CalleeHasDebugInfo)
1396 continue;
Fangrui Songf78650a2018-07-30 19:41:25 +00001397
Andrea Di Biagioeff22832016-12-07 12:01:45 +00001398 // If the inlined instruction has no line number, make it look as if it
1399 // originates from the call location. This is important for
1400 // ((__always_inline__, __nodebug__)) functions which must use caller
1401 // location for all instructions in their function body.
1402
1403 // Don't update static allocas, as they may get moved later.
1404 if (auto *AI = dyn_cast<AllocaInst>(BI))
1405 if (allocaWouldBeStaticInEntry(AI))
1406 continue;
1407
1408 BI->setDebugLoc(TheCallDL);
Devang Patel35797402011-07-08 18:01:31 +00001409 }
1410 }
1411}
Eugene Zelenko6cadde72017-10-17 21:27:42 +00001412
Easwaran Raman12585b02017-01-20 22:44:04 +00001413/// Update the block frequencies of the caller after a callee has been inlined.
1414///
1415/// Each block cloned into the caller has its block frequency scaled by the
1416/// ratio of CallSiteFreq/CalleeEntryFreq. This ensures that the cloned copy of
1417/// callee's entry block gets the same frequency as the callsite block and the
1418/// relative frequencies of all cloned blocks remain the same after cloning.
1419static void updateCallerBFI(BasicBlock *CallSiteBlock,
1420 const ValueToValueMapTy &VMap,
1421 BlockFrequencyInfo *CallerBFI,
1422 BlockFrequencyInfo *CalleeBFI,
1423 const BasicBlock &CalleeEntryBlock) {
1424 SmallPtrSet<BasicBlock *, 16> ClonedBBs;
1425 for (auto const &Entry : VMap) {
1426 if (!isa<BasicBlock>(Entry.first) || !Entry.second)
1427 continue;
1428 auto *OrigBB = cast<BasicBlock>(Entry.first);
1429 auto *ClonedBB = cast<BasicBlock>(Entry.second);
Easwaran Raman5a12f232017-02-14 22:49:28 +00001430 uint64_t Freq = CalleeBFI->getBlockFreq(OrigBB).getFrequency();
1431 if (!ClonedBBs.insert(ClonedBB).second) {
1432 // Multiple blocks in the callee might get mapped to one cloned block in
1433 // the caller since we prune the callee as we clone it. When that happens,
1434 // we want to use the maximum among the original blocks' frequencies.
1435 uint64_t NewFreq = CallerBFI->getBlockFreq(ClonedBB).getFrequency();
1436 if (NewFreq > Freq)
1437 Freq = NewFreq;
1438 }
1439 CallerBFI->setBlockFreq(ClonedBB, Freq);
Easwaran Raman12585b02017-01-20 22:44:04 +00001440 }
1441 BasicBlock *EntryClone = cast<BasicBlock>(VMap.lookup(&CalleeEntryBlock));
1442 CallerBFI->setBlockFreqAndScale(
1443 EntryClone, CallerBFI->getBlockFreq(CallSiteBlock).getFrequency(),
1444 ClonedBBs);
1445}
1446
Dehao Chene5930492017-03-20 16:40:44 +00001447/// Update the branch metadata for cloned call instructions.
1448static void updateCallProfile(Function *Callee, const ValueToValueMapTy &VMap,
Easwaran Ramane5b8de22018-01-17 22:24:23 +00001449 const ProfileCount &CalleeEntryCount,
Easwaran Ramanf5f91602017-05-09 23:21:10 +00001450 const Instruction *TheCall,
Teresa Johnson525dcb62017-05-22 20:28:18 +00001451 ProfileSummaryInfo *PSI,
1452 BlockFrequencyInfo *CallerBFI) {
Easwaran Ramane5b8de22018-01-17 22:24:23 +00001453 if (!CalleeEntryCount.hasValue() || CalleeEntryCount.isSynthetic() ||
1454 CalleeEntryCount.getCount() < 1)
Dehao Chene5930492017-03-20 16:40:44 +00001455 return;
Easwaran Ramane5b8de22018-01-17 22:24:23 +00001456 auto CallSiteCount = PSI ? PSI->getProfileCount(TheCall, CallerBFI) : None;
Dehao Chene5930492017-03-20 16:40:44 +00001457 uint64_t CallCount =
1458 std::min(CallSiteCount.hasValue() ? CallSiteCount.getValue() : 0,
Easwaran Ramane5b8de22018-01-17 22:24:23 +00001459 CalleeEntryCount.getCount());
Dehao Chene5930492017-03-20 16:40:44 +00001460
1461 for (auto const &Entry : VMap)
David Blaikie795dc942017-03-20 18:01:07 +00001462 if (isa<CallInst>(Entry.first))
1463 if (auto *CI = dyn_cast_or_null<CallInst>(Entry.second))
Easwaran Ramane5b8de22018-01-17 22:24:23 +00001464 CI->updateProfWeight(CallCount, CalleeEntryCount.getCount());
Dehao Chene5930492017-03-20 16:40:44 +00001465 for (BasicBlock &BB : *Callee)
1466 // No need to update the callsite if it is pruned during inlining.
1467 if (VMap.count(&BB))
1468 for (Instruction &I : BB)
1469 if (CallInst *CI = dyn_cast<CallInst>(&I))
Easwaran Ramane5b8de22018-01-17 22:24:23 +00001470 CI->updateProfWeight(CalleeEntryCount.getCount() - CallCount,
1471 CalleeEntryCount.getCount());
Dehao Chene5930492017-03-20 16:40:44 +00001472}
1473
Easwaran Raman12585b02017-01-20 22:44:04 +00001474/// Update the entry count of callee after inlining.
1475///
1476/// The callsite's block count is subtracted from the callee's function entry
1477/// count.
Dehao Chene5930492017-03-20 16:40:44 +00001478static void updateCalleeCount(BlockFrequencyInfo *CallerBFI, BasicBlock *CallBB,
Easwaran Ramanf5f91602017-05-09 23:21:10 +00001479 Instruction *CallInst, Function *Callee,
1480 ProfileSummaryInfo *PSI) {
Easwaran Raman12585b02017-01-20 22:44:04 +00001481 // If the callee has a original count of N, and the estimated count of
1482 // callsite is M, the new callee count is set to N - M. M is estimated from
1483 // the caller's entry count, its entry block frequency and the block frequency
1484 // of the callsite.
Easwaran Ramane5b8de22018-01-17 22:24:23 +00001485 auto CalleeCount = Callee->getEntryCount();
Easwaran Ramanf5f91602017-05-09 23:21:10 +00001486 if (!CalleeCount.hasValue() || !PSI)
Easwaran Raman12585b02017-01-20 22:44:04 +00001487 return;
Easwaran Ramane5b8de22018-01-17 22:24:23 +00001488 auto CallCount = PSI->getProfileCount(CallInst, CallerBFI);
Dehao Chene5930492017-03-20 16:40:44 +00001489 if (!CallCount.hasValue())
Easwaran Raman12585b02017-01-20 22:44:04 +00001490 return;
1491 // Since CallSiteCount is an estimate, it could exceed the original callee
1492 // count and has to be set to 0.
Easwaran Ramane5b8de22018-01-17 22:24:23 +00001493 if (CallCount.getValue() > CalleeCount.getCount())
1494 CalleeCount.setCount(0);
Easwaran Raman12585b02017-01-20 22:44:04 +00001495 else
Easwaran Ramane5b8de22018-01-17 22:24:23 +00001496 CalleeCount.setCount(CalleeCount.getCount() - CallCount.getValue());
1497 Callee->setEntryCount(CalleeCount);
Easwaran Raman12585b02017-01-20 22:44:04 +00001498}
Devang Patel35797402011-07-08 18:01:31 +00001499
Sanjay Patel0fdb4372015-03-10 19:42:57 +00001500/// This function inlines the called function into the basic block of the
1501/// caller. This returns false if it is not possible to inline this call.
1502/// The program is still in a well defined state if this occurs though.
Bill Wendlingce0c2292012-01-31 01:01:16 +00001503///
1504/// Note that this only does one level of inlining. For example, if the
1505/// instruction 'call B' is inlined, and 'B' calls 'C', then the call to 'C' now
1506/// exists in the instruction stream. Similarly this will inline a recursive
1507/// function by one level.
David Bolvanskyc0aa4b72018-08-05 14:53:08 +00001508llvm::InlineResult llvm::InlineFunction(CallSite CS, InlineFunctionInfo &IFI,
1509 AAResults *CalleeAAR,
1510 bool InsertLifetime,
1511 Function *ForwardVarArgsTo) {
Chris Lattner0cc265e2003-08-24 06:59:16 +00001512 Instruction *TheCall = CS.getInstruction();
Sanjay Patel288f0752017-02-15 15:22:18 +00001513 assert(TheCall->getParent() && TheCall->getFunction()
1514 && "Instruction not in function!");
Chris Lattner530d4bf2003-05-29 15:11:31 +00001515
Chris Lattner4ba01ec2010-04-22 23:07:58 +00001516 // If IFI has any state in it, zap it before we fill it in.
1517 IFI.reset();
Easwaran Raman12585b02017-01-20 22:44:04 +00001518
1519 Function *CalledFunc = CS.getCalledFunction();
Florian Hahn80788d82018-01-06 19:45:40 +00001520 if (!CalledFunc || // Can't inline external function or indirect
1521 CalledFunc->isDeclaration()) // call!
David Bolvanskyc0aa4b72018-08-05 14:53:08 +00001522 return "external or indirect";
Chris Lattner530d4bf2003-05-29 15:11:31 +00001523
Sanjoy Das2d161452015-11-18 06:23:38 +00001524 // The inliner does not know how to inline through calls with operand bundles
1525 // in general ...
1526 if (CS.hasOperandBundles()) {
David Majnemer3bb88c02015-12-15 21:27:27 +00001527 for (int i = 0, e = CS.getNumOperandBundles(); i != e; ++i) {
1528 uint32_t Tag = CS.getOperandBundleAt(i).getTagID();
1529 // ... but it knows how to inline through "deopt" operand bundles ...
1530 if (Tag == LLVMContext::OB_deopt)
1531 continue;
1532 // ... and "funclet" operand bundles.
1533 if (Tag == LLVMContext::OB_funclet)
1534 continue;
1535
David Bolvanskyc0aa4b72018-08-05 14:53:08 +00001536 return "unsupported operand bundle";
David Majnemer3bb88c02015-12-15 21:27:27 +00001537 }
Sanjoy Das2d161452015-11-18 06:23:38 +00001538 }
Sanjoy Das0a1bee82015-10-23 20:09:55 +00001539
Duncan Sandsaa31b922007-12-19 21:13:37 +00001540 // If the call to the callee cannot throw, set the 'nounwind' flag on any
1541 // calls that we inline.
1542 bool MarkNoUnwind = CS.doesNotThrow();
1543
Chris Lattner0cc265e2003-08-24 06:59:16 +00001544 BasicBlock *OrigBB = TheCall->getParent();
Chris Lattner530d4bf2003-05-29 15:11:31 +00001545 Function *Caller = OrigBB->getParent();
1546
Gordon Henriksenb969c592007-12-25 03:10:07 +00001547 // GC poses two hazards to inlining, which only occur when the callee has GC:
1548 // 1. If the caller has no GC, then the callee's GC must be propagated to the
1549 // caller.
1550 // 2. If the caller has a differing GC, it is invalid to inline.
Gordon Henriksend930f912008-08-17 18:44:35 +00001551 if (CalledFunc->hasGC()) {
1552 if (!Caller->hasGC())
1553 Caller->setGC(CalledFunc->getGC());
1554 else if (CalledFunc->getGC() != Caller->getGC())
David Bolvanskyc0aa4b72018-08-05 14:53:08 +00001555 return "incompatible GC";
Gordon Henriksenb969c592007-12-25 03:10:07 +00001556 }
Duncan Sands7c8fb1a2008-09-05 12:37:12 +00001557
Benjamin Kramer4d2b8712011-12-02 18:37:31 +00001558 // Get the personality function from the callee if it contains a landing pad.
David Majnemer7fddecc2015-06-17 20:52:32 +00001559 Constant *CalledPersonality =
David Majnemereba62792015-10-13 22:08:17 +00001560 CalledFunc->hasPersonalityFn()
1561 ? CalledFunc->getPersonalityFn()->stripPointerCasts()
1562 : nullptr;
Benjamin Kramer4d2b8712011-12-02 18:37:31 +00001563
Bill Wendling55421f02011-08-14 08:01:36 +00001564 // Find the personality function used by the landing pads of the caller. If it
1565 // exists, then check to see that it matches the personality function used in
1566 // the callee.
David Majnemer7fddecc2015-06-17 20:52:32 +00001567 Constant *CallerPersonality =
David Majnemereba62792015-10-13 22:08:17 +00001568 Caller->hasPersonalityFn()
1569 ? Caller->getPersonalityFn()->stripPointerCasts()
1570 : nullptr;
David Majnemer7fddecc2015-06-17 20:52:32 +00001571 if (CalledPersonality) {
1572 if (!CallerPersonality)
1573 Caller->setPersonalityFn(CalledPersonality);
1574 // If the personality functions match, then we can perform the
1575 // inlining. Otherwise, we can't inline.
1576 // TODO: This isn't 100% true. Some personality functions are proper
1577 // supersets of others and can be used in place of the other.
1578 else if (CalledPersonality != CallerPersonality)
David Bolvanskyc0aa4b72018-08-05 14:53:08 +00001579 return "incompatible personality";
Bill Wendlingce0c2292012-01-31 01:01:16 +00001580 }
Bill Wendling55421f02011-08-14 08:01:36 +00001581
David Majnemer8a1c45d2015-12-12 05:38:55 +00001582 // We need to figure out which funclet the callsite was in so that we may
1583 // properly nest the callee.
1584 Instruction *CallSiteEHPad = nullptr;
David Majnemer3bb88c02015-12-15 21:27:27 +00001585 if (CallerPersonality) {
1586 EHPersonality Personality = classifyEHPersonality(CallerPersonality);
Heejin Ahnb4be38f2018-05-17 20:52:03 +00001587 if (isScopedEHPersonality(Personality)) {
David Majnemer3bb88c02015-12-15 21:27:27 +00001588 Optional<OperandBundleUse> ParentFunclet =
1589 CS.getOperandBundle(LLVMContext::OB_funclet);
1590 if (ParentFunclet)
1591 CallSiteEHPad = cast<FuncletPadInst>(ParentFunclet->Inputs.front());
David Majnemer8a1c45d2015-12-12 05:38:55 +00001592
1593 // OK, the inlining site is legal. What about the target function?
1594
1595 if (CallSiteEHPad) {
1596 if (Personality == EHPersonality::MSVC_CXX) {
1597 // The MSVC personality cannot tolerate catches getting inlined into
1598 // cleanup funclets.
1599 if (isa<CleanupPadInst>(CallSiteEHPad)) {
1600 // Ok, the call site is within a cleanuppad. Let's check the callee
1601 // for catchpads.
1602 for (const BasicBlock &CalledBB : *CalledFunc) {
David Majnemer3bb88c02015-12-15 21:27:27 +00001603 if (isa<CatchSwitchInst>(CalledBB.getFirstNonPHI()))
David Bolvanskyc0aa4b72018-08-05 14:53:08 +00001604 return "catch in cleanup funclet";
David Majnemer8a1c45d2015-12-12 05:38:55 +00001605 }
1606 }
1607 } else if (isAsynchronousEHPersonality(Personality)) {
1608 // SEH is even less tolerant, there may not be any sort of exceptional
1609 // funclet in the callee.
1610 for (const BasicBlock &CalledBB : *CalledFunc) {
1611 if (CalledBB.isEHPad())
David Bolvanskyc0aa4b72018-08-05 14:53:08 +00001612 return "SEH in cleanup funclet";
David Majnemer8a1c45d2015-12-12 05:38:55 +00001613 }
1614 }
1615 }
1616 }
1617 }
1618
David Majnemer223538f2016-02-23 17:11:04 +00001619 // Determine if we are dealing with a call in an EHPad which does not unwind
1620 // to caller.
1621 bool EHPadForCallUnwindsLocally = false;
1622 if (CallSiteEHPad && CS.isCall()) {
1623 UnwindDestMemoTy FuncletUnwindMap;
1624 Value *CallSiteUnwindDestToken =
1625 getUnwindDestToken(CallSiteEHPad, FuncletUnwindMap);
1626
1627 EHPadForCallUnwindsLocally =
1628 CallSiteUnwindDestToken &&
1629 !isa<ConstantTokenNone>(CallSiteUnwindDestToken);
1630 }
1631
Chris Lattner9fc977e2004-02-04 01:41:09 +00001632 // Get an iterator to the last basic block in the function, which will have
1633 // the new function inlined after it.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001634 Function::iterator LastBlock = --Caller->end();
Chris Lattner9fc977e2004-02-04 01:41:09 +00001635
Chris Lattner18ef3fd2004-02-04 02:51:48 +00001636 // Make sure to capture all of the return instructions from the cloned
Chris Lattner530d4bf2003-05-29 15:11:31 +00001637 // function.
Chris Lattnerd84dbb32009-08-27 04:02:30 +00001638 SmallVector<ReturnInst*, 8> Returns;
Chris Lattner908d7952006-01-13 19:05:59 +00001639 ClonedCodeInfo InlinedFunctionInfo;
Dale Johannesen845e5822009-03-04 02:09:48 +00001640 Function::iterator FirstNewBlock;
Duncan Sandsaa31b922007-12-19 21:13:37 +00001641
Devang Patelb8f11de2010-06-23 23:55:51 +00001642 { // Scope to destroy VMap after cloning.
Rafael Espindola229e38f2010-10-13 01:36:30 +00001643 ValueToValueMapTy VMap;
Julien Lerouge957e91c2014-04-15 18:01:54 +00001644 // Keep a list of pair (dst, src) to emit byval initializations.
1645 SmallVector<std::pair<Value*, Value*>, 4> ByValInit;
Chris Lattnerbe853d72006-05-27 01:28:04 +00001646
Mehdi Amini46a43552015-03-04 18:43:29 +00001647 auto &DL = Caller->getParent()->getDataLayout();
1648
Chris Lattner908117b2008-01-11 06:09:30 +00001649 // Calculate the vector of arguments to pass into the function cloner, which
1650 // matches up the formal to the actual argument values.
Chris Lattner18ef3fd2004-02-04 02:51:48 +00001651 CallSite::arg_iterator AI = CS.arg_begin();
Chris Lattner908117b2008-01-11 06:09:30 +00001652 unsigned ArgNo = 0;
Reid Kleckner45707d42017-03-16 22:59:15 +00001653 for (Function::arg_iterator I = CalledFunc->arg_begin(),
Chris Lattner908117b2008-01-11 06:09:30 +00001654 E = CalledFunc->arg_end(); I != E; ++I, ++AI, ++ArgNo) {
1655 Value *ActualArg = *AI;
Duncan Sands7c8fb1a2008-09-05 12:37:12 +00001656
Duncan Sands053c9872008-01-27 18:12:58 +00001657 // When byval arguments actually inlined, we need to make the copy implied
1658 // by them explicit. However, we don't do this if the callee is readonly
1659 // or readnone, because the copy would be unneeded: the callee doesn't
1660 // modify the struct.
Nick Lewycky612d70b2011-11-20 19:09:04 +00001661 if (CS.isByValArgument(ArgNo)) {
David Majnemer120f4a02013-11-03 12:22:13 +00001662 ActualArg = HandleByValArgument(ActualArg, TheCall, CalledFunc, IFI,
Reid Kleckner859f8b52017-04-28 20:34:27 +00001663 CalledFunc->getParamAlignment(ArgNo));
Reid Kleckner9b2cc642014-04-21 20:48:47 +00001664 if (ActualArg != *AI)
Julien Lerouge957e91c2014-04-15 18:01:54 +00001665 ByValInit.push_back(std::make_pair(ActualArg, (Value*) *AI));
Chris Lattner908117b2008-01-11 06:09:30 +00001666 }
Duncan Sands7c8fb1a2008-09-05 12:37:12 +00001667
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001668 VMap[&*I] = ActualArg;
Chris Lattner908117b2008-01-11 06:09:30 +00001669 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001670
Hans Wennborg2d5841f2017-02-27 22:33:02 +00001671 // Add alignment assumptions if necessary. We do this before the inlined
1672 // instructions are actually cloned into the caller so that we can easily
1673 // check what will be known at the start of the inlined code.
1674 AddAlignmentAssumptions(CS, IFI);
Hal Finkel68dc3c72014-10-15 23:44:41 +00001675
Chris Lattnerbe853d72006-05-27 01:28:04 +00001676 // We want the inliner to prune the code as it copies. We would LOVE to
1677 // have no dead or constant instructions leftover after inlining occurs
1678 // (which can happen, e.g., because an argument was constant), but we'll be
1679 // happy with whatever the cloner can do.
Mehdi Amini46a43552015-03-04 18:43:29 +00001680 CloneAndPruneFunctionInto(Caller, CalledFunc, VMap,
Dan Gohmanca26f792010-08-26 15:41:53 +00001681 /*ModuleLevelChanges=*/false, Returns, ".i",
Easwaran Ramanb1bd3982016-03-08 00:36:35 +00001682 &InlinedFunctionInfo, TheCall);
Chris Lattner5de3b8b2006-07-12 18:29:36 +00001683 // Remember the first block that is newly cloned over.
1684 FirstNewBlock = LastBlock; ++FirstNewBlock;
Duncan Sands7c8fb1a2008-09-05 12:37:12 +00001685
Dehao Chene5930492017-03-20 16:40:44 +00001686 if (IFI.CallerBFI != nullptr && IFI.CalleeBFI != nullptr)
Easwaran Raman12585b02017-01-20 22:44:04 +00001687 // Update the BFI of blocks cloned into the caller.
1688 updateCallerBFI(OrigBB, VMap, IFI.CallerBFI, IFI.CalleeBFI,
1689 CalledFunc->front());
Dehao Chene5930492017-03-20 16:40:44 +00001690
Easwaran Ramanf5f91602017-05-09 23:21:10 +00001691 updateCallProfile(CalledFunc, VMap, CalledFunc->getEntryCount(), TheCall,
Teresa Johnson525dcb62017-05-22 20:28:18 +00001692 IFI.PSI, IFI.CallerBFI);
Dehao Chene5930492017-03-20 16:40:44 +00001693 // Update the profile count of callee.
Easwaran Ramanf5f91602017-05-09 23:21:10 +00001694 updateCalleeCount(IFI.CallerBFI, OrigBB, TheCall, CalledFunc, IFI.PSI);
Easwaran Raman12585b02017-01-20 22:44:04 +00001695
Julien Lerouge957e91c2014-04-15 18:01:54 +00001696 // Inject byval arguments initialization.
1697 for (std::pair<Value*, Value*> &Init : ByValInit)
1698 HandleByValArgumentInit(Init.first, Init.second, Caller->getParent(),
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001699 &*FirstNewBlock, IFI);
Julien Lerouge957e91c2014-04-15 18:01:54 +00001700
David Majnemer3bb88c02015-12-15 21:27:27 +00001701 Optional<OperandBundleUse> ParentDeopt =
1702 CS.getOperandBundle(LLVMContext::OB_deopt);
1703 if (ParentDeopt) {
Sanjoy Das2d161452015-11-18 06:23:38 +00001704 SmallVector<OperandBundleDef, 2> OpDefs;
1705
1706 for (auto &VH : InlinedFunctionInfo.OperandBundleCallSites) {
Sanjoy Dasab0626e2015-12-19 22:40:28 +00001707 Instruction *I = dyn_cast_or_null<Instruction>(VH);
1708 if (!I) continue; // instruction was DCE'd or RAUW'ed to undef
Sanjoy Das2d161452015-11-18 06:23:38 +00001709
1710 OpDefs.clear();
1711
1712 CallSite ICS(I);
1713 OpDefs.reserve(ICS.getNumOperandBundles());
1714
1715 for (unsigned i = 0, e = ICS.getNumOperandBundles(); i < e; ++i) {
1716 auto ChildOB = ICS.getOperandBundleAt(i);
1717 if (ChildOB.getTagID() != LLVMContext::OB_deopt) {
1718 // If the inlined call has other operand bundles, let them be
1719 OpDefs.emplace_back(ChildOB);
1720 continue;
1721 }
1722
1723 // It may be useful to separate this logic (of handling operand
1724 // bundles) out to a separate "policy" component if this gets crowded.
1725 // Prepend the parent's deoptimization continuation to the newly
1726 // inlined call's deoptimization continuation.
1727 std::vector<Value *> MergedDeoptArgs;
David Majnemer3bb88c02015-12-15 21:27:27 +00001728 MergedDeoptArgs.reserve(ParentDeopt->Inputs.size() +
Sanjoy Das2d161452015-11-18 06:23:38 +00001729 ChildOB.Inputs.size());
1730
1731 MergedDeoptArgs.insert(MergedDeoptArgs.end(),
David Majnemer3bb88c02015-12-15 21:27:27 +00001732 ParentDeopt->Inputs.begin(),
1733 ParentDeopt->Inputs.end());
Sanjoy Das2d161452015-11-18 06:23:38 +00001734 MergedDeoptArgs.insert(MergedDeoptArgs.end(), ChildOB.Inputs.begin(),
1735 ChildOB.Inputs.end());
1736
Sanjoy Das8da1f952015-12-08 03:50:32 +00001737 OpDefs.emplace_back("deopt", std::move(MergedDeoptArgs));
Sanjoy Das2d161452015-11-18 06:23:38 +00001738 }
1739
1740 Instruction *NewI = nullptr;
1741 if (isa<CallInst>(I))
1742 NewI = CallInst::Create(cast<CallInst>(I), OpDefs, I);
1743 else
1744 NewI = InvokeInst::Create(cast<InvokeInst>(I), OpDefs, I);
1745
1746 // Note: the RAUW does the appropriate fixup in VMap, so we need to do
1747 // this even if the call returns void.
1748 I->replaceAllUsesWith(NewI);
1749
1750 VH = nullptr;
1751 I->eraseFromParent();
1752 }
1753 }
1754
Chris Lattner5de3b8b2006-07-12 18:29:36 +00001755 // Update the callgraph if requested.
Chandler Carruth0ee8bb12016-12-27 01:24:50 +00001756 if (IFI.CG)
Devang Patelb8f11de2010-06-23 23:55:51 +00001757 UpdateCallGraphAfterInlining(CS, FirstNewBlock, VMap, IFI);
Devang Patel35797402011-07-08 18:01:31 +00001758
Andrea Di Biagio32d5aed2016-12-07 10:37:26 +00001759 // For 'nodebug' functions, the associated DISubprogram is always null.
1760 // Conservatively avoid propagating the callsite debug location to
1761 // instructions inlined from a function whose DISubprogram is not null.
Adrian Prantld4056502017-03-07 17:28:57 +00001762 fixupLineNumbers(Caller, FirstNewBlock, TheCall,
1763 CalledFunc->getSubprogram() != nullptr);
Hal Finkel94146652014-07-24 14:25:39 +00001764
1765 // Clone existing noalias metadata if necessary.
1766 CloneAliasScopeMetadata(CS, VMap);
Hal Finkelff0bcb62014-07-25 15:50:08 +00001767
1768 // Add noalias metadata if necessary.
Chandler Carruth7b560d42015-09-09 17:55:00 +00001769 AddAliasScopeMetadata(CS, VMap, DL, CalleeAAR);
Hal Finkel74c2f352014-09-07 12:44:26 +00001770
Hal Finkel50316d92016-04-28 23:00:04 +00001771 // Propagate llvm.mem.parallel_loop_access if necessary.
1772 PropagateParallelLoopAccessMetadata(CS, VMap);
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001773
1774 // Register any cloned assumptions.
1775 if (IFI.GetAssumptionCache)
1776 for (BasicBlock &NewBlock :
1777 make_range(FirstNewBlock->getIterator(), Caller->end()))
1778 for (Instruction &I : NewBlock) {
1779 if (auto *II = dyn_cast<IntrinsicInst>(&I))
1780 if (II->getIntrinsicID() == Intrinsic::assume)
1781 (*IFI.GetAssumptionCache)(*Caller).registerAssumption(II);
1782 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001783 }
Duncan Sands7c8fb1a2008-09-05 12:37:12 +00001784
Chris Lattner530d4bf2003-05-29 15:11:31 +00001785 // If there are any alloca instructions in the block that used to be the entry
1786 // block for the callee, move them to the entry block of the caller. First
1787 // calculate which instruction they should be inserted before. We insert the
1788 // instructions at the end of the current alloca list.
Chris Lattner257492c2006-01-13 18:16:48 +00001789 {
Chris Lattner0cc265e2003-08-24 06:59:16 +00001790 BasicBlock::iterator InsertPoint = Caller->begin()->begin();
Chris Lattner18ef3fd2004-02-04 02:51:48 +00001791 for (BasicBlock::iterator I = FirstNewBlock->begin(),
Chris Lattner5eef6ad2009-08-27 03:51:50 +00001792 E = FirstNewBlock->end(); I != E; ) {
1793 AllocaInst *AI = dyn_cast<AllocaInst>(I++);
Craig Topperf40110f2014-04-25 05:29:35 +00001794 if (!AI) continue;
Fangrui Songf78650a2018-07-30 19:41:25 +00001795
Chris Lattner5eef6ad2009-08-27 03:51:50 +00001796 // If the alloca is now dead, remove it. This often occurs due to code
1797 // specialization.
1798 if (AI->use_empty()) {
1799 AI->eraseFromParent();
1800 continue;
Chris Lattner6ef6d062006-09-13 19:23:57 +00001801 }
Chris Lattner5eef6ad2009-08-27 03:51:50 +00001802
Reid Kleckner6ee00a22016-08-12 22:23:04 +00001803 if (!allocaWouldBeStaticInEntry(AI))
Chris Lattner5eef6ad2009-08-27 03:51:50 +00001804 continue;
Fangrui Songf78650a2018-07-30 19:41:25 +00001805
Chris Lattnercd3af962010-12-06 07:43:04 +00001806 // Keep track of the static allocas that we inline into the caller.
Chris Lattner4ba01ec2010-04-22 23:07:58 +00001807 IFI.StaticAllocas.push_back(AI);
Fangrui Songf78650a2018-07-30 19:41:25 +00001808
Chris Lattner5eef6ad2009-08-27 03:51:50 +00001809 // Scan for the block of allocas that we can move over, and move them
1810 // all at once.
1811 while (isa<AllocaInst>(I) &&
Reid Kleckner6ee00a22016-08-12 22:23:04 +00001812 allocaWouldBeStaticInEntry(cast<AllocaInst>(I))) {
Chris Lattner4ba01ec2010-04-22 23:07:58 +00001813 IFI.StaticAllocas.push_back(cast<AllocaInst>(I));
Chris Lattner5eef6ad2009-08-27 03:51:50 +00001814 ++I;
Chris Lattnerb1cba3f2009-08-27 04:20:52 +00001815 }
Chris Lattner5eef6ad2009-08-27 03:51:50 +00001816
1817 // Transfer all of the allocas over in a block. Using splice means
1818 // that the instructions aren't removed from the symbol table, then
1819 // reinserted.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001820 Caller->getEntryBlock().getInstList().splice(
1821 InsertPoint, FirstNewBlock->getInstList(), AI->getIterator(), I);
Chris Lattner5eef6ad2009-08-27 03:51:50 +00001822 }
Adrian Prantl4d365252015-01-30 01:55:25 +00001823 // Move any dbg.declares describing the allocas into the entry basic block.
Adrian Prantl3e2659e2015-01-30 19:37:48 +00001824 DIBuilder DIB(*Caller->getParent());
Adrian Prantl133e1022015-01-30 19:42:59 +00001825 for (auto &AI : IFI.StaticAllocas)
Adrian Prantld1317012017-12-08 21:58:18 +00001826 replaceDbgDeclareForAlloca(AI, AI, DIB, DIExpression::NoDeref, 0,
1827 DIExpression::NoDeref);
Chris Lattner0cc265e2003-08-24 06:59:16 +00001828 }
Chris Lattner530d4bf2003-05-29 15:11:31 +00001829
Florian Hahn0e9dec62017-11-13 10:35:52 +00001830 SmallVector<Value*,4> VarArgsToForward;
Florian Hahnde10e6e2018-01-06 20:46:00 +00001831 SmallVector<AttributeSet, 4> VarArgsAttrs;
Florian Hahn0e9dec62017-11-13 10:35:52 +00001832 for (unsigned i = CalledFunc->getFunctionType()->getNumParams();
Florian Hahnde10e6e2018-01-06 20:46:00 +00001833 i < CS.getNumArgOperands(); i++) {
Florian Hahn0e9dec62017-11-13 10:35:52 +00001834 VarArgsToForward.push_back(CS.getArgOperand(i));
Florian Hahnde10e6e2018-01-06 20:46:00 +00001835 VarArgsAttrs.push_back(CS.getAttributes().getParamAttributes(i));
1836 }
Florian Hahn0e9dec62017-11-13 10:35:52 +00001837
Sanjoy Dasb51325d2016-03-11 19:08:34 +00001838 bool InlinedMustTailCalls = false, InlinedDeoptimizeCalls = false;
Reid Klecknerf0915aa2014-05-15 20:11:28 +00001839 if (InlinedFunctionInfo.ContainsCalls) {
Reid Kleckner6af21242014-05-15 20:39:42 +00001840 CallInst::TailCallKind CallSiteTailKind = CallInst::TCK_None;
1841 if (CallInst *CI = dyn_cast<CallInst>(TheCall))
1842 CallSiteTailKind = CI->getTailCallKind();
1843
Reid Klecknera9e99182018-04-02 21:23:16 +00001844 // For inlining purposes, the "notail" marker is the same as no marker.
1845 if (CallSiteTailKind == CallInst::TCK_NoTail)
1846 CallSiteTailKind = CallInst::TCK_None;
1847
Reid Klecknerf0915aa2014-05-15 20:11:28 +00001848 for (Function::iterator BB = FirstNewBlock, E = Caller->end(); BB != E;
1849 ++BB) {
Florian Hahn0e9dec62017-11-13 10:35:52 +00001850 for (auto II = BB->begin(); II != BB->end();) {
1851 Instruction &I = *II++;
Reid Klecknerf0915aa2014-05-15 20:11:28 +00001852 CallInst *CI = dyn_cast<CallInst>(&I);
1853 if (!CI)
1854 continue;
1855
Florian Hahn80788d82018-01-06 19:45:40 +00001856 // Forward varargs from inlined call site to calls to the
1857 // ForwardVarArgsTo function, if requested, and to musttail calls.
1858 if (!VarArgsToForward.empty() &&
1859 ((ForwardVarArgsTo &&
1860 CI->getCalledFunction() == ForwardVarArgsTo) ||
1861 CI->isMustTailCall())) {
Florian Hahnde10e6e2018-01-06 20:46:00 +00001862 // Collect attributes for non-vararg parameters.
1863 AttributeList Attrs = CI->getAttributes();
1864 SmallVector<AttributeSet, 8> ArgAttrs;
Florian Hahn8f804fc2018-02-04 18:27:47 +00001865 if (!Attrs.isEmpty() || !VarArgsAttrs.empty()) {
Florian Hahnde10e6e2018-01-06 20:46:00 +00001866 for (unsigned ArgNo = 0;
1867 ArgNo < CI->getFunctionType()->getNumParams(); ++ArgNo)
1868 ArgAttrs.push_back(Attrs.getParamAttributes(ArgNo));
1869 }
1870
1871 // Add VarArg attributes.
1872 ArgAttrs.append(VarArgsAttrs.begin(), VarArgsAttrs.end());
1873 Attrs = AttributeList::get(CI->getContext(), Attrs.getFnAttributes(),
1874 Attrs.getRetAttributes(), ArgAttrs);
1875 // Add VarArgs to existing parameters.
Florian Hahn80788d82018-01-06 19:45:40 +00001876 SmallVector<Value *, 6> Params(CI->arg_operands());
1877 Params.append(VarArgsToForward.begin(), VarArgsToForward.end());
Florian Hahnde10e6e2018-01-06 20:46:00 +00001878 CallInst *NewCI =
Florian Hahn80788d82018-01-06 19:45:40 +00001879 CallInst::Create(CI->getCalledFunction() ? CI->getCalledFunction()
1880 : CI->getCalledValue(),
1881 Params, "", CI);
Florian Hahnde10e6e2018-01-06 20:46:00 +00001882 NewCI->setDebugLoc(CI->getDebugLoc());
1883 NewCI->setAttributes(Attrs);
Florian Hahna82eef22018-01-06 20:56:27 +00001884 NewCI->setCallingConv(CI->getCallingConv());
Florian Hahnde10e6e2018-01-06 20:46:00 +00001885 CI->replaceAllUsesWith(NewCI);
Florian Hahn80788d82018-01-06 19:45:40 +00001886 CI->eraseFromParent();
Florian Hahnde10e6e2018-01-06 20:46:00 +00001887 CI = NewCI;
Florian Hahn80788d82018-01-06 19:45:40 +00001888 }
1889
Sanjoy Dasb51325d2016-03-11 19:08:34 +00001890 if (Function *F = CI->getCalledFunction())
1891 InlinedDeoptimizeCalls |=
1892 F->getIntrinsicID() == Intrinsic::experimental_deoptimize;
1893
Reid Klecknerf0915aa2014-05-15 20:11:28 +00001894 // We need to reduce the strength of any inlined tail calls. For
1895 // musttail, we have to avoid introducing potential unbounded stack
1896 // growth. For example, if functions 'f' and 'g' are mutually recursive
1897 // with musttail, we can inline 'g' into 'f' so long as we preserve
1898 // musttail on the cloned call to 'f'. If either the inlined call site
1899 // or the cloned call site is *not* musttail, the program already has
1900 // one frame of stack growth, so it's safe to remove musttail. Here is
1901 // a table of example transformations:
1902 //
1903 // f -> musttail g -> musttail f ==> f -> musttail f
1904 // f -> musttail g -> tail f ==> f -> tail f
1905 // f -> g -> musttail f ==> f -> f
1906 // f -> g -> tail f ==> f -> f
Reid Klecknera9e99182018-04-02 21:23:16 +00001907 //
1908 // Inlined notail calls should remain notail calls.
Reid Klecknerf0915aa2014-05-15 20:11:28 +00001909 CallInst::TailCallKind ChildTCK = CI->getTailCallKind();
Arnold Schwaighoferd9e71092017-11-27 19:03:40 +00001910 if (ChildTCK != CallInst::TCK_NoTail)
1911 ChildTCK = std::min(CallSiteTailKind, ChildTCK);
Reid Klecknerdd3f3ed2014-11-04 02:02:14 +00001912 CI->setTailCallKind(ChildTCK);
Reid Klecknerf0915aa2014-05-15 20:11:28 +00001913 InlinedMustTailCalls |= CI->isMustTailCall();
1914
1915 // Calls inlined through a 'nounwind' call site should be marked
1916 // 'nounwind'.
1917 if (MarkNoUnwind)
1918 CI->setDoesNotThrow();
1919 }
1920 }
1921 }
1922
Nick Lewyckya68ec832011-05-22 05:22:10 +00001923 // Leave lifetime markers for the static alloca's, scoping them to the
1924 // function we just inlined.
Chad Rosier07d37bc2012-02-25 02:56:01 +00001925 if (InsertLifetime && !IFI.StaticAllocas.empty()) {
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001926 IRBuilder<> builder(&FirstNewBlock->front());
Nick Lewyckya68ec832011-05-22 05:22:10 +00001927 for (unsigned ai = 0, ae = IFI.StaticAllocas.size(); ai != ae; ++ai) {
1928 AllocaInst *AI = IFI.StaticAllocas[ai];
Arnold Schwaighoferc9277f42016-09-09 22:40:27 +00001929 // Don't mark swifterror allocas. They can't have bitcast uses.
1930 if (AI->isSwiftError())
1931 continue;
Nick Lewyckya68ec832011-05-22 05:22:10 +00001932
1933 // If the alloca is already scoped to something smaller than the whole
1934 // function then there's no need to add redundant, less accurate markers.
1935 if (hasLifetimeMarkers(AI))
1936 continue;
1937
Alexey Samsonovcfd662f2012-11-13 07:15:32 +00001938 // Try to determine the size of the allocation.
Craig Topperf40110f2014-04-25 05:29:35 +00001939 ConstantInt *AllocaSize = nullptr;
Alexey Samsonovcfd662f2012-11-13 07:15:32 +00001940 if (ConstantInt *AIArraySize =
1941 dyn_cast<ConstantInt>(AI->getArraySize())) {
Mehdi Amini46a43552015-03-04 18:43:29 +00001942 auto &DL = Caller->getParent()->getDataLayout();
1943 Type *AllocaType = AI->getAllocatedType();
1944 uint64_t AllocaTypeSize = DL.getTypeAllocSize(AllocaType);
1945 uint64_t AllocaArraySize = AIArraySize->getLimitedValue();
Akira Hatanaka2cc2b632015-04-20 16:11:05 +00001946
1947 // Don't add markers for zero-sized allocas.
1948 if (AllocaArraySize == 0)
1949 continue;
1950
Mehdi Amini46a43552015-03-04 18:43:29 +00001951 // Check that array size doesn't saturate uint64_t and doesn't
1952 // overflow when it's multiplied by type size.
Eugene Zelenko6cadde72017-10-17 21:27:42 +00001953 if (AllocaArraySize != std::numeric_limits<uint64_t>::max() &&
1954 std::numeric_limits<uint64_t>::max() / AllocaArraySize >=
1955 AllocaTypeSize) {
Mehdi Amini46a43552015-03-04 18:43:29 +00001956 AllocaSize = ConstantInt::get(Type::getInt64Ty(AI->getContext()),
1957 AllocaArraySize * AllocaTypeSize);
Alexey Samsonovcfd662f2012-11-13 07:15:32 +00001958 }
1959 }
1960
1961 builder.CreateLifetimeStart(AI, AllocaSize);
Reid Kleckner900d46f2014-05-15 21:10:46 +00001962 for (ReturnInst *RI : Returns) {
Sanjoy Das18b92962016-04-01 02:51:26 +00001963 // Don't insert llvm.lifetime.end calls between a musttail or deoptimize
1964 // call and a return. The return kills all local allocas.
Reid Klecknere31acf22014-08-12 00:05:15 +00001965 if (InlinedMustTailCalls &&
1966 RI->getParent()->getTerminatingMustTailCall())
Reid Kleckner900d46f2014-05-15 21:10:46 +00001967 continue;
Sanjoy Das18b92962016-04-01 02:51:26 +00001968 if (InlinedDeoptimizeCalls &&
1969 RI->getParent()->getTerminatingDeoptimizeCall())
1970 continue;
Reid Klecknerf0915aa2014-05-15 20:11:28 +00001971 IRBuilder<>(RI).CreateLifetimeEnd(AI, AllocaSize);
Reid Kleckner900d46f2014-05-15 21:10:46 +00001972 }
Nick Lewyckya68ec832011-05-22 05:22:10 +00001973 }
1974 }
1975
Chris Lattner2be06072006-01-13 19:34:14 +00001976 // If the inlined code contained dynamic alloca instructions, wrap the inlined
1977 // code with llvm.stacksave/llvm.stackrestore intrinsics.
1978 if (InlinedFunctionInfo.ContainsDynamicAllocas) {
1979 Module *M = Caller->getParent();
Chris Lattner2be06072006-01-13 19:34:14 +00001980 // Get the two intrinsics we care about.
Chris Lattner88b36f12009-10-17 05:39:39 +00001981 Function *StackSave = Intrinsic::getDeclaration(M, Intrinsic::stacksave);
1982 Function *StackRestore=Intrinsic::getDeclaration(M,Intrinsic::stackrestore);
Chris Lattner5de3b8b2006-07-12 18:29:36 +00001983
Chris Lattner2be06072006-01-13 19:34:14 +00001984 // Insert the llvm.stacksave.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001985 CallInst *SavedPtr = IRBuilder<>(&*FirstNewBlock, FirstNewBlock->begin())
David Blaikieff6409d2015-05-18 22:13:54 +00001986 .CreateCall(StackSave, {}, "savedstack");
Duncan Sands7c8fb1a2008-09-05 12:37:12 +00001987
Chris Lattner2be06072006-01-13 19:34:14 +00001988 // Insert a call to llvm.stackrestore before any return instructions in the
1989 // inlined function.
Reid Kleckner900d46f2014-05-15 21:10:46 +00001990 for (ReturnInst *RI : Returns) {
Sanjoy Dasf83ab6d2016-04-01 02:51:30 +00001991 // Don't insert llvm.stackrestore calls between a musttail or deoptimize
1992 // call and a return. The return will restore the stack pointer.
Reid Klecknere31acf22014-08-12 00:05:15 +00001993 if (InlinedMustTailCalls && RI->getParent()->getTerminatingMustTailCall())
Reid Kleckner900d46f2014-05-15 21:10:46 +00001994 continue;
Sanjoy Dasf83ab6d2016-04-01 02:51:30 +00001995 if (InlinedDeoptimizeCalls && RI->getParent()->getTerminatingDeoptimizeCall())
1996 continue;
Reid Klecknerf0915aa2014-05-15 20:11:28 +00001997 IRBuilder<>(RI).CreateCall(StackRestore, SavedPtr);
Reid Kleckner900d46f2014-05-15 21:10:46 +00001998 }
Chris Lattner9f3dced2005-05-06 06:47:52 +00001999 }
2000
Joseph Tremouletb41632b2016-01-20 02:15:15 +00002001 // If we are inlining for an invoke instruction, we must make sure to rewrite
2002 // any call instructions into invoke instructions. This is sensitive to which
2003 // funclet pads were top-level in the inlinee, so must be done before
2004 // rewriting the "parent pad" links.
2005 if (auto *II = dyn_cast<InvokeInst>(TheCall)) {
2006 BasicBlock *UnwindDest = II->getUnwindDest();
2007 Instruction *FirstNonPHI = UnwindDest->getFirstNonPHI();
2008 if (isa<LandingPadInst>(FirstNonPHI)) {
2009 HandleInlinedLandingPad(II, &*FirstNewBlock, InlinedFunctionInfo);
2010 } else {
2011 HandleInlinedEHPad(II, &*FirstNewBlock, InlinedFunctionInfo);
2012 }
2013 }
2014
David Majnemer3bb88c02015-12-15 21:27:27 +00002015 // Update the lexical scopes of the new funclets and callsites.
2016 // Anything that had 'none' as its parent is now nested inside the callsite's
2017 // EHPad.
2018
David Majnemer8a1c45d2015-12-12 05:38:55 +00002019 if (CallSiteEHPad) {
2020 for (Function::iterator BB = FirstNewBlock->getIterator(),
2021 E = Caller->end();
2022 BB != E; ++BB) {
David Majnemer3bb88c02015-12-15 21:27:27 +00002023 // Add bundle operands to any top-level call sites.
2024 SmallVector<OperandBundleDef, 1> OpBundles;
2025 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E;) {
2026 Instruction *I = &*BBI++;
2027 CallSite CS(I);
2028 if (!CS)
2029 continue;
2030
2031 // Skip call sites which are nounwind intrinsics.
2032 auto *CalledFn =
2033 dyn_cast<Function>(CS.getCalledValue()->stripPointerCasts());
2034 if (CalledFn && CalledFn->isIntrinsic() && CS.doesNotThrow())
2035 continue;
2036
2037 // Skip call sites which already have a "funclet" bundle.
2038 if (CS.getOperandBundle(LLVMContext::OB_funclet))
2039 continue;
2040
2041 CS.getOperandBundlesAsDefs(OpBundles);
2042 OpBundles.emplace_back("funclet", CallSiteEHPad);
2043
2044 Instruction *NewInst;
2045 if (CS.isCall())
2046 NewInst = CallInst::Create(cast<CallInst>(I), OpBundles, I);
2047 else
2048 NewInst = InvokeInst::Create(cast<InvokeInst>(I), OpBundles, I);
David Majnemer3bb88c02015-12-15 21:27:27 +00002049 NewInst->takeName(I);
2050 I->replaceAllUsesWith(NewInst);
2051 I->eraseFromParent();
2052
2053 OpBundles.clear();
2054 }
2055
David Majnemer223538f2016-02-23 17:11:04 +00002056 // It is problematic if the inlinee has a cleanupret which unwinds to
2057 // caller and we inline it into a call site which doesn't unwind but into
2058 // an EH pad that does. Such an edge must be dynamically unreachable.
2059 // As such, we replace the cleanupret with unreachable.
2060 if (auto *CleanupRet = dyn_cast<CleanupReturnInst>(BB->getTerminator()))
2061 if (CleanupRet->unwindsToCaller() && EHPadForCallUnwindsLocally)
David Majnemere14e7bc2016-06-25 08:19:55 +00002062 changeToUnreachable(CleanupRet, /*UseLLVMTrap=*/false);
David Majnemer223538f2016-02-23 17:11:04 +00002063
David Majnemer8a1c45d2015-12-12 05:38:55 +00002064 Instruction *I = BB->getFirstNonPHI();
2065 if (!I->isEHPad())
2066 continue;
2067
David Majnemerbbfc7212015-12-14 18:34:23 +00002068 if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(I)) {
David Majnemer8a1c45d2015-12-12 05:38:55 +00002069 if (isa<ConstantTokenNone>(CatchSwitch->getParentPad()))
2070 CatchSwitch->setParentPad(CallSiteEHPad);
2071 } else {
2072 auto *FPI = cast<FuncletPadInst>(I);
2073 if (isa<ConstantTokenNone>(FPI->getParentPad()))
2074 FPI->setParentPad(CallSiteEHPad);
2075 }
2076 }
2077 }
2078
Sanjoy Dasb51325d2016-03-11 19:08:34 +00002079 if (InlinedDeoptimizeCalls) {
2080 // We need to at least remove the deoptimizing returns from the Return set,
2081 // so that the control flow from those returns does not get merged into the
2082 // caller (but terminate it instead). If the caller's return type does not
2083 // match the callee's return type, we also need to change the return type of
2084 // the intrinsic.
2085 if (Caller->getReturnType() == TheCall->getType()) {
Eugene Zelenko6cadde72017-10-17 21:27:42 +00002086 auto NewEnd = llvm::remove_if(Returns, [](ReturnInst *RI) {
Sanjoy Dasb51325d2016-03-11 19:08:34 +00002087 return RI->getParent()->getTerminatingDeoptimizeCall() != nullptr;
2088 });
2089 Returns.erase(NewEnd, Returns.end());
2090 } else {
2091 SmallVector<ReturnInst *, 8> NormalReturns;
2092 Function *NewDeoptIntrinsic = Intrinsic::getDeclaration(
2093 Caller->getParent(), Intrinsic::experimental_deoptimize,
2094 {Caller->getReturnType()});
2095
2096 for (ReturnInst *RI : Returns) {
2097 CallInst *DeoptCall = RI->getParent()->getTerminatingDeoptimizeCall();
2098 if (!DeoptCall) {
2099 NormalReturns.push_back(RI);
2100 continue;
2101 }
2102
Sanjoy Dase0aa4142016-05-12 01:17:38 +00002103 // The calling convention on the deoptimize call itself may be bogus,
2104 // since the code we're inlining may have undefined behavior (and may
2105 // never actually execute at runtime); but all
2106 // @llvm.experimental.deoptimize declarations have to have the same
2107 // calling convention in a well-formed module.
2108 auto CallingConv = DeoptCall->getCalledFunction()->getCallingConv();
2109 NewDeoptIntrinsic->setCallingConv(CallingConv);
Sanjoy Dasb51325d2016-03-11 19:08:34 +00002110 auto *CurBB = RI->getParent();
2111 RI->eraseFromParent();
2112
2113 SmallVector<Value *, 4> CallArgs(DeoptCall->arg_begin(),
2114 DeoptCall->arg_end());
2115
2116 SmallVector<OperandBundleDef, 1> OpBundles;
2117 DeoptCall->getOperandBundlesAsDefs(OpBundles);
2118 DeoptCall->eraseFromParent();
2119 assert(!OpBundles.empty() &&
2120 "Expected at least the deopt operand bundle");
2121
2122 IRBuilder<> Builder(CurBB);
Sanjoy Dasdd77e1e2016-04-09 00:22:59 +00002123 CallInst *NewDeoptCall =
Sanjoy Dasb51325d2016-03-11 19:08:34 +00002124 Builder.CreateCall(NewDeoptIntrinsic, CallArgs, OpBundles);
Sanjoy Dasdd77e1e2016-04-09 00:22:59 +00002125 NewDeoptCall->setCallingConv(CallingConv);
Sanjoy Dasb51325d2016-03-11 19:08:34 +00002126 if (NewDeoptCall->getType()->isVoidTy())
2127 Builder.CreateRetVoid();
2128 else
2129 Builder.CreateRet(NewDeoptCall);
2130 }
2131
2132 // Leave behind the normal returns so we can merge control flow.
2133 std::swap(Returns, NormalReturns);
2134 }
2135 }
2136
Reid Klecknerf0915aa2014-05-15 20:11:28 +00002137 // Handle any inlined musttail call sites. In order for a new call site to be
2138 // musttail, the source of the clone and the inlined call site must have been
2139 // musttail. Therefore it's safe to return without merging control into the
2140 // phi below.
2141 if (InlinedMustTailCalls) {
2142 // Check if we need to bitcast the result of any musttail calls.
2143 Type *NewRetTy = Caller->getReturnType();
2144 bool NeedBitCast = !TheCall->use_empty() && TheCall->getType() != NewRetTy;
2145
2146 // Handle the returns preceded by musttail calls separately.
2147 SmallVector<ReturnInst *, 8> NormalReturns;
2148 for (ReturnInst *RI : Returns) {
Reid Klecknere31acf22014-08-12 00:05:15 +00002149 CallInst *ReturnedMustTail =
2150 RI->getParent()->getTerminatingMustTailCall();
Reid Klecknerf0915aa2014-05-15 20:11:28 +00002151 if (!ReturnedMustTail) {
2152 NormalReturns.push_back(RI);
2153 continue;
2154 }
2155 if (!NeedBitCast)
2156 continue;
2157
2158 // Delete the old return and any preceding bitcast.
2159 BasicBlock *CurBB = RI->getParent();
2160 auto *OldCast = dyn_cast_or_null<BitCastInst>(RI->getReturnValue());
2161 RI->eraseFromParent();
2162 if (OldCast)
2163 OldCast->eraseFromParent();
2164
2165 // Insert a new bitcast and return with the right type.
2166 IRBuilder<> Builder(CurBB);
2167 Builder.CreateRet(Builder.CreateBitCast(ReturnedMustTail, NewRetTy));
2168 }
2169
2170 // Leave behind the normal returns so we can merge control flow.
2171 std::swap(Returns, NormalReturns);
2172 }
2173
Chandler Carruth0ee8bb12016-12-27 01:24:50 +00002174 // Now that all of the transforms on the inlined code have taken place but
2175 // before we splice the inlined code into the CFG and lose track of which
2176 // blocks were actually inlined, collect the call sites. We only do this if
2177 // call graph updates weren't requested, as those provide value handle based
2178 // tracking of inlined call sites instead.
2179 if (InlinedFunctionInfo.ContainsCalls && !IFI.CG) {
2180 // Otherwise just collect the raw call sites that were inlined.
2181 for (BasicBlock &NewBB :
2182 make_range(FirstNewBlock->getIterator(), Caller->end()))
2183 for (Instruction &I : NewBB)
2184 if (auto CS = CallSite(&I))
2185 IFI.InlinedCallSites.push_back(CS);
2186 }
2187
Chris Lattner0fa8c7c2004-02-04 04:17:06 +00002188 // If we cloned in _exactly one_ basic block, and if that block ends in a
2189 // return instruction, we splice the body of the inlined callee directly into
2190 // the calling basic block.
2191 if (Returns.size() == 1 && std::distance(FirstNewBlock, Caller->end()) == 1) {
2192 // Move all of the instructions right before the call.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002193 OrigBB->getInstList().splice(TheCall->getIterator(),
2194 FirstNewBlock->getInstList(),
Chris Lattner0fa8c7c2004-02-04 04:17:06 +00002195 FirstNewBlock->begin(), FirstNewBlock->end());
2196 // Remove the cloned basic block.
2197 Caller->getBasicBlockList().pop_back();
Misha Brukmanb1c93172005-04-21 23:48:37 +00002198
Chris Lattner0fa8c7c2004-02-04 04:17:06 +00002199 // If the call site was an invoke instruction, add a branch to the normal
2200 // destination.
Adrian Prantl15db52b2013-04-23 19:56:03 +00002201 if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall)) {
2202 BranchInst *NewBr = BranchInst::Create(II->getNormalDest(), TheCall);
2203 NewBr->setDebugLoc(Returns[0]->getDebugLoc());
2204 }
Chris Lattner0fa8c7c2004-02-04 04:17:06 +00002205
2206 // If the return instruction returned a value, replace uses of the call with
2207 // uses of the returned value.
Devang Patel841322b2008-03-04 21:15:15 +00002208 if (!TheCall->use_empty()) {
2209 ReturnInst *R = Returns[0];
Eli Friedman36b90262009-05-08 00:22:04 +00002210 if (TheCall == R->getReturnValue())
Owen Andersonb292b8c2009-07-30 23:03:37 +00002211 TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
Eli Friedman36b90262009-05-08 00:22:04 +00002212 else
2213 TheCall->replaceAllUsesWith(R->getReturnValue());
Devang Patel841322b2008-03-04 21:15:15 +00002214 }
Chris Lattner0fa8c7c2004-02-04 04:17:06 +00002215 // Since we are now done with the Call/Invoke, we can delete it.
Dan Gohman158ff2c2008-06-21 22:08:46 +00002216 TheCall->eraseFromParent();
Chris Lattner0fa8c7c2004-02-04 04:17:06 +00002217
2218 // Since we are now done with the return instruction, delete it also.
Dan Gohman158ff2c2008-06-21 22:08:46 +00002219 Returns[0]->eraseFromParent();
Chris Lattner0fa8c7c2004-02-04 04:17:06 +00002220
2221 // We are now done with the inlining.
2222 return true;
2223 }
2224
2225 // Otherwise, we have the normal case, of more than one block to inline or
2226 // multiple return sites.
2227
Chris Lattner18ef3fd2004-02-04 02:51:48 +00002228 // We want to clone the entire callee function into the hole between the
2229 // "starter" and "ender" blocks. How we accomplish this depends on whether
2230 // this is an invoke instruction or a call instruction.
2231 BasicBlock *AfterCallBB;
Craig Topperf40110f2014-04-25 05:29:35 +00002232 BranchInst *CreatedBranchToNormalDest = nullptr;
Chris Lattner18ef3fd2004-02-04 02:51:48 +00002233 if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall)) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00002234
Chris Lattner18ef3fd2004-02-04 02:51:48 +00002235 // Add an unconditional branch to make this look like the CallInst case...
Adrian Prantl15db52b2013-04-23 19:56:03 +00002236 CreatedBranchToNormalDest = BranchInst::Create(II->getNormalDest(), TheCall);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002237
Chris Lattner18ef3fd2004-02-04 02:51:48 +00002238 // Split the basic block. This guarantees that no PHI nodes will have to be
2239 // updated due to new incoming edges, and make the invoke case more
2240 // symmetric to the call case.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002241 AfterCallBB =
2242 OrigBB->splitBasicBlock(CreatedBranchToNormalDest->getIterator(),
2243 CalledFunc->getName() + ".exit");
Misha Brukmanb1c93172005-04-21 23:48:37 +00002244
Chris Lattner18ef3fd2004-02-04 02:51:48 +00002245 } else { // It's a call
Chris Lattner0fa8c7c2004-02-04 04:17:06 +00002246 // If this is a call instruction, we need to split the basic block that
2247 // the call lives in.
Chris Lattner18ef3fd2004-02-04 02:51:48 +00002248 //
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002249 AfterCallBB = OrigBB->splitBasicBlock(TheCall->getIterator(),
2250 CalledFunc->getName() + ".exit");
Chris Lattner18ef3fd2004-02-04 02:51:48 +00002251 }
2252
Easwaran Raman12585b02017-01-20 22:44:04 +00002253 if (IFI.CallerBFI) {
2254 // Copy original BB's block frequency to AfterCallBB
2255 IFI.CallerBFI->setBlockFreq(
2256 AfterCallBB, IFI.CallerBFI->getBlockFreq(OrigBB).getFrequency());
2257 }
2258
Chris Lattner0fa8c7c2004-02-04 04:17:06 +00002259 // Change the branch that used to go to AfterCallBB to branch to the first
2260 // basic block of the inlined function.
2261 //
Chandler Carruthedb12a82018-10-15 10:04:59 +00002262 Instruction *Br = OrigBB->getTerminator();
Misha Brukmanb1c93172005-04-21 23:48:37 +00002263 assert(Br && Br->getOpcode() == Instruction::Br &&
Chris Lattner0fa8c7c2004-02-04 04:17:06 +00002264 "splitBasicBlock broken!");
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002265 Br->setOperand(0, &*FirstNewBlock);
Chris Lattner0fa8c7c2004-02-04 04:17:06 +00002266
2267 // Now that the function is correct, make it a little bit nicer. In
2268 // particular, move the basic blocks inserted from the end of the function
2269 // into the space made by splitting the source basic block.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002270 Caller->getBasicBlockList().splice(AfterCallBB->getIterator(),
2271 Caller->getBasicBlockList(), FirstNewBlock,
2272 Caller->end());
Chris Lattner0fa8c7c2004-02-04 04:17:06 +00002273
Chris Lattner18ef3fd2004-02-04 02:51:48 +00002274 // Handle all of the return instructions that we just cloned in, and eliminate
2275 // any users of the original call/invoke instruction.
Chris Lattner229907c2011-07-18 04:54:35 +00002276 Type *RTy = CalledFunc->getReturnType();
Dan Gohman3b18fd72008-06-20 01:03:44 +00002277
Craig Topperf40110f2014-04-25 05:29:35 +00002278 PHINode *PHI = nullptr;
Dan Gohmanfa1211f2008-07-23 00:34:11 +00002279 if (Returns.size() > 1) {
Chris Lattner18ef3fd2004-02-04 02:51:48 +00002280 // The PHI node should go at the front of the new basic block to merge all
2281 // possible incoming values.
Chris Lattner18ef3fd2004-02-04 02:51:48 +00002282 if (!TheCall->use_empty()) {
Jay Foad52131342011-03-30 11:28:46 +00002283 PHI = PHINode::Create(RTy, Returns.size(), TheCall->getName(),
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002284 &AfterCallBB->front());
Dan Gohmanfa1211f2008-07-23 00:34:11 +00002285 // Anything that used the result of the function call should now use the
2286 // PHI node as their operand.
Duncan Sands7c8fb1a2008-09-05 12:37:12 +00002287 TheCall->replaceAllUsesWith(PHI);
Chris Lattner18ef3fd2004-02-04 02:51:48 +00002288 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002289
Gabor Greif5aa19222009-01-15 18:40:09 +00002290 // Loop over all of the return instructions adding entries to the PHI node
2291 // as appropriate.
Dan Gohmanfa1211f2008-07-23 00:34:11 +00002292 if (PHI) {
2293 for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
2294 ReturnInst *RI = Returns[i];
2295 assert(RI->getReturnValue()->getType() == PHI->getType() &&
2296 "Ret value not consistent in function!");
2297 PHI->addIncoming(RI->getReturnValue(), RI->getParent());
Devang Patel780b3ca62008-03-07 20:06:16 +00002298 }
2299 }
2300
Gabor Greif8c573f72009-01-16 23:08:50 +00002301 // Add a branch to the merge points and remove return instructions.
Richard Trieu624c2eb2013-04-30 22:45:10 +00002302 DebugLoc Loc;
Chris Lattner18ef3fd2004-02-04 02:51:48 +00002303 for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
Richard Trieu624c2eb2013-04-30 22:45:10 +00002304 ReturnInst *RI = Returns[i];
Adrian Prantl09416382013-04-30 17:08:16 +00002305 BranchInst* BI = BranchInst::Create(AfterCallBB, RI);
Richard Trieu624c2eb2013-04-30 22:45:10 +00002306 Loc = RI->getDebugLoc();
2307 BI->setDebugLoc(Loc);
Devang Patel64d0f072008-03-10 18:34:00 +00002308 RI->eraseFromParent();
Chris Lattner18ef3fd2004-02-04 02:51:48 +00002309 }
Adrian Prantl09416382013-04-30 17:08:16 +00002310 // We need to set the debug location to *somewhere* inside the
Adrian Prantl8beccf92013-04-30 17:33:32 +00002311 // inlined function. The line number may be nonsensical, but the
Adrian Prantl09416382013-04-30 17:08:16 +00002312 // instruction will at least be associated with the right
2313 // function.
2314 if (CreatedBranchToNormalDest)
Richard Trieu624c2eb2013-04-30 22:45:10 +00002315 CreatedBranchToNormalDest->setDebugLoc(Loc);
Devang Patel64d0f072008-03-10 18:34:00 +00002316 } else if (!Returns.empty()) {
2317 // Otherwise, if there is exactly one return value, just replace anything
2318 // using the return value of the call with the computed value.
Eli Friedman36b90262009-05-08 00:22:04 +00002319 if (!TheCall->use_empty()) {
2320 if (TheCall == Returns[0]->getReturnValue())
Owen Andersonb292b8c2009-07-30 23:03:37 +00002321 TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
Eli Friedman36b90262009-05-08 00:22:04 +00002322 else
2323 TheCall->replaceAllUsesWith(Returns[0]->getReturnValue());
2324 }
Duncan Sands7c8fb1a2008-09-05 12:37:12 +00002325
Jay Foad61ea0e42011-06-23 09:09:15 +00002326 // Update PHI nodes that use the ReturnBB to use the AfterCallBB.
2327 BasicBlock *ReturnBB = Returns[0]->getParent();
2328 ReturnBB->replaceAllUsesWith(AfterCallBB);
2329
Devang Patel64d0f072008-03-10 18:34:00 +00002330 // Splice the code from the return block into the block that it will return
2331 // to, which contains the code that was after the call.
Devang Patel64d0f072008-03-10 18:34:00 +00002332 AfterCallBB->getInstList().splice(AfterCallBB->begin(),
2333 ReturnBB->getInstList());
Duncan Sands7c8fb1a2008-09-05 12:37:12 +00002334
Adrian Prantl15db52b2013-04-23 19:56:03 +00002335 if (CreatedBranchToNormalDest)
2336 CreatedBranchToNormalDest->setDebugLoc(Returns[0]->getDebugLoc());
2337
Devang Patel64d0f072008-03-10 18:34:00 +00002338 // Delete the return instruction now and empty ReturnBB now.
2339 Returns[0]->eraseFromParent();
2340 ReturnBB->eraseFromParent();
Chris Lattner6e79e552004-10-17 23:21:07 +00002341 } else if (!TheCall->use_empty()) {
2342 // No returns, but something is using the return value of the call. Just
2343 // nuke the result.
Owen Andersonb292b8c2009-07-30 23:03:37 +00002344 TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
Chris Lattner18ef3fd2004-02-04 02:51:48 +00002345 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002346
Chris Lattner18ef3fd2004-02-04 02:51:48 +00002347 // Since we are now done with the Call/Invoke, we can delete it.
Chris Lattner6e79e552004-10-17 23:21:07 +00002348 TheCall->eraseFromParent();
Chris Lattner530d4bf2003-05-29 15:11:31 +00002349
Reid Klecknerf0915aa2014-05-15 20:11:28 +00002350 // If we inlined any musttail calls and the original return is now
2351 // unreachable, delete it. It can only contain a bitcast and ret.
Easwaran Ramanb1bd3982016-03-08 00:36:35 +00002352 if (InlinedMustTailCalls && pred_begin(AfterCallBB) == pred_end(AfterCallBB))
Reid Klecknerf0915aa2014-05-15 20:11:28 +00002353 AfterCallBB->eraseFromParent();
2354
Chris Lattnerfc3fe5c2003-08-24 04:06:56 +00002355 // We should always be able to fold the entry block of the function into the
2356 // single predecessor of the block...
Chris Lattner0328d752004-04-16 05:17:59 +00002357 assert(cast<BranchInst>(Br)->isUnconditional() && "splitBasicBlock broken!");
Chris Lattnerfc3fe5c2003-08-24 04:06:56 +00002358 BasicBlock *CalleeEntry = cast<BranchInst>(Br)->getSuccessor(0);
Chris Lattner0fa8c7c2004-02-04 04:17:06 +00002359
Chris Lattner0328d752004-04-16 05:17:59 +00002360 // Splice the code entry block into calling block, right before the
2361 // unconditional branch.
Eric Christopher96513122011-06-23 06:24:52 +00002362 CalleeEntry->replaceAllUsesWith(OrigBB); // Update PHI nodes
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002363 OrigBB->getInstList().splice(Br->getIterator(), CalleeEntry->getInstList());
Chris Lattner0328d752004-04-16 05:17:59 +00002364
2365 // Remove the unconditional branch.
2366 OrigBB->getInstList().erase(Br);
2367
2368 // Now we can remove the CalleeEntry block, which is now empty.
2369 Caller->getBasicBlockList().erase(CalleeEntry);
Duncan Sands7c8fb1a2008-09-05 12:37:12 +00002370
Duncan Sands9d9a4e22010-11-17 11:16:23 +00002371 // If we inserted a phi node, check to see if it has a single value (e.g. all
2372 // the entries are the same or undef). If so, remove the PHI so it doesn't
2373 // block other optimizations.
Bill Wendlingce0c2292012-01-31 01:01:16 +00002374 if (PHI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002375 AssumptionCache *AC =
2376 IFI.GetAssumptionCache ? &(*IFI.GetAssumptionCache)(*Caller) : nullptr;
Mehdi Amini46a43552015-03-04 18:43:29 +00002377 auto &DL = Caller->getParent()->getDataLayout();
Daniel Berlin4d0fe642017-04-28 19:55:38 +00002378 if (Value *V = SimplifyInstruction(PHI, {DL, nullptr, nullptr, AC})) {
Duncan Sands9d9a4e22010-11-17 11:16:23 +00002379 PHI->replaceAllUsesWith(V);
2380 PHI->eraseFromParent();
2381 }
Bill Wendlingce0c2292012-01-31 01:01:16 +00002382 }
Duncan Sands9d9a4e22010-11-17 11:16:23 +00002383
Chris Lattner530d4bf2003-05-29 15:11:31 +00002384 return true;
2385}