blob: 5574a3d2687a6478b80d21d0dccf30ca53f1c9fc [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"
Hal Finkel94146652014-07-24 14:25:39 +000032#include "llvm/Analysis/ValueTracking.h"
Eugene Zelenko6cadde72017-10-17 21:27:42 +000033#include "llvm/IR/Argument.h"
34#include "llvm/IR/BasicBlock.h"
Reid Klecknerf0915aa2014-05-15 20:11:28 +000035#include "llvm/IR/CFG.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000036#include "llvm/IR/CallSite.h"
Eugene Zelenko6cadde72017-10-17 21:27:42 +000037#include "llvm/IR/Constant.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000038#include "llvm/IR/Constants.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000039#include "llvm/IR/DIBuilder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000040#include "llvm/IR/DataLayout.h"
Eugene Zelenko6cadde72017-10-17 21:27:42 +000041#include "llvm/IR/DebugInfoMetadata.h"
42#include "llvm/IR/DebugLoc.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000043#include "llvm/IR/DerivedTypes.h"
Hal Finkelff0bcb62014-07-25 15:50:08 +000044#include "llvm/IR/Dominators.h"
Eugene Zelenko6cadde72017-10-17 21:27:42 +000045#include "llvm/IR/Function.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000046#include "llvm/IR/IRBuilder.h"
Eugene Zelenko6cadde72017-10-17 21:27:42 +000047#include "llvm/IR/InstrTypes.h"
48#include "llvm/IR/Instruction.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000049#include "llvm/IR/Instructions.h"
50#include "llvm/IR/IntrinsicInst.h"
51#include "llvm/IR/Intrinsics.h"
Eugene Zelenko6cadde72017-10-17 21:27:42 +000052#include "llvm/IR/LLVMContext.h"
Hal Finkel94146652014-07-24 14:25:39 +000053#include "llvm/IR/MDBuilder.h"
Eugene Zelenko6cadde72017-10-17 21:27:42 +000054#include "llvm/IR/Metadata.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000055#include "llvm/IR/Module.h"
Eugene Zelenko6cadde72017-10-17 21:27:42 +000056#include "llvm/IR/Type.h"
57#include "llvm/IR/User.h"
58#include "llvm/IR/Value.h"
59#include "llvm/Support/Casting.h"
Hal Finkelff0bcb62014-07-25 15:50:08 +000060#include "llvm/Support/CommandLine.h"
Eugene Zelenko6cadde72017-10-17 21:27:42 +000061#include "llvm/Support/ErrorHandling.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000062#include "llvm/Transforms/Utils/Cloning.h"
Easwaran Raman12585b02017-01-20 22:44:04 +000063#include "llvm/Transforms/Utils/Local.h"
Eugene Zelenko6cadde72017-10-17 21:27:42 +000064#include "llvm/Transforms/Utils/ValueMapper.h"
Hal Finkelff0bcb62014-07-25 15:50:08 +000065#include <algorithm>
Eugene Zelenko6cadde72017-10-17 21:27:42 +000066#include <cassert>
67#include <cstdint>
68#include <iterator>
69#include <limits>
70#include <string>
71#include <utility>
72#include <vector>
Hans Wennborg083ca9b2015-10-06 23:24:35 +000073
Chris Lattnerdf3c3422004-01-09 06:12:26 +000074using namespace llvm;
Chris Lattner530d4bf2003-05-29 15:11:31 +000075
Hal Finkelff0bcb62014-07-25 15:50:08 +000076static cl::opt<bool>
James Molloy6b95d8e2014-09-04 13:23:08 +000077EnableNoAliasConversion("enable-noalias-to-md-conversion", cl::init(true),
Hal Finkelff0bcb62014-07-25 15:50:08 +000078 cl::Hidden,
79 cl::desc("Convert noalias attributes to metadata during inlining."));
80
Hal Finkel68dc3c72014-10-15 23:44:41 +000081static cl::opt<bool>
82PreserveAlignmentAssumptions("preserve-alignment-assumptions-during-inlining",
83 cl::init(true), cl::Hidden,
84 cl::desc("Convert align attributes to assumptions during inlining."));
85
Eric Christopherf16bee82012-03-26 19:09:38 +000086bool llvm::InlineFunction(CallInst *CI, InlineFunctionInfo &IFI,
Chandler Carruth7b560d42015-09-09 17:55:00 +000087 AAResults *CalleeAAR, bool InsertLifetime) {
88 return InlineFunction(CallSite(CI), IFI, CalleeAAR, InsertLifetime);
Chris Lattner0841fb12006-01-14 20:07:50 +000089}
Eugene Zelenko6cadde72017-10-17 21:27:42 +000090
Eric Christopherf16bee82012-03-26 19:09:38 +000091bool llvm::InlineFunction(InvokeInst *II, InlineFunctionInfo &IFI,
Chandler Carruth7b560d42015-09-09 17:55:00 +000092 AAResults *CalleeAAR, bool InsertLifetime) {
93 return InlineFunction(CallSite(II), IFI, CalleeAAR, InsertLifetime);
Chris Lattner0841fb12006-01-14 20:07:50 +000094}
Chris Lattner0cc265e2003-08-24 06:59:16 +000095
John McCallbd04b742011-05-27 18:34:38 +000096namespace {
Eugene Zelenko6cadde72017-10-17 21:27:42 +000097
David Majnemer654e1302015-07-31 17:58:14 +000098 /// A class for recording information about inlining a landing pad.
99 class LandingPadInliningInfo {
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000100 /// Destination of the invoke's unwind.
101 BasicBlock *OuterResumeDest;
102
103 /// Destination for the callee's resume.
104 BasicBlock *InnerResumeDest = nullptr;
105
106 /// LandingPadInst associated with the invoke.
107 LandingPadInst *CallerLPad = nullptr;
108
109 /// PHI for EH values from landingpad insts.
110 PHINode *InnerEHValuesPHI = nullptr;
111
Bill Wendling0c2d82b2012-01-31 01:22:03 +0000112 SmallVector<Value*, 8> UnwindDestPHIValues;
Bill Wendlingfa284402011-07-28 07:31:46 +0000113
Bill Wendling55421f02011-08-14 08:01:36 +0000114 public:
David Majnemer654e1302015-07-31 17:58:14 +0000115 LandingPadInliningInfo(InvokeInst *II)
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000116 : OuterResumeDest(II->getUnwindDest()) {
Bill Wendling55421f02011-08-14 08:01:36 +0000117 // If there are PHI nodes in the unwind destination block, we need to keep
118 // track of which values came into them from the invoke before removing
119 // the edge from this block.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000120 BasicBlock *InvokeBB = II->getParent();
Bill Wendlingea6e9352012-01-31 01:25:54 +0000121 BasicBlock::iterator I = OuterResumeDest->begin();
Bill Wendling55421f02011-08-14 08:01:36 +0000122 for (; isa<PHINode>(I); ++I) {
John McCallbd04b742011-05-27 18:34:38 +0000123 // Save the value to use for this edge.
Bill Wendling55421f02011-08-14 08:01:36 +0000124 PHINode *PHI = cast<PHINode>(I);
125 UnwindDestPHIValues.push_back(PHI->getIncomingValueForBlock(InvokeBB));
126 }
127
Bill Wendlingf3cae512012-01-31 00:56:53 +0000128 CallerLPad = cast<LandingPadInst>(I);
John McCallbd04b742011-05-27 18:34:38 +0000129 }
130
Sanjay Patel0fdb4372015-03-10 19:42:57 +0000131 /// The outer unwind destination is the target of
Bill Wendlingea6e9352012-01-31 01:25:54 +0000132 /// unwind edges introduced for calls within the inlined function.
Bill Wendling0c2d82b2012-01-31 01:22:03 +0000133 BasicBlock *getOuterResumeDest() const {
Bill Wendlingea6e9352012-01-31 01:25:54 +0000134 return OuterResumeDest;
John McCallbd04b742011-05-27 18:34:38 +0000135 }
136
Bill Wendling3fd879d2012-01-31 01:48:40 +0000137 BasicBlock *getInnerResumeDest();
Bill Wendling55421f02011-08-14 08:01:36 +0000138
139 LandingPadInst *getLandingPadInst() const { return CallerLPad; }
140
Sanjay Patel0fdb4372015-03-10 19:42:57 +0000141 /// Forward the 'resume' instruction to the caller's landing pad block.
142 /// When the landing pad block has only one predecessor, this is
Bill Wendling55421f02011-08-14 08:01:36 +0000143 /// a simple branch. When there is more than one predecessor, we need to
144 /// split the landing pad block after the landingpad instruction and jump
145 /// to there.
Bill Wendling56f15bf2013-03-22 20:31:05 +0000146 void forwardResume(ResumeInst *RI,
Craig Topper71b7b682014-08-21 05:55:13 +0000147 SmallPtrSetImpl<LandingPadInst*> &InlinedLPads);
Bill Wendling55421f02011-08-14 08:01:36 +0000148
Sanjay Patel0fdb4372015-03-10 19:42:57 +0000149 /// Add incoming-PHI values to the unwind destination block for the given
150 /// basic block, using the values for the original invoke's source block.
John McCallbd04b742011-05-27 18:34:38 +0000151 void addIncomingPHIValuesFor(BasicBlock *BB) const {
Bill Wendlingea6e9352012-01-31 01:25:54 +0000152 addIncomingPHIValuesForInto(BB, OuterResumeDest);
John McCall046c47e2011-05-28 07:45:59 +0000153 }
Bill Wendlingad088e62011-07-30 05:42:50 +0000154
John McCall046c47e2011-05-28 07:45:59 +0000155 void addIncomingPHIValuesForInto(BasicBlock *src, BasicBlock *dest) const {
156 BasicBlock::iterator I = dest->begin();
John McCallbd04b742011-05-27 18:34:38 +0000157 for (unsigned i = 0, e = UnwindDestPHIValues.size(); i != e; ++i, ++I) {
Bill Wendlingad088e62011-07-30 05:42:50 +0000158 PHINode *phi = cast<PHINode>(I);
159 phi->addIncoming(UnwindDestPHIValues[i], src);
John McCallbd04b742011-05-27 18:34:38 +0000160 }
161 }
162 };
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000163
164} // end anonymous namespace
John McCallbd04b742011-05-27 18:34:38 +0000165
Sanjay Patel0fdb4372015-03-10 19:42:57 +0000166/// Get or create a target for the branch from ResumeInsts.
David Majnemer654e1302015-07-31 17:58:14 +0000167BasicBlock *LandingPadInliningInfo::getInnerResumeDest() {
Bill Wendling55421f02011-08-14 08:01:36 +0000168 if (InnerResumeDest) return InnerResumeDest;
169
170 // Split the landing pad.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000171 BasicBlock::iterator SplitPoint = ++CallerLPad->getIterator();
Bill Wendling55421f02011-08-14 08:01:36 +0000172 InnerResumeDest =
173 OuterResumeDest->splitBasicBlock(SplitPoint,
174 OuterResumeDest->getName() + ".body");
175
176 // The number of incoming edges we expect to the inner landing pad.
177 const unsigned PHICapacity = 2;
178
179 // Create corresponding new PHIs for all the PHIs in the outer landing pad.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000180 Instruction *InsertPoint = &InnerResumeDest->front();
Bill Wendling55421f02011-08-14 08:01:36 +0000181 BasicBlock::iterator I = OuterResumeDest->begin();
182 for (unsigned i = 0, e = UnwindDestPHIValues.size(); i != e; ++i, ++I) {
183 PHINode *OuterPHI = cast<PHINode>(I);
184 PHINode *InnerPHI = PHINode::Create(OuterPHI->getType(), PHICapacity,
185 OuterPHI->getName() + ".lpad-body",
186 InsertPoint);
187 OuterPHI->replaceAllUsesWith(InnerPHI);
188 InnerPHI->addIncoming(OuterPHI, OuterResumeDest);
189 }
190
191 // Create a PHI for the exception values.
192 InnerEHValuesPHI = PHINode::Create(CallerLPad->getType(), PHICapacity,
193 "eh.lpad-body", InsertPoint);
194 CallerLPad->replaceAllUsesWith(InnerEHValuesPHI);
195 InnerEHValuesPHI->addIncoming(CallerLPad, OuterResumeDest);
196
197 // All done.
198 return InnerResumeDest;
199}
200
Sanjay Patel0fdb4372015-03-10 19:42:57 +0000201/// Forward the 'resume' instruction to the caller's landing pad block.
202/// When the landing pad block has only one predecessor, this is a simple
Bill Wendling55421f02011-08-14 08:01:36 +0000203/// branch. When there is more than one predecessor, we need to split the
204/// landing pad block after the landingpad instruction and jump to there.
David Majnemer654e1302015-07-31 17:58:14 +0000205void LandingPadInliningInfo::forwardResume(
206 ResumeInst *RI, SmallPtrSetImpl<LandingPadInst *> &InlinedLPads) {
Bill Wendling3fd879d2012-01-31 01:48:40 +0000207 BasicBlock *Dest = getInnerResumeDest();
Bill Wendling55421f02011-08-14 08:01:36 +0000208 BasicBlock *Src = RI->getParent();
209
210 BranchInst::Create(Dest, Src);
211
212 // Update the PHIs in the destination. They were inserted in an order which
213 // makes this work.
214 addIncomingPHIValuesForInto(Src, Dest);
215
216 InnerEHValuesPHI->addIncoming(RI->getOperand(0), Src);
217 RI->eraseFromParent();
218}
219
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000220/// Helper for getUnwindDestToken/getUnwindDestTokenHelper.
221static Value *getParentPad(Value *EHPad) {
222 if (auto *FPI = dyn_cast<FuncletPadInst>(EHPad))
223 return FPI->getParentPad();
224 return cast<CatchSwitchInst>(EHPad)->getParentPad();
225}
226
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000227using UnwindDestMemoTy = DenseMap<Instruction *, Value *>;
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000228
229/// Helper for getUnwindDestToken that does the descendant-ward part of
230/// the search.
231static Value *getUnwindDestTokenHelper(Instruction *EHPad,
232 UnwindDestMemoTy &MemoMap) {
233 SmallVector<Instruction *, 8> Worklist(1, EHPad);
234
235 while (!Worklist.empty()) {
236 Instruction *CurrentPad = Worklist.pop_back_val();
237 // We only put pads on the worklist that aren't in the MemoMap. When
238 // we find an unwind dest for a pad we may update its ancestors, but
239 // the queue only ever contains uncles/great-uncles/etc. of CurrentPad,
240 // so they should never get updated while queued on the worklist.
241 assert(!MemoMap.count(CurrentPad));
242 Value *UnwindDestToken = nullptr;
243 if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(CurrentPad)) {
244 if (CatchSwitch->hasUnwindDest()) {
245 UnwindDestToken = CatchSwitch->getUnwindDest()->getFirstNonPHI();
246 } else {
247 // Catchswitch doesn't have a 'nounwind' variant, and one might be
248 // annotated as "unwinds to caller" when really it's nounwind (see
249 // e.g. SimplifyCFGOpt::SimplifyUnreachable), so we can't infer the
250 // parent's unwind dest from this. We can check its catchpads'
251 // descendants, since they might include a cleanuppad with an
252 // "unwinds to caller" cleanupret, which can be trusted.
253 for (auto HI = CatchSwitch->handler_begin(),
254 HE = CatchSwitch->handler_end();
255 HI != HE && !UnwindDestToken; ++HI) {
256 BasicBlock *HandlerBlock = *HI;
257 auto *CatchPad = cast<CatchPadInst>(HandlerBlock->getFirstNonPHI());
258 for (User *Child : CatchPad->users()) {
259 // Intentionally ignore invokes here -- since the catchswitch is
260 // marked "unwind to caller", it would be a verifier error if it
261 // contained an invoke which unwinds out of it, so any invoke we'd
262 // encounter must unwind to some child of the catch.
263 if (!isa<CleanupPadInst>(Child) && !isa<CatchSwitchInst>(Child))
264 continue;
265
266 Instruction *ChildPad = cast<Instruction>(Child);
267 auto Memo = MemoMap.find(ChildPad);
268 if (Memo == MemoMap.end()) {
Joseph Tremoulete92e0a92016-09-04 01:23:20 +0000269 // Haven't figured out this child pad yet; queue it.
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000270 Worklist.push_back(ChildPad);
271 continue;
272 }
273 // We've already checked this child, but might have found that
274 // it offers no proof either way.
275 Value *ChildUnwindDestToken = Memo->second;
276 if (!ChildUnwindDestToken)
277 continue;
278 // We already know the child's unwind dest, which can either
279 // be ConstantTokenNone to indicate unwind to caller, or can
280 // be another child of the catchpad. Only the former indicates
281 // the unwind dest of the catchswitch.
282 if (isa<ConstantTokenNone>(ChildUnwindDestToken)) {
283 UnwindDestToken = ChildUnwindDestToken;
284 break;
285 }
286 assert(getParentPad(ChildUnwindDestToken) == CatchPad);
287 }
288 }
289 }
290 } else {
291 auto *CleanupPad = cast<CleanupPadInst>(CurrentPad);
292 for (User *U : CleanupPad->users()) {
293 if (auto *CleanupRet = dyn_cast<CleanupReturnInst>(U)) {
294 if (BasicBlock *RetUnwindDest = CleanupRet->getUnwindDest())
295 UnwindDestToken = RetUnwindDest->getFirstNonPHI();
296 else
297 UnwindDestToken = ConstantTokenNone::get(CleanupPad->getContext());
298 break;
299 }
300 Value *ChildUnwindDestToken;
301 if (auto *Invoke = dyn_cast<InvokeInst>(U)) {
302 ChildUnwindDestToken = Invoke->getUnwindDest()->getFirstNonPHI();
303 } else if (isa<CleanupPadInst>(U) || isa<CatchSwitchInst>(U)) {
304 Instruction *ChildPad = cast<Instruction>(U);
305 auto Memo = MemoMap.find(ChildPad);
306 if (Memo == MemoMap.end()) {
307 // Haven't resolved this child yet; queue it and keep searching.
308 Worklist.push_back(ChildPad);
309 continue;
310 }
311 // We've checked this child, but still need to ignore it if it
312 // had no proof either way.
313 ChildUnwindDestToken = Memo->second;
314 if (!ChildUnwindDestToken)
315 continue;
316 } else {
317 // Not a relevant user of the cleanuppad
318 continue;
319 }
320 // In a well-formed program, the child/invoke must either unwind to
321 // an(other) child of the cleanup, or exit the cleanup. In the
322 // first case, continue searching.
323 if (isa<Instruction>(ChildUnwindDestToken) &&
324 getParentPad(ChildUnwindDestToken) == CleanupPad)
325 continue;
326 UnwindDestToken = ChildUnwindDestToken;
327 break;
328 }
329 }
330 // If we haven't found an unwind dest for CurrentPad, we may have queued its
331 // children, so move on to the next in the worklist.
332 if (!UnwindDestToken)
333 continue;
334
335 // Now we know that CurrentPad unwinds to UnwindDestToken. It also exits
336 // any ancestors of CurrentPad up to but not including UnwindDestToken's
337 // parent pad. Record this in the memo map, and check to see if the
338 // original EHPad being queried is one of the ones exited.
339 Value *UnwindParent;
340 if (auto *UnwindPad = dyn_cast<Instruction>(UnwindDestToken))
341 UnwindParent = getParentPad(UnwindPad);
342 else
343 UnwindParent = nullptr;
344 bool ExitedOriginalPad = false;
345 for (Instruction *ExitedPad = CurrentPad;
346 ExitedPad && ExitedPad != UnwindParent;
347 ExitedPad = dyn_cast<Instruction>(getParentPad(ExitedPad))) {
348 // Skip over catchpads since they just follow their catchswitches.
349 if (isa<CatchPadInst>(ExitedPad))
350 continue;
351 MemoMap[ExitedPad] = UnwindDestToken;
352 ExitedOriginalPad |= (ExitedPad == EHPad);
353 }
354
355 if (ExitedOriginalPad)
356 return UnwindDestToken;
357
358 // Continue the search.
359 }
360
361 // No definitive information is contained within this funclet.
362 return nullptr;
363}
364
365/// Given an EH pad, find where it unwinds. If it unwinds to an EH pad,
366/// return that pad instruction. If it unwinds to caller, return
367/// ConstantTokenNone. If it does not have a definitive unwind destination,
368/// return nullptr.
369///
370/// This routine gets invoked for calls in funclets in inlinees when inlining
371/// an invoke. Since many funclets don't have calls inside them, it's queried
372/// on-demand rather than building a map of pads to unwind dests up front.
373/// Determining a funclet's unwind dest may require recursively searching its
374/// descendants, and also ancestors and cousins if the descendants don't provide
375/// an answer. Since most funclets will have their unwind dest immediately
376/// available as the unwind dest of a catchswitch or cleanupret, this routine
377/// searches top-down from the given pad and then up. To avoid worst-case
378/// quadratic run-time given that approach, it uses a memo map to avoid
379/// re-processing funclet trees. The callers that rewrite the IR as they go
380/// take advantage of this, for correctness, by checking/forcing rewritten
381/// pads' entries to match the original callee view.
382static Value *getUnwindDestToken(Instruction *EHPad,
383 UnwindDestMemoTy &MemoMap) {
384 // Catchpads unwind to the same place as their catchswitch;
385 // redirct any queries on catchpads so the code below can
386 // deal with just catchswitches and cleanuppads.
387 if (auto *CPI = dyn_cast<CatchPadInst>(EHPad))
388 EHPad = CPI->getCatchSwitch();
389
390 // Check if we've already determined the unwind dest for this pad.
391 auto Memo = MemoMap.find(EHPad);
392 if (Memo != MemoMap.end())
393 return Memo->second;
394
395 // Search EHPad and, if necessary, its descendants.
396 Value *UnwindDestToken = getUnwindDestTokenHelper(EHPad, MemoMap);
397 assert((UnwindDestToken == nullptr) != (MemoMap.count(EHPad) != 0));
398 if (UnwindDestToken)
399 return UnwindDestToken;
400
401 // No information is available for this EHPad from itself or any of its
402 // descendants. An unwind all the way out to a pad in the caller would
403 // need also to agree with the unwind dest of the parent funclet, so
404 // search up the chain to try to find a funclet with information. Put
405 // null entries in the memo map to avoid re-processing as we go up.
406 MemoMap[EHPad] = nullptr;
Joseph Tremoulete92e0a92016-09-04 01:23:20 +0000407#ifndef NDEBUG
408 SmallPtrSet<Instruction *, 4> TempMemos;
409 TempMemos.insert(EHPad);
410#endif
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000411 Instruction *LastUselessPad = EHPad;
412 Value *AncestorToken;
413 for (AncestorToken = getParentPad(EHPad);
414 auto *AncestorPad = dyn_cast<Instruction>(AncestorToken);
415 AncestorToken = getParentPad(AncestorToken)) {
416 // Skip over catchpads since they just follow their catchswitches.
417 if (isa<CatchPadInst>(AncestorPad))
418 continue;
Joseph Tremoulete92e0a92016-09-04 01:23:20 +0000419 // If the MemoMap had an entry mapping AncestorPad to nullptr, since we
420 // haven't yet called getUnwindDestTokenHelper for AncestorPad in this
421 // call to getUnwindDestToken, that would mean that AncestorPad had no
422 // information in itself, its descendants, or its ancestors. If that
423 // were the case, then we should also have recorded the lack of information
424 // for the descendant that we're coming from. So assert that we don't
425 // find a null entry in the MemoMap for AncestorPad.
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000426 assert(!MemoMap.count(AncestorPad) || MemoMap[AncestorPad]);
427 auto AncestorMemo = MemoMap.find(AncestorPad);
428 if (AncestorMemo == MemoMap.end()) {
429 UnwindDestToken = getUnwindDestTokenHelper(AncestorPad, MemoMap);
430 } else {
431 UnwindDestToken = AncestorMemo->second;
432 }
433 if (UnwindDestToken)
434 break;
435 LastUselessPad = AncestorPad;
Joseph Tremoulete92e0a92016-09-04 01:23:20 +0000436 MemoMap[LastUselessPad] = nullptr;
437#ifndef NDEBUG
438 TempMemos.insert(LastUselessPad);
439#endif
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000440 }
441
Joseph Tremoulete92e0a92016-09-04 01:23:20 +0000442 // We know that getUnwindDestTokenHelper was called on LastUselessPad and
443 // returned nullptr (and likewise for EHPad and any of its ancestors up to
444 // LastUselessPad), so LastUselessPad has no information from below. Since
445 // getUnwindDestTokenHelper must investigate all downward paths through
446 // no-information nodes to prove that a node has no information like this,
447 // and since any time it finds information it records it in the MemoMap for
448 // not just the immediately-containing funclet but also any ancestors also
449 // exited, it must be the case that, walking downward from LastUselessPad,
450 // visiting just those nodes which have not been mapped to an unwind dest
451 // by getUnwindDestTokenHelper (the nullptr TempMemos notwithstanding, since
452 // they are just used to keep getUnwindDestTokenHelper from repeating work),
453 // any node visited must have been exhaustively searched with no information
454 // for it found.
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000455 SmallVector<Instruction *, 8> Worklist(1, LastUselessPad);
456 while (!Worklist.empty()) {
457 Instruction *UselessPad = Worklist.pop_back_val();
Joseph Tremoulete92e0a92016-09-04 01:23:20 +0000458 auto Memo = MemoMap.find(UselessPad);
459 if (Memo != MemoMap.end() && Memo->second) {
460 // Here the name 'UselessPad' is a bit of a misnomer, because we've found
461 // that it is a funclet that does have information about unwinding to
462 // a particular destination; its parent was a useless pad.
463 // Since its parent has no information, the unwind edge must not escape
464 // the parent, and must target a sibling of this pad. This local unwind
465 // gives us no information about EHPad. Leave it and the subtree rooted
466 // at it alone.
467 assert(getParentPad(Memo->second) == getParentPad(UselessPad));
468 continue;
469 }
470 // We know we don't have information for UselesPad. If it has an entry in
471 // the MemoMap (mapping it to nullptr), it must be one of the TempMemos
472 // added on this invocation of getUnwindDestToken; if a previous invocation
473 // recorded nullptr, it would have had to prove that the ancestors of
474 // UselessPad, which include LastUselessPad, had no information, and that
475 // in turn would have required proving that the descendants of
476 // LastUselesPad, which include EHPad, have no information about
477 // LastUselessPad, which would imply that EHPad was mapped to nullptr in
478 // the MemoMap on that invocation, which isn't the case if we got here.
479 assert(!MemoMap.count(UselessPad) || TempMemos.count(UselessPad));
480 // Assert as we enumerate users that 'UselessPad' doesn't have any unwind
481 // information that we'd be contradicting by making a map entry for it
482 // (which is something that getUnwindDestTokenHelper must have proved for
483 // us to get here). Just assert on is direct users here; the checks in
484 // this downward walk at its descendants will verify that they don't have
485 // any unwind edges that exit 'UselessPad' either (i.e. they either have no
486 // unwind edges or unwind to a sibling).
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000487 MemoMap[UselessPad] = UnwindDestToken;
488 if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(UselessPad)) {
Joseph Tremoulete92e0a92016-09-04 01:23:20 +0000489 assert(CatchSwitch->getUnwindDest() == nullptr && "Expected useless pad");
490 for (BasicBlock *HandlerBlock : CatchSwitch->handlers()) {
491 auto *CatchPad = HandlerBlock->getFirstNonPHI();
492 for (User *U : CatchPad->users()) {
493 assert(
494 (!isa<InvokeInst>(U) ||
495 (getParentPad(
496 cast<InvokeInst>(U)->getUnwindDest()->getFirstNonPHI()) ==
497 CatchPad)) &&
498 "Expected useless pad");
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000499 if (isa<CatchSwitchInst>(U) || isa<CleanupPadInst>(U))
500 Worklist.push_back(cast<Instruction>(U));
Joseph Tremoulete92e0a92016-09-04 01:23:20 +0000501 }
502 }
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000503 } else {
504 assert(isa<CleanupPadInst>(UselessPad));
Joseph Tremoulete92e0a92016-09-04 01:23:20 +0000505 for (User *U : UselessPad->users()) {
506 assert(!isa<CleanupReturnInst>(U) && "Expected useless pad");
507 assert((!isa<InvokeInst>(U) ||
508 (getParentPad(
509 cast<InvokeInst>(U)->getUnwindDest()->getFirstNonPHI()) ==
510 UselessPad)) &&
511 "Expected useless pad");
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000512 if (isa<CatchSwitchInst>(U) || isa<CleanupPadInst>(U))
513 Worklist.push_back(cast<Instruction>(U));
Joseph Tremoulete92e0a92016-09-04 01:23:20 +0000514 }
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000515 }
516 }
517
518 return UnwindDestToken;
519}
520
Sanjay Patel0fdb4372015-03-10 19:42:57 +0000521/// When we inline a basic block into an invoke,
522/// we have to turn all of the calls that can throw into invokes.
523/// This function analyze BB to see if there are any calls, and if so,
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000524/// it rewrites them to be invokes that jump to InvokeDest and fills in the PHI
Chris Lattner8900f3e2009-09-01 18:44:06 +0000525/// nodes in that block with the values specified in InvokeDestPHIValues.
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000526static BasicBlock *HandleCallsInBlockInlinedThroughInvoke(
527 BasicBlock *BB, BasicBlock *UnwindEdge,
528 UnwindDestMemoTy *FuncletUnwindMap = nullptr) {
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000529 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000530 Instruction *I = &*BBI++;
Bill Wendling55421f02011-08-14 08:01:36 +0000531
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000532 // We only need to check for function calls: inlined invoke
533 // instructions require no special handling.
534 CallInst *CI = dyn_cast<CallInst>(I);
John McCallbd04b742011-05-27 18:34:38 +0000535
Manman Ren87a2adc2013-10-31 21:56:03 +0000536 if (!CI || CI->doesNotThrow() || isa<InlineAsm>(CI->getCalledValue()))
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000537 continue;
Bill Wendling518a2052012-01-31 01:05:20 +0000538
Sanjoy Dasb51325d2016-03-11 19:08:34 +0000539 // We do not need to (and in fact, cannot) convert possibly throwing calls
Sanjoy Das021de052016-03-31 00:18:46 +0000540 // to @llvm.experimental_deoptimize (resp. @llvm.experimental.guard) into
541 // invokes. The caller's "segment" of the deoptimization continuation
542 // attached to the newly inlined @llvm.experimental_deoptimize
543 // (resp. @llvm.experimental.guard) call should contain the exception
544 // handling logic, if any.
Sanjoy Dasb51325d2016-03-11 19:08:34 +0000545 if (auto *F = CI->getCalledFunction())
Sanjoy Das021de052016-03-31 00:18:46 +0000546 if (F->getIntrinsicID() == Intrinsic::experimental_deoptimize ||
547 F->getIntrinsicID() == Intrinsic::experimental_guard)
Sanjoy Dasb51325d2016-03-11 19:08:34 +0000548 continue;
549
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000550 if (auto FuncletBundle = CI->getOperandBundle(LLVMContext::OB_funclet)) {
551 // This call is nested inside a funclet. If that funclet has an unwind
552 // destination within the inlinee, then unwinding out of this call would
553 // be UB. Rewriting this call to an invoke which targets the inlined
554 // invoke's unwind dest would give the call's parent funclet multiple
555 // unwind destinations, which is something that subsequent EH table
556 // generation can't handle and that the veirifer rejects. So when we
557 // see such a call, leave it as a call.
558 auto *FuncletPad = cast<Instruction>(FuncletBundle->Inputs[0]);
559 Value *UnwindDestToken =
560 getUnwindDestToken(FuncletPad, *FuncletUnwindMap);
561 if (UnwindDestToken && !isa<ConstantTokenNone>(UnwindDestToken))
562 continue;
563#ifndef NDEBUG
564 Instruction *MemoKey;
565 if (auto *CatchPad = dyn_cast<CatchPadInst>(FuncletPad))
566 MemoKey = CatchPad->getCatchSwitch();
567 else
568 MemoKey = FuncletPad;
569 assert(FuncletUnwindMap->count(MemoKey) &&
570 (*FuncletUnwindMap)[MemoKey] == UnwindDestToken &&
571 "must get memoized to avoid confusing later searches");
572#endif // NDEBUG
573 }
574
Kuba Breckaddfdba32016-11-14 21:41:13 +0000575 changeToInvokeAndSplitBasicBlock(CI, UnwindEdge);
David Majnemer654e1302015-07-31 17:58:14 +0000576 return BB;
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000577 }
David Majnemer654e1302015-07-31 17:58:14 +0000578 return nullptr;
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000579}
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000580
Sanjay Patel0fdb4372015-03-10 19:42:57 +0000581/// If we inlined an invoke site, we need to convert calls
Bill Wendling0aef16a2012-02-06 21:44:22 +0000582/// in the body of the inlined function into invokes.
Chris Lattner908d7952006-01-13 19:05:59 +0000583///
Nick Lewycky12a130b2009-02-03 04:34:40 +0000584/// II is the invoke instruction being inlined. FirstNewBlock is the first
Chris Lattner908d7952006-01-13 19:05:59 +0000585/// block of the inlined code (the last block is the end of the function),
586/// and InlineCodeInfo is information about the code that got inlined.
David Majnemer654e1302015-07-31 17:58:14 +0000587static void HandleInlinedLandingPad(InvokeInst *II, BasicBlock *FirstNewBlock,
588 ClonedCodeInfo &InlinedCodeInfo) {
Chris Lattner908d7952006-01-13 19:05:59 +0000589 BasicBlock *InvokeDest = II->getUnwindDest();
Chris Lattner908d7952006-01-13 19:05:59 +0000590
591 Function *Caller = FirstNewBlock->getParent();
Duncan Sands7c8fb1a2008-09-05 12:37:12 +0000592
Chris Lattner908d7952006-01-13 19:05:59 +0000593 // The inlined code is currently at the end of the function, scan from the
594 // start of the inlined code to its end, checking for stuff we need to
Bill Wendling173c71f2013-03-21 23:30:12 +0000595 // rewrite.
David Majnemer654e1302015-07-31 17:58:14 +0000596 LandingPadInliningInfo Invoke(II);
Bill Wendling173c71f2013-03-21 23:30:12 +0000597
Bill Wendling56f15bf2013-03-22 20:31:05 +0000598 // Get all of the inlined landing pad instructions.
599 SmallPtrSet<LandingPadInst*, 16> InlinedLPads;
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000600 for (Function::iterator I = FirstNewBlock->getIterator(), E = Caller->end();
601 I != E; ++I)
Bill Wendling56f15bf2013-03-22 20:31:05 +0000602 if (InvokeInst *II = dyn_cast<InvokeInst>(I->getTerminator()))
603 InlinedLPads.insert(II->getLandingPadInst());
604
Mark Seabornef3dbb92013-12-08 00:50:58 +0000605 // Append the clauses from the outer landing pad instruction into the inlined
606 // landing pad instructions.
607 LandingPadInst *OuterLPad = Invoke.getLandingPadInst();
Craig Topper46276792014-08-24 23:23:06 +0000608 for (LandingPadInst *InlinedLPad : InlinedLPads) {
Mark Seabornef3dbb92013-12-08 00:50:58 +0000609 unsigned OuterNum = OuterLPad->getNumClauses();
610 InlinedLPad->reserveClauses(OuterNum);
611 for (unsigned OuterIdx = 0; OuterIdx != OuterNum; ++OuterIdx)
612 InlinedLPad->addClause(OuterLPad->getClause(OuterIdx));
Mark Seaborn1b3dd352013-12-08 00:51:21 +0000613 if (OuterLPad->isCleanup())
614 InlinedLPad->setCleanup(true);
Mark Seabornef3dbb92013-12-08 00:50:58 +0000615 }
616
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000617 for (Function::iterator BB = FirstNewBlock->getIterator(), E = Caller->end();
618 BB != E; ++BB) {
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000619 if (InlinedCodeInfo.ContainsCalls)
David Majnemer654e1302015-07-31 17:58:14 +0000620 if (BasicBlock *NewBB = HandleCallsInBlockInlinedThroughInvoke(
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000621 &*BB, Invoke.getOuterResumeDest()))
David Majnemer654e1302015-07-31 17:58:14 +0000622 // Update any PHI nodes in the exceptional block to indicate that there
623 // is now a new entry in them.
624 Invoke.addIncomingPHIValuesFor(NewBB);
Duncan Sands7c8fb1a2008-09-05 12:37:12 +0000625
Bill Wendling173c71f2013-03-21 23:30:12 +0000626 // Forward any resumes that are remaining here.
Bill Wendling621699d2012-01-31 01:14:49 +0000627 if (ResumeInst *RI = dyn_cast<ResumeInst>(BB->getTerminator()))
Bill Wendling56f15bf2013-03-22 20:31:05 +0000628 Invoke.forwardResume(RI, InlinedLPads);
Chris Lattner908d7952006-01-13 19:05:59 +0000629 }
630
631 // Now that everything is happy, we have one final detail. The PHI nodes in
632 // the exception destination block still have entries due to the original
Bill Wendling173c71f2013-03-21 23:30:12 +0000633 // invoke instruction. Eliminate these entries (which might even delete the
Chris Lattner908d7952006-01-13 19:05:59 +0000634 // PHI node) now.
635 InvokeDest->removePredecessor(II->getParent());
636}
637
David Majnemer654e1302015-07-31 17:58:14 +0000638/// If we inlined an invoke site, we need to convert calls
639/// in the body of the inlined function into invokes.
640///
641/// II is the invoke instruction being inlined. FirstNewBlock is the first
642/// block of the inlined code (the last block is the end of the function),
643/// and InlineCodeInfo is information about the code that got inlined.
644static void HandleInlinedEHPad(InvokeInst *II, BasicBlock *FirstNewBlock,
645 ClonedCodeInfo &InlinedCodeInfo) {
646 BasicBlock *UnwindDest = II->getUnwindDest();
647 Function *Caller = FirstNewBlock->getParent();
648
649 assert(UnwindDest->getFirstNonPHI()->isEHPad() && "unexpected BasicBlock!");
650
651 // If there are PHI nodes in the unwind destination block, we need to keep
652 // track of which values came into them from the invoke before removing the
653 // edge from this block.
654 SmallVector<Value *, 8> UnwindDestPHIValues;
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000655 BasicBlock *InvokeBB = II->getParent();
David Majnemer654e1302015-07-31 17:58:14 +0000656 for (Instruction &I : *UnwindDest) {
657 // Save the value to use for this edge.
658 PHINode *PHI = dyn_cast<PHINode>(&I);
659 if (!PHI)
660 break;
661 UnwindDestPHIValues.push_back(PHI->getIncomingValueForBlock(InvokeBB));
662 }
663
664 // Add incoming-PHI values to the unwind destination block for the given basic
665 // block, using the values for the original invoke's source block.
666 auto UpdatePHINodes = [&](BasicBlock *Src) {
667 BasicBlock::iterator I = UnwindDest->begin();
668 for (Value *V : UnwindDestPHIValues) {
669 PHINode *PHI = cast<PHINode>(I);
670 PHI->addIncoming(V, Src);
671 ++I;
672 }
673 };
674
David Majnemer8a1c45d2015-12-12 05:38:55 +0000675 // This connects all the instructions which 'unwind to caller' to the invoke
676 // destination.
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000677 UnwindDestMemoTy FuncletUnwindMap;
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000678 for (Function::iterator BB = FirstNewBlock->getIterator(), E = Caller->end();
679 BB != E; ++BB) {
David Majnemer654e1302015-07-31 17:58:14 +0000680 if (auto *CRI = dyn_cast<CleanupReturnInst>(BB->getTerminator())) {
681 if (CRI->unwindsToCaller()) {
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000682 auto *CleanupPad = CRI->getCleanupPad();
683 CleanupReturnInst::Create(CleanupPad, UnwindDest, CRI);
David Majnemer654e1302015-07-31 17:58:14 +0000684 CRI->eraseFromParent();
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000685 UpdatePHINodes(&*BB);
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000686 // Finding a cleanupret with an unwind destination would confuse
687 // subsequent calls to getUnwindDestToken, so map the cleanuppad
688 // to short-circuit any such calls and recognize this as an "unwind
689 // to caller" cleanup.
690 assert(!FuncletUnwindMap.count(CleanupPad) ||
691 isa<ConstantTokenNone>(FuncletUnwindMap[CleanupPad]));
692 FuncletUnwindMap[CleanupPad] =
693 ConstantTokenNone::get(Caller->getContext());
David Majnemer654e1302015-07-31 17:58:14 +0000694 }
695 }
David Majnemer8a1c45d2015-12-12 05:38:55 +0000696
697 Instruction *I = BB->getFirstNonPHI();
698 if (!I->isEHPad())
699 continue;
700
701 Instruction *Replacement = nullptr;
David Majnemerbbfc7212015-12-14 18:34:23 +0000702 if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(I)) {
David Majnemer8a1c45d2015-12-12 05:38:55 +0000703 if (CatchSwitch->unwindsToCaller()) {
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000704 Value *UnwindDestToken;
705 if (auto *ParentPad =
706 dyn_cast<Instruction>(CatchSwitch->getParentPad())) {
707 // This catchswitch is nested inside another funclet. If that
708 // funclet has an unwind destination within the inlinee, then
709 // unwinding out of this catchswitch would be UB. Rewriting this
710 // catchswitch to unwind to the inlined invoke's unwind dest would
711 // give the parent funclet multiple unwind destinations, which is
712 // something that subsequent EH table generation can't handle and
713 // that the veirifer rejects. So when we see such a call, leave it
714 // as "unwind to caller".
715 UnwindDestToken = getUnwindDestToken(ParentPad, FuncletUnwindMap);
716 if (UnwindDestToken && !isa<ConstantTokenNone>(UnwindDestToken))
717 continue;
718 } else {
719 // This catchswitch has no parent to inherit constraints from, and
720 // none of its descendants can have an unwind edge that exits it and
721 // targets another funclet in the inlinee. It may or may not have a
722 // descendant that definitively has an unwind to caller. In either
723 // case, we'll have to assume that any unwinds out of it may need to
724 // be routed to the caller, so treat it as though it has a definitive
725 // unwind to caller.
726 UnwindDestToken = ConstantTokenNone::get(Caller->getContext());
727 }
David Majnemer8a1c45d2015-12-12 05:38:55 +0000728 auto *NewCatchSwitch = CatchSwitchInst::Create(
729 CatchSwitch->getParentPad(), UnwindDest,
730 CatchSwitch->getNumHandlers(), CatchSwitch->getName(),
731 CatchSwitch);
732 for (BasicBlock *PadBB : CatchSwitch->handlers())
733 NewCatchSwitch->addHandler(PadBB);
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000734 // Propagate info for the old catchswitch over to the new one in
735 // the unwind map. This also serves to short-circuit any subsequent
736 // checks for the unwind dest of this catchswitch, which would get
737 // confused if they found the outer handler in the callee.
738 FuncletUnwindMap[NewCatchSwitch] = UnwindDestToken;
David Majnemer8a1c45d2015-12-12 05:38:55 +0000739 Replacement = NewCatchSwitch;
740 }
741 } else if (!isa<FuncletPadInst>(I)) {
742 llvm_unreachable("unexpected EHPad!");
743 }
744
745 if (Replacement) {
746 Replacement->takeName(I);
747 I->replaceAllUsesWith(Replacement);
748 I->eraseFromParent();
749 UpdatePHINodes(&*BB);
750 }
David Majnemer654e1302015-07-31 17:58:14 +0000751 }
752
753 if (InlinedCodeInfo.ContainsCalls)
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000754 for (Function::iterator BB = FirstNewBlock->getIterator(),
755 E = Caller->end();
756 BB != E; ++BB)
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000757 if (BasicBlock *NewBB = HandleCallsInBlockInlinedThroughInvoke(
758 &*BB, UnwindDest, &FuncletUnwindMap))
David Majnemer654e1302015-07-31 17:58:14 +0000759 // Update any PHI nodes in the exceptional block to indicate that there
760 // is now a new entry in them.
761 UpdatePHINodes(NewBB);
762
763 // Now that everything is happy, we have one final detail. The PHI nodes in
764 // the exception destination block still have entries due to the original
765 // invoke instruction. Eliminate these entries (which might even delete the
766 // PHI node) now.
767 UnwindDest->removePredecessor(InvokeBB);
768}
769
Hal Finkel50316d92016-04-28 23:00:04 +0000770/// When inlining a call site that has !llvm.mem.parallel_loop_access metadata,
771/// that metadata should be propagated to all memory-accessing cloned
772/// instructions.
773static void PropagateParallelLoopAccessMetadata(CallSite CS,
774 ValueToValueMapTy &VMap) {
775 MDNode *M =
776 CS.getInstruction()->getMetadata(LLVMContext::MD_mem_parallel_loop_access);
777 if (!M)
778 return;
779
780 for (ValueToValueMapTy::iterator VMI = VMap.begin(), VMIE = VMap.end();
781 VMI != VMIE; ++VMI) {
782 if (!VMI->second)
783 continue;
784
785 Instruction *NI = dyn_cast<Instruction>(VMI->second);
786 if (!NI)
787 continue;
788
789 if (MDNode *PM = NI->getMetadata(LLVMContext::MD_mem_parallel_loop_access)) {
790 M = MDNode::concatenate(PM, M);
791 NI->setMetadata(LLVMContext::MD_mem_parallel_loop_access, M);
792 } else if (NI->mayReadOrWriteMemory()) {
793 NI->setMetadata(LLVMContext::MD_mem_parallel_loop_access, M);
794 }
795 }
796}
797
Sanjay Patel0fdb4372015-03-10 19:42:57 +0000798/// When inlining a function that contains noalias scope metadata,
799/// this metadata needs to be cloned so that the inlined blocks
Sanjay Patel65d533c2017-01-02 19:05:11 +0000800/// have different "unique scopes" at every call site. Were this not done, then
Hal Finkel94146652014-07-24 14:25:39 +0000801/// aliasing scopes from a function inlined into a caller multiple times could
802/// not be differentiated (and this would lead to miscompiles because the
803/// non-aliasing property communicated by the metadata could have
804/// call-site-specific control dependencies).
805static void CloneAliasScopeMetadata(CallSite CS, ValueToValueMapTy &VMap) {
806 const Function *CalledFunc = CS.getCalledFunction();
807 SetVector<const MDNode *> MD;
808
809 // Note: We could only clone the metadata if it is already used in the
810 // caller. I'm omitting that check here because it might confuse
811 // inter-procedural alias analysis passes. We can revisit this if it becomes
812 // an efficiency or overhead problem.
813
Benjamin Kramer135f7352016-06-26 12:28:59 +0000814 for (const BasicBlock &I : *CalledFunc)
815 for (const Instruction &J : I) {
816 if (const MDNode *M = J.getMetadata(LLVMContext::MD_alias_scope))
Hal Finkel94146652014-07-24 14:25:39 +0000817 MD.insert(M);
Benjamin Kramer135f7352016-06-26 12:28:59 +0000818 if (const MDNode *M = J.getMetadata(LLVMContext::MD_noalias))
Hal Finkel94146652014-07-24 14:25:39 +0000819 MD.insert(M);
820 }
821
822 if (MD.empty())
823 return;
824
825 // Walk the existing metadata, adding the complete (perhaps cyclic) chain to
826 // the set.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000827 SmallVector<const Metadata *, 16> Queue(MD.begin(), MD.end());
Hal Finkel94146652014-07-24 14:25:39 +0000828 while (!Queue.empty()) {
829 const MDNode *M = cast<MDNode>(Queue.pop_back_val());
830 for (unsigned i = 0, ie = M->getNumOperands(); i != ie; ++i)
831 if (const MDNode *M1 = dyn_cast<MDNode>(M->getOperand(i)))
832 if (MD.insert(M1))
833 Queue.push_back(M1);
834 }
835
836 // Now we have a complete set of all metadata in the chains used to specify
837 // the noalias scopes and the lists of those scopes.
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000838 SmallVector<TempMDTuple, 16> DummyNodes;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000839 DenseMap<const MDNode *, TrackingMDNodeRef> MDMap;
Benjamin Kramer135f7352016-06-26 12:28:59 +0000840 for (const MDNode *I : MD) {
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000841 DummyNodes.push_back(MDTuple::getTemporary(CalledFunc->getContext(), None));
Benjamin Kramer135f7352016-06-26 12:28:59 +0000842 MDMap[I].reset(DummyNodes.back().get());
Hal Finkel94146652014-07-24 14:25:39 +0000843 }
844
845 // Create new metadata nodes to replace the dummy nodes, replacing old
846 // metadata references with either a dummy node or an already-created new
847 // node.
Benjamin Kramer135f7352016-06-26 12:28:59 +0000848 for (const MDNode *I : MD) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000849 SmallVector<Metadata *, 4> NewOps;
Benjamin Kramer135f7352016-06-26 12:28:59 +0000850 for (unsigned i = 0, ie = I->getNumOperands(); i != ie; ++i) {
851 const Metadata *V = I->getOperand(i);
Hal Finkel94146652014-07-24 14:25:39 +0000852 if (const MDNode *M = dyn_cast<MDNode>(V))
853 NewOps.push_back(MDMap[M]);
854 else
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000855 NewOps.push_back(const_cast<Metadata *>(V));
Hal Finkel94146652014-07-24 14:25:39 +0000856 }
857
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000858 MDNode *NewM = MDNode::get(CalledFunc->getContext(), NewOps);
Benjamin Kramer135f7352016-06-26 12:28:59 +0000859 MDTuple *TempM = cast<MDTuple>(MDMap[I]);
Duncan P. N. Exon Smith946fdcc2015-01-19 20:36:39 +0000860 assert(TempM->isTemporary() && "Expected temporary node");
Hal Finkel94146652014-07-24 14:25:39 +0000861
862 TempM->replaceAllUsesWith(NewM);
863 }
864
865 // Now replace the metadata in the new inlined instructions with the
866 // repacements from the map.
867 for (ValueToValueMapTy::iterator VMI = VMap.begin(), VMIE = VMap.end();
868 VMI != VMIE; ++VMI) {
869 if (!VMI->second)
870 continue;
871
872 Instruction *NI = dyn_cast<Instruction>(VMI->second);
873 if (!NI)
874 continue;
875
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000876 if (MDNode *M = NI->getMetadata(LLVMContext::MD_alias_scope)) {
Hal Finkel61c38612014-08-14 21:09:37 +0000877 MDNode *NewMD = MDMap[M];
878 // If the call site also had alias scope metadata (a list of scopes to
879 // which instructions inside it might belong), propagate those scopes to
880 // the inlined instructions.
881 if (MDNode *CSM =
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000882 CS.getInstruction()->getMetadata(LLVMContext::MD_alias_scope))
Hal Finkel61c38612014-08-14 21:09:37 +0000883 NewMD = MDNode::concatenate(NewMD, CSM);
884 NI->setMetadata(LLVMContext::MD_alias_scope, NewMD);
885 } else if (NI->mayReadOrWriteMemory()) {
886 if (MDNode *M =
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000887 CS.getInstruction()->getMetadata(LLVMContext::MD_alias_scope))
Hal Finkel61c38612014-08-14 21:09:37 +0000888 NI->setMetadata(LLVMContext::MD_alias_scope, M);
889 }
Hal Finkel94146652014-07-24 14:25:39 +0000890
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000891 if (MDNode *M = NI->getMetadata(LLVMContext::MD_noalias)) {
Hal Finkel61c38612014-08-14 21:09:37 +0000892 MDNode *NewMD = MDMap[M];
893 // If the call site also had noalias metadata (a list of scopes with
894 // which instructions inside it don't alias), propagate those scopes to
895 // the inlined instructions.
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000896 if (MDNode *CSM =
897 CS.getInstruction()->getMetadata(LLVMContext::MD_noalias))
Hal Finkel61c38612014-08-14 21:09:37 +0000898 NewMD = MDNode::concatenate(NewMD, CSM);
899 NI->setMetadata(LLVMContext::MD_noalias, NewMD);
900 } else if (NI->mayReadOrWriteMemory()) {
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000901 if (MDNode *M = CS.getInstruction()->getMetadata(LLVMContext::MD_noalias))
Hal Finkel61c38612014-08-14 21:09:37 +0000902 NI->setMetadata(LLVMContext::MD_noalias, M);
903 }
Hal Finkel94146652014-07-24 14:25:39 +0000904 }
Hal Finkel94146652014-07-24 14:25:39 +0000905}
906
Sanjay Patel0fdb4372015-03-10 19:42:57 +0000907/// If the inlined function has noalias arguments,
908/// then add new alias scopes for each noalias argument, tag the mapped noalias
Hal Finkelff0bcb62014-07-25 15:50:08 +0000909/// parameters with noalias metadata specifying the new scope, and tag all
910/// non-derived loads, stores and memory intrinsics with the new alias scopes.
911static void AddAliasScopeMetadata(CallSite CS, ValueToValueMapTy &VMap,
Chandler Carruth7b560d42015-09-09 17:55:00 +0000912 const DataLayout &DL, AAResults *CalleeAAR) {
Hal Finkelff0bcb62014-07-25 15:50:08 +0000913 if (!EnableNoAliasConversion)
914 return;
915
916 const Function *CalledFunc = CS.getCalledFunction();
917 SmallVector<const Argument *, 4> NoAliasArgs;
918
Sanjay Patel42c73552016-01-13 22:16:48 +0000919 for (const Argument &Arg : CalledFunc->args())
920 if (Arg.hasNoAliasAttr() && !Arg.use_empty())
921 NoAliasArgs.push_back(&Arg);
Hal Finkelff0bcb62014-07-25 15:50:08 +0000922
923 if (NoAliasArgs.empty())
924 return;
925
926 // To do a good job, if a noalias variable is captured, we need to know if
927 // the capture point dominates the particular use we're considering.
928 DominatorTree DT;
929 DT.recalculate(const_cast<Function&>(*CalledFunc));
930
931 // noalias indicates that pointer values based on the argument do not alias
932 // pointer values which are not based on it. So we add a new "scope" for each
933 // noalias function argument. Accesses using pointers based on that argument
934 // become part of that alias scope, accesses using pointers not based on that
935 // argument are tagged as noalias with that scope.
936
937 DenseMap<const Argument *, MDNode *> NewScopes;
938 MDBuilder MDB(CalledFunc->getContext());
939
940 // Create a new scope domain for this function.
941 MDNode *NewDomain =
942 MDB.createAnonymousAliasScopeDomain(CalledFunc->getName());
943 for (unsigned i = 0, e = NoAliasArgs.size(); i != e; ++i) {
944 const Argument *A = NoAliasArgs[i];
945
946 std::string Name = CalledFunc->getName();
947 if (A->hasName()) {
948 Name += ": %";
949 Name += A->getName();
950 } else {
951 Name += ": argument ";
952 Name += utostr(i);
953 }
954
955 // Note: We always create a new anonymous root here. This is true regardless
956 // of the linkage of the callee because the aliasing "scope" is not just a
957 // property of the callee, but also all control dependencies in the caller.
958 MDNode *NewScope = MDB.createAnonymousAliasScope(NewDomain, Name);
959 NewScopes.insert(std::make_pair(A, NewScope));
960 }
961
962 // Iterate over all new instructions in the map; for all memory-access
963 // instructions, add the alias scope metadata.
964 for (ValueToValueMapTy::iterator VMI = VMap.begin(), VMIE = VMap.end();
965 VMI != VMIE; ++VMI) {
966 if (const Instruction *I = dyn_cast<Instruction>(VMI->first)) {
967 if (!VMI->second)
968 continue;
969
970 Instruction *NI = dyn_cast<Instruction>(VMI->second);
971 if (!NI)
972 continue;
973
Hal Finkel0c083022014-09-01 09:01:39 +0000974 bool IsArgMemOnlyCall = false, IsFuncCall = false;
Hal Finkelff0bcb62014-07-25 15:50:08 +0000975 SmallVector<const Value *, 2> PtrArgs;
976
977 if (const LoadInst *LI = dyn_cast<LoadInst>(I))
978 PtrArgs.push_back(LI->getPointerOperand());
979 else if (const StoreInst *SI = dyn_cast<StoreInst>(I))
980 PtrArgs.push_back(SI->getPointerOperand());
981 else if (const VAArgInst *VAAI = dyn_cast<VAArgInst>(I))
982 PtrArgs.push_back(VAAI->getPointerOperand());
983 else if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(I))
984 PtrArgs.push_back(CXI->getPointerOperand());
985 else if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(I))
986 PtrArgs.push_back(RMWI->getPointerOperand());
Hal Finkeld2dee162014-08-14 16:44:03 +0000987 else if (ImmutableCallSite ICS = ImmutableCallSite(I)) {
Hal Finkela3708df2014-08-30 12:48:33 +0000988 // If we know that the call does not access memory, then we'll still
989 // know that about the inlined clone of this call site, and we don't
990 // need to add metadata.
Hal Finkeld2dee162014-08-14 16:44:03 +0000991 if (ICS.doesNotAccessMemory())
992 continue;
993
Hal Finkel0c083022014-09-01 09:01:39 +0000994 IsFuncCall = true;
Chandler Carruth7b560d42015-09-09 17:55:00 +0000995 if (CalleeAAR) {
996 FunctionModRefBehavior MRB = CalleeAAR->getModRefBehavior(ICS);
Chandler Carruth194f59c2015-07-22 23:15:57 +0000997 if (MRB == FMRB_OnlyAccessesArgumentPointees ||
998 MRB == FMRB_OnlyReadsArgumentPointees)
Hal Finkel0c083022014-09-01 09:01:39 +0000999 IsArgMemOnlyCall = true;
1000 }
1001
Sanjay Patele01dcab2016-01-13 21:39:26 +00001002 for (Value *Arg : ICS.args()) {
Hal Finkela3708df2014-08-30 12:48:33 +00001003 // We need to check the underlying objects of all arguments, not just
1004 // the pointer arguments, because we might be passing pointers as
1005 // integers, etc.
Hal Finkel0c083022014-09-01 09:01:39 +00001006 // However, if we know that the call only accesses pointer arguments,
Hal Finkeld2dee162014-08-14 16:44:03 +00001007 // then we only need to check the pointer arguments.
Sanjay Patele01dcab2016-01-13 21:39:26 +00001008 if (IsArgMemOnlyCall && !Arg->getType()->isPointerTy())
Hal Finkel0c083022014-09-01 09:01:39 +00001009 continue;
Hal Finkelff0bcb62014-07-25 15:50:08 +00001010
Sanjay Patele01dcab2016-01-13 21:39:26 +00001011 PtrArgs.push_back(Arg);
Hal Finkel0c083022014-09-01 09:01:39 +00001012 }
1013 }
Hal Finkelcbb85f22014-09-01 04:26:40 +00001014
Hal Finkelff0bcb62014-07-25 15:50:08 +00001015 // If we found no pointers, then this instruction is not suitable for
1016 // pairing with an instruction to receive aliasing metadata.
Hal Finkeld2dee162014-08-14 16:44:03 +00001017 // However, if this is a call, this we might just alias with none of the
1018 // noalias arguments.
Hal Finkelcbb85f22014-09-01 04:26:40 +00001019 if (PtrArgs.empty() && !IsFuncCall)
Hal Finkelff0bcb62014-07-25 15:50:08 +00001020 continue;
1021
1022 // It is possible that there is only one underlying object, but you
1023 // need to go through several PHIs to see it, and thus could be
1024 // repeated in the Objects list.
1025 SmallPtrSet<const Value *, 4> ObjSet;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001026 SmallVector<Metadata *, 4> Scopes, NoAliases;
Hal Finkelff0bcb62014-07-25 15:50:08 +00001027
1028 SmallSetVector<const Argument *, 4> NAPtrArgs;
Sanjay Patele01dcab2016-01-13 21:39:26 +00001029 for (const Value *V : PtrArgs) {
Hal Finkelff0bcb62014-07-25 15:50:08 +00001030 SmallVector<Value *, 4> Objects;
Sanjay Patele01dcab2016-01-13 21:39:26 +00001031 GetUnderlyingObjects(const_cast<Value*>(V),
Hans Wennborg083ca9b2015-10-06 23:24:35 +00001032 Objects, DL, /* LI = */ nullptr);
Hal Finkelff0bcb62014-07-25 15:50:08 +00001033
1034 for (Value *O : Objects)
1035 ObjSet.insert(O);
1036 }
1037
Hal Finkel2d3d6da2014-08-29 16:33:41 +00001038 // Figure out if we're derived from anything that is not a noalias
Hal Finkelff0bcb62014-07-25 15:50:08 +00001039 // argument.
Hal Finkela3708df2014-08-30 12:48:33 +00001040 bool CanDeriveViaCapture = false, UsesAliasingPtr = false;
1041 for (const Value *V : ObjSet) {
1042 // Is this value a constant that cannot be derived from any pointer
1043 // value (we need to exclude constant expressions, for example, that
1044 // are formed from arithmetic on global symbols).
1045 bool IsNonPtrConst = isa<ConstantInt>(V) || isa<ConstantFP>(V) ||
1046 isa<ConstantPointerNull>(V) ||
1047 isa<ConstantDataVector>(V) || isa<UndefValue>(V);
Hal Finkelcbb85f22014-09-01 04:26:40 +00001048 if (IsNonPtrConst)
1049 continue;
1050
1051 // If this is anything other than a noalias argument, then we cannot
1052 // completely describe the aliasing properties using alias.scope
1053 // metadata (and, thus, won't add any).
1054 if (const Argument *A = dyn_cast<Argument>(V)) {
1055 if (!A->hasNoAliasAttr())
1056 UsesAliasingPtr = true;
1057 } else {
Hal Finkela3708df2014-08-30 12:48:33 +00001058 UsesAliasingPtr = true;
Hal Finkelff0bcb62014-07-25 15:50:08 +00001059 }
Hal Finkelcbb85f22014-09-01 04:26:40 +00001060
1061 // If this is not some identified function-local object (which cannot
1062 // directly alias a noalias argument), or some other argument (which,
1063 // by definition, also cannot alias a noalias argument), then we could
1064 // alias a noalias argument that has been captured).
1065 if (!isa<Argument>(V) &&
1066 !isIdentifiedFunctionLocal(const_cast<Value*>(V)))
1067 CanDeriveViaCapture = true;
Hal Finkela3708df2014-08-30 12:48:33 +00001068 }
Hal Finkelcbb85f22014-09-01 04:26:40 +00001069
1070 // A function call can always get captured noalias pointers (via other
1071 // parameters, globals, etc.).
1072 if (IsFuncCall && !IsArgMemOnlyCall)
1073 CanDeriveViaCapture = true;
1074
Hal Finkelff0bcb62014-07-25 15:50:08 +00001075 // First, we want to figure out all of the sets with which we definitely
1076 // don't alias. Iterate over all noalias set, and add those for which:
1077 // 1. The noalias argument is not in the set of objects from which we
1078 // definitely derive.
1079 // 2. The noalias argument has not yet been captured.
Hal Finkelcbb85f22014-09-01 04:26:40 +00001080 // An arbitrary function that might load pointers could see captured
1081 // noalias arguments via other noalias arguments or globals, and so we
1082 // must always check for prior capture.
Hal Finkelff0bcb62014-07-25 15:50:08 +00001083 for (const Argument *A : NoAliasArgs) {
1084 if (!ObjSet.count(A) && (!CanDeriveViaCapture ||
Hal Finkela3708df2014-08-30 12:48:33 +00001085 // It might be tempting to skip the
1086 // PointerMayBeCapturedBefore check if
1087 // A->hasNoCaptureAttr() is true, but this is
1088 // incorrect because nocapture only guarantees
1089 // that no copies outlive the function, not
1090 // that the value cannot be locally captured.
Hal Finkelff0bcb62014-07-25 15:50:08 +00001091 !PointerMayBeCapturedBefore(A,
1092 /* ReturnCaptures */ false,
1093 /* StoreCaptures */ false, I, &DT)))
1094 NoAliases.push_back(NewScopes[A]);
1095 }
1096
1097 if (!NoAliases.empty())
Duncan P. N. Exon Smith3872d002014-11-01 00:10:31 +00001098 NI->setMetadata(LLVMContext::MD_noalias,
1099 MDNode::concatenate(
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001100 NI->getMetadata(LLVMContext::MD_noalias),
Duncan P. N. Exon Smith3872d002014-11-01 00:10:31 +00001101 MDNode::get(CalledFunc->getContext(), NoAliases)));
Hal Finkela3708df2014-08-30 12:48:33 +00001102
Hal Finkelff0bcb62014-07-25 15:50:08 +00001103 // Next, we want to figure out all of the sets to which we might belong.
Hal Finkela3708df2014-08-30 12:48:33 +00001104 // We might belong to a set if the noalias argument is in the set of
1105 // underlying objects. If there is some non-noalias argument in our list
1106 // of underlying objects, then we cannot add a scope because the fact
1107 // that some access does not alias with any set of our noalias arguments
1108 // cannot itself guarantee that it does not alias with this access
1109 // (because there is some pointer of unknown origin involved and the
1110 // other access might also depend on this pointer). We also cannot add
1111 // scopes to arbitrary functions unless we know they don't access any
1112 // non-parameter pointer-values.
1113 bool CanAddScopes = !UsesAliasingPtr;
Hal Finkelcbb85f22014-09-01 04:26:40 +00001114 if (CanAddScopes && IsFuncCall)
1115 CanAddScopes = IsArgMemOnlyCall;
Hal Finkelff0bcb62014-07-25 15:50:08 +00001116
Hal Finkela3708df2014-08-30 12:48:33 +00001117 if (CanAddScopes)
1118 for (const Argument *A : NoAliasArgs) {
1119 if (ObjSet.count(A))
1120 Scopes.push_back(NewScopes[A]);
1121 }
1122
Hal Finkelff0bcb62014-07-25 15:50:08 +00001123 if (!Scopes.empty())
Duncan P. N. Exon Smith3872d002014-11-01 00:10:31 +00001124 NI->setMetadata(
1125 LLVMContext::MD_alias_scope,
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001126 MDNode::concatenate(NI->getMetadata(LLVMContext::MD_alias_scope),
Duncan P. N. Exon Smith3872d002014-11-01 00:10:31 +00001127 MDNode::get(CalledFunc->getContext(), Scopes)));
Hal Finkelff0bcb62014-07-25 15:50:08 +00001128 }
1129 }
1130}
1131
Hans Wennborg2d5841f2017-02-27 22:33:02 +00001132/// If the inlined function has non-byval align arguments, then
1133/// add @llvm.assume-based alignment assumptions to preserve this information.
1134static void AddAlignmentAssumptions(CallSite CS, InlineFunctionInfo &IFI) {
1135 if (!PreserveAlignmentAssumptions || !IFI.GetAssumptionCache)
Hal Finkel68dc3c72014-10-15 23:44:41 +00001136 return;
Sanjay Patelaea60842016-12-31 17:54:05 +00001137
1138 AssumptionCache *AC = &(*IFI.GetAssumptionCache)(*CS.getCaller());
Mehdi Amini46a43552015-03-04 18:43:29 +00001139 auto &DL = CS.getCaller()->getParent()->getDataLayout();
Hal Finkel68dc3c72014-10-15 23:44:41 +00001140
Hans Wennborg2d5841f2017-02-27 22:33:02 +00001141 // To avoid inserting redundant assumptions, we should check for assumptions
1142 // already in the caller. To do this, we might need a DT of the caller.
Hal Finkel68dc3c72014-10-15 23:44:41 +00001143 DominatorTree DT;
1144 bool DTCalculated = false;
1145
Chandler Carruth66b31302015-01-04 12:03:27 +00001146 Function *CalledFunc = CS.getCalledFunction();
Sanjay Patelada717e2017-02-15 14:56:11 +00001147 for (Argument &Arg : CalledFunc->args()) {
Sanjay Patel40975e02017-02-27 18:13:48 +00001148 unsigned Align = Arg.getType()->isPointerTy() ? Arg.getParamAlignment() : 0;
Hans Wennborg2d5841f2017-02-27 22:33:02 +00001149 if (Align && !Arg.hasByValOrInAllocaAttr() && !Arg.hasNUses(0)) {
1150 if (!DTCalculated) {
1151 DT.recalculate(*CS.getCaller());
1152 DTCalculated = true;
1153 }
1154
Hal Finkel68dc3c72014-10-15 23:44:41 +00001155 // If we can already prove the asserted alignment in the context of the
1156 // caller, then don't bother inserting the assumption.
Hans Wennborg2d5841f2017-02-27 22:33:02 +00001157 Value *ArgVal = CS.getArgument(Arg.getArgNo());
1158 if (getKnownAlignment(ArgVal, DL, CS.getInstruction(), AC, &DT) >= Align)
1159 continue;
Hal Finkel68dc3c72014-10-15 23:44:41 +00001160
Hans Wennborg2d5841f2017-02-27 22:33:02 +00001161 CallInst *NewAsmp = IRBuilder<>(CS.getInstruction())
1162 .CreateAlignmentAssumption(DL, ArgVal, Align);
1163 AC->registerAssumption(NewAsmp);
Hal Finkel68dc3c72014-10-15 23:44:41 +00001164 }
1165 }
1166}
1167
Sanjay Patel0fdb4372015-03-10 19:42:57 +00001168/// Once we have cloned code over from a callee into the caller,
1169/// update the specified callgraph to reflect the changes we made.
1170/// Note that it's possible that not all code was copied over, so only
Duncan Sands46911f12008-09-08 11:05:51 +00001171/// some edges of the callgraph may remain.
1172static void UpdateCallGraphAfterInlining(CallSite CS,
Chris Lattner5de3b8b2006-07-12 18:29:36 +00001173 Function::iterator FirstNewBlock,
Rafael Espindola229e38f2010-10-13 01:36:30 +00001174 ValueToValueMapTy &VMap,
Chris Lattner2eee5d32010-04-22 23:37:35 +00001175 InlineFunctionInfo &IFI) {
1176 CallGraph &CG = *IFI.CG;
Sanjay Patel32d753c2017-02-15 15:08:38 +00001177 const Function *Caller = CS.getCaller();
Duncan Sands46911f12008-09-08 11:05:51 +00001178 const Function *Callee = CS.getCalledFunction();
Chris Lattner0841fb12006-01-14 20:07:50 +00001179 CallGraphNode *CalleeNode = CG[Callee];
1180 CallGraphNode *CallerNode = CG[Caller];
Duncan Sands7c8fb1a2008-09-05 12:37:12 +00001181
Chris Lattner5de3b8b2006-07-12 18:29:36 +00001182 // Since we inlined some uninlined call sites in the callee into the caller,
Chris Lattner0841fb12006-01-14 20:07:50 +00001183 // add edges from the caller to all of the callees of the callee.
Gabor Greif5aa19222009-01-15 18:40:09 +00001184 CallGraphNode::iterator I = CalleeNode->begin(), E = CalleeNode->end();
1185
1186 // Consider the case where CalleeNode == CallerNode.
Gabor Greiff1abfdc2009-01-17 00:09:08 +00001187 CallGraphNode::CalledFunctionsVector CallCache;
Gabor Greif5aa19222009-01-15 18:40:09 +00001188 if (CalleeNode == CallerNode) {
1189 CallCache.assign(I, E);
1190 I = CallCache.begin();
1191 E = CallCache.end();
1192 }
1193
1194 for (; I != E; ++I) {
Chris Lattner063d0652009-09-01 06:31:31 +00001195 const Value *OrigCall = I->first;
Duncan Sands7c8fb1a2008-09-05 12:37:12 +00001196
Rafael Espindola229e38f2010-10-13 01:36:30 +00001197 ValueToValueMapTy::iterator VMI = VMap.find(OrigCall);
Chris Lattnerb3c64f72006-07-12 21:37:11 +00001198 // Only copy the edge if the call was inlined!
Craig Topperf40110f2014-04-25 05:29:35 +00001199 if (VMI == VMap.end() || VMI->second == nullptr)
Chris Lattner5eef6ad2009-08-27 03:51:50 +00001200 continue;
1201
1202 // If the call was inlined, but then constant folded, there is no edge to
1203 // add. Check for this case.
Chris Lattner016c00a2010-04-22 21:31:00 +00001204 Instruction *NewCall = dyn_cast<Instruction>(VMI->second);
Sanjay Patelc04b6f22015-03-11 15:12:32 +00001205 if (!NewCall)
1206 continue;
Chris Lattnerc2432b92010-05-01 01:26:13 +00001207
Sanjay Patelc04b6f22015-03-11 15:12:32 +00001208 // We do not treat intrinsic calls like real function calls because we
1209 // expect them to become inline code; do not add an edge for an intrinsic.
1210 CallSite CS = CallSite(NewCall);
1211 if (CS && CS.getCalledFunction() && CS.getCalledFunction()->isIntrinsic())
1212 continue;
1213
Chris Lattnerc2432b92010-05-01 01:26:13 +00001214 // Remember that this call site got inlined for the client of
1215 // InlineFunction.
1216 IFI.InlinedCalls.push_back(NewCall);
1217
Chris Lattner016c00a2010-04-22 21:31:00 +00001218 // It's possible that inlining the callsite will cause it to go from an
1219 // indirect to a direct call by resolving a function pointer. If this
1220 // happens, set the callee of the new call site to a more precise
1221 // destination. This can also happen if the call graph node of the caller
1222 // was just unnecessarily imprecise.
Craig Topperf40110f2014-04-25 05:29:35 +00001223 if (!I->second->getFunction())
Chris Lattner016c00a2010-04-22 21:31:00 +00001224 if (Function *F = CallSite(NewCall).getCalledFunction()) {
1225 // Indirect call site resolved to direct call.
Gabor Greif7b0a5fd2010-07-27 15:02:37 +00001226 CallerNode->addCalledFunction(CallSite(NewCall), CG[F]);
1227
Chris Lattner016c00a2010-04-22 21:31:00 +00001228 continue;
1229 }
Gabor Greif7b0a5fd2010-07-27 15:02:37 +00001230
1231 CallerNode->addCalledFunction(CallSite(NewCall), I->second);
Chris Lattner5de3b8b2006-07-12 18:29:36 +00001232 }
Chris Lattner5eef6ad2009-08-27 03:51:50 +00001233
Dale Johannesen0aeabdf2009-01-13 22:43:37 +00001234 // Update the call graph by deleting the edge from Callee to Caller. We must
1235 // do this after the loop above in case Caller and Callee are the same.
1236 CallerNode->removeCallEdgeFor(CS);
Chris Lattner0841fb12006-01-14 20:07:50 +00001237}
1238
Julien Lerouge957e91c2014-04-15 18:01:54 +00001239static void HandleByValArgumentInit(Value *Dst, Value *Src, Module *M,
1240 BasicBlock *InsertBlock,
1241 InlineFunctionInfo &IFI) {
Julien Lerouge957e91c2014-04-15 18:01:54 +00001242 Type *AggTy = cast<PointerType>(Src->getType())->getElementType();
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001243 IRBuilder<> Builder(InsertBlock, InsertBlock->begin());
Julien Lerouge957e91c2014-04-15 18:01:54 +00001244
Mehdi Amini46a43552015-03-04 18:43:29 +00001245 Value *Size = Builder.getInt64(M->getDataLayout().getTypeStoreSize(AggTy));
Julien Lerouge957e91c2014-04-15 18:01:54 +00001246
1247 // Always generate a memcpy of alignment 1 here because we don't know
1248 // the alignment of the src pointer. Other optimizations can infer
1249 // better alignment.
Pete Cooper67cf9a72015-11-19 05:56:52 +00001250 Builder.CreateMemCpy(Dst, Src, Size, /*Align=*/1);
Julien Lerouge957e91c2014-04-15 18:01:54 +00001251}
1252
Sanjay Patel0fdb4372015-03-10 19:42:57 +00001253/// When inlining a call site that has a byval argument,
Chris Lattner0f114952010-12-20 08:10:40 +00001254/// we have to make the implicit memcpy explicit by adding it.
David Majnemer120f4a02013-11-03 12:22:13 +00001255static Value *HandleByValArgument(Value *Arg, Instruction *TheCall,
Chris Lattner00997442010-12-20 07:57:41 +00001256 const Function *CalledFunc,
1257 InlineFunctionInfo &IFI,
Reid Klecknerdd3f3ed2014-11-04 02:02:14 +00001258 unsigned ByValAlignment) {
Matt Arsenaultbe558882014-04-23 20:58:57 +00001259 PointerType *ArgTy = cast<PointerType>(Arg->getType());
1260 Type *AggTy = ArgTy->getElementType();
Chris Lattner0f114952010-12-20 08:10:40 +00001261
Sanjay Patel288f0752017-02-15 15:22:18 +00001262 Function *Caller = TheCall->getFunction();
Matt Arsenault3c1fc762017-04-10 22:27:50 +00001263 const DataLayout &DL = Caller->getParent()->getDataLayout();
Chandler Carruth66b31302015-01-04 12:03:27 +00001264
Chris Lattner0f114952010-12-20 08:10:40 +00001265 // If the called function is readonly, then it could not mutate the caller's
1266 // copy of the byval'd memory. In this case, it is safe to elide the copy and
1267 // temporary.
David Majnemer120f4a02013-11-03 12:22:13 +00001268 if (CalledFunc->onlyReadsMemory()) {
Chris Lattner0f114952010-12-20 08:10:40 +00001269 // If the byval argument has a specified alignment that is greater than the
1270 // passed in pointer, then we either have to round up the input pointer or
1271 // give up on this transformation.
1272 if (ByValAlignment <= 1) // 0 = unspecified, 1 = no particular alignment.
David Majnemer120f4a02013-11-03 12:22:13 +00001273 return Arg;
Chris Lattner0f114952010-12-20 08:10:40 +00001274
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001275 AssumptionCache *AC =
1276 IFI.GetAssumptionCache ? &(*IFI.GetAssumptionCache)(*Caller) : nullptr;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001277
Chris Lattner20fca482010-12-25 20:42:38 +00001278 // If the pointer is already known to be sufficiently aligned, or if we can
1279 // round it up to a larger alignment, then we don't need a temporary.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001280 if (getOrEnforceKnownAlignment(Arg, ByValAlignment, DL, TheCall, AC) >=
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001281 ByValAlignment)
David Majnemer120f4a02013-11-03 12:22:13 +00001282 return Arg;
Matt Arsenault3c1fc762017-04-10 22:27:50 +00001283
Chris Lattner20fca482010-12-25 20:42:38 +00001284 // Otherwise, we have to make a memcpy to get a safe alignment. This is bad
1285 // for code quality, but rarely happens and is required for correctness.
Chris Lattner0f114952010-12-20 08:10:40 +00001286 }
Chris Lattner00997442010-12-20 07:57:41 +00001287
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001288 // Create the alloca. If we have DataLayout, use nice alignment.
Matt Arsenault3c1fc762017-04-10 22:27:50 +00001289 unsigned Align = DL.getPrefTypeAlignment(AggTy);
Mehdi Amini46a43552015-03-04 18:43:29 +00001290
Chris Lattner00997442010-12-20 07:57:41 +00001291 // If the byval had an alignment specified, we *must* use at least that
1292 // alignment, as it is required by the byval argument (and uses of the
1293 // pointer inside the callee).
1294 Align = std::max(Align, ByValAlignment);
Matt Arsenault3c1fc762017-04-10 22:27:50 +00001295
1296 Value *NewAlloca = new AllocaInst(AggTy, DL.getAllocaAddrSpace(),
1297 nullptr, Align, Arg->getName(),
Chris Lattner00997442010-12-20 07:57:41 +00001298 &*Caller->begin()->begin());
Julien Lerougebe4fe322014-04-15 18:06:46 +00001299 IFI.StaticAllocas.push_back(cast<AllocaInst>(NewAlloca));
Matt Arsenault3c1fc762017-04-10 22:27:50 +00001300
Chris Lattner00997442010-12-20 07:57:41 +00001301 // Uses of the argument in the function should use our new alloca
1302 // instead.
1303 return NewAlloca;
1304}
1305
Sanjay Patel0fdb4372015-03-10 19:42:57 +00001306// Check whether this Value is used by a lifetime intrinsic.
Nick Lewyckya68ec832011-05-22 05:22:10 +00001307static bool isUsedByLifetimeMarker(Value *V) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001308 for (User *U : V->users()) {
1309 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U)) {
Nick Lewyckya68ec832011-05-22 05:22:10 +00001310 switch (II->getIntrinsicID()) {
1311 default: break;
1312 case Intrinsic::lifetime_start:
1313 case Intrinsic::lifetime_end:
1314 return true;
1315 }
1316 }
1317 }
1318 return false;
1319}
1320
Sanjay Patel0fdb4372015-03-10 19:42:57 +00001321// Check whether the given alloca already has
Nick Lewyckya68ec832011-05-22 05:22:10 +00001322// lifetime.start or lifetime.end intrinsics.
1323static bool hasLifetimeMarkers(AllocaInst *AI) {
Matt Arsenaultbe558882014-04-23 20:58:57 +00001324 Type *Ty = AI->getType();
1325 Type *Int8PtrTy = Type::getInt8PtrTy(Ty->getContext(),
1326 Ty->getPointerAddressSpace());
1327 if (Ty == Int8PtrTy)
Nick Lewyckya68ec832011-05-22 05:22:10 +00001328 return isUsedByLifetimeMarker(AI);
1329
Nick Lewycky9711b5c2011-06-14 00:59:24 +00001330 // Do a scan to find all the casts to i8*.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001331 for (User *U : AI->users()) {
1332 if (U->getType() != Int8PtrTy) continue;
1333 if (U->stripPointerCasts() != AI) continue;
1334 if (isUsedByLifetimeMarker(U))
Nick Lewyckya68ec832011-05-22 05:22:10 +00001335 return true;
1336 }
1337 return false;
1338}
1339
Reid Kleckner6ee00a22016-08-12 22:23:04 +00001340/// Return the result of AI->isStaticAlloca() if AI were moved to the entry
1341/// block. Allocas used in inalloca calls and allocas of dynamic array size
1342/// cannot be static.
1343static bool allocaWouldBeStaticInEntry(const AllocaInst *AI ) {
1344 return isa<Constant>(AI->getArraySize()) && !AI->isUsedWithInAlloca();
1345}
1346
Adrian Prantld4056502017-03-07 17:28:57 +00001347/// Update inlined instructions' line numbers to
1348/// to encode location where these instructions are inlined.
1349static void fixupLineNumbers(Function *Fn, Function::iterator FI,
1350 Instruction *TheCall, bool CalleeHasDebugInfo) {
Benjamin Kramer4ca41fd2016-06-12 17:30:47 +00001351 const DebugLoc &TheCallDL = TheCall->getDebugLoc();
Adrian Prantld4056502017-03-07 17:28:57 +00001352 if (!TheCallDL)
1353 return;
Devang Patel35797402011-07-08 18:01:31 +00001354
David Blaikiedf706282015-01-21 22:57:29 +00001355 auto &Ctx = Fn->getContext();
Adrian Prantld4056502017-03-07 17:28:57 +00001356 DILocation *InlinedAtNode = TheCallDL;
David Blaikiedf706282015-01-21 22:57:29 +00001357
1358 // Create a unique call site, not to be confused with any other call from the
1359 // same location.
Adrian Prantld4056502017-03-07 17:28:57 +00001360 InlinedAtNode = DILocation::getDistinct(
1361 Ctx, InlinedAtNode->getLine(), InlinedAtNode->getColumn(),
1362 InlinedAtNode->getScope(), InlinedAtNode->getInlinedAt());
David Blaikiedf706282015-01-21 22:57:29 +00001363
1364 // Cache the inlined-at nodes as they're built so they are reused, without
1365 // this every instruction's inlined-at chain would become distinct from each
1366 // other.
Adrian Prantlc10d0e52017-05-09 19:47:37 +00001367 DenseMap<const MDNode *, MDNode *> IANodes;
David Blaikiedf706282015-01-21 22:57:29 +00001368
Devang Patel35797402011-07-08 18:01:31 +00001369 for (; FI != Fn->end(); ++FI) {
1370 for (BasicBlock::iterator BI = FI->begin(), BE = FI->end();
1371 BI != BE; ++BI) {
Andrea Di Biagioeff22832016-12-07 12:01:45 +00001372 if (DebugLoc DL = BI->getDebugLoc()) {
Adrian Prantlc10d0e52017-05-09 19:47:37 +00001373 auto IA = DebugLoc::appendInlinedAt(DL, InlinedAtNode, BI->getContext(),
1374 IANodes);
1375 auto IDL = DebugLoc::get(DL.getLine(), DL.getCol(), DL.getScope(), IA);
1376 BI->setDebugLoc(IDL);
Andrea Di Biagioeff22832016-12-07 12:01:45 +00001377 continue;
Devang Patelbb23a4a2011-08-10 21:50:54 +00001378 }
Andrea Di Biagioeff22832016-12-07 12:01:45 +00001379
1380 if (CalleeHasDebugInfo)
1381 continue;
1382
1383 // If the inlined instruction has no line number, make it look as if it
1384 // originates from the call location. This is important for
1385 // ((__always_inline__, __nodebug__)) functions which must use caller
1386 // location for all instructions in their function body.
1387
1388 // Don't update static allocas, as they may get moved later.
1389 if (auto *AI = dyn_cast<AllocaInst>(BI))
1390 if (allocaWouldBeStaticInEntry(AI))
1391 continue;
1392
1393 BI->setDebugLoc(TheCallDL);
Devang Patel35797402011-07-08 18:01:31 +00001394 }
1395 }
1396}
Eugene Zelenko6cadde72017-10-17 21:27:42 +00001397
Easwaran Raman12585b02017-01-20 22:44:04 +00001398/// Update the block frequencies of the caller after a callee has been inlined.
1399///
1400/// Each block cloned into the caller has its block frequency scaled by the
1401/// ratio of CallSiteFreq/CalleeEntryFreq. This ensures that the cloned copy of
1402/// callee's entry block gets the same frequency as the callsite block and the
1403/// relative frequencies of all cloned blocks remain the same after cloning.
1404static void updateCallerBFI(BasicBlock *CallSiteBlock,
1405 const ValueToValueMapTy &VMap,
1406 BlockFrequencyInfo *CallerBFI,
1407 BlockFrequencyInfo *CalleeBFI,
1408 const BasicBlock &CalleeEntryBlock) {
1409 SmallPtrSet<BasicBlock *, 16> ClonedBBs;
1410 for (auto const &Entry : VMap) {
1411 if (!isa<BasicBlock>(Entry.first) || !Entry.second)
1412 continue;
1413 auto *OrigBB = cast<BasicBlock>(Entry.first);
1414 auto *ClonedBB = cast<BasicBlock>(Entry.second);
Easwaran Raman5a12f232017-02-14 22:49:28 +00001415 uint64_t Freq = CalleeBFI->getBlockFreq(OrigBB).getFrequency();
1416 if (!ClonedBBs.insert(ClonedBB).second) {
1417 // Multiple blocks in the callee might get mapped to one cloned block in
1418 // the caller since we prune the callee as we clone it. When that happens,
1419 // we want to use the maximum among the original blocks' frequencies.
1420 uint64_t NewFreq = CallerBFI->getBlockFreq(ClonedBB).getFrequency();
1421 if (NewFreq > Freq)
1422 Freq = NewFreq;
1423 }
1424 CallerBFI->setBlockFreq(ClonedBB, Freq);
Easwaran Raman12585b02017-01-20 22:44:04 +00001425 }
1426 BasicBlock *EntryClone = cast<BasicBlock>(VMap.lookup(&CalleeEntryBlock));
1427 CallerBFI->setBlockFreqAndScale(
1428 EntryClone, CallerBFI->getBlockFreq(CallSiteBlock).getFrequency(),
1429 ClonedBBs);
1430}
1431
Dehao Chene5930492017-03-20 16:40:44 +00001432/// Update the branch metadata for cloned call instructions.
1433static void updateCallProfile(Function *Callee, const ValueToValueMapTy &VMap,
1434 const Optional<uint64_t> &CalleeEntryCount,
Easwaran Ramanf5f91602017-05-09 23:21:10 +00001435 const Instruction *TheCall,
Teresa Johnson525dcb62017-05-22 20:28:18 +00001436 ProfileSummaryInfo *PSI,
1437 BlockFrequencyInfo *CallerBFI) {
Dehao Chene5930492017-03-20 16:40:44 +00001438 if (!CalleeEntryCount.hasValue() || CalleeEntryCount.getValue() < 1)
1439 return;
1440 Optional<uint64_t> CallSiteCount =
Teresa Johnson525dcb62017-05-22 20:28:18 +00001441 PSI ? PSI->getProfileCount(TheCall, CallerBFI) : None;
Dehao Chene5930492017-03-20 16:40:44 +00001442 uint64_t CallCount =
1443 std::min(CallSiteCount.hasValue() ? CallSiteCount.getValue() : 0,
1444 CalleeEntryCount.getValue());
1445
1446 for (auto const &Entry : VMap)
David Blaikie795dc942017-03-20 18:01:07 +00001447 if (isa<CallInst>(Entry.first))
1448 if (auto *CI = dyn_cast_or_null<CallInst>(Entry.second))
1449 CI->updateProfWeight(CallCount, CalleeEntryCount.getValue());
Dehao Chene5930492017-03-20 16:40:44 +00001450 for (BasicBlock &BB : *Callee)
1451 // No need to update the callsite if it is pruned during inlining.
1452 if (VMap.count(&BB))
1453 for (Instruction &I : BB)
1454 if (CallInst *CI = dyn_cast<CallInst>(&I))
1455 CI->updateProfWeight(CalleeEntryCount.getValue() - CallCount,
1456 CalleeEntryCount.getValue());
1457}
1458
Easwaran Raman12585b02017-01-20 22:44:04 +00001459/// Update the entry count of callee after inlining.
1460///
1461/// The callsite's block count is subtracted from the callee's function entry
1462/// count.
Dehao Chene5930492017-03-20 16:40:44 +00001463static void updateCalleeCount(BlockFrequencyInfo *CallerBFI, BasicBlock *CallBB,
Easwaran Ramanf5f91602017-05-09 23:21:10 +00001464 Instruction *CallInst, Function *Callee,
1465 ProfileSummaryInfo *PSI) {
Easwaran Raman12585b02017-01-20 22:44:04 +00001466 // If the callee has a original count of N, and the estimated count of
1467 // callsite is M, the new callee count is set to N - M. M is estimated from
1468 // the caller's entry count, its entry block frequency and the block frequency
1469 // of the callsite.
1470 Optional<uint64_t> CalleeCount = Callee->getEntryCount();
Easwaran Ramanf5f91602017-05-09 23:21:10 +00001471 if (!CalleeCount.hasValue() || !PSI)
Easwaran Raman12585b02017-01-20 22:44:04 +00001472 return;
Easwaran Ramanf5f91602017-05-09 23:21:10 +00001473 Optional<uint64_t> CallCount = PSI->getProfileCount(CallInst, CallerBFI);
Dehao Chene5930492017-03-20 16:40:44 +00001474 if (!CallCount.hasValue())
Easwaran Raman12585b02017-01-20 22:44:04 +00001475 return;
1476 // Since CallSiteCount is an estimate, it could exceed the original callee
1477 // count and has to be set to 0.
Dehao Chene5930492017-03-20 16:40:44 +00001478 if (CallCount.getValue() > CalleeCount.getValue())
Easwaran Raman12585b02017-01-20 22:44:04 +00001479 Callee->setEntryCount(0);
1480 else
Dehao Chene5930492017-03-20 16:40:44 +00001481 Callee->setEntryCount(CalleeCount.getValue() - CallCount.getValue());
Easwaran Raman12585b02017-01-20 22:44:04 +00001482}
Devang Patel35797402011-07-08 18:01:31 +00001483
Sanjay Patel0fdb4372015-03-10 19:42:57 +00001484/// This function inlines the called function into the basic block of the
1485/// caller. This returns false if it is not possible to inline this call.
1486/// The program is still in a well defined state if this occurs though.
Bill Wendlingce0c2292012-01-31 01:01:16 +00001487///
1488/// Note that this only does one level of inlining. For example, if the
1489/// instruction 'call B' is inlined, and 'B' calls 'C', then the call to 'C' now
1490/// exists in the instruction stream. Similarly this will inline a recursive
1491/// function by one level.
Eric Christopherf16bee82012-03-26 19:09:38 +00001492bool llvm::InlineFunction(CallSite CS, InlineFunctionInfo &IFI,
Florian Hahn0e9dec62017-11-13 10:35:52 +00001493 AAResults *CalleeAAR, bool InsertLifetime,
1494 Function *ForwardVarArgsTo) {
Chris Lattner0cc265e2003-08-24 06:59:16 +00001495 Instruction *TheCall = CS.getInstruction();
Sanjay Patel288f0752017-02-15 15:22:18 +00001496 assert(TheCall->getParent() && TheCall->getFunction()
1497 && "Instruction not in function!");
Chris Lattner530d4bf2003-05-29 15:11:31 +00001498
Chris Lattner4ba01ec2010-04-22 23:07:58 +00001499 // If IFI has any state in it, zap it before we fill it in.
1500 IFI.reset();
Easwaran Raman12585b02017-01-20 22:44:04 +00001501
1502 Function *CalledFunc = CS.getCalledFunction();
Florian Hahn80788d82018-01-06 19:45:40 +00001503 if (!CalledFunc || // Can't inline external function or indirect
1504 CalledFunc->isDeclaration()) // call!
1505 return false;
Chris Lattner530d4bf2003-05-29 15:11:31 +00001506
Sanjoy Das2d161452015-11-18 06:23:38 +00001507 // The inliner does not know how to inline through calls with operand bundles
1508 // in general ...
1509 if (CS.hasOperandBundles()) {
David Majnemer3bb88c02015-12-15 21:27:27 +00001510 for (int i = 0, e = CS.getNumOperandBundles(); i != e; ++i) {
1511 uint32_t Tag = CS.getOperandBundleAt(i).getTagID();
1512 // ... but it knows how to inline through "deopt" operand bundles ...
1513 if (Tag == LLVMContext::OB_deopt)
1514 continue;
1515 // ... and "funclet" operand bundles.
1516 if (Tag == LLVMContext::OB_funclet)
1517 continue;
1518
Sanjoy Das2d161452015-11-18 06:23:38 +00001519 return false;
David Majnemer3bb88c02015-12-15 21:27:27 +00001520 }
Sanjoy Das2d161452015-11-18 06:23:38 +00001521 }
Sanjoy Das0a1bee82015-10-23 20:09:55 +00001522
Duncan Sandsaa31b922007-12-19 21:13:37 +00001523 // If the call to the callee cannot throw, set the 'nounwind' flag on any
1524 // calls that we inline.
1525 bool MarkNoUnwind = CS.doesNotThrow();
1526
Chris Lattner0cc265e2003-08-24 06:59:16 +00001527 BasicBlock *OrigBB = TheCall->getParent();
Chris Lattner530d4bf2003-05-29 15:11:31 +00001528 Function *Caller = OrigBB->getParent();
1529
Gordon Henriksenb969c592007-12-25 03:10:07 +00001530 // GC poses two hazards to inlining, which only occur when the callee has GC:
1531 // 1. If the caller has no GC, then the callee's GC must be propagated to the
1532 // caller.
1533 // 2. If the caller has a differing GC, it is invalid to inline.
Gordon Henriksend930f912008-08-17 18:44:35 +00001534 if (CalledFunc->hasGC()) {
1535 if (!Caller->hasGC())
1536 Caller->setGC(CalledFunc->getGC());
1537 else if (CalledFunc->getGC() != Caller->getGC())
Gordon Henriksenb969c592007-12-25 03:10:07 +00001538 return false;
1539 }
Duncan Sands7c8fb1a2008-09-05 12:37:12 +00001540
Benjamin Kramer4d2b8712011-12-02 18:37:31 +00001541 // Get the personality function from the callee if it contains a landing pad.
David Majnemer7fddecc2015-06-17 20:52:32 +00001542 Constant *CalledPersonality =
David Majnemereba62792015-10-13 22:08:17 +00001543 CalledFunc->hasPersonalityFn()
1544 ? CalledFunc->getPersonalityFn()->stripPointerCasts()
1545 : nullptr;
Benjamin Kramer4d2b8712011-12-02 18:37:31 +00001546
Bill Wendling55421f02011-08-14 08:01:36 +00001547 // Find the personality function used by the landing pads of the caller. If it
1548 // exists, then check to see that it matches the personality function used in
1549 // the callee.
David Majnemer7fddecc2015-06-17 20:52:32 +00001550 Constant *CallerPersonality =
David Majnemereba62792015-10-13 22:08:17 +00001551 Caller->hasPersonalityFn()
1552 ? Caller->getPersonalityFn()->stripPointerCasts()
1553 : nullptr;
David Majnemer7fddecc2015-06-17 20:52:32 +00001554 if (CalledPersonality) {
1555 if (!CallerPersonality)
1556 Caller->setPersonalityFn(CalledPersonality);
1557 // If the personality functions match, then we can perform the
1558 // inlining. Otherwise, we can't inline.
1559 // TODO: This isn't 100% true. Some personality functions are proper
1560 // supersets of others and can be used in place of the other.
1561 else if (CalledPersonality != CallerPersonality)
1562 return false;
Bill Wendlingce0c2292012-01-31 01:01:16 +00001563 }
Bill Wendling55421f02011-08-14 08:01:36 +00001564
David Majnemer8a1c45d2015-12-12 05:38:55 +00001565 // We need to figure out which funclet the callsite was in so that we may
1566 // properly nest the callee.
1567 Instruction *CallSiteEHPad = nullptr;
David Majnemer3bb88c02015-12-15 21:27:27 +00001568 if (CallerPersonality) {
1569 EHPersonality Personality = classifyEHPersonality(CallerPersonality);
David Majnemer8a1c45d2015-12-12 05:38:55 +00001570 if (isFuncletEHPersonality(Personality)) {
David Majnemer3bb88c02015-12-15 21:27:27 +00001571 Optional<OperandBundleUse> ParentFunclet =
1572 CS.getOperandBundle(LLVMContext::OB_funclet);
1573 if (ParentFunclet)
1574 CallSiteEHPad = cast<FuncletPadInst>(ParentFunclet->Inputs.front());
David Majnemer8a1c45d2015-12-12 05:38:55 +00001575
1576 // OK, the inlining site is legal. What about the target function?
1577
1578 if (CallSiteEHPad) {
1579 if (Personality == EHPersonality::MSVC_CXX) {
1580 // The MSVC personality cannot tolerate catches getting inlined into
1581 // cleanup funclets.
1582 if (isa<CleanupPadInst>(CallSiteEHPad)) {
1583 // Ok, the call site is within a cleanuppad. Let's check the callee
1584 // for catchpads.
1585 for (const BasicBlock &CalledBB : *CalledFunc) {
David Majnemer3bb88c02015-12-15 21:27:27 +00001586 if (isa<CatchSwitchInst>(CalledBB.getFirstNonPHI()))
David Majnemer8a1c45d2015-12-12 05:38:55 +00001587 return false;
1588 }
1589 }
1590 } else if (isAsynchronousEHPersonality(Personality)) {
1591 // SEH is even less tolerant, there may not be any sort of exceptional
1592 // funclet in the callee.
1593 for (const BasicBlock &CalledBB : *CalledFunc) {
1594 if (CalledBB.isEHPad())
1595 return false;
1596 }
1597 }
1598 }
1599 }
1600 }
1601
David Majnemer223538f2016-02-23 17:11:04 +00001602 // Determine if we are dealing with a call in an EHPad which does not unwind
1603 // to caller.
1604 bool EHPadForCallUnwindsLocally = false;
1605 if (CallSiteEHPad && CS.isCall()) {
1606 UnwindDestMemoTy FuncletUnwindMap;
1607 Value *CallSiteUnwindDestToken =
1608 getUnwindDestToken(CallSiteEHPad, FuncletUnwindMap);
1609
1610 EHPadForCallUnwindsLocally =
1611 CallSiteUnwindDestToken &&
1612 !isa<ConstantTokenNone>(CallSiteUnwindDestToken);
1613 }
1614
Chris Lattner9fc977e2004-02-04 01:41:09 +00001615 // Get an iterator to the last basic block in the function, which will have
1616 // the new function inlined after it.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001617 Function::iterator LastBlock = --Caller->end();
Chris Lattner9fc977e2004-02-04 01:41:09 +00001618
Chris Lattner18ef3fd2004-02-04 02:51:48 +00001619 // Make sure to capture all of the return instructions from the cloned
Chris Lattner530d4bf2003-05-29 15:11:31 +00001620 // function.
Chris Lattnerd84dbb32009-08-27 04:02:30 +00001621 SmallVector<ReturnInst*, 8> Returns;
Chris Lattner908d7952006-01-13 19:05:59 +00001622 ClonedCodeInfo InlinedFunctionInfo;
Dale Johannesen845e5822009-03-04 02:09:48 +00001623 Function::iterator FirstNewBlock;
Duncan Sandsaa31b922007-12-19 21:13:37 +00001624
Devang Patelb8f11de2010-06-23 23:55:51 +00001625 { // Scope to destroy VMap after cloning.
Rafael Espindola229e38f2010-10-13 01:36:30 +00001626 ValueToValueMapTy VMap;
Julien Lerouge957e91c2014-04-15 18:01:54 +00001627 // Keep a list of pair (dst, src) to emit byval initializations.
1628 SmallVector<std::pair<Value*, Value*>, 4> ByValInit;
Chris Lattnerbe853d72006-05-27 01:28:04 +00001629
Mehdi Amini46a43552015-03-04 18:43:29 +00001630 auto &DL = Caller->getParent()->getDataLayout();
1631
Chris Lattner908117b2008-01-11 06:09:30 +00001632 // Calculate the vector of arguments to pass into the function cloner, which
1633 // matches up the formal to the actual argument values.
Chris Lattner18ef3fd2004-02-04 02:51:48 +00001634 CallSite::arg_iterator AI = CS.arg_begin();
Chris Lattner908117b2008-01-11 06:09:30 +00001635 unsigned ArgNo = 0;
Reid Kleckner45707d42017-03-16 22:59:15 +00001636 for (Function::arg_iterator I = CalledFunc->arg_begin(),
Chris Lattner908117b2008-01-11 06:09:30 +00001637 E = CalledFunc->arg_end(); I != E; ++I, ++AI, ++ArgNo) {
1638 Value *ActualArg = *AI;
Duncan Sands7c8fb1a2008-09-05 12:37:12 +00001639
Duncan Sands053c9872008-01-27 18:12:58 +00001640 // When byval arguments actually inlined, we need to make the copy implied
1641 // by them explicit. However, we don't do this if the callee is readonly
1642 // or readnone, because the copy would be unneeded: the callee doesn't
1643 // modify the struct.
Nick Lewycky612d70b2011-11-20 19:09:04 +00001644 if (CS.isByValArgument(ArgNo)) {
David Majnemer120f4a02013-11-03 12:22:13 +00001645 ActualArg = HandleByValArgument(ActualArg, TheCall, CalledFunc, IFI,
Reid Kleckner859f8b52017-04-28 20:34:27 +00001646 CalledFunc->getParamAlignment(ArgNo));
Reid Kleckner9b2cc642014-04-21 20:48:47 +00001647 if (ActualArg != *AI)
Julien Lerouge957e91c2014-04-15 18:01:54 +00001648 ByValInit.push_back(std::make_pair(ActualArg, (Value*) *AI));
Chris Lattner908117b2008-01-11 06:09:30 +00001649 }
Duncan Sands7c8fb1a2008-09-05 12:37:12 +00001650
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001651 VMap[&*I] = ActualArg;
Chris Lattner908117b2008-01-11 06:09:30 +00001652 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001653
Hans Wennborg2d5841f2017-02-27 22:33:02 +00001654 // Add alignment assumptions if necessary. We do this before the inlined
1655 // instructions are actually cloned into the caller so that we can easily
1656 // check what will be known at the start of the inlined code.
1657 AddAlignmentAssumptions(CS, IFI);
Hal Finkel68dc3c72014-10-15 23:44:41 +00001658
Chris Lattnerbe853d72006-05-27 01:28:04 +00001659 // We want the inliner to prune the code as it copies. We would LOVE to
1660 // have no dead or constant instructions leftover after inlining occurs
1661 // (which can happen, e.g., because an argument was constant), but we'll be
1662 // happy with whatever the cloner can do.
Mehdi Amini46a43552015-03-04 18:43:29 +00001663 CloneAndPruneFunctionInto(Caller, CalledFunc, VMap,
Dan Gohmanca26f792010-08-26 15:41:53 +00001664 /*ModuleLevelChanges=*/false, Returns, ".i",
Easwaran Ramanb1bd3982016-03-08 00:36:35 +00001665 &InlinedFunctionInfo, TheCall);
Chris Lattner5de3b8b2006-07-12 18:29:36 +00001666 // Remember the first block that is newly cloned over.
1667 FirstNewBlock = LastBlock; ++FirstNewBlock;
Duncan Sands7c8fb1a2008-09-05 12:37:12 +00001668
Dehao Chene5930492017-03-20 16:40:44 +00001669 if (IFI.CallerBFI != nullptr && IFI.CalleeBFI != nullptr)
Easwaran Raman12585b02017-01-20 22:44:04 +00001670 // Update the BFI of blocks cloned into the caller.
1671 updateCallerBFI(OrigBB, VMap, IFI.CallerBFI, IFI.CalleeBFI,
1672 CalledFunc->front());
Dehao Chene5930492017-03-20 16:40:44 +00001673
Easwaran Ramanf5f91602017-05-09 23:21:10 +00001674 updateCallProfile(CalledFunc, VMap, CalledFunc->getEntryCount(), TheCall,
Teresa Johnson525dcb62017-05-22 20:28:18 +00001675 IFI.PSI, IFI.CallerBFI);
Dehao Chene5930492017-03-20 16:40:44 +00001676 // Update the profile count of callee.
Easwaran Ramanf5f91602017-05-09 23:21:10 +00001677 updateCalleeCount(IFI.CallerBFI, OrigBB, TheCall, CalledFunc, IFI.PSI);
Easwaran Raman12585b02017-01-20 22:44:04 +00001678
Julien Lerouge957e91c2014-04-15 18:01:54 +00001679 // Inject byval arguments initialization.
1680 for (std::pair<Value*, Value*> &Init : ByValInit)
1681 HandleByValArgumentInit(Init.first, Init.second, Caller->getParent(),
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001682 &*FirstNewBlock, IFI);
Julien Lerouge957e91c2014-04-15 18:01:54 +00001683
David Majnemer3bb88c02015-12-15 21:27:27 +00001684 Optional<OperandBundleUse> ParentDeopt =
1685 CS.getOperandBundle(LLVMContext::OB_deopt);
1686 if (ParentDeopt) {
Sanjoy Das2d161452015-11-18 06:23:38 +00001687 SmallVector<OperandBundleDef, 2> OpDefs;
1688
1689 for (auto &VH : InlinedFunctionInfo.OperandBundleCallSites) {
Sanjoy Dasab0626e2015-12-19 22:40:28 +00001690 Instruction *I = dyn_cast_or_null<Instruction>(VH);
1691 if (!I) continue; // instruction was DCE'd or RAUW'ed to undef
Sanjoy Das2d161452015-11-18 06:23:38 +00001692
1693 OpDefs.clear();
1694
1695 CallSite ICS(I);
1696 OpDefs.reserve(ICS.getNumOperandBundles());
1697
1698 for (unsigned i = 0, e = ICS.getNumOperandBundles(); i < e; ++i) {
1699 auto ChildOB = ICS.getOperandBundleAt(i);
1700 if (ChildOB.getTagID() != LLVMContext::OB_deopt) {
1701 // If the inlined call has other operand bundles, let them be
1702 OpDefs.emplace_back(ChildOB);
1703 continue;
1704 }
1705
1706 // It may be useful to separate this logic (of handling operand
1707 // bundles) out to a separate "policy" component if this gets crowded.
1708 // Prepend the parent's deoptimization continuation to the newly
1709 // inlined call's deoptimization continuation.
1710 std::vector<Value *> MergedDeoptArgs;
David Majnemer3bb88c02015-12-15 21:27:27 +00001711 MergedDeoptArgs.reserve(ParentDeopt->Inputs.size() +
Sanjoy Das2d161452015-11-18 06:23:38 +00001712 ChildOB.Inputs.size());
1713
1714 MergedDeoptArgs.insert(MergedDeoptArgs.end(),
David Majnemer3bb88c02015-12-15 21:27:27 +00001715 ParentDeopt->Inputs.begin(),
1716 ParentDeopt->Inputs.end());
Sanjoy Das2d161452015-11-18 06:23:38 +00001717 MergedDeoptArgs.insert(MergedDeoptArgs.end(), ChildOB.Inputs.begin(),
1718 ChildOB.Inputs.end());
1719
Sanjoy Das8da1f952015-12-08 03:50:32 +00001720 OpDefs.emplace_back("deopt", std::move(MergedDeoptArgs));
Sanjoy Das2d161452015-11-18 06:23:38 +00001721 }
1722
1723 Instruction *NewI = nullptr;
1724 if (isa<CallInst>(I))
1725 NewI = CallInst::Create(cast<CallInst>(I), OpDefs, I);
1726 else
1727 NewI = InvokeInst::Create(cast<InvokeInst>(I), OpDefs, I);
1728
1729 // Note: the RAUW does the appropriate fixup in VMap, so we need to do
1730 // this even if the call returns void.
1731 I->replaceAllUsesWith(NewI);
1732
1733 VH = nullptr;
1734 I->eraseFromParent();
1735 }
1736 }
1737
Chris Lattner5de3b8b2006-07-12 18:29:36 +00001738 // Update the callgraph if requested.
Chandler Carruth0ee8bb12016-12-27 01:24:50 +00001739 if (IFI.CG)
Devang Patelb8f11de2010-06-23 23:55:51 +00001740 UpdateCallGraphAfterInlining(CS, FirstNewBlock, VMap, IFI);
Devang Patel35797402011-07-08 18:01:31 +00001741
Andrea Di Biagio32d5aed2016-12-07 10:37:26 +00001742 // For 'nodebug' functions, the associated DISubprogram is always null.
1743 // Conservatively avoid propagating the callsite debug location to
1744 // instructions inlined from a function whose DISubprogram is not null.
Adrian Prantld4056502017-03-07 17:28:57 +00001745 fixupLineNumbers(Caller, FirstNewBlock, TheCall,
1746 CalledFunc->getSubprogram() != nullptr);
Hal Finkel94146652014-07-24 14:25:39 +00001747
1748 // Clone existing noalias metadata if necessary.
1749 CloneAliasScopeMetadata(CS, VMap);
Hal Finkelff0bcb62014-07-25 15:50:08 +00001750
1751 // Add noalias metadata if necessary.
Chandler Carruth7b560d42015-09-09 17:55:00 +00001752 AddAliasScopeMetadata(CS, VMap, DL, CalleeAAR);
Hal Finkel74c2f352014-09-07 12:44:26 +00001753
Hal Finkel50316d92016-04-28 23:00:04 +00001754 // Propagate llvm.mem.parallel_loop_access if necessary.
1755 PropagateParallelLoopAccessMetadata(CS, VMap);
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001756
1757 // Register any cloned assumptions.
1758 if (IFI.GetAssumptionCache)
1759 for (BasicBlock &NewBlock :
1760 make_range(FirstNewBlock->getIterator(), Caller->end()))
1761 for (Instruction &I : NewBlock) {
1762 if (auto *II = dyn_cast<IntrinsicInst>(&I))
1763 if (II->getIntrinsicID() == Intrinsic::assume)
1764 (*IFI.GetAssumptionCache)(*Caller).registerAssumption(II);
1765 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001766 }
Duncan Sands7c8fb1a2008-09-05 12:37:12 +00001767
Chris Lattner530d4bf2003-05-29 15:11:31 +00001768 // If there are any alloca instructions in the block that used to be the entry
1769 // block for the callee, move them to the entry block of the caller. First
1770 // calculate which instruction they should be inserted before. We insert the
1771 // instructions at the end of the current alloca list.
Chris Lattner257492c2006-01-13 18:16:48 +00001772 {
Chris Lattner0cc265e2003-08-24 06:59:16 +00001773 BasicBlock::iterator InsertPoint = Caller->begin()->begin();
Chris Lattner18ef3fd2004-02-04 02:51:48 +00001774 for (BasicBlock::iterator I = FirstNewBlock->begin(),
Chris Lattner5eef6ad2009-08-27 03:51:50 +00001775 E = FirstNewBlock->end(); I != E; ) {
1776 AllocaInst *AI = dyn_cast<AllocaInst>(I++);
Craig Topperf40110f2014-04-25 05:29:35 +00001777 if (!AI) continue;
Chris Lattner5eef6ad2009-08-27 03:51:50 +00001778
1779 // If the alloca is now dead, remove it. This often occurs due to code
1780 // specialization.
1781 if (AI->use_empty()) {
1782 AI->eraseFromParent();
1783 continue;
Chris Lattner6ef6d062006-09-13 19:23:57 +00001784 }
Chris Lattner5eef6ad2009-08-27 03:51:50 +00001785
Reid Kleckner6ee00a22016-08-12 22:23:04 +00001786 if (!allocaWouldBeStaticInEntry(AI))
Chris Lattner5eef6ad2009-08-27 03:51:50 +00001787 continue;
1788
Chris Lattnercd3af962010-12-06 07:43:04 +00001789 // Keep track of the static allocas that we inline into the caller.
Chris Lattner4ba01ec2010-04-22 23:07:58 +00001790 IFI.StaticAllocas.push_back(AI);
Chris Lattnerb1cba3f2009-08-27 04:20:52 +00001791
Chris Lattner5eef6ad2009-08-27 03:51:50 +00001792 // Scan for the block of allocas that we can move over, and move them
1793 // all at once.
1794 while (isa<AllocaInst>(I) &&
Reid Kleckner6ee00a22016-08-12 22:23:04 +00001795 allocaWouldBeStaticInEntry(cast<AllocaInst>(I))) {
Chris Lattner4ba01ec2010-04-22 23:07:58 +00001796 IFI.StaticAllocas.push_back(cast<AllocaInst>(I));
Chris Lattner5eef6ad2009-08-27 03:51:50 +00001797 ++I;
Chris Lattnerb1cba3f2009-08-27 04:20:52 +00001798 }
Chris Lattner5eef6ad2009-08-27 03:51:50 +00001799
1800 // Transfer all of the allocas over in a block. Using splice means
1801 // that the instructions aren't removed from the symbol table, then
1802 // reinserted.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001803 Caller->getEntryBlock().getInstList().splice(
1804 InsertPoint, FirstNewBlock->getInstList(), AI->getIterator(), I);
Chris Lattner5eef6ad2009-08-27 03:51:50 +00001805 }
Adrian Prantl4d365252015-01-30 01:55:25 +00001806 // Move any dbg.declares describing the allocas into the entry basic block.
Adrian Prantl3e2659e2015-01-30 19:37:48 +00001807 DIBuilder DIB(*Caller->getParent());
Adrian Prantl133e1022015-01-30 19:42:59 +00001808 for (auto &AI : IFI.StaticAllocas)
Adrian Prantld1317012017-12-08 21:58:18 +00001809 replaceDbgDeclareForAlloca(AI, AI, DIB, DIExpression::NoDeref, 0,
1810 DIExpression::NoDeref);
Chris Lattner0cc265e2003-08-24 06:59:16 +00001811 }
Chris Lattner530d4bf2003-05-29 15:11:31 +00001812
Florian Hahn0e9dec62017-11-13 10:35:52 +00001813 SmallVector<Value*,4> VarArgsToForward;
Florian Hahnde10e6e2018-01-06 20:46:00 +00001814 SmallVector<AttributeSet, 4> VarArgsAttrs;
Florian Hahn0e9dec62017-11-13 10:35:52 +00001815 for (unsigned i = CalledFunc->getFunctionType()->getNumParams();
Florian Hahnde10e6e2018-01-06 20:46:00 +00001816 i < CS.getNumArgOperands(); i++) {
Florian Hahn0e9dec62017-11-13 10:35:52 +00001817 VarArgsToForward.push_back(CS.getArgOperand(i));
Florian Hahnde10e6e2018-01-06 20:46:00 +00001818 VarArgsAttrs.push_back(CS.getAttributes().getParamAttributes(i));
1819 }
Florian Hahn0e9dec62017-11-13 10:35:52 +00001820
Sanjoy Dasb51325d2016-03-11 19:08:34 +00001821 bool InlinedMustTailCalls = false, InlinedDeoptimizeCalls = false;
Reid Klecknerf0915aa2014-05-15 20:11:28 +00001822 if (InlinedFunctionInfo.ContainsCalls) {
Reid Kleckner6af21242014-05-15 20:39:42 +00001823 CallInst::TailCallKind CallSiteTailKind = CallInst::TCK_None;
1824 if (CallInst *CI = dyn_cast<CallInst>(TheCall))
1825 CallSiteTailKind = CI->getTailCallKind();
1826
Reid Klecknerf0915aa2014-05-15 20:11:28 +00001827 for (Function::iterator BB = FirstNewBlock, E = Caller->end(); BB != E;
1828 ++BB) {
Florian Hahn0e9dec62017-11-13 10:35:52 +00001829 for (auto II = BB->begin(); II != BB->end();) {
1830 Instruction &I = *II++;
Reid Klecknerf0915aa2014-05-15 20:11:28 +00001831 CallInst *CI = dyn_cast<CallInst>(&I);
1832 if (!CI)
1833 continue;
1834
Florian Hahn80788d82018-01-06 19:45:40 +00001835 // Forward varargs from inlined call site to calls to the
1836 // ForwardVarArgsTo function, if requested, and to musttail calls.
1837 if (!VarArgsToForward.empty() &&
1838 ((ForwardVarArgsTo &&
1839 CI->getCalledFunction() == ForwardVarArgsTo) ||
1840 CI->isMustTailCall())) {
Florian Hahnde10e6e2018-01-06 20:46:00 +00001841 // Collect attributes for non-vararg parameters.
1842 AttributeList Attrs = CI->getAttributes();
1843 SmallVector<AttributeSet, 8> ArgAttrs;
1844 if (!Attrs.isEmpty()) {
1845 for (unsigned ArgNo = 0;
1846 ArgNo < CI->getFunctionType()->getNumParams(); ++ArgNo)
1847 ArgAttrs.push_back(Attrs.getParamAttributes(ArgNo));
1848 }
1849
1850 // Add VarArg attributes.
1851 ArgAttrs.append(VarArgsAttrs.begin(), VarArgsAttrs.end());
1852 Attrs = AttributeList::get(CI->getContext(), Attrs.getFnAttributes(),
1853 Attrs.getRetAttributes(), ArgAttrs);
1854 // Add VarArgs to existing parameters.
Florian Hahn80788d82018-01-06 19:45:40 +00001855 SmallVector<Value *, 6> Params(CI->arg_operands());
1856 Params.append(VarArgsToForward.begin(), VarArgsToForward.end());
Florian Hahnde10e6e2018-01-06 20:46:00 +00001857 CallInst *NewCI =
Florian Hahn80788d82018-01-06 19:45:40 +00001858 CallInst::Create(CI->getCalledFunction() ? CI->getCalledFunction()
1859 : CI->getCalledValue(),
1860 Params, "", CI);
Florian Hahnde10e6e2018-01-06 20:46:00 +00001861 NewCI->setDebugLoc(CI->getDebugLoc());
1862 NewCI->setAttributes(Attrs);
1863 CI->replaceAllUsesWith(NewCI);
Florian Hahn80788d82018-01-06 19:45:40 +00001864 CI->eraseFromParent();
Florian Hahnde10e6e2018-01-06 20:46:00 +00001865 CI = NewCI;
Florian Hahn80788d82018-01-06 19:45:40 +00001866 }
1867
Sanjoy Dasb51325d2016-03-11 19:08:34 +00001868 if (Function *F = CI->getCalledFunction())
1869 InlinedDeoptimizeCalls |=
1870 F->getIntrinsicID() == Intrinsic::experimental_deoptimize;
1871
Reid Klecknerf0915aa2014-05-15 20:11:28 +00001872 // We need to reduce the strength of any inlined tail calls. For
1873 // musttail, we have to avoid introducing potential unbounded stack
1874 // growth. For example, if functions 'f' and 'g' are mutually recursive
1875 // with musttail, we can inline 'g' into 'f' so long as we preserve
1876 // musttail on the cloned call to 'f'. If either the inlined call site
1877 // or the cloned call site is *not* musttail, the program already has
1878 // one frame of stack growth, so it's safe to remove musttail. Here is
1879 // a table of example transformations:
1880 //
1881 // f -> musttail g -> musttail f ==> f -> musttail f
1882 // f -> musttail g -> tail f ==> f -> tail f
1883 // f -> g -> musttail f ==> f -> f
1884 // f -> g -> tail f ==> f -> f
1885 CallInst::TailCallKind ChildTCK = CI->getTailCallKind();
Arnold Schwaighoferd9e71092017-11-27 19:03:40 +00001886 if (ChildTCK != CallInst::TCK_NoTail)
1887 ChildTCK = std::min(CallSiteTailKind, ChildTCK);
Reid Klecknerdd3f3ed2014-11-04 02:02:14 +00001888 CI->setTailCallKind(ChildTCK);
Reid Klecknerf0915aa2014-05-15 20:11:28 +00001889 InlinedMustTailCalls |= CI->isMustTailCall();
1890
1891 // Calls inlined through a 'nounwind' call site should be marked
1892 // 'nounwind'.
1893 if (MarkNoUnwind)
1894 CI->setDoesNotThrow();
1895 }
1896 }
1897 }
1898
Nick Lewyckya68ec832011-05-22 05:22:10 +00001899 // Leave lifetime markers for the static alloca's, scoping them to the
1900 // function we just inlined.
Chad Rosier07d37bc2012-02-25 02:56:01 +00001901 if (InsertLifetime && !IFI.StaticAllocas.empty()) {
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001902 IRBuilder<> builder(&FirstNewBlock->front());
Nick Lewyckya68ec832011-05-22 05:22:10 +00001903 for (unsigned ai = 0, ae = IFI.StaticAllocas.size(); ai != ae; ++ai) {
1904 AllocaInst *AI = IFI.StaticAllocas[ai];
Arnold Schwaighoferc9277f42016-09-09 22:40:27 +00001905 // Don't mark swifterror allocas. They can't have bitcast uses.
1906 if (AI->isSwiftError())
1907 continue;
Nick Lewyckya68ec832011-05-22 05:22:10 +00001908
1909 // If the alloca is already scoped to something smaller than the whole
1910 // function then there's no need to add redundant, less accurate markers.
1911 if (hasLifetimeMarkers(AI))
1912 continue;
1913
Alexey Samsonovcfd662f2012-11-13 07:15:32 +00001914 // Try to determine the size of the allocation.
Craig Topperf40110f2014-04-25 05:29:35 +00001915 ConstantInt *AllocaSize = nullptr;
Alexey Samsonovcfd662f2012-11-13 07:15:32 +00001916 if (ConstantInt *AIArraySize =
1917 dyn_cast<ConstantInt>(AI->getArraySize())) {
Mehdi Amini46a43552015-03-04 18:43:29 +00001918 auto &DL = Caller->getParent()->getDataLayout();
1919 Type *AllocaType = AI->getAllocatedType();
1920 uint64_t AllocaTypeSize = DL.getTypeAllocSize(AllocaType);
1921 uint64_t AllocaArraySize = AIArraySize->getLimitedValue();
Akira Hatanaka2cc2b632015-04-20 16:11:05 +00001922
1923 // Don't add markers for zero-sized allocas.
1924 if (AllocaArraySize == 0)
1925 continue;
1926
Mehdi Amini46a43552015-03-04 18:43:29 +00001927 // Check that array size doesn't saturate uint64_t and doesn't
1928 // overflow when it's multiplied by type size.
Eugene Zelenko6cadde72017-10-17 21:27:42 +00001929 if (AllocaArraySize != std::numeric_limits<uint64_t>::max() &&
1930 std::numeric_limits<uint64_t>::max() / AllocaArraySize >=
1931 AllocaTypeSize) {
Mehdi Amini46a43552015-03-04 18:43:29 +00001932 AllocaSize = ConstantInt::get(Type::getInt64Ty(AI->getContext()),
1933 AllocaArraySize * AllocaTypeSize);
Alexey Samsonovcfd662f2012-11-13 07:15:32 +00001934 }
1935 }
1936
1937 builder.CreateLifetimeStart(AI, AllocaSize);
Reid Kleckner900d46f2014-05-15 21:10:46 +00001938 for (ReturnInst *RI : Returns) {
Sanjoy Das18b92962016-04-01 02:51:26 +00001939 // Don't insert llvm.lifetime.end calls between a musttail or deoptimize
1940 // call and a return. The return kills all local allocas.
Reid Klecknere31acf22014-08-12 00:05:15 +00001941 if (InlinedMustTailCalls &&
1942 RI->getParent()->getTerminatingMustTailCall())
Reid Kleckner900d46f2014-05-15 21:10:46 +00001943 continue;
Sanjoy Das18b92962016-04-01 02:51:26 +00001944 if (InlinedDeoptimizeCalls &&
1945 RI->getParent()->getTerminatingDeoptimizeCall())
1946 continue;
Reid Klecknerf0915aa2014-05-15 20:11:28 +00001947 IRBuilder<>(RI).CreateLifetimeEnd(AI, AllocaSize);
Reid Kleckner900d46f2014-05-15 21:10:46 +00001948 }
Nick Lewyckya68ec832011-05-22 05:22:10 +00001949 }
1950 }
1951
Chris Lattner2be06072006-01-13 19:34:14 +00001952 // If the inlined code contained dynamic alloca instructions, wrap the inlined
1953 // code with llvm.stacksave/llvm.stackrestore intrinsics.
1954 if (InlinedFunctionInfo.ContainsDynamicAllocas) {
1955 Module *M = Caller->getParent();
Chris Lattner2be06072006-01-13 19:34:14 +00001956 // Get the two intrinsics we care about.
Chris Lattner88b36f12009-10-17 05:39:39 +00001957 Function *StackSave = Intrinsic::getDeclaration(M, Intrinsic::stacksave);
1958 Function *StackRestore=Intrinsic::getDeclaration(M,Intrinsic::stackrestore);
Chris Lattner5de3b8b2006-07-12 18:29:36 +00001959
Chris Lattner2be06072006-01-13 19:34:14 +00001960 // Insert the llvm.stacksave.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001961 CallInst *SavedPtr = IRBuilder<>(&*FirstNewBlock, FirstNewBlock->begin())
David Blaikieff6409d2015-05-18 22:13:54 +00001962 .CreateCall(StackSave, {}, "savedstack");
Duncan Sands7c8fb1a2008-09-05 12:37:12 +00001963
Chris Lattner2be06072006-01-13 19:34:14 +00001964 // Insert a call to llvm.stackrestore before any return instructions in the
1965 // inlined function.
Reid Kleckner900d46f2014-05-15 21:10:46 +00001966 for (ReturnInst *RI : Returns) {
Sanjoy Dasf83ab6d2016-04-01 02:51:30 +00001967 // Don't insert llvm.stackrestore calls between a musttail or deoptimize
1968 // call and a return. The return will restore the stack pointer.
Reid Klecknere31acf22014-08-12 00:05:15 +00001969 if (InlinedMustTailCalls && RI->getParent()->getTerminatingMustTailCall())
Reid Kleckner900d46f2014-05-15 21:10:46 +00001970 continue;
Sanjoy Dasf83ab6d2016-04-01 02:51:30 +00001971 if (InlinedDeoptimizeCalls && RI->getParent()->getTerminatingDeoptimizeCall())
1972 continue;
Reid Klecknerf0915aa2014-05-15 20:11:28 +00001973 IRBuilder<>(RI).CreateCall(StackRestore, SavedPtr);
Reid Kleckner900d46f2014-05-15 21:10:46 +00001974 }
Chris Lattner9f3dced2005-05-06 06:47:52 +00001975 }
1976
Joseph Tremouletb41632b2016-01-20 02:15:15 +00001977 // If we are inlining for an invoke instruction, we must make sure to rewrite
1978 // any call instructions into invoke instructions. This is sensitive to which
1979 // funclet pads were top-level in the inlinee, so must be done before
1980 // rewriting the "parent pad" links.
1981 if (auto *II = dyn_cast<InvokeInst>(TheCall)) {
1982 BasicBlock *UnwindDest = II->getUnwindDest();
1983 Instruction *FirstNonPHI = UnwindDest->getFirstNonPHI();
1984 if (isa<LandingPadInst>(FirstNonPHI)) {
1985 HandleInlinedLandingPad(II, &*FirstNewBlock, InlinedFunctionInfo);
1986 } else {
1987 HandleInlinedEHPad(II, &*FirstNewBlock, InlinedFunctionInfo);
1988 }
1989 }
1990
David Majnemer3bb88c02015-12-15 21:27:27 +00001991 // Update the lexical scopes of the new funclets and callsites.
1992 // Anything that had 'none' as its parent is now nested inside the callsite's
1993 // EHPad.
1994
David Majnemer8a1c45d2015-12-12 05:38:55 +00001995 if (CallSiteEHPad) {
1996 for (Function::iterator BB = FirstNewBlock->getIterator(),
1997 E = Caller->end();
1998 BB != E; ++BB) {
David Majnemer3bb88c02015-12-15 21:27:27 +00001999 // Add bundle operands to any top-level call sites.
2000 SmallVector<OperandBundleDef, 1> OpBundles;
2001 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E;) {
2002 Instruction *I = &*BBI++;
2003 CallSite CS(I);
2004 if (!CS)
2005 continue;
2006
2007 // Skip call sites which are nounwind intrinsics.
2008 auto *CalledFn =
2009 dyn_cast<Function>(CS.getCalledValue()->stripPointerCasts());
2010 if (CalledFn && CalledFn->isIntrinsic() && CS.doesNotThrow())
2011 continue;
2012
2013 // Skip call sites which already have a "funclet" bundle.
2014 if (CS.getOperandBundle(LLVMContext::OB_funclet))
2015 continue;
2016
2017 CS.getOperandBundlesAsDefs(OpBundles);
2018 OpBundles.emplace_back("funclet", CallSiteEHPad);
2019
2020 Instruction *NewInst;
2021 if (CS.isCall())
2022 NewInst = CallInst::Create(cast<CallInst>(I), OpBundles, I);
2023 else
2024 NewInst = InvokeInst::Create(cast<InvokeInst>(I), OpBundles, I);
David Majnemer3bb88c02015-12-15 21:27:27 +00002025 NewInst->takeName(I);
2026 I->replaceAllUsesWith(NewInst);
2027 I->eraseFromParent();
2028
2029 OpBundles.clear();
2030 }
2031
David Majnemer223538f2016-02-23 17:11:04 +00002032 // It is problematic if the inlinee has a cleanupret which unwinds to
2033 // caller and we inline it into a call site which doesn't unwind but into
2034 // an EH pad that does. Such an edge must be dynamically unreachable.
2035 // As such, we replace the cleanupret with unreachable.
2036 if (auto *CleanupRet = dyn_cast<CleanupReturnInst>(BB->getTerminator()))
2037 if (CleanupRet->unwindsToCaller() && EHPadForCallUnwindsLocally)
David Majnemere14e7bc2016-06-25 08:19:55 +00002038 changeToUnreachable(CleanupRet, /*UseLLVMTrap=*/false);
David Majnemer223538f2016-02-23 17:11:04 +00002039
David Majnemer8a1c45d2015-12-12 05:38:55 +00002040 Instruction *I = BB->getFirstNonPHI();
2041 if (!I->isEHPad())
2042 continue;
2043
David Majnemerbbfc7212015-12-14 18:34:23 +00002044 if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(I)) {
David Majnemer8a1c45d2015-12-12 05:38:55 +00002045 if (isa<ConstantTokenNone>(CatchSwitch->getParentPad()))
2046 CatchSwitch->setParentPad(CallSiteEHPad);
2047 } else {
2048 auto *FPI = cast<FuncletPadInst>(I);
2049 if (isa<ConstantTokenNone>(FPI->getParentPad()))
2050 FPI->setParentPad(CallSiteEHPad);
2051 }
2052 }
2053 }
2054
Sanjoy Dasb51325d2016-03-11 19:08:34 +00002055 if (InlinedDeoptimizeCalls) {
2056 // We need to at least remove the deoptimizing returns from the Return set,
2057 // so that the control flow from those returns does not get merged into the
2058 // caller (but terminate it instead). If the caller's return type does not
2059 // match the callee's return type, we also need to change the return type of
2060 // the intrinsic.
2061 if (Caller->getReturnType() == TheCall->getType()) {
Eugene Zelenko6cadde72017-10-17 21:27:42 +00002062 auto NewEnd = llvm::remove_if(Returns, [](ReturnInst *RI) {
Sanjoy Dasb51325d2016-03-11 19:08:34 +00002063 return RI->getParent()->getTerminatingDeoptimizeCall() != nullptr;
2064 });
2065 Returns.erase(NewEnd, Returns.end());
2066 } else {
2067 SmallVector<ReturnInst *, 8> NormalReturns;
2068 Function *NewDeoptIntrinsic = Intrinsic::getDeclaration(
2069 Caller->getParent(), Intrinsic::experimental_deoptimize,
2070 {Caller->getReturnType()});
2071
2072 for (ReturnInst *RI : Returns) {
2073 CallInst *DeoptCall = RI->getParent()->getTerminatingDeoptimizeCall();
2074 if (!DeoptCall) {
2075 NormalReturns.push_back(RI);
2076 continue;
2077 }
2078
Sanjoy Dase0aa4142016-05-12 01:17:38 +00002079 // The calling convention on the deoptimize call itself may be bogus,
2080 // since the code we're inlining may have undefined behavior (and may
2081 // never actually execute at runtime); but all
2082 // @llvm.experimental.deoptimize declarations have to have the same
2083 // calling convention in a well-formed module.
2084 auto CallingConv = DeoptCall->getCalledFunction()->getCallingConv();
2085 NewDeoptIntrinsic->setCallingConv(CallingConv);
Sanjoy Dasb51325d2016-03-11 19:08:34 +00002086 auto *CurBB = RI->getParent();
2087 RI->eraseFromParent();
2088
2089 SmallVector<Value *, 4> CallArgs(DeoptCall->arg_begin(),
2090 DeoptCall->arg_end());
2091
2092 SmallVector<OperandBundleDef, 1> OpBundles;
2093 DeoptCall->getOperandBundlesAsDefs(OpBundles);
2094 DeoptCall->eraseFromParent();
2095 assert(!OpBundles.empty() &&
2096 "Expected at least the deopt operand bundle");
2097
2098 IRBuilder<> Builder(CurBB);
Sanjoy Dasdd77e1e2016-04-09 00:22:59 +00002099 CallInst *NewDeoptCall =
Sanjoy Dasb51325d2016-03-11 19:08:34 +00002100 Builder.CreateCall(NewDeoptIntrinsic, CallArgs, OpBundles);
Sanjoy Dasdd77e1e2016-04-09 00:22:59 +00002101 NewDeoptCall->setCallingConv(CallingConv);
Sanjoy Dasb51325d2016-03-11 19:08:34 +00002102 if (NewDeoptCall->getType()->isVoidTy())
2103 Builder.CreateRetVoid();
2104 else
2105 Builder.CreateRet(NewDeoptCall);
2106 }
2107
2108 // Leave behind the normal returns so we can merge control flow.
2109 std::swap(Returns, NormalReturns);
2110 }
2111 }
2112
Reid Klecknerf0915aa2014-05-15 20:11:28 +00002113 // Handle any inlined musttail call sites. In order for a new call site to be
2114 // musttail, the source of the clone and the inlined call site must have been
2115 // musttail. Therefore it's safe to return without merging control into the
2116 // phi below.
2117 if (InlinedMustTailCalls) {
2118 // Check if we need to bitcast the result of any musttail calls.
2119 Type *NewRetTy = Caller->getReturnType();
2120 bool NeedBitCast = !TheCall->use_empty() && TheCall->getType() != NewRetTy;
2121
2122 // Handle the returns preceded by musttail calls separately.
2123 SmallVector<ReturnInst *, 8> NormalReturns;
2124 for (ReturnInst *RI : Returns) {
Reid Klecknere31acf22014-08-12 00:05:15 +00002125 CallInst *ReturnedMustTail =
2126 RI->getParent()->getTerminatingMustTailCall();
Reid Klecknerf0915aa2014-05-15 20:11:28 +00002127 if (!ReturnedMustTail) {
2128 NormalReturns.push_back(RI);
2129 continue;
2130 }
2131 if (!NeedBitCast)
2132 continue;
2133
2134 // Delete the old return and any preceding bitcast.
2135 BasicBlock *CurBB = RI->getParent();
2136 auto *OldCast = dyn_cast_or_null<BitCastInst>(RI->getReturnValue());
2137 RI->eraseFromParent();
2138 if (OldCast)
2139 OldCast->eraseFromParent();
2140
2141 // Insert a new bitcast and return with the right type.
2142 IRBuilder<> Builder(CurBB);
2143 Builder.CreateRet(Builder.CreateBitCast(ReturnedMustTail, NewRetTy));
2144 }
2145
2146 // Leave behind the normal returns so we can merge control flow.
2147 std::swap(Returns, NormalReturns);
2148 }
2149
Chandler Carruth0ee8bb12016-12-27 01:24:50 +00002150 // Now that all of the transforms on the inlined code have taken place but
2151 // before we splice the inlined code into the CFG and lose track of which
2152 // blocks were actually inlined, collect the call sites. We only do this if
2153 // call graph updates weren't requested, as those provide value handle based
2154 // tracking of inlined call sites instead.
2155 if (InlinedFunctionInfo.ContainsCalls && !IFI.CG) {
2156 // Otherwise just collect the raw call sites that were inlined.
2157 for (BasicBlock &NewBB :
2158 make_range(FirstNewBlock->getIterator(), Caller->end()))
2159 for (Instruction &I : NewBB)
2160 if (auto CS = CallSite(&I))
2161 IFI.InlinedCallSites.push_back(CS);
2162 }
2163
Chris Lattner0fa8c7c2004-02-04 04:17:06 +00002164 // If we cloned in _exactly one_ basic block, and if that block ends in a
2165 // return instruction, we splice the body of the inlined callee directly into
2166 // the calling basic block.
2167 if (Returns.size() == 1 && std::distance(FirstNewBlock, Caller->end()) == 1) {
2168 // Move all of the instructions right before the call.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002169 OrigBB->getInstList().splice(TheCall->getIterator(),
2170 FirstNewBlock->getInstList(),
Chris Lattner0fa8c7c2004-02-04 04:17:06 +00002171 FirstNewBlock->begin(), FirstNewBlock->end());
2172 // Remove the cloned basic block.
2173 Caller->getBasicBlockList().pop_back();
Misha Brukmanb1c93172005-04-21 23:48:37 +00002174
Chris Lattner0fa8c7c2004-02-04 04:17:06 +00002175 // If the call site was an invoke instruction, add a branch to the normal
2176 // destination.
Adrian Prantl15db52b2013-04-23 19:56:03 +00002177 if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall)) {
2178 BranchInst *NewBr = BranchInst::Create(II->getNormalDest(), TheCall);
2179 NewBr->setDebugLoc(Returns[0]->getDebugLoc());
2180 }
Chris Lattner0fa8c7c2004-02-04 04:17:06 +00002181
2182 // If the return instruction returned a value, replace uses of the call with
2183 // uses of the returned value.
Devang Patel841322b2008-03-04 21:15:15 +00002184 if (!TheCall->use_empty()) {
2185 ReturnInst *R = Returns[0];
Eli Friedman36b90262009-05-08 00:22:04 +00002186 if (TheCall == R->getReturnValue())
Owen Andersonb292b8c2009-07-30 23:03:37 +00002187 TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
Eli Friedman36b90262009-05-08 00:22:04 +00002188 else
2189 TheCall->replaceAllUsesWith(R->getReturnValue());
Devang Patel841322b2008-03-04 21:15:15 +00002190 }
Chris Lattner0fa8c7c2004-02-04 04:17:06 +00002191 // Since we are now done with the Call/Invoke, we can delete it.
Dan Gohman158ff2c2008-06-21 22:08:46 +00002192 TheCall->eraseFromParent();
Chris Lattner0fa8c7c2004-02-04 04:17:06 +00002193
2194 // Since we are now done with the return instruction, delete it also.
Dan Gohman158ff2c2008-06-21 22:08:46 +00002195 Returns[0]->eraseFromParent();
Chris Lattner0fa8c7c2004-02-04 04:17:06 +00002196
2197 // We are now done with the inlining.
2198 return true;
2199 }
2200
2201 // Otherwise, we have the normal case, of more than one block to inline or
2202 // multiple return sites.
2203
Chris Lattner18ef3fd2004-02-04 02:51:48 +00002204 // We want to clone the entire callee function into the hole between the
2205 // "starter" and "ender" blocks. How we accomplish this depends on whether
2206 // this is an invoke instruction or a call instruction.
2207 BasicBlock *AfterCallBB;
Craig Topperf40110f2014-04-25 05:29:35 +00002208 BranchInst *CreatedBranchToNormalDest = nullptr;
Chris Lattner18ef3fd2004-02-04 02:51:48 +00002209 if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall)) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00002210
Chris Lattner18ef3fd2004-02-04 02:51:48 +00002211 // Add an unconditional branch to make this look like the CallInst case...
Adrian Prantl15db52b2013-04-23 19:56:03 +00002212 CreatedBranchToNormalDest = BranchInst::Create(II->getNormalDest(), TheCall);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002213
Chris Lattner18ef3fd2004-02-04 02:51:48 +00002214 // Split the basic block. This guarantees that no PHI nodes will have to be
2215 // updated due to new incoming edges, and make the invoke case more
2216 // symmetric to the call case.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002217 AfterCallBB =
2218 OrigBB->splitBasicBlock(CreatedBranchToNormalDest->getIterator(),
2219 CalledFunc->getName() + ".exit");
Misha Brukmanb1c93172005-04-21 23:48:37 +00002220
Chris Lattner18ef3fd2004-02-04 02:51:48 +00002221 } else { // It's a call
Chris Lattner0fa8c7c2004-02-04 04:17:06 +00002222 // If this is a call instruction, we need to split the basic block that
2223 // the call lives in.
Chris Lattner18ef3fd2004-02-04 02:51:48 +00002224 //
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002225 AfterCallBB = OrigBB->splitBasicBlock(TheCall->getIterator(),
2226 CalledFunc->getName() + ".exit");
Chris Lattner18ef3fd2004-02-04 02:51:48 +00002227 }
2228
Easwaran Raman12585b02017-01-20 22:44:04 +00002229 if (IFI.CallerBFI) {
2230 // Copy original BB's block frequency to AfterCallBB
2231 IFI.CallerBFI->setBlockFreq(
2232 AfterCallBB, IFI.CallerBFI->getBlockFreq(OrigBB).getFrequency());
2233 }
2234
Chris Lattner0fa8c7c2004-02-04 04:17:06 +00002235 // Change the branch that used to go to AfterCallBB to branch to the first
2236 // basic block of the inlined function.
2237 //
2238 TerminatorInst *Br = OrigBB->getTerminator();
Misha Brukmanb1c93172005-04-21 23:48:37 +00002239 assert(Br && Br->getOpcode() == Instruction::Br &&
Chris Lattner0fa8c7c2004-02-04 04:17:06 +00002240 "splitBasicBlock broken!");
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002241 Br->setOperand(0, &*FirstNewBlock);
Chris Lattner0fa8c7c2004-02-04 04:17:06 +00002242
2243 // Now that the function is correct, make it a little bit nicer. In
2244 // particular, move the basic blocks inserted from the end of the function
2245 // into the space made by splitting the source basic block.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002246 Caller->getBasicBlockList().splice(AfterCallBB->getIterator(),
2247 Caller->getBasicBlockList(), FirstNewBlock,
2248 Caller->end());
Chris Lattner0fa8c7c2004-02-04 04:17:06 +00002249
Chris Lattner18ef3fd2004-02-04 02:51:48 +00002250 // Handle all of the return instructions that we just cloned in, and eliminate
2251 // any users of the original call/invoke instruction.
Chris Lattner229907c2011-07-18 04:54:35 +00002252 Type *RTy = CalledFunc->getReturnType();
Dan Gohman3b18fd72008-06-20 01:03:44 +00002253
Craig Topperf40110f2014-04-25 05:29:35 +00002254 PHINode *PHI = nullptr;
Dan Gohmanfa1211f2008-07-23 00:34:11 +00002255 if (Returns.size() > 1) {
Chris Lattner18ef3fd2004-02-04 02:51:48 +00002256 // The PHI node should go at the front of the new basic block to merge all
2257 // possible incoming values.
Chris Lattner18ef3fd2004-02-04 02:51:48 +00002258 if (!TheCall->use_empty()) {
Jay Foad52131342011-03-30 11:28:46 +00002259 PHI = PHINode::Create(RTy, Returns.size(), TheCall->getName(),
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002260 &AfterCallBB->front());
Dan Gohmanfa1211f2008-07-23 00:34:11 +00002261 // Anything that used the result of the function call should now use the
2262 // PHI node as their operand.
Duncan Sands7c8fb1a2008-09-05 12:37:12 +00002263 TheCall->replaceAllUsesWith(PHI);
Chris Lattner18ef3fd2004-02-04 02:51:48 +00002264 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002265
Gabor Greif5aa19222009-01-15 18:40:09 +00002266 // Loop over all of the return instructions adding entries to the PHI node
2267 // as appropriate.
Dan Gohmanfa1211f2008-07-23 00:34:11 +00002268 if (PHI) {
2269 for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
2270 ReturnInst *RI = Returns[i];
2271 assert(RI->getReturnValue()->getType() == PHI->getType() &&
2272 "Ret value not consistent in function!");
2273 PHI->addIncoming(RI->getReturnValue(), RI->getParent());
Devang Patel780b3ca62008-03-07 20:06:16 +00002274 }
2275 }
2276
Gabor Greif8c573f72009-01-16 23:08:50 +00002277 // Add a branch to the merge points and remove return instructions.
Richard Trieu624c2eb2013-04-30 22:45:10 +00002278 DebugLoc Loc;
Chris Lattner18ef3fd2004-02-04 02:51:48 +00002279 for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
Richard Trieu624c2eb2013-04-30 22:45:10 +00002280 ReturnInst *RI = Returns[i];
Adrian Prantl09416382013-04-30 17:08:16 +00002281 BranchInst* BI = BranchInst::Create(AfterCallBB, RI);
Richard Trieu624c2eb2013-04-30 22:45:10 +00002282 Loc = RI->getDebugLoc();
2283 BI->setDebugLoc(Loc);
Devang Patel64d0f072008-03-10 18:34:00 +00002284 RI->eraseFromParent();
Chris Lattner18ef3fd2004-02-04 02:51:48 +00002285 }
Adrian Prantl09416382013-04-30 17:08:16 +00002286 // We need to set the debug location to *somewhere* inside the
Adrian Prantl8beccf92013-04-30 17:33:32 +00002287 // inlined function. The line number may be nonsensical, but the
Adrian Prantl09416382013-04-30 17:08:16 +00002288 // instruction will at least be associated with the right
2289 // function.
2290 if (CreatedBranchToNormalDest)
Richard Trieu624c2eb2013-04-30 22:45:10 +00002291 CreatedBranchToNormalDest->setDebugLoc(Loc);
Devang Patel64d0f072008-03-10 18:34:00 +00002292 } else if (!Returns.empty()) {
2293 // Otherwise, if there is exactly one return value, just replace anything
2294 // using the return value of the call with the computed value.
Eli Friedman36b90262009-05-08 00:22:04 +00002295 if (!TheCall->use_empty()) {
2296 if (TheCall == Returns[0]->getReturnValue())
Owen Andersonb292b8c2009-07-30 23:03:37 +00002297 TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
Eli Friedman36b90262009-05-08 00:22:04 +00002298 else
2299 TheCall->replaceAllUsesWith(Returns[0]->getReturnValue());
2300 }
Duncan Sands7c8fb1a2008-09-05 12:37:12 +00002301
Jay Foad61ea0e42011-06-23 09:09:15 +00002302 // Update PHI nodes that use the ReturnBB to use the AfterCallBB.
2303 BasicBlock *ReturnBB = Returns[0]->getParent();
2304 ReturnBB->replaceAllUsesWith(AfterCallBB);
2305
Devang Patel64d0f072008-03-10 18:34:00 +00002306 // Splice the code from the return block into the block that it will return
2307 // to, which contains the code that was after the call.
Devang Patel64d0f072008-03-10 18:34:00 +00002308 AfterCallBB->getInstList().splice(AfterCallBB->begin(),
2309 ReturnBB->getInstList());
Duncan Sands7c8fb1a2008-09-05 12:37:12 +00002310
Adrian Prantl15db52b2013-04-23 19:56:03 +00002311 if (CreatedBranchToNormalDest)
2312 CreatedBranchToNormalDest->setDebugLoc(Returns[0]->getDebugLoc());
2313
Devang Patel64d0f072008-03-10 18:34:00 +00002314 // Delete the return instruction now and empty ReturnBB now.
2315 Returns[0]->eraseFromParent();
2316 ReturnBB->eraseFromParent();
Chris Lattner6e79e552004-10-17 23:21:07 +00002317 } else if (!TheCall->use_empty()) {
2318 // No returns, but something is using the return value of the call. Just
2319 // nuke the result.
Owen Andersonb292b8c2009-07-30 23:03:37 +00002320 TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
Chris Lattner18ef3fd2004-02-04 02:51:48 +00002321 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002322
Chris Lattner18ef3fd2004-02-04 02:51:48 +00002323 // Since we are now done with the Call/Invoke, we can delete it.
Chris Lattner6e79e552004-10-17 23:21:07 +00002324 TheCall->eraseFromParent();
Chris Lattner530d4bf2003-05-29 15:11:31 +00002325
Reid Klecknerf0915aa2014-05-15 20:11:28 +00002326 // If we inlined any musttail calls and the original return is now
2327 // unreachable, delete it. It can only contain a bitcast and ret.
Easwaran Ramanb1bd3982016-03-08 00:36:35 +00002328 if (InlinedMustTailCalls && pred_begin(AfterCallBB) == pred_end(AfterCallBB))
Reid Klecknerf0915aa2014-05-15 20:11:28 +00002329 AfterCallBB->eraseFromParent();
2330
Chris Lattnerfc3fe5c2003-08-24 04:06:56 +00002331 // We should always be able to fold the entry block of the function into the
2332 // single predecessor of the block...
Chris Lattner0328d752004-04-16 05:17:59 +00002333 assert(cast<BranchInst>(Br)->isUnconditional() && "splitBasicBlock broken!");
Chris Lattnerfc3fe5c2003-08-24 04:06:56 +00002334 BasicBlock *CalleeEntry = cast<BranchInst>(Br)->getSuccessor(0);
Chris Lattner0fa8c7c2004-02-04 04:17:06 +00002335
Chris Lattner0328d752004-04-16 05:17:59 +00002336 // Splice the code entry block into calling block, right before the
2337 // unconditional branch.
Eric Christopher96513122011-06-23 06:24:52 +00002338 CalleeEntry->replaceAllUsesWith(OrigBB); // Update PHI nodes
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002339 OrigBB->getInstList().splice(Br->getIterator(), CalleeEntry->getInstList());
Chris Lattner0328d752004-04-16 05:17:59 +00002340
2341 // Remove the unconditional branch.
2342 OrigBB->getInstList().erase(Br);
2343
2344 // Now we can remove the CalleeEntry block, which is now empty.
2345 Caller->getBasicBlockList().erase(CalleeEntry);
Duncan Sands7c8fb1a2008-09-05 12:37:12 +00002346
Duncan Sands9d9a4e22010-11-17 11:16:23 +00002347 // If we inserted a phi node, check to see if it has a single value (e.g. all
2348 // the entries are the same or undef). If so, remove the PHI so it doesn't
2349 // block other optimizations.
Bill Wendlingce0c2292012-01-31 01:01:16 +00002350 if (PHI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002351 AssumptionCache *AC =
2352 IFI.GetAssumptionCache ? &(*IFI.GetAssumptionCache)(*Caller) : nullptr;
Mehdi Amini46a43552015-03-04 18:43:29 +00002353 auto &DL = Caller->getParent()->getDataLayout();
Daniel Berlin4d0fe642017-04-28 19:55:38 +00002354 if (Value *V = SimplifyInstruction(PHI, {DL, nullptr, nullptr, AC})) {
Duncan Sands9d9a4e22010-11-17 11:16:23 +00002355 PHI->replaceAllUsesWith(V);
2356 PHI->eraseFromParent();
2357 }
Bill Wendlingce0c2292012-01-31 01:01:16 +00002358 }
Duncan Sands9d9a4e22010-11-17 11:16:23 +00002359
Chris Lattner530d4bf2003-05-29 15:11:31 +00002360 return true;
2361}