blob: 5d6fbc3325fff5ff6c71e6e3305fb90a74a1e396 [file] [log] [blame]
Chris Lattner530d4bf2003-05-29 15:11:31 +00001//===- InlineFunction.cpp - Code to perform function inlining -------------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner530d4bf2003-05-29 15:11:31 +00009//
10// This file implements inlining of a function into a call site, resolving
11// parameters and the return value as appropriate.
12//
Chris Lattner530d4bf2003-05-29 15:11:31 +000013//===----------------------------------------------------------------------===//
14
15#include "llvm/Transforms/Utils/Cloning.h"
Weiming Zhao45d4cb92015-11-24 18:57:06 +000016#include "llvm/ADT/SetVector.h"
Joseph Tremoulete92e0a92016-09-04 01:23:20 +000017#include "llvm/ADT/SmallPtrSet.h"
Hal Finkel94146652014-07-24 14:25:39 +000018#include "llvm/ADT/SmallSet.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000019#include "llvm/ADT/SmallVector.h"
20#include "llvm/ADT/StringExtras.h"
Hal Finkelff0bcb62014-07-25 15:50:08 +000021#include "llvm/Analysis/AliasAnalysis.h"
Daniel Jasperaec2fa32016-12-19 08:22:17 +000022#include "llvm/Analysis/AssumptionCache.h"
Easwaran Raman12585b02017-01-20 22:44:04 +000023#include "llvm/Analysis/BlockFrequencyInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000024#include "llvm/Analysis/CallGraph.h"
Hal Finkelff0bcb62014-07-25 15:50:08 +000025#include "llvm/Analysis/CaptureTracking.h"
David Majnemer8a1c45d2015-12-12 05:38:55 +000026#include "llvm/Analysis/EHPersonalities.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000027#include "llvm/Analysis/InstructionSimplify.h"
Dehao Chene5930492017-03-20 16:40:44 +000028#include "llvm/Analysis/ProfileSummaryInfo.h"
Hal Finkel94146652014-07-24 14:25:39 +000029#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000030#include "llvm/IR/Attributes.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000031#include "llvm/IR/CallSite.h"
Reid Klecknerf0915aa2014-05-15 20:11:28 +000032#include "llvm/IR/CFG.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000033#include "llvm/IR/Constants.h"
34#include "llvm/IR/DataLayout.h"
Chandler Carruth9a4c9e52014-03-06 00:46:21 +000035#include "llvm/IR/DebugInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000036#include "llvm/IR/DerivedTypes.h"
Adrian Prantl3e2659e2015-01-30 19:37:48 +000037#include "llvm/IR/DIBuilder.h"
Hal Finkelff0bcb62014-07-25 15:50:08 +000038#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000039#include "llvm/IR/IRBuilder.h"
40#include "llvm/IR/Instructions.h"
41#include "llvm/IR/IntrinsicInst.h"
42#include "llvm/IR/Intrinsics.h"
Hal Finkel94146652014-07-24 14:25:39 +000043#include "llvm/IR/MDBuilder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000044#include "llvm/IR/Module.h"
Hal Finkelff0bcb62014-07-25 15:50:08 +000045#include "llvm/Support/CommandLine.h"
Easwaran Raman12585b02017-01-20 22:44:04 +000046#include "llvm/Transforms/Utils/Local.h"
Hal Finkelff0bcb62014-07-25 15:50:08 +000047#include <algorithm>
Hans Wennborg083ca9b2015-10-06 23:24:35 +000048
Chris Lattnerdf3c3422004-01-09 06:12:26 +000049using namespace llvm;
Chris Lattner530d4bf2003-05-29 15:11:31 +000050
Hal Finkelff0bcb62014-07-25 15:50:08 +000051static cl::opt<bool>
James Molloy6b95d8e2014-09-04 13:23:08 +000052EnableNoAliasConversion("enable-noalias-to-md-conversion", cl::init(true),
Hal Finkelff0bcb62014-07-25 15:50:08 +000053 cl::Hidden,
54 cl::desc("Convert noalias attributes to metadata during inlining."));
55
Hal Finkel68dc3c72014-10-15 23:44:41 +000056static cl::opt<bool>
57PreserveAlignmentAssumptions("preserve-alignment-assumptions-during-inlining",
58 cl::init(true), cl::Hidden,
59 cl::desc("Convert align attributes to assumptions during inlining."));
60
Eric Christopherf16bee82012-03-26 19:09:38 +000061bool llvm::InlineFunction(CallInst *CI, InlineFunctionInfo &IFI,
Chandler Carruth7b560d42015-09-09 17:55:00 +000062 AAResults *CalleeAAR, bool InsertLifetime) {
63 return InlineFunction(CallSite(CI), IFI, CalleeAAR, InsertLifetime);
Chris Lattner0841fb12006-01-14 20:07:50 +000064}
Eric Christopherf16bee82012-03-26 19:09:38 +000065bool llvm::InlineFunction(InvokeInst *II, InlineFunctionInfo &IFI,
Chandler Carruth7b560d42015-09-09 17:55:00 +000066 AAResults *CalleeAAR, bool InsertLifetime) {
67 return InlineFunction(CallSite(II), IFI, CalleeAAR, InsertLifetime);
Chris Lattner0841fb12006-01-14 20:07:50 +000068}
Chris Lattner0cc265e2003-08-24 06:59:16 +000069
John McCallbd04b742011-05-27 18:34:38 +000070namespace {
David Majnemer654e1302015-07-31 17:58:14 +000071 /// A class for recording information about inlining a landing pad.
72 class LandingPadInliningInfo {
Dmitri Gribenkodbeafa72012-06-09 00:01:45 +000073 BasicBlock *OuterResumeDest; ///< Destination of the invoke's unwind.
74 BasicBlock *InnerResumeDest; ///< Destination for the callee's resume.
75 LandingPadInst *CallerLPad; ///< LandingPadInst associated with the invoke.
76 PHINode *InnerEHValuesPHI; ///< PHI for EH values from landingpad insts.
Bill Wendling0c2d82b2012-01-31 01:22:03 +000077 SmallVector<Value*, 8> UnwindDestPHIValues;
Bill Wendlingfa284402011-07-28 07:31:46 +000078
Bill Wendling55421f02011-08-14 08:01:36 +000079 public:
David Majnemer654e1302015-07-31 17:58:14 +000080 LandingPadInliningInfo(InvokeInst *II)
Craig Topperf40110f2014-04-25 05:29:35 +000081 : OuterResumeDest(II->getUnwindDest()), InnerResumeDest(nullptr),
82 CallerLPad(nullptr), InnerEHValuesPHI(nullptr) {
Bill Wendling55421f02011-08-14 08:01:36 +000083 // If there are PHI nodes in the unwind destination block, we need to keep
84 // track of which values came into them from the invoke before removing
85 // the edge from this block.
86 llvm::BasicBlock *InvokeBB = II->getParent();
Bill Wendlingea6e9352012-01-31 01:25:54 +000087 BasicBlock::iterator I = OuterResumeDest->begin();
Bill Wendling55421f02011-08-14 08:01:36 +000088 for (; isa<PHINode>(I); ++I) {
John McCallbd04b742011-05-27 18:34:38 +000089 // Save the value to use for this edge.
Bill Wendling55421f02011-08-14 08:01:36 +000090 PHINode *PHI = cast<PHINode>(I);
91 UnwindDestPHIValues.push_back(PHI->getIncomingValueForBlock(InvokeBB));
92 }
93
Bill Wendlingf3cae512012-01-31 00:56:53 +000094 CallerLPad = cast<LandingPadInst>(I);
John McCallbd04b742011-05-27 18:34:38 +000095 }
96
Sanjay Patel0fdb4372015-03-10 19:42:57 +000097 /// The outer unwind destination is the target of
Bill Wendlingea6e9352012-01-31 01:25:54 +000098 /// unwind edges introduced for calls within the inlined function.
Bill Wendling0c2d82b2012-01-31 01:22:03 +000099 BasicBlock *getOuterResumeDest() const {
Bill Wendlingea6e9352012-01-31 01:25:54 +0000100 return OuterResumeDest;
John McCallbd04b742011-05-27 18:34:38 +0000101 }
102
Bill Wendling3fd879d2012-01-31 01:48:40 +0000103 BasicBlock *getInnerResumeDest();
Bill Wendling55421f02011-08-14 08:01:36 +0000104
105 LandingPadInst *getLandingPadInst() const { return CallerLPad; }
106
Sanjay Patel0fdb4372015-03-10 19:42:57 +0000107 /// Forward the 'resume' instruction to the caller's landing pad block.
108 /// When the landing pad block has only one predecessor, this is
Bill Wendling55421f02011-08-14 08:01:36 +0000109 /// a simple branch. When there is more than one predecessor, we need to
110 /// split the landing pad block after the landingpad instruction and jump
111 /// to there.
Bill Wendling56f15bf2013-03-22 20:31:05 +0000112 void forwardResume(ResumeInst *RI,
Craig Topper71b7b682014-08-21 05:55:13 +0000113 SmallPtrSetImpl<LandingPadInst*> &InlinedLPads);
Bill Wendling55421f02011-08-14 08:01:36 +0000114
Sanjay Patel0fdb4372015-03-10 19:42:57 +0000115 /// Add incoming-PHI values to the unwind destination block for the given
116 /// basic block, using the values for the original invoke's source block.
John McCallbd04b742011-05-27 18:34:38 +0000117 void addIncomingPHIValuesFor(BasicBlock *BB) const {
Bill Wendlingea6e9352012-01-31 01:25:54 +0000118 addIncomingPHIValuesForInto(BB, OuterResumeDest);
John McCall046c47e2011-05-28 07:45:59 +0000119 }
Bill Wendlingad088e62011-07-30 05:42:50 +0000120
John McCall046c47e2011-05-28 07:45:59 +0000121 void addIncomingPHIValuesForInto(BasicBlock *src, BasicBlock *dest) const {
122 BasicBlock::iterator I = dest->begin();
John McCallbd04b742011-05-27 18:34:38 +0000123 for (unsigned i = 0, e = UnwindDestPHIValues.size(); i != e; ++i, ++I) {
Bill Wendlingad088e62011-07-30 05:42:50 +0000124 PHINode *phi = cast<PHINode>(I);
125 phi->addIncoming(UnwindDestPHIValues[i], src);
John McCallbd04b742011-05-27 18:34:38 +0000126 }
127 }
128 };
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000129} // anonymous namespace
John McCallbd04b742011-05-27 18:34:38 +0000130
Sanjay Patel0fdb4372015-03-10 19:42:57 +0000131/// Get or create a target for the branch from ResumeInsts.
David Majnemer654e1302015-07-31 17:58:14 +0000132BasicBlock *LandingPadInliningInfo::getInnerResumeDest() {
Bill Wendling55421f02011-08-14 08:01:36 +0000133 if (InnerResumeDest) return InnerResumeDest;
134
135 // Split the landing pad.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000136 BasicBlock::iterator SplitPoint = ++CallerLPad->getIterator();
Bill Wendling55421f02011-08-14 08:01:36 +0000137 InnerResumeDest =
138 OuterResumeDest->splitBasicBlock(SplitPoint,
139 OuterResumeDest->getName() + ".body");
140
141 // The number of incoming edges we expect to the inner landing pad.
142 const unsigned PHICapacity = 2;
143
144 // Create corresponding new PHIs for all the PHIs in the outer landing pad.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000145 Instruction *InsertPoint = &InnerResumeDest->front();
Bill Wendling55421f02011-08-14 08:01:36 +0000146 BasicBlock::iterator I = OuterResumeDest->begin();
147 for (unsigned i = 0, e = UnwindDestPHIValues.size(); i != e; ++i, ++I) {
148 PHINode *OuterPHI = cast<PHINode>(I);
149 PHINode *InnerPHI = PHINode::Create(OuterPHI->getType(), PHICapacity,
150 OuterPHI->getName() + ".lpad-body",
151 InsertPoint);
152 OuterPHI->replaceAllUsesWith(InnerPHI);
153 InnerPHI->addIncoming(OuterPHI, OuterResumeDest);
154 }
155
156 // Create a PHI for the exception values.
157 InnerEHValuesPHI = PHINode::Create(CallerLPad->getType(), PHICapacity,
158 "eh.lpad-body", InsertPoint);
159 CallerLPad->replaceAllUsesWith(InnerEHValuesPHI);
160 InnerEHValuesPHI->addIncoming(CallerLPad, OuterResumeDest);
161
162 // All done.
163 return InnerResumeDest;
164}
165
Sanjay Patel0fdb4372015-03-10 19:42:57 +0000166/// Forward the 'resume' instruction to the caller's landing pad block.
167/// When the landing pad block has only one predecessor, this is a simple
Bill Wendling55421f02011-08-14 08:01:36 +0000168/// branch. When there is more than one predecessor, we need to split the
169/// landing pad block after the landingpad instruction and jump to there.
David Majnemer654e1302015-07-31 17:58:14 +0000170void LandingPadInliningInfo::forwardResume(
171 ResumeInst *RI, SmallPtrSetImpl<LandingPadInst *> &InlinedLPads) {
Bill Wendling3fd879d2012-01-31 01:48:40 +0000172 BasicBlock *Dest = getInnerResumeDest();
Bill Wendling55421f02011-08-14 08:01:36 +0000173 BasicBlock *Src = RI->getParent();
174
175 BranchInst::Create(Dest, Src);
176
177 // Update the PHIs in the destination. They were inserted in an order which
178 // makes this work.
179 addIncomingPHIValuesForInto(Src, Dest);
180
181 InnerEHValuesPHI->addIncoming(RI->getOperand(0), Src);
182 RI->eraseFromParent();
183}
184
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000185/// Helper for getUnwindDestToken/getUnwindDestTokenHelper.
186static Value *getParentPad(Value *EHPad) {
187 if (auto *FPI = dyn_cast<FuncletPadInst>(EHPad))
188 return FPI->getParentPad();
189 return cast<CatchSwitchInst>(EHPad)->getParentPad();
190}
191
192typedef DenseMap<Instruction *, Value *> UnwindDestMemoTy;
193
194/// Helper for getUnwindDestToken that does the descendant-ward part of
195/// the search.
196static Value *getUnwindDestTokenHelper(Instruction *EHPad,
197 UnwindDestMemoTy &MemoMap) {
198 SmallVector<Instruction *, 8> Worklist(1, EHPad);
199
200 while (!Worklist.empty()) {
201 Instruction *CurrentPad = Worklist.pop_back_val();
202 // We only put pads on the worklist that aren't in the MemoMap. When
203 // we find an unwind dest for a pad we may update its ancestors, but
204 // the queue only ever contains uncles/great-uncles/etc. of CurrentPad,
205 // so they should never get updated while queued on the worklist.
206 assert(!MemoMap.count(CurrentPad));
207 Value *UnwindDestToken = nullptr;
208 if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(CurrentPad)) {
209 if (CatchSwitch->hasUnwindDest()) {
210 UnwindDestToken = CatchSwitch->getUnwindDest()->getFirstNonPHI();
211 } else {
212 // Catchswitch doesn't have a 'nounwind' variant, and one might be
213 // annotated as "unwinds to caller" when really it's nounwind (see
214 // e.g. SimplifyCFGOpt::SimplifyUnreachable), so we can't infer the
215 // parent's unwind dest from this. We can check its catchpads'
216 // descendants, since they might include a cleanuppad with an
217 // "unwinds to caller" cleanupret, which can be trusted.
218 for (auto HI = CatchSwitch->handler_begin(),
219 HE = CatchSwitch->handler_end();
220 HI != HE && !UnwindDestToken; ++HI) {
221 BasicBlock *HandlerBlock = *HI;
222 auto *CatchPad = cast<CatchPadInst>(HandlerBlock->getFirstNonPHI());
223 for (User *Child : CatchPad->users()) {
224 // Intentionally ignore invokes here -- since the catchswitch is
225 // marked "unwind to caller", it would be a verifier error if it
226 // contained an invoke which unwinds out of it, so any invoke we'd
227 // encounter must unwind to some child of the catch.
228 if (!isa<CleanupPadInst>(Child) && !isa<CatchSwitchInst>(Child))
229 continue;
230
231 Instruction *ChildPad = cast<Instruction>(Child);
232 auto Memo = MemoMap.find(ChildPad);
233 if (Memo == MemoMap.end()) {
Joseph Tremoulete92e0a92016-09-04 01:23:20 +0000234 // Haven't figured out this child pad yet; queue it.
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000235 Worklist.push_back(ChildPad);
236 continue;
237 }
238 // We've already checked this child, but might have found that
239 // it offers no proof either way.
240 Value *ChildUnwindDestToken = Memo->second;
241 if (!ChildUnwindDestToken)
242 continue;
243 // We already know the child's unwind dest, which can either
244 // be ConstantTokenNone to indicate unwind to caller, or can
245 // be another child of the catchpad. Only the former indicates
246 // the unwind dest of the catchswitch.
247 if (isa<ConstantTokenNone>(ChildUnwindDestToken)) {
248 UnwindDestToken = ChildUnwindDestToken;
249 break;
250 }
251 assert(getParentPad(ChildUnwindDestToken) == CatchPad);
252 }
253 }
254 }
255 } else {
256 auto *CleanupPad = cast<CleanupPadInst>(CurrentPad);
257 for (User *U : CleanupPad->users()) {
258 if (auto *CleanupRet = dyn_cast<CleanupReturnInst>(U)) {
259 if (BasicBlock *RetUnwindDest = CleanupRet->getUnwindDest())
260 UnwindDestToken = RetUnwindDest->getFirstNonPHI();
261 else
262 UnwindDestToken = ConstantTokenNone::get(CleanupPad->getContext());
263 break;
264 }
265 Value *ChildUnwindDestToken;
266 if (auto *Invoke = dyn_cast<InvokeInst>(U)) {
267 ChildUnwindDestToken = Invoke->getUnwindDest()->getFirstNonPHI();
268 } else if (isa<CleanupPadInst>(U) || isa<CatchSwitchInst>(U)) {
269 Instruction *ChildPad = cast<Instruction>(U);
270 auto Memo = MemoMap.find(ChildPad);
271 if (Memo == MemoMap.end()) {
272 // Haven't resolved this child yet; queue it and keep searching.
273 Worklist.push_back(ChildPad);
274 continue;
275 }
276 // We've checked this child, but still need to ignore it if it
277 // had no proof either way.
278 ChildUnwindDestToken = Memo->second;
279 if (!ChildUnwindDestToken)
280 continue;
281 } else {
282 // Not a relevant user of the cleanuppad
283 continue;
284 }
285 // In a well-formed program, the child/invoke must either unwind to
286 // an(other) child of the cleanup, or exit the cleanup. In the
287 // first case, continue searching.
288 if (isa<Instruction>(ChildUnwindDestToken) &&
289 getParentPad(ChildUnwindDestToken) == CleanupPad)
290 continue;
291 UnwindDestToken = ChildUnwindDestToken;
292 break;
293 }
294 }
295 // If we haven't found an unwind dest for CurrentPad, we may have queued its
296 // children, so move on to the next in the worklist.
297 if (!UnwindDestToken)
298 continue;
299
300 // Now we know that CurrentPad unwinds to UnwindDestToken. It also exits
301 // any ancestors of CurrentPad up to but not including UnwindDestToken's
302 // parent pad. Record this in the memo map, and check to see if the
303 // original EHPad being queried is one of the ones exited.
304 Value *UnwindParent;
305 if (auto *UnwindPad = dyn_cast<Instruction>(UnwindDestToken))
306 UnwindParent = getParentPad(UnwindPad);
307 else
308 UnwindParent = nullptr;
309 bool ExitedOriginalPad = false;
310 for (Instruction *ExitedPad = CurrentPad;
311 ExitedPad && ExitedPad != UnwindParent;
312 ExitedPad = dyn_cast<Instruction>(getParentPad(ExitedPad))) {
313 // Skip over catchpads since they just follow their catchswitches.
314 if (isa<CatchPadInst>(ExitedPad))
315 continue;
316 MemoMap[ExitedPad] = UnwindDestToken;
317 ExitedOriginalPad |= (ExitedPad == EHPad);
318 }
319
320 if (ExitedOriginalPad)
321 return UnwindDestToken;
322
323 // Continue the search.
324 }
325
326 // No definitive information is contained within this funclet.
327 return nullptr;
328}
329
330/// Given an EH pad, find where it unwinds. If it unwinds to an EH pad,
331/// return that pad instruction. If it unwinds to caller, return
332/// ConstantTokenNone. If it does not have a definitive unwind destination,
333/// return nullptr.
334///
335/// This routine gets invoked for calls in funclets in inlinees when inlining
336/// an invoke. Since many funclets don't have calls inside them, it's queried
337/// on-demand rather than building a map of pads to unwind dests up front.
338/// Determining a funclet's unwind dest may require recursively searching its
339/// descendants, and also ancestors and cousins if the descendants don't provide
340/// an answer. Since most funclets will have their unwind dest immediately
341/// available as the unwind dest of a catchswitch or cleanupret, this routine
342/// searches top-down from the given pad and then up. To avoid worst-case
343/// quadratic run-time given that approach, it uses a memo map to avoid
344/// re-processing funclet trees. The callers that rewrite the IR as they go
345/// take advantage of this, for correctness, by checking/forcing rewritten
346/// pads' entries to match the original callee view.
347static Value *getUnwindDestToken(Instruction *EHPad,
348 UnwindDestMemoTy &MemoMap) {
349 // Catchpads unwind to the same place as their catchswitch;
350 // redirct any queries on catchpads so the code below can
351 // deal with just catchswitches and cleanuppads.
352 if (auto *CPI = dyn_cast<CatchPadInst>(EHPad))
353 EHPad = CPI->getCatchSwitch();
354
355 // Check if we've already determined the unwind dest for this pad.
356 auto Memo = MemoMap.find(EHPad);
357 if (Memo != MemoMap.end())
358 return Memo->second;
359
360 // Search EHPad and, if necessary, its descendants.
361 Value *UnwindDestToken = getUnwindDestTokenHelper(EHPad, MemoMap);
362 assert((UnwindDestToken == nullptr) != (MemoMap.count(EHPad) != 0));
363 if (UnwindDestToken)
364 return UnwindDestToken;
365
366 // No information is available for this EHPad from itself or any of its
367 // descendants. An unwind all the way out to a pad in the caller would
368 // need also to agree with the unwind dest of the parent funclet, so
369 // search up the chain to try to find a funclet with information. Put
370 // null entries in the memo map to avoid re-processing as we go up.
371 MemoMap[EHPad] = nullptr;
Joseph Tremoulete92e0a92016-09-04 01:23:20 +0000372#ifndef NDEBUG
373 SmallPtrSet<Instruction *, 4> TempMemos;
374 TempMemos.insert(EHPad);
375#endif
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000376 Instruction *LastUselessPad = EHPad;
377 Value *AncestorToken;
378 for (AncestorToken = getParentPad(EHPad);
379 auto *AncestorPad = dyn_cast<Instruction>(AncestorToken);
380 AncestorToken = getParentPad(AncestorToken)) {
381 // Skip over catchpads since they just follow their catchswitches.
382 if (isa<CatchPadInst>(AncestorPad))
383 continue;
Joseph Tremoulete92e0a92016-09-04 01:23:20 +0000384 // If the MemoMap had an entry mapping AncestorPad to nullptr, since we
385 // haven't yet called getUnwindDestTokenHelper for AncestorPad in this
386 // call to getUnwindDestToken, that would mean that AncestorPad had no
387 // information in itself, its descendants, or its ancestors. If that
388 // were the case, then we should also have recorded the lack of information
389 // for the descendant that we're coming from. So assert that we don't
390 // find a null entry in the MemoMap for AncestorPad.
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000391 assert(!MemoMap.count(AncestorPad) || MemoMap[AncestorPad]);
392 auto AncestorMemo = MemoMap.find(AncestorPad);
393 if (AncestorMemo == MemoMap.end()) {
394 UnwindDestToken = getUnwindDestTokenHelper(AncestorPad, MemoMap);
395 } else {
396 UnwindDestToken = AncestorMemo->second;
397 }
398 if (UnwindDestToken)
399 break;
400 LastUselessPad = AncestorPad;
Joseph Tremoulete92e0a92016-09-04 01:23:20 +0000401 MemoMap[LastUselessPad] = nullptr;
402#ifndef NDEBUG
403 TempMemos.insert(LastUselessPad);
404#endif
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000405 }
406
Joseph Tremoulete92e0a92016-09-04 01:23:20 +0000407 // We know that getUnwindDestTokenHelper was called on LastUselessPad and
408 // returned nullptr (and likewise for EHPad and any of its ancestors up to
409 // LastUselessPad), so LastUselessPad has no information from below. Since
410 // getUnwindDestTokenHelper must investigate all downward paths through
411 // no-information nodes to prove that a node has no information like this,
412 // and since any time it finds information it records it in the MemoMap for
413 // not just the immediately-containing funclet but also any ancestors also
414 // exited, it must be the case that, walking downward from LastUselessPad,
415 // visiting just those nodes which have not been mapped to an unwind dest
416 // by getUnwindDestTokenHelper (the nullptr TempMemos notwithstanding, since
417 // they are just used to keep getUnwindDestTokenHelper from repeating work),
418 // any node visited must have been exhaustively searched with no information
419 // for it found.
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000420 SmallVector<Instruction *, 8> Worklist(1, LastUselessPad);
421 while (!Worklist.empty()) {
422 Instruction *UselessPad = Worklist.pop_back_val();
Joseph Tremoulete92e0a92016-09-04 01:23:20 +0000423 auto Memo = MemoMap.find(UselessPad);
424 if (Memo != MemoMap.end() && Memo->second) {
425 // Here the name 'UselessPad' is a bit of a misnomer, because we've found
426 // that it is a funclet that does have information about unwinding to
427 // a particular destination; its parent was a useless pad.
428 // Since its parent has no information, the unwind edge must not escape
429 // the parent, and must target a sibling of this pad. This local unwind
430 // gives us no information about EHPad. Leave it and the subtree rooted
431 // at it alone.
432 assert(getParentPad(Memo->second) == getParentPad(UselessPad));
433 continue;
434 }
435 // We know we don't have information for UselesPad. If it has an entry in
436 // the MemoMap (mapping it to nullptr), it must be one of the TempMemos
437 // added on this invocation of getUnwindDestToken; if a previous invocation
438 // recorded nullptr, it would have had to prove that the ancestors of
439 // UselessPad, which include LastUselessPad, had no information, and that
440 // in turn would have required proving that the descendants of
441 // LastUselesPad, which include EHPad, have no information about
442 // LastUselessPad, which would imply that EHPad was mapped to nullptr in
443 // the MemoMap on that invocation, which isn't the case if we got here.
444 assert(!MemoMap.count(UselessPad) || TempMemos.count(UselessPad));
445 // Assert as we enumerate users that 'UselessPad' doesn't have any unwind
446 // information that we'd be contradicting by making a map entry for it
447 // (which is something that getUnwindDestTokenHelper must have proved for
448 // us to get here). Just assert on is direct users here; the checks in
449 // this downward walk at its descendants will verify that they don't have
450 // any unwind edges that exit 'UselessPad' either (i.e. they either have no
451 // unwind edges or unwind to a sibling).
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000452 MemoMap[UselessPad] = UnwindDestToken;
453 if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(UselessPad)) {
Joseph Tremoulete92e0a92016-09-04 01:23:20 +0000454 assert(CatchSwitch->getUnwindDest() == nullptr && "Expected useless pad");
455 for (BasicBlock *HandlerBlock : CatchSwitch->handlers()) {
456 auto *CatchPad = HandlerBlock->getFirstNonPHI();
457 for (User *U : CatchPad->users()) {
458 assert(
459 (!isa<InvokeInst>(U) ||
460 (getParentPad(
461 cast<InvokeInst>(U)->getUnwindDest()->getFirstNonPHI()) ==
462 CatchPad)) &&
463 "Expected useless pad");
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000464 if (isa<CatchSwitchInst>(U) || isa<CleanupPadInst>(U))
465 Worklist.push_back(cast<Instruction>(U));
Joseph Tremoulete92e0a92016-09-04 01:23:20 +0000466 }
467 }
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000468 } else {
469 assert(isa<CleanupPadInst>(UselessPad));
Joseph Tremoulete92e0a92016-09-04 01:23:20 +0000470 for (User *U : UselessPad->users()) {
471 assert(!isa<CleanupReturnInst>(U) && "Expected useless pad");
472 assert((!isa<InvokeInst>(U) ||
473 (getParentPad(
474 cast<InvokeInst>(U)->getUnwindDest()->getFirstNonPHI()) ==
475 UselessPad)) &&
476 "Expected useless pad");
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000477 if (isa<CatchSwitchInst>(U) || isa<CleanupPadInst>(U))
478 Worklist.push_back(cast<Instruction>(U));
Joseph Tremoulete92e0a92016-09-04 01:23:20 +0000479 }
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000480 }
481 }
482
483 return UnwindDestToken;
484}
485
Sanjay Patel0fdb4372015-03-10 19:42:57 +0000486/// When we inline a basic block into an invoke,
487/// we have to turn all of the calls that can throw into invokes.
488/// This function analyze BB to see if there are any calls, and if so,
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000489/// it rewrites them to be invokes that jump to InvokeDest and fills in the PHI
Chris Lattner8900f3e2009-09-01 18:44:06 +0000490/// nodes in that block with the values specified in InvokeDestPHIValues.
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000491static BasicBlock *HandleCallsInBlockInlinedThroughInvoke(
492 BasicBlock *BB, BasicBlock *UnwindEdge,
493 UnwindDestMemoTy *FuncletUnwindMap = nullptr) {
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000494 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000495 Instruction *I = &*BBI++;
Bill Wendling55421f02011-08-14 08:01:36 +0000496
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000497 // We only need to check for function calls: inlined invoke
498 // instructions require no special handling.
499 CallInst *CI = dyn_cast<CallInst>(I);
John McCallbd04b742011-05-27 18:34:38 +0000500
Manman Ren87a2adc2013-10-31 21:56:03 +0000501 if (!CI || CI->doesNotThrow() || isa<InlineAsm>(CI->getCalledValue()))
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000502 continue;
Bill Wendling518a2052012-01-31 01:05:20 +0000503
Sanjoy Dasb51325d2016-03-11 19:08:34 +0000504 // We do not need to (and in fact, cannot) convert possibly throwing calls
Sanjoy Das021de052016-03-31 00:18:46 +0000505 // to @llvm.experimental_deoptimize (resp. @llvm.experimental.guard) into
506 // invokes. The caller's "segment" of the deoptimization continuation
507 // attached to the newly inlined @llvm.experimental_deoptimize
508 // (resp. @llvm.experimental.guard) call should contain the exception
509 // handling logic, if any.
Sanjoy Dasb51325d2016-03-11 19:08:34 +0000510 if (auto *F = CI->getCalledFunction())
Sanjoy Das021de052016-03-31 00:18:46 +0000511 if (F->getIntrinsicID() == Intrinsic::experimental_deoptimize ||
512 F->getIntrinsicID() == Intrinsic::experimental_guard)
Sanjoy Dasb51325d2016-03-11 19:08:34 +0000513 continue;
514
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000515 if (auto FuncletBundle = CI->getOperandBundle(LLVMContext::OB_funclet)) {
516 // This call is nested inside a funclet. If that funclet has an unwind
517 // destination within the inlinee, then unwinding out of this call would
518 // be UB. Rewriting this call to an invoke which targets the inlined
519 // invoke's unwind dest would give the call's parent funclet multiple
520 // unwind destinations, which is something that subsequent EH table
521 // generation can't handle and that the veirifer rejects. So when we
522 // see such a call, leave it as a call.
523 auto *FuncletPad = cast<Instruction>(FuncletBundle->Inputs[0]);
524 Value *UnwindDestToken =
525 getUnwindDestToken(FuncletPad, *FuncletUnwindMap);
526 if (UnwindDestToken && !isa<ConstantTokenNone>(UnwindDestToken))
527 continue;
528#ifndef NDEBUG
529 Instruction *MemoKey;
530 if (auto *CatchPad = dyn_cast<CatchPadInst>(FuncletPad))
531 MemoKey = CatchPad->getCatchSwitch();
532 else
533 MemoKey = FuncletPad;
534 assert(FuncletUnwindMap->count(MemoKey) &&
535 (*FuncletUnwindMap)[MemoKey] == UnwindDestToken &&
536 "must get memoized to avoid confusing later searches");
537#endif // NDEBUG
538 }
539
Kuba Breckaddfdba32016-11-14 21:41:13 +0000540 changeToInvokeAndSplitBasicBlock(CI, UnwindEdge);
David Majnemer654e1302015-07-31 17:58:14 +0000541 return BB;
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000542 }
David Majnemer654e1302015-07-31 17:58:14 +0000543 return nullptr;
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000544}
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000545
Sanjay Patel0fdb4372015-03-10 19:42:57 +0000546/// If we inlined an invoke site, we need to convert calls
Bill Wendling0aef16a2012-02-06 21:44:22 +0000547/// in the body of the inlined function into invokes.
Chris Lattner908d7952006-01-13 19:05:59 +0000548///
Nick Lewycky12a130b2009-02-03 04:34:40 +0000549/// II is the invoke instruction being inlined. FirstNewBlock is the first
Chris Lattner908d7952006-01-13 19:05:59 +0000550/// block of the inlined code (the last block is the end of the function),
551/// and InlineCodeInfo is information about the code that got inlined.
David Majnemer654e1302015-07-31 17:58:14 +0000552static void HandleInlinedLandingPad(InvokeInst *II, BasicBlock *FirstNewBlock,
553 ClonedCodeInfo &InlinedCodeInfo) {
Chris Lattner908d7952006-01-13 19:05:59 +0000554 BasicBlock *InvokeDest = II->getUnwindDest();
Chris Lattner908d7952006-01-13 19:05:59 +0000555
556 Function *Caller = FirstNewBlock->getParent();
Duncan Sands7c8fb1a2008-09-05 12:37:12 +0000557
Chris Lattner908d7952006-01-13 19:05:59 +0000558 // The inlined code is currently at the end of the function, scan from the
559 // start of the inlined code to its end, checking for stuff we need to
Bill Wendling173c71f2013-03-21 23:30:12 +0000560 // rewrite.
David Majnemer654e1302015-07-31 17:58:14 +0000561 LandingPadInliningInfo Invoke(II);
Bill Wendling173c71f2013-03-21 23:30:12 +0000562
Bill Wendling56f15bf2013-03-22 20:31:05 +0000563 // Get all of the inlined landing pad instructions.
564 SmallPtrSet<LandingPadInst*, 16> InlinedLPads;
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000565 for (Function::iterator I = FirstNewBlock->getIterator(), E = Caller->end();
566 I != E; ++I)
Bill Wendling56f15bf2013-03-22 20:31:05 +0000567 if (InvokeInst *II = dyn_cast<InvokeInst>(I->getTerminator()))
568 InlinedLPads.insert(II->getLandingPadInst());
569
Mark Seabornef3dbb92013-12-08 00:50:58 +0000570 // Append the clauses from the outer landing pad instruction into the inlined
571 // landing pad instructions.
572 LandingPadInst *OuterLPad = Invoke.getLandingPadInst();
Craig Topper46276792014-08-24 23:23:06 +0000573 for (LandingPadInst *InlinedLPad : InlinedLPads) {
Mark Seabornef3dbb92013-12-08 00:50:58 +0000574 unsigned OuterNum = OuterLPad->getNumClauses();
575 InlinedLPad->reserveClauses(OuterNum);
576 for (unsigned OuterIdx = 0; OuterIdx != OuterNum; ++OuterIdx)
577 InlinedLPad->addClause(OuterLPad->getClause(OuterIdx));
Mark Seaborn1b3dd352013-12-08 00:51:21 +0000578 if (OuterLPad->isCleanup())
579 InlinedLPad->setCleanup(true);
Mark Seabornef3dbb92013-12-08 00:50:58 +0000580 }
581
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000582 for (Function::iterator BB = FirstNewBlock->getIterator(), E = Caller->end();
583 BB != E; ++BB) {
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000584 if (InlinedCodeInfo.ContainsCalls)
David Majnemer654e1302015-07-31 17:58:14 +0000585 if (BasicBlock *NewBB = HandleCallsInBlockInlinedThroughInvoke(
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000586 &*BB, Invoke.getOuterResumeDest()))
David Majnemer654e1302015-07-31 17:58:14 +0000587 // Update any PHI nodes in the exceptional block to indicate that there
588 // is now a new entry in them.
589 Invoke.addIncomingPHIValuesFor(NewBB);
Duncan Sands7c8fb1a2008-09-05 12:37:12 +0000590
Bill Wendling173c71f2013-03-21 23:30:12 +0000591 // Forward any resumes that are remaining here.
Bill Wendling621699d2012-01-31 01:14:49 +0000592 if (ResumeInst *RI = dyn_cast<ResumeInst>(BB->getTerminator()))
Bill Wendling56f15bf2013-03-22 20:31:05 +0000593 Invoke.forwardResume(RI, InlinedLPads);
Chris Lattner908d7952006-01-13 19:05:59 +0000594 }
595
596 // Now that everything is happy, we have one final detail. The PHI nodes in
597 // the exception destination block still have entries due to the original
Bill Wendling173c71f2013-03-21 23:30:12 +0000598 // invoke instruction. Eliminate these entries (which might even delete the
Chris Lattner908d7952006-01-13 19:05:59 +0000599 // PHI node) now.
600 InvokeDest->removePredecessor(II->getParent());
601}
602
David Majnemer654e1302015-07-31 17:58:14 +0000603/// If we inlined an invoke site, we need to convert calls
604/// in the body of the inlined function into invokes.
605///
606/// II is the invoke instruction being inlined. FirstNewBlock is the first
607/// block of the inlined code (the last block is the end of the function),
608/// and InlineCodeInfo is information about the code that got inlined.
609static void HandleInlinedEHPad(InvokeInst *II, BasicBlock *FirstNewBlock,
610 ClonedCodeInfo &InlinedCodeInfo) {
611 BasicBlock *UnwindDest = II->getUnwindDest();
612 Function *Caller = FirstNewBlock->getParent();
613
614 assert(UnwindDest->getFirstNonPHI()->isEHPad() && "unexpected BasicBlock!");
615
616 // If there are PHI nodes in the unwind destination block, we need to keep
617 // track of which values came into them from the invoke before removing the
618 // edge from this block.
619 SmallVector<Value *, 8> UnwindDestPHIValues;
620 llvm::BasicBlock *InvokeBB = II->getParent();
621 for (Instruction &I : *UnwindDest) {
622 // Save the value to use for this edge.
623 PHINode *PHI = dyn_cast<PHINode>(&I);
624 if (!PHI)
625 break;
626 UnwindDestPHIValues.push_back(PHI->getIncomingValueForBlock(InvokeBB));
627 }
628
629 // Add incoming-PHI values to the unwind destination block for the given basic
630 // block, using the values for the original invoke's source block.
631 auto UpdatePHINodes = [&](BasicBlock *Src) {
632 BasicBlock::iterator I = UnwindDest->begin();
633 for (Value *V : UnwindDestPHIValues) {
634 PHINode *PHI = cast<PHINode>(I);
635 PHI->addIncoming(V, Src);
636 ++I;
637 }
638 };
639
David Majnemer8a1c45d2015-12-12 05:38:55 +0000640 // This connects all the instructions which 'unwind to caller' to the invoke
641 // destination.
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000642 UnwindDestMemoTy FuncletUnwindMap;
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000643 for (Function::iterator BB = FirstNewBlock->getIterator(), E = Caller->end();
644 BB != E; ++BB) {
David Majnemer654e1302015-07-31 17:58:14 +0000645 if (auto *CRI = dyn_cast<CleanupReturnInst>(BB->getTerminator())) {
646 if (CRI->unwindsToCaller()) {
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000647 auto *CleanupPad = CRI->getCleanupPad();
648 CleanupReturnInst::Create(CleanupPad, UnwindDest, CRI);
David Majnemer654e1302015-07-31 17:58:14 +0000649 CRI->eraseFromParent();
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000650 UpdatePHINodes(&*BB);
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000651 // Finding a cleanupret with an unwind destination would confuse
652 // subsequent calls to getUnwindDestToken, so map the cleanuppad
653 // to short-circuit any such calls and recognize this as an "unwind
654 // to caller" cleanup.
655 assert(!FuncletUnwindMap.count(CleanupPad) ||
656 isa<ConstantTokenNone>(FuncletUnwindMap[CleanupPad]));
657 FuncletUnwindMap[CleanupPad] =
658 ConstantTokenNone::get(Caller->getContext());
David Majnemer654e1302015-07-31 17:58:14 +0000659 }
660 }
David Majnemer8a1c45d2015-12-12 05:38:55 +0000661
662 Instruction *I = BB->getFirstNonPHI();
663 if (!I->isEHPad())
664 continue;
665
666 Instruction *Replacement = nullptr;
David Majnemerbbfc7212015-12-14 18:34:23 +0000667 if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(I)) {
David Majnemer8a1c45d2015-12-12 05:38:55 +0000668 if (CatchSwitch->unwindsToCaller()) {
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000669 Value *UnwindDestToken;
670 if (auto *ParentPad =
671 dyn_cast<Instruction>(CatchSwitch->getParentPad())) {
672 // This catchswitch is nested inside another funclet. If that
673 // funclet has an unwind destination within the inlinee, then
674 // unwinding out of this catchswitch would be UB. Rewriting this
675 // catchswitch to unwind to the inlined invoke's unwind dest would
676 // give the parent funclet multiple unwind destinations, which is
677 // something that subsequent EH table generation can't handle and
678 // that the veirifer rejects. So when we see such a call, leave it
679 // as "unwind to caller".
680 UnwindDestToken = getUnwindDestToken(ParentPad, FuncletUnwindMap);
681 if (UnwindDestToken && !isa<ConstantTokenNone>(UnwindDestToken))
682 continue;
683 } else {
684 // This catchswitch has no parent to inherit constraints from, and
685 // none of its descendants can have an unwind edge that exits it and
686 // targets another funclet in the inlinee. It may or may not have a
687 // descendant that definitively has an unwind to caller. In either
688 // case, we'll have to assume that any unwinds out of it may need to
689 // be routed to the caller, so treat it as though it has a definitive
690 // unwind to caller.
691 UnwindDestToken = ConstantTokenNone::get(Caller->getContext());
692 }
David Majnemer8a1c45d2015-12-12 05:38:55 +0000693 auto *NewCatchSwitch = CatchSwitchInst::Create(
694 CatchSwitch->getParentPad(), UnwindDest,
695 CatchSwitch->getNumHandlers(), CatchSwitch->getName(),
696 CatchSwitch);
697 for (BasicBlock *PadBB : CatchSwitch->handlers())
698 NewCatchSwitch->addHandler(PadBB);
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000699 // Propagate info for the old catchswitch over to the new one in
700 // the unwind map. This also serves to short-circuit any subsequent
701 // checks for the unwind dest of this catchswitch, which would get
702 // confused if they found the outer handler in the callee.
703 FuncletUnwindMap[NewCatchSwitch] = UnwindDestToken;
David Majnemer8a1c45d2015-12-12 05:38:55 +0000704 Replacement = NewCatchSwitch;
705 }
706 } else if (!isa<FuncletPadInst>(I)) {
707 llvm_unreachable("unexpected EHPad!");
708 }
709
710 if (Replacement) {
711 Replacement->takeName(I);
712 I->replaceAllUsesWith(Replacement);
713 I->eraseFromParent();
714 UpdatePHINodes(&*BB);
715 }
David Majnemer654e1302015-07-31 17:58:14 +0000716 }
717
718 if (InlinedCodeInfo.ContainsCalls)
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000719 for (Function::iterator BB = FirstNewBlock->getIterator(),
720 E = Caller->end();
721 BB != E; ++BB)
Joseph Tremouletb41632b2016-01-20 02:15:15 +0000722 if (BasicBlock *NewBB = HandleCallsInBlockInlinedThroughInvoke(
723 &*BB, UnwindDest, &FuncletUnwindMap))
David Majnemer654e1302015-07-31 17:58:14 +0000724 // Update any PHI nodes in the exceptional block to indicate that there
725 // is now a new entry in them.
726 UpdatePHINodes(NewBB);
727
728 // Now that everything is happy, we have one final detail. The PHI nodes in
729 // the exception destination block still have entries due to the original
730 // invoke instruction. Eliminate these entries (which might even delete the
731 // PHI node) now.
732 UnwindDest->removePredecessor(InvokeBB);
733}
734
Hal Finkel50316d92016-04-28 23:00:04 +0000735/// When inlining a call site that has !llvm.mem.parallel_loop_access metadata,
736/// that metadata should be propagated to all memory-accessing cloned
737/// instructions.
738static void PropagateParallelLoopAccessMetadata(CallSite CS,
739 ValueToValueMapTy &VMap) {
740 MDNode *M =
741 CS.getInstruction()->getMetadata(LLVMContext::MD_mem_parallel_loop_access);
742 if (!M)
743 return;
744
745 for (ValueToValueMapTy::iterator VMI = VMap.begin(), VMIE = VMap.end();
746 VMI != VMIE; ++VMI) {
747 if (!VMI->second)
748 continue;
749
750 Instruction *NI = dyn_cast<Instruction>(VMI->second);
751 if (!NI)
752 continue;
753
754 if (MDNode *PM = NI->getMetadata(LLVMContext::MD_mem_parallel_loop_access)) {
755 M = MDNode::concatenate(PM, M);
756 NI->setMetadata(LLVMContext::MD_mem_parallel_loop_access, M);
757 } else if (NI->mayReadOrWriteMemory()) {
758 NI->setMetadata(LLVMContext::MD_mem_parallel_loop_access, M);
759 }
760 }
761}
762
Sanjay Patel0fdb4372015-03-10 19:42:57 +0000763/// When inlining a function that contains noalias scope metadata,
764/// this metadata needs to be cloned so that the inlined blocks
Sanjay Patel65d533c2017-01-02 19:05:11 +0000765/// have different "unique scopes" at every call site. Were this not done, then
Hal Finkel94146652014-07-24 14:25:39 +0000766/// aliasing scopes from a function inlined into a caller multiple times could
767/// not be differentiated (and this would lead to miscompiles because the
768/// non-aliasing property communicated by the metadata could have
769/// call-site-specific control dependencies).
770static void CloneAliasScopeMetadata(CallSite CS, ValueToValueMapTy &VMap) {
771 const Function *CalledFunc = CS.getCalledFunction();
772 SetVector<const MDNode *> MD;
773
774 // Note: We could only clone the metadata if it is already used in the
775 // caller. I'm omitting that check here because it might confuse
776 // inter-procedural alias analysis passes. We can revisit this if it becomes
777 // an efficiency or overhead problem.
778
Benjamin Kramer135f7352016-06-26 12:28:59 +0000779 for (const BasicBlock &I : *CalledFunc)
780 for (const Instruction &J : I) {
781 if (const MDNode *M = J.getMetadata(LLVMContext::MD_alias_scope))
Hal Finkel94146652014-07-24 14:25:39 +0000782 MD.insert(M);
Benjamin Kramer135f7352016-06-26 12:28:59 +0000783 if (const MDNode *M = J.getMetadata(LLVMContext::MD_noalias))
Hal Finkel94146652014-07-24 14:25:39 +0000784 MD.insert(M);
785 }
786
787 if (MD.empty())
788 return;
789
790 // Walk the existing metadata, adding the complete (perhaps cyclic) chain to
791 // the set.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000792 SmallVector<const Metadata *, 16> Queue(MD.begin(), MD.end());
Hal Finkel94146652014-07-24 14:25:39 +0000793 while (!Queue.empty()) {
794 const MDNode *M = cast<MDNode>(Queue.pop_back_val());
795 for (unsigned i = 0, ie = M->getNumOperands(); i != ie; ++i)
796 if (const MDNode *M1 = dyn_cast<MDNode>(M->getOperand(i)))
797 if (MD.insert(M1))
798 Queue.push_back(M1);
799 }
800
801 // Now we have a complete set of all metadata in the chains used to specify
802 // the noalias scopes and the lists of those scopes.
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000803 SmallVector<TempMDTuple, 16> DummyNodes;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000804 DenseMap<const MDNode *, TrackingMDNodeRef> MDMap;
Benjamin Kramer135f7352016-06-26 12:28:59 +0000805 for (const MDNode *I : MD) {
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000806 DummyNodes.push_back(MDTuple::getTemporary(CalledFunc->getContext(), None));
Benjamin Kramer135f7352016-06-26 12:28:59 +0000807 MDMap[I].reset(DummyNodes.back().get());
Hal Finkel94146652014-07-24 14:25:39 +0000808 }
809
810 // Create new metadata nodes to replace the dummy nodes, replacing old
811 // metadata references with either a dummy node or an already-created new
812 // node.
Benjamin Kramer135f7352016-06-26 12:28:59 +0000813 for (const MDNode *I : MD) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000814 SmallVector<Metadata *, 4> NewOps;
Benjamin Kramer135f7352016-06-26 12:28:59 +0000815 for (unsigned i = 0, ie = I->getNumOperands(); i != ie; ++i) {
816 const Metadata *V = I->getOperand(i);
Hal Finkel94146652014-07-24 14:25:39 +0000817 if (const MDNode *M = dyn_cast<MDNode>(V))
818 NewOps.push_back(MDMap[M]);
819 else
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000820 NewOps.push_back(const_cast<Metadata *>(V));
Hal Finkel94146652014-07-24 14:25:39 +0000821 }
822
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000823 MDNode *NewM = MDNode::get(CalledFunc->getContext(), NewOps);
Benjamin Kramer135f7352016-06-26 12:28:59 +0000824 MDTuple *TempM = cast<MDTuple>(MDMap[I]);
Duncan P. N. Exon Smith946fdcc2015-01-19 20:36:39 +0000825 assert(TempM->isTemporary() && "Expected temporary node");
Hal Finkel94146652014-07-24 14:25:39 +0000826
827 TempM->replaceAllUsesWith(NewM);
828 }
829
830 // Now replace the metadata in the new inlined instructions with the
831 // repacements from the map.
832 for (ValueToValueMapTy::iterator VMI = VMap.begin(), VMIE = VMap.end();
833 VMI != VMIE; ++VMI) {
834 if (!VMI->second)
835 continue;
836
837 Instruction *NI = dyn_cast<Instruction>(VMI->second);
838 if (!NI)
839 continue;
840
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000841 if (MDNode *M = NI->getMetadata(LLVMContext::MD_alias_scope)) {
Hal Finkel61c38612014-08-14 21:09:37 +0000842 MDNode *NewMD = MDMap[M];
843 // If the call site also had alias scope metadata (a list of scopes to
844 // which instructions inside it might belong), propagate those scopes to
845 // the inlined instructions.
846 if (MDNode *CSM =
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000847 CS.getInstruction()->getMetadata(LLVMContext::MD_alias_scope))
Hal Finkel61c38612014-08-14 21:09:37 +0000848 NewMD = MDNode::concatenate(NewMD, CSM);
849 NI->setMetadata(LLVMContext::MD_alias_scope, NewMD);
850 } else if (NI->mayReadOrWriteMemory()) {
851 if (MDNode *M =
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000852 CS.getInstruction()->getMetadata(LLVMContext::MD_alias_scope))
Hal Finkel61c38612014-08-14 21:09:37 +0000853 NI->setMetadata(LLVMContext::MD_alias_scope, M);
854 }
Hal Finkel94146652014-07-24 14:25:39 +0000855
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000856 if (MDNode *M = NI->getMetadata(LLVMContext::MD_noalias)) {
Hal Finkel61c38612014-08-14 21:09:37 +0000857 MDNode *NewMD = MDMap[M];
858 // If the call site also had noalias metadata (a list of scopes with
859 // which instructions inside it don't alias), propagate those scopes to
860 // the inlined instructions.
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000861 if (MDNode *CSM =
862 CS.getInstruction()->getMetadata(LLVMContext::MD_noalias))
Hal Finkel61c38612014-08-14 21:09:37 +0000863 NewMD = MDNode::concatenate(NewMD, CSM);
864 NI->setMetadata(LLVMContext::MD_noalias, NewMD);
865 } else if (NI->mayReadOrWriteMemory()) {
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000866 if (MDNode *M = CS.getInstruction()->getMetadata(LLVMContext::MD_noalias))
Hal Finkel61c38612014-08-14 21:09:37 +0000867 NI->setMetadata(LLVMContext::MD_noalias, M);
868 }
Hal Finkel94146652014-07-24 14:25:39 +0000869 }
Hal Finkel94146652014-07-24 14:25:39 +0000870}
871
Sanjay Patel0fdb4372015-03-10 19:42:57 +0000872/// If the inlined function has noalias arguments,
873/// then add new alias scopes for each noalias argument, tag the mapped noalias
Hal Finkelff0bcb62014-07-25 15:50:08 +0000874/// parameters with noalias metadata specifying the new scope, and tag all
875/// non-derived loads, stores and memory intrinsics with the new alias scopes.
876static void AddAliasScopeMetadata(CallSite CS, ValueToValueMapTy &VMap,
Chandler Carruth7b560d42015-09-09 17:55:00 +0000877 const DataLayout &DL, AAResults *CalleeAAR) {
Hal Finkelff0bcb62014-07-25 15:50:08 +0000878 if (!EnableNoAliasConversion)
879 return;
880
881 const Function *CalledFunc = CS.getCalledFunction();
882 SmallVector<const Argument *, 4> NoAliasArgs;
883
Sanjay Patel42c73552016-01-13 22:16:48 +0000884 for (const Argument &Arg : CalledFunc->args())
885 if (Arg.hasNoAliasAttr() && !Arg.use_empty())
886 NoAliasArgs.push_back(&Arg);
Hal Finkelff0bcb62014-07-25 15:50:08 +0000887
888 if (NoAliasArgs.empty())
889 return;
890
891 // To do a good job, if a noalias variable is captured, we need to know if
892 // the capture point dominates the particular use we're considering.
893 DominatorTree DT;
894 DT.recalculate(const_cast<Function&>(*CalledFunc));
895
896 // noalias indicates that pointer values based on the argument do not alias
897 // pointer values which are not based on it. So we add a new "scope" for each
898 // noalias function argument. Accesses using pointers based on that argument
899 // become part of that alias scope, accesses using pointers not based on that
900 // argument are tagged as noalias with that scope.
901
902 DenseMap<const Argument *, MDNode *> NewScopes;
903 MDBuilder MDB(CalledFunc->getContext());
904
905 // Create a new scope domain for this function.
906 MDNode *NewDomain =
907 MDB.createAnonymousAliasScopeDomain(CalledFunc->getName());
908 for (unsigned i = 0, e = NoAliasArgs.size(); i != e; ++i) {
909 const Argument *A = NoAliasArgs[i];
910
911 std::string Name = CalledFunc->getName();
912 if (A->hasName()) {
913 Name += ": %";
914 Name += A->getName();
915 } else {
916 Name += ": argument ";
917 Name += utostr(i);
918 }
919
920 // Note: We always create a new anonymous root here. This is true regardless
921 // of the linkage of the callee because the aliasing "scope" is not just a
922 // property of the callee, but also all control dependencies in the caller.
923 MDNode *NewScope = MDB.createAnonymousAliasScope(NewDomain, Name);
924 NewScopes.insert(std::make_pair(A, NewScope));
925 }
926
927 // Iterate over all new instructions in the map; for all memory-access
928 // instructions, add the alias scope metadata.
929 for (ValueToValueMapTy::iterator VMI = VMap.begin(), VMIE = VMap.end();
930 VMI != VMIE; ++VMI) {
931 if (const Instruction *I = dyn_cast<Instruction>(VMI->first)) {
932 if (!VMI->second)
933 continue;
934
935 Instruction *NI = dyn_cast<Instruction>(VMI->second);
936 if (!NI)
937 continue;
938
Hal Finkel0c083022014-09-01 09:01:39 +0000939 bool IsArgMemOnlyCall = false, IsFuncCall = false;
Hal Finkelff0bcb62014-07-25 15:50:08 +0000940 SmallVector<const Value *, 2> PtrArgs;
941
942 if (const LoadInst *LI = dyn_cast<LoadInst>(I))
943 PtrArgs.push_back(LI->getPointerOperand());
944 else if (const StoreInst *SI = dyn_cast<StoreInst>(I))
945 PtrArgs.push_back(SI->getPointerOperand());
946 else if (const VAArgInst *VAAI = dyn_cast<VAArgInst>(I))
947 PtrArgs.push_back(VAAI->getPointerOperand());
948 else if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(I))
949 PtrArgs.push_back(CXI->getPointerOperand());
950 else if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(I))
951 PtrArgs.push_back(RMWI->getPointerOperand());
Hal Finkeld2dee162014-08-14 16:44:03 +0000952 else if (ImmutableCallSite ICS = ImmutableCallSite(I)) {
Hal Finkela3708df2014-08-30 12:48:33 +0000953 // If we know that the call does not access memory, then we'll still
954 // know that about the inlined clone of this call site, and we don't
955 // need to add metadata.
Hal Finkeld2dee162014-08-14 16:44:03 +0000956 if (ICS.doesNotAccessMemory())
957 continue;
958
Hal Finkel0c083022014-09-01 09:01:39 +0000959 IsFuncCall = true;
Chandler Carruth7b560d42015-09-09 17:55:00 +0000960 if (CalleeAAR) {
961 FunctionModRefBehavior MRB = CalleeAAR->getModRefBehavior(ICS);
Chandler Carruth194f59c2015-07-22 23:15:57 +0000962 if (MRB == FMRB_OnlyAccessesArgumentPointees ||
963 MRB == FMRB_OnlyReadsArgumentPointees)
Hal Finkel0c083022014-09-01 09:01:39 +0000964 IsArgMemOnlyCall = true;
965 }
966
Sanjay Patele01dcab2016-01-13 21:39:26 +0000967 for (Value *Arg : ICS.args()) {
Hal Finkela3708df2014-08-30 12:48:33 +0000968 // We need to check the underlying objects of all arguments, not just
969 // the pointer arguments, because we might be passing pointers as
970 // integers, etc.
Hal Finkel0c083022014-09-01 09:01:39 +0000971 // However, if we know that the call only accesses pointer arguments,
Hal Finkeld2dee162014-08-14 16:44:03 +0000972 // then we only need to check the pointer arguments.
Sanjay Patele01dcab2016-01-13 21:39:26 +0000973 if (IsArgMemOnlyCall && !Arg->getType()->isPointerTy())
Hal Finkel0c083022014-09-01 09:01:39 +0000974 continue;
Hal Finkelff0bcb62014-07-25 15:50:08 +0000975
Sanjay Patele01dcab2016-01-13 21:39:26 +0000976 PtrArgs.push_back(Arg);
Hal Finkel0c083022014-09-01 09:01:39 +0000977 }
978 }
Hal Finkelcbb85f22014-09-01 04:26:40 +0000979
Hal Finkelff0bcb62014-07-25 15:50:08 +0000980 // If we found no pointers, then this instruction is not suitable for
981 // pairing with an instruction to receive aliasing metadata.
Hal Finkeld2dee162014-08-14 16:44:03 +0000982 // However, if this is a call, this we might just alias with none of the
983 // noalias arguments.
Hal Finkelcbb85f22014-09-01 04:26:40 +0000984 if (PtrArgs.empty() && !IsFuncCall)
Hal Finkelff0bcb62014-07-25 15:50:08 +0000985 continue;
986
987 // It is possible that there is only one underlying object, but you
988 // need to go through several PHIs to see it, and thus could be
989 // repeated in the Objects list.
990 SmallPtrSet<const Value *, 4> ObjSet;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000991 SmallVector<Metadata *, 4> Scopes, NoAliases;
Hal Finkelff0bcb62014-07-25 15:50:08 +0000992
993 SmallSetVector<const Argument *, 4> NAPtrArgs;
Sanjay Patele01dcab2016-01-13 21:39:26 +0000994 for (const Value *V : PtrArgs) {
Hal Finkelff0bcb62014-07-25 15:50:08 +0000995 SmallVector<Value *, 4> Objects;
Sanjay Patele01dcab2016-01-13 21:39:26 +0000996 GetUnderlyingObjects(const_cast<Value*>(V),
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000997 Objects, DL, /* LI = */ nullptr);
Hal Finkelff0bcb62014-07-25 15:50:08 +0000998
999 for (Value *O : Objects)
1000 ObjSet.insert(O);
1001 }
1002
Hal Finkel2d3d6da2014-08-29 16:33:41 +00001003 // Figure out if we're derived from anything that is not a noalias
Hal Finkelff0bcb62014-07-25 15:50:08 +00001004 // argument.
Hal Finkela3708df2014-08-30 12:48:33 +00001005 bool CanDeriveViaCapture = false, UsesAliasingPtr = false;
1006 for (const Value *V : ObjSet) {
1007 // Is this value a constant that cannot be derived from any pointer
1008 // value (we need to exclude constant expressions, for example, that
1009 // are formed from arithmetic on global symbols).
1010 bool IsNonPtrConst = isa<ConstantInt>(V) || isa<ConstantFP>(V) ||
1011 isa<ConstantPointerNull>(V) ||
1012 isa<ConstantDataVector>(V) || isa<UndefValue>(V);
Hal Finkelcbb85f22014-09-01 04:26:40 +00001013 if (IsNonPtrConst)
1014 continue;
1015
1016 // If this is anything other than a noalias argument, then we cannot
1017 // completely describe the aliasing properties using alias.scope
1018 // metadata (and, thus, won't add any).
1019 if (const Argument *A = dyn_cast<Argument>(V)) {
1020 if (!A->hasNoAliasAttr())
1021 UsesAliasingPtr = true;
1022 } else {
Hal Finkela3708df2014-08-30 12:48:33 +00001023 UsesAliasingPtr = true;
Hal Finkelff0bcb62014-07-25 15:50:08 +00001024 }
Hal Finkelcbb85f22014-09-01 04:26:40 +00001025
1026 // If this is not some identified function-local object (which cannot
1027 // directly alias a noalias argument), or some other argument (which,
1028 // by definition, also cannot alias a noalias argument), then we could
1029 // alias a noalias argument that has been captured).
1030 if (!isa<Argument>(V) &&
1031 !isIdentifiedFunctionLocal(const_cast<Value*>(V)))
1032 CanDeriveViaCapture = true;
Hal Finkela3708df2014-08-30 12:48:33 +00001033 }
Hal Finkelcbb85f22014-09-01 04:26:40 +00001034
1035 // A function call can always get captured noalias pointers (via other
1036 // parameters, globals, etc.).
1037 if (IsFuncCall && !IsArgMemOnlyCall)
1038 CanDeriveViaCapture = true;
1039
Hal Finkelff0bcb62014-07-25 15:50:08 +00001040 // First, we want to figure out all of the sets with which we definitely
1041 // don't alias. Iterate over all noalias set, and add those for which:
1042 // 1. The noalias argument is not in the set of objects from which we
1043 // definitely derive.
1044 // 2. The noalias argument has not yet been captured.
Hal Finkelcbb85f22014-09-01 04:26:40 +00001045 // An arbitrary function that might load pointers could see captured
1046 // noalias arguments via other noalias arguments or globals, and so we
1047 // must always check for prior capture.
Hal Finkelff0bcb62014-07-25 15:50:08 +00001048 for (const Argument *A : NoAliasArgs) {
1049 if (!ObjSet.count(A) && (!CanDeriveViaCapture ||
Hal Finkela3708df2014-08-30 12:48:33 +00001050 // It might be tempting to skip the
1051 // PointerMayBeCapturedBefore check if
1052 // A->hasNoCaptureAttr() is true, but this is
1053 // incorrect because nocapture only guarantees
1054 // that no copies outlive the function, not
1055 // that the value cannot be locally captured.
Hal Finkelff0bcb62014-07-25 15:50:08 +00001056 !PointerMayBeCapturedBefore(A,
1057 /* ReturnCaptures */ false,
1058 /* StoreCaptures */ false, I, &DT)))
1059 NoAliases.push_back(NewScopes[A]);
1060 }
1061
1062 if (!NoAliases.empty())
Duncan P. N. Exon Smith3872d002014-11-01 00:10:31 +00001063 NI->setMetadata(LLVMContext::MD_noalias,
1064 MDNode::concatenate(
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001065 NI->getMetadata(LLVMContext::MD_noalias),
Duncan P. N. Exon Smith3872d002014-11-01 00:10:31 +00001066 MDNode::get(CalledFunc->getContext(), NoAliases)));
Hal Finkela3708df2014-08-30 12:48:33 +00001067
Hal Finkelff0bcb62014-07-25 15:50:08 +00001068 // Next, we want to figure out all of the sets to which we might belong.
Hal Finkela3708df2014-08-30 12:48:33 +00001069 // We might belong to a set if the noalias argument is in the set of
1070 // underlying objects. If there is some non-noalias argument in our list
1071 // of underlying objects, then we cannot add a scope because the fact
1072 // that some access does not alias with any set of our noalias arguments
1073 // cannot itself guarantee that it does not alias with this access
1074 // (because there is some pointer of unknown origin involved and the
1075 // other access might also depend on this pointer). We also cannot add
1076 // scopes to arbitrary functions unless we know they don't access any
1077 // non-parameter pointer-values.
1078 bool CanAddScopes = !UsesAliasingPtr;
Hal Finkelcbb85f22014-09-01 04:26:40 +00001079 if (CanAddScopes && IsFuncCall)
1080 CanAddScopes = IsArgMemOnlyCall;
Hal Finkelff0bcb62014-07-25 15:50:08 +00001081
Hal Finkela3708df2014-08-30 12:48:33 +00001082 if (CanAddScopes)
1083 for (const Argument *A : NoAliasArgs) {
1084 if (ObjSet.count(A))
1085 Scopes.push_back(NewScopes[A]);
1086 }
1087
Hal Finkelff0bcb62014-07-25 15:50:08 +00001088 if (!Scopes.empty())
Duncan P. N. Exon Smith3872d002014-11-01 00:10:31 +00001089 NI->setMetadata(
1090 LLVMContext::MD_alias_scope,
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001091 MDNode::concatenate(NI->getMetadata(LLVMContext::MD_alias_scope),
Duncan P. N. Exon Smith3872d002014-11-01 00:10:31 +00001092 MDNode::get(CalledFunc->getContext(), Scopes)));
Hal Finkelff0bcb62014-07-25 15:50:08 +00001093 }
1094 }
1095}
1096
Hans Wennborg2d5841f2017-02-27 22:33:02 +00001097/// If the inlined function has non-byval align arguments, then
1098/// add @llvm.assume-based alignment assumptions to preserve this information.
1099static void AddAlignmentAssumptions(CallSite CS, InlineFunctionInfo &IFI) {
1100 if (!PreserveAlignmentAssumptions || !IFI.GetAssumptionCache)
Hal Finkel68dc3c72014-10-15 23:44:41 +00001101 return;
Sanjay Patelaea60842016-12-31 17:54:05 +00001102
1103 AssumptionCache *AC = &(*IFI.GetAssumptionCache)(*CS.getCaller());
Mehdi Amini46a43552015-03-04 18:43:29 +00001104 auto &DL = CS.getCaller()->getParent()->getDataLayout();
Hal Finkel68dc3c72014-10-15 23:44:41 +00001105
Hans Wennborg2d5841f2017-02-27 22:33:02 +00001106 // To avoid inserting redundant assumptions, we should check for assumptions
1107 // already in the caller. To do this, we might need a DT of the caller.
Hal Finkel68dc3c72014-10-15 23:44:41 +00001108 DominatorTree DT;
1109 bool DTCalculated = false;
1110
Chandler Carruth66b31302015-01-04 12:03:27 +00001111 Function *CalledFunc = CS.getCalledFunction();
Sanjay Patelada717e2017-02-15 14:56:11 +00001112 for (Argument &Arg : CalledFunc->args()) {
Sanjay Patel40975e02017-02-27 18:13:48 +00001113 unsigned Align = Arg.getType()->isPointerTy() ? Arg.getParamAlignment() : 0;
Hans Wennborg2d5841f2017-02-27 22:33:02 +00001114 if (Align && !Arg.hasByValOrInAllocaAttr() && !Arg.hasNUses(0)) {
1115 if (!DTCalculated) {
1116 DT.recalculate(*CS.getCaller());
1117 DTCalculated = true;
1118 }
1119
Hal Finkel68dc3c72014-10-15 23:44:41 +00001120 // If we can already prove the asserted alignment in the context of the
1121 // caller, then don't bother inserting the assumption.
Hans Wennborg2d5841f2017-02-27 22:33:02 +00001122 Value *ArgVal = CS.getArgument(Arg.getArgNo());
1123 if (getKnownAlignment(ArgVal, DL, CS.getInstruction(), AC, &DT) >= Align)
1124 continue;
Hal Finkel68dc3c72014-10-15 23:44:41 +00001125
Hans Wennborg2d5841f2017-02-27 22:33:02 +00001126 CallInst *NewAsmp = IRBuilder<>(CS.getInstruction())
1127 .CreateAlignmentAssumption(DL, ArgVal, Align);
1128 AC->registerAssumption(NewAsmp);
Hal Finkel68dc3c72014-10-15 23:44:41 +00001129 }
1130 }
1131}
1132
Sanjay Patel0fdb4372015-03-10 19:42:57 +00001133/// Once we have cloned code over from a callee into the caller,
1134/// update the specified callgraph to reflect the changes we made.
1135/// Note that it's possible that not all code was copied over, so only
Duncan Sands46911f12008-09-08 11:05:51 +00001136/// some edges of the callgraph may remain.
1137static void UpdateCallGraphAfterInlining(CallSite CS,
Chris Lattner5de3b8b2006-07-12 18:29:36 +00001138 Function::iterator FirstNewBlock,
Rafael Espindola229e38f2010-10-13 01:36:30 +00001139 ValueToValueMapTy &VMap,
Chris Lattner2eee5d32010-04-22 23:37:35 +00001140 InlineFunctionInfo &IFI) {
1141 CallGraph &CG = *IFI.CG;
Sanjay Patel32d753c2017-02-15 15:08:38 +00001142 const Function *Caller = CS.getCaller();
Duncan Sands46911f12008-09-08 11:05:51 +00001143 const Function *Callee = CS.getCalledFunction();
Chris Lattner0841fb12006-01-14 20:07:50 +00001144 CallGraphNode *CalleeNode = CG[Callee];
1145 CallGraphNode *CallerNode = CG[Caller];
Duncan Sands7c8fb1a2008-09-05 12:37:12 +00001146
Chris Lattner5de3b8b2006-07-12 18:29:36 +00001147 // Since we inlined some uninlined call sites in the callee into the caller,
Chris Lattner0841fb12006-01-14 20:07:50 +00001148 // add edges from the caller to all of the callees of the callee.
Gabor Greif5aa19222009-01-15 18:40:09 +00001149 CallGraphNode::iterator I = CalleeNode->begin(), E = CalleeNode->end();
1150
1151 // Consider the case where CalleeNode == CallerNode.
Gabor Greiff1abfdc2009-01-17 00:09:08 +00001152 CallGraphNode::CalledFunctionsVector CallCache;
Gabor Greif5aa19222009-01-15 18:40:09 +00001153 if (CalleeNode == CallerNode) {
1154 CallCache.assign(I, E);
1155 I = CallCache.begin();
1156 E = CallCache.end();
1157 }
1158
1159 for (; I != E; ++I) {
Chris Lattner063d0652009-09-01 06:31:31 +00001160 const Value *OrigCall = I->first;
Duncan Sands7c8fb1a2008-09-05 12:37:12 +00001161
Rafael Espindola229e38f2010-10-13 01:36:30 +00001162 ValueToValueMapTy::iterator VMI = VMap.find(OrigCall);
Chris Lattnerb3c64f72006-07-12 21:37:11 +00001163 // Only copy the edge if the call was inlined!
Craig Topperf40110f2014-04-25 05:29:35 +00001164 if (VMI == VMap.end() || VMI->second == nullptr)
Chris Lattner5eef6ad2009-08-27 03:51:50 +00001165 continue;
1166
1167 // If the call was inlined, but then constant folded, there is no edge to
1168 // add. Check for this case.
Chris Lattner016c00a2010-04-22 21:31:00 +00001169 Instruction *NewCall = dyn_cast<Instruction>(VMI->second);
Sanjay Patelc04b6f22015-03-11 15:12:32 +00001170 if (!NewCall)
1171 continue;
Chris Lattnerc2432b92010-05-01 01:26:13 +00001172
Sanjay Patelc04b6f22015-03-11 15:12:32 +00001173 // We do not treat intrinsic calls like real function calls because we
1174 // expect them to become inline code; do not add an edge for an intrinsic.
1175 CallSite CS = CallSite(NewCall);
1176 if (CS && CS.getCalledFunction() && CS.getCalledFunction()->isIntrinsic())
1177 continue;
1178
Chris Lattnerc2432b92010-05-01 01:26:13 +00001179 // Remember that this call site got inlined for the client of
1180 // InlineFunction.
1181 IFI.InlinedCalls.push_back(NewCall);
1182
Chris Lattner016c00a2010-04-22 21:31:00 +00001183 // It's possible that inlining the callsite will cause it to go from an
1184 // indirect to a direct call by resolving a function pointer. If this
1185 // happens, set the callee of the new call site to a more precise
1186 // destination. This can also happen if the call graph node of the caller
1187 // was just unnecessarily imprecise.
Craig Topperf40110f2014-04-25 05:29:35 +00001188 if (!I->second->getFunction())
Chris Lattner016c00a2010-04-22 21:31:00 +00001189 if (Function *F = CallSite(NewCall).getCalledFunction()) {
1190 // Indirect call site resolved to direct call.
Gabor Greif7b0a5fd2010-07-27 15:02:37 +00001191 CallerNode->addCalledFunction(CallSite(NewCall), CG[F]);
1192
Chris Lattner016c00a2010-04-22 21:31:00 +00001193 continue;
1194 }
Gabor Greif7b0a5fd2010-07-27 15:02:37 +00001195
1196 CallerNode->addCalledFunction(CallSite(NewCall), I->second);
Chris Lattner5de3b8b2006-07-12 18:29:36 +00001197 }
Chris Lattner5eef6ad2009-08-27 03:51:50 +00001198
Dale Johannesen0aeabdf2009-01-13 22:43:37 +00001199 // Update the call graph by deleting the edge from Callee to Caller. We must
1200 // do this after the loop above in case Caller and Callee are the same.
1201 CallerNode->removeCallEdgeFor(CS);
Chris Lattner0841fb12006-01-14 20:07:50 +00001202}
1203
Julien Lerouge957e91c2014-04-15 18:01:54 +00001204static void HandleByValArgumentInit(Value *Dst, Value *Src, Module *M,
1205 BasicBlock *InsertBlock,
1206 InlineFunctionInfo &IFI) {
Julien Lerouge957e91c2014-04-15 18:01:54 +00001207 Type *AggTy = cast<PointerType>(Src->getType())->getElementType();
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001208 IRBuilder<> Builder(InsertBlock, InsertBlock->begin());
Julien Lerouge957e91c2014-04-15 18:01:54 +00001209
Mehdi Amini46a43552015-03-04 18:43:29 +00001210 Value *Size = Builder.getInt64(M->getDataLayout().getTypeStoreSize(AggTy));
Julien Lerouge957e91c2014-04-15 18:01:54 +00001211
1212 // Always generate a memcpy of alignment 1 here because we don't know
1213 // the alignment of the src pointer. Other optimizations can infer
1214 // better alignment.
Pete Cooper67cf9a72015-11-19 05:56:52 +00001215 Builder.CreateMemCpy(Dst, Src, Size, /*Align=*/1);
Julien Lerouge957e91c2014-04-15 18:01:54 +00001216}
1217
Sanjay Patel0fdb4372015-03-10 19:42:57 +00001218/// When inlining a call site that has a byval argument,
Chris Lattner0f114952010-12-20 08:10:40 +00001219/// we have to make the implicit memcpy explicit by adding it.
David Majnemer120f4a02013-11-03 12:22:13 +00001220static Value *HandleByValArgument(Value *Arg, Instruction *TheCall,
Chris Lattner00997442010-12-20 07:57:41 +00001221 const Function *CalledFunc,
1222 InlineFunctionInfo &IFI,
Reid Klecknerdd3f3ed2014-11-04 02:02:14 +00001223 unsigned ByValAlignment) {
Matt Arsenaultbe558882014-04-23 20:58:57 +00001224 PointerType *ArgTy = cast<PointerType>(Arg->getType());
1225 Type *AggTy = ArgTy->getElementType();
Chris Lattner0f114952010-12-20 08:10:40 +00001226
Sanjay Patel288f0752017-02-15 15:22:18 +00001227 Function *Caller = TheCall->getFunction();
Matt Arsenault3c1fc762017-04-10 22:27:50 +00001228 const DataLayout &DL = Caller->getParent()->getDataLayout();
Chandler Carruth66b31302015-01-04 12:03:27 +00001229
Chris Lattner0f114952010-12-20 08:10:40 +00001230 // If the called function is readonly, then it could not mutate the caller's
1231 // copy of the byval'd memory. In this case, it is safe to elide the copy and
1232 // temporary.
David Majnemer120f4a02013-11-03 12:22:13 +00001233 if (CalledFunc->onlyReadsMemory()) {
Chris Lattner0f114952010-12-20 08:10:40 +00001234 // If the byval argument has a specified alignment that is greater than the
1235 // passed in pointer, then we either have to round up the input pointer or
1236 // give up on this transformation.
1237 if (ByValAlignment <= 1) // 0 = unspecified, 1 = no particular alignment.
David Majnemer120f4a02013-11-03 12:22:13 +00001238 return Arg;
Chris Lattner0f114952010-12-20 08:10:40 +00001239
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001240 AssumptionCache *AC =
1241 IFI.GetAssumptionCache ? &(*IFI.GetAssumptionCache)(*Caller) : nullptr;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001242
Chris Lattner20fca482010-12-25 20:42:38 +00001243 // If the pointer is already known to be sufficiently aligned, or if we can
1244 // round it up to a larger alignment, then we don't need a temporary.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001245 if (getOrEnforceKnownAlignment(Arg, ByValAlignment, DL, TheCall, AC) >=
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001246 ByValAlignment)
David Majnemer120f4a02013-11-03 12:22:13 +00001247 return Arg;
Matt Arsenault3c1fc762017-04-10 22:27:50 +00001248
Chris Lattner20fca482010-12-25 20:42:38 +00001249 // Otherwise, we have to make a memcpy to get a safe alignment. This is bad
1250 // for code quality, but rarely happens and is required for correctness.
Chris Lattner0f114952010-12-20 08:10:40 +00001251 }
Chris Lattner00997442010-12-20 07:57:41 +00001252
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001253 // Create the alloca. If we have DataLayout, use nice alignment.
Matt Arsenault3c1fc762017-04-10 22:27:50 +00001254 unsigned Align = DL.getPrefTypeAlignment(AggTy);
Mehdi Amini46a43552015-03-04 18:43:29 +00001255
Chris Lattner00997442010-12-20 07:57:41 +00001256 // If the byval had an alignment specified, we *must* use at least that
1257 // alignment, as it is required by the byval argument (and uses of the
1258 // pointer inside the callee).
1259 Align = std::max(Align, ByValAlignment);
Matt Arsenault3c1fc762017-04-10 22:27:50 +00001260
1261 Value *NewAlloca = new AllocaInst(AggTy, DL.getAllocaAddrSpace(),
1262 nullptr, Align, Arg->getName(),
Chris Lattner00997442010-12-20 07:57:41 +00001263 &*Caller->begin()->begin());
Julien Lerougebe4fe322014-04-15 18:06:46 +00001264 IFI.StaticAllocas.push_back(cast<AllocaInst>(NewAlloca));
Matt Arsenault3c1fc762017-04-10 22:27:50 +00001265
Chris Lattner00997442010-12-20 07:57:41 +00001266 // Uses of the argument in the function should use our new alloca
1267 // instead.
1268 return NewAlloca;
1269}
1270
Sanjay Patel0fdb4372015-03-10 19:42:57 +00001271// Check whether this Value is used by a lifetime intrinsic.
Nick Lewyckya68ec832011-05-22 05:22:10 +00001272static bool isUsedByLifetimeMarker(Value *V) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001273 for (User *U : V->users()) {
1274 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U)) {
Nick Lewyckya68ec832011-05-22 05:22:10 +00001275 switch (II->getIntrinsicID()) {
1276 default: break;
1277 case Intrinsic::lifetime_start:
1278 case Intrinsic::lifetime_end:
1279 return true;
1280 }
1281 }
1282 }
1283 return false;
1284}
1285
Sanjay Patel0fdb4372015-03-10 19:42:57 +00001286// Check whether the given alloca already has
Nick Lewyckya68ec832011-05-22 05:22:10 +00001287// lifetime.start or lifetime.end intrinsics.
1288static bool hasLifetimeMarkers(AllocaInst *AI) {
Matt Arsenaultbe558882014-04-23 20:58:57 +00001289 Type *Ty = AI->getType();
1290 Type *Int8PtrTy = Type::getInt8PtrTy(Ty->getContext(),
1291 Ty->getPointerAddressSpace());
1292 if (Ty == Int8PtrTy)
Nick Lewyckya68ec832011-05-22 05:22:10 +00001293 return isUsedByLifetimeMarker(AI);
1294
Nick Lewycky9711b5c2011-06-14 00:59:24 +00001295 // Do a scan to find all the casts to i8*.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001296 for (User *U : AI->users()) {
1297 if (U->getType() != Int8PtrTy) continue;
1298 if (U->stripPointerCasts() != AI) continue;
1299 if (isUsedByLifetimeMarker(U))
Nick Lewyckya68ec832011-05-22 05:22:10 +00001300 return true;
1301 }
1302 return false;
1303}
1304
David Blaikiedf706282015-01-21 22:57:29 +00001305/// Rebuild the entire inlined-at chain for this instruction so that the top of
1306/// the chain now is inlined-at the new call site.
1307static DebugLoc
Benjamin Kramerbdc49562016-06-12 15:39:02 +00001308updateInlinedAtInfo(const DebugLoc &DL, DILocation *InlinedAtNode,
1309 LLVMContext &Ctx,
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001310 DenseMap<const DILocation *, DILocation *> &IANodes) {
1311 SmallVector<DILocation *, 3> InlinedAtLocations;
1312 DILocation *Last = InlinedAtNode;
1313 DILocation *CurInlinedAt = DL;
David Blaikiedf706282015-01-21 22:57:29 +00001314
1315 // Gather all the inlined-at nodes
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001316 while (DILocation *IA = CurInlinedAt->getInlinedAt()) {
David Blaikiedf706282015-01-21 22:57:29 +00001317 // Skip any we've already built nodes for
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001318 if (DILocation *Found = IANodes[IA]) {
David Blaikiedf706282015-01-21 22:57:29 +00001319 Last = Found;
1320 break;
1321 }
1322
1323 InlinedAtLocations.push_back(IA);
Duncan P. N. Exon Smithec819c02015-03-30 19:49:49 +00001324 CurInlinedAt = IA;
Devang Patel35797402011-07-08 18:01:31 +00001325 }
Eric Christopherf16bee82012-03-26 19:09:38 +00001326
David Blaikiedf706282015-01-21 22:57:29 +00001327 // Starting from the top, rebuild the nodes to point to the new inlined-at
1328 // location (then rebuilding the rest of the chain behind it) and update the
1329 // map of already-constructed inlined-at nodes.
David Majnemerd7708772016-06-24 04:05:21 +00001330 for (const DILocation *MD : reverse(InlinedAtLocations)) {
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001331 Last = IANodes[MD] = DILocation::getDistinct(
David Blaikiedf706282015-01-21 22:57:29 +00001332 Ctx, MD->getLine(), MD->getColumn(), MD->getScope(), Last);
1333 }
1334
1335 // And finally create the normal location for this instruction, referring to
1336 // the new inlined-at chain.
Duncan P. N. Exon Smithec819c02015-03-30 19:49:49 +00001337 return DebugLoc::get(DL.getLine(), DL.getCol(), DL.getScope(), Last);
Devang Patel35797402011-07-08 18:01:31 +00001338}
1339
Reid Kleckner6ee00a22016-08-12 22:23:04 +00001340/// Return the result of AI->isStaticAlloca() if AI were moved to the entry
1341/// block. Allocas used in inalloca calls and allocas of dynamic array size
1342/// cannot be static.
1343static bool allocaWouldBeStaticInEntry(const AllocaInst *AI ) {
1344 return isa<Constant>(AI->getArraySize()) && !AI->isUsedWithInAlloca();
1345}
1346
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.
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001367 DenseMap<const DILocation *, DILocation *> IANodes;
David Blaikiedf706282015-01-21 22:57:29 +00001368
Devang Patel35797402011-07-08 18:01:31 +00001369 for (; FI != Fn->end(); ++FI) {
1370 for (BasicBlock::iterator BI = FI->begin(), BE = FI->end();
1371 BI != BE; ++BI) {
Andrea Di Biagioeff22832016-12-07 12:01:45 +00001372 if (DebugLoc DL = BI->getDebugLoc()) {
1373 BI->setDebugLoc(
1374 updateInlinedAtInfo(DL, InlinedAtNode, BI->getContext(), IANodes));
1375 continue;
Devang Patelbb23a4a2011-08-10 21:50:54 +00001376 }
Andrea Di Biagioeff22832016-12-07 12:01:45 +00001377
1378 if (CalleeHasDebugInfo)
1379 continue;
1380
1381 // If the inlined instruction has no line number, make it look as if it
1382 // originates from the call location. This is important for
1383 // ((__always_inline__, __nodebug__)) functions which must use caller
1384 // location for all instructions in their function body.
1385
1386 // Don't update static allocas, as they may get moved later.
1387 if (auto *AI = dyn_cast<AllocaInst>(BI))
1388 if (allocaWouldBeStaticInEntry(AI))
1389 continue;
1390
1391 BI->setDebugLoc(TheCallDL);
Devang Patel35797402011-07-08 18:01:31 +00001392 }
1393 }
1394}
Easwaran Raman12585b02017-01-20 22:44:04 +00001395/// Update the block frequencies of the caller after a callee has been inlined.
1396///
1397/// Each block cloned into the caller has its block frequency scaled by the
1398/// ratio of CallSiteFreq/CalleeEntryFreq. This ensures that the cloned copy of
1399/// callee's entry block gets the same frequency as the callsite block and the
1400/// relative frequencies of all cloned blocks remain the same after cloning.
1401static void updateCallerBFI(BasicBlock *CallSiteBlock,
1402 const ValueToValueMapTy &VMap,
1403 BlockFrequencyInfo *CallerBFI,
1404 BlockFrequencyInfo *CalleeBFI,
1405 const BasicBlock &CalleeEntryBlock) {
1406 SmallPtrSet<BasicBlock *, 16> ClonedBBs;
1407 for (auto const &Entry : VMap) {
1408 if (!isa<BasicBlock>(Entry.first) || !Entry.second)
1409 continue;
1410 auto *OrigBB = cast<BasicBlock>(Entry.first);
1411 auto *ClonedBB = cast<BasicBlock>(Entry.second);
Easwaran Raman5a12f232017-02-14 22:49:28 +00001412 uint64_t Freq = CalleeBFI->getBlockFreq(OrigBB).getFrequency();
1413 if (!ClonedBBs.insert(ClonedBB).second) {
1414 // Multiple blocks in the callee might get mapped to one cloned block in
1415 // the caller since we prune the callee as we clone it. When that happens,
1416 // we want to use the maximum among the original blocks' frequencies.
1417 uint64_t NewFreq = CallerBFI->getBlockFreq(ClonedBB).getFrequency();
1418 if (NewFreq > Freq)
1419 Freq = NewFreq;
1420 }
1421 CallerBFI->setBlockFreq(ClonedBB, Freq);
Easwaran Raman12585b02017-01-20 22:44:04 +00001422 }
1423 BasicBlock *EntryClone = cast<BasicBlock>(VMap.lookup(&CalleeEntryBlock));
1424 CallerBFI->setBlockFreqAndScale(
1425 EntryClone, CallerBFI->getBlockFreq(CallSiteBlock).getFrequency(),
1426 ClonedBBs);
1427}
1428
Dehao Chene5930492017-03-20 16:40:44 +00001429/// Update the branch metadata for cloned call instructions.
1430static void updateCallProfile(Function *Callee, const ValueToValueMapTy &VMap,
1431 const Optional<uint64_t> &CalleeEntryCount,
1432 const Instruction *TheCall) {
1433 if (!CalleeEntryCount.hasValue() || CalleeEntryCount.getValue() < 1)
1434 return;
1435 Optional<uint64_t> CallSiteCount =
1436 ProfileSummaryInfo::getProfileCount(TheCall, nullptr);
1437 uint64_t CallCount =
1438 std::min(CallSiteCount.hasValue() ? CallSiteCount.getValue() : 0,
1439 CalleeEntryCount.getValue());
1440
1441 for (auto const &Entry : VMap)
David Blaikie795dc942017-03-20 18:01:07 +00001442 if (isa<CallInst>(Entry.first))
1443 if (auto *CI = dyn_cast_or_null<CallInst>(Entry.second))
1444 CI->updateProfWeight(CallCount, CalleeEntryCount.getValue());
Dehao Chene5930492017-03-20 16:40:44 +00001445 for (BasicBlock &BB : *Callee)
1446 // No need to update the callsite if it is pruned during inlining.
1447 if (VMap.count(&BB))
1448 for (Instruction &I : BB)
1449 if (CallInst *CI = dyn_cast<CallInst>(&I))
1450 CI->updateProfWeight(CalleeEntryCount.getValue() - CallCount,
1451 CalleeEntryCount.getValue());
1452}
1453
Easwaran Raman12585b02017-01-20 22:44:04 +00001454/// Update the entry count of callee after inlining.
1455///
1456/// The callsite's block count is subtracted from the callee's function entry
1457/// count.
Dehao Chene5930492017-03-20 16:40:44 +00001458static void updateCalleeCount(BlockFrequencyInfo *CallerBFI, BasicBlock *CallBB,
1459 Instruction *CallInst, Function *Callee) {
Easwaran Raman12585b02017-01-20 22:44:04 +00001460 // If the callee has a original count of N, and the estimated count of
1461 // callsite is M, the new callee count is set to N - M. M is estimated from
1462 // the caller's entry count, its entry block frequency and the block frequency
1463 // of the callsite.
1464 Optional<uint64_t> CalleeCount = Callee->getEntryCount();
Dehao Chene5930492017-03-20 16:40:44 +00001465 if (!CalleeCount.hasValue())
Easwaran Raman12585b02017-01-20 22:44:04 +00001466 return;
Dehao Chene5930492017-03-20 16:40:44 +00001467 Optional<uint64_t> CallCount =
1468 ProfileSummaryInfo::getProfileCount(CallInst, CallerBFI);
1469 if (!CallCount.hasValue())
Easwaran Raman12585b02017-01-20 22:44:04 +00001470 return;
1471 // Since CallSiteCount is an estimate, it could exceed the original callee
1472 // count and has to be set to 0.
Dehao Chene5930492017-03-20 16:40:44 +00001473 if (CallCount.getValue() > CalleeCount.getValue())
Easwaran Raman12585b02017-01-20 22:44:04 +00001474 Callee->setEntryCount(0);
1475 else
Dehao Chene5930492017-03-20 16:40:44 +00001476 Callee->setEntryCount(CalleeCount.getValue() - CallCount.getValue());
Easwaran Raman12585b02017-01-20 22:44:04 +00001477}
Devang Patel35797402011-07-08 18:01:31 +00001478
Sanjay Patel0fdb4372015-03-10 19:42:57 +00001479/// This function inlines the called function into the basic block of the
1480/// caller. This returns false if it is not possible to inline this call.
1481/// The program is still in a well defined state if this occurs though.
Bill Wendlingce0c2292012-01-31 01:01:16 +00001482///
1483/// Note that this only does one level of inlining. For example, if the
1484/// instruction 'call B' is inlined, and 'B' calls 'C', then the call to 'C' now
1485/// exists in the instruction stream. Similarly this will inline a recursive
1486/// function by one level.
Eric Christopherf16bee82012-03-26 19:09:38 +00001487bool llvm::InlineFunction(CallSite CS, InlineFunctionInfo &IFI,
Chandler Carruth7b560d42015-09-09 17:55:00 +00001488 AAResults *CalleeAAR, bool InsertLifetime) {
Chris Lattner0cc265e2003-08-24 06:59:16 +00001489 Instruction *TheCall = CS.getInstruction();
Sanjay Patel288f0752017-02-15 15:22:18 +00001490 assert(TheCall->getParent() && TheCall->getFunction()
1491 && "Instruction not in function!");
Chris Lattner530d4bf2003-05-29 15:11:31 +00001492
Chris Lattner4ba01ec2010-04-22 23:07:58 +00001493 // If IFI has any state in it, zap it before we fill it in.
1494 IFI.reset();
Easwaran Raman12585b02017-01-20 22:44:04 +00001495
1496 Function *CalledFunc = CS.getCalledFunction();
Craig Topperf40110f2014-04-25 05:29:35 +00001497 if (!CalledFunc || // Can't inline external function or indirect
Reid Spencer5301e7c2007-01-30 20:08:39 +00001498 CalledFunc->isDeclaration() || // call, or call to a vararg function!
Eric Christopher1d385382010-03-24 23:35:21 +00001499 CalledFunc->getFunctionType()->isVarArg()) return false;
Chris Lattner530d4bf2003-05-29 15:11:31 +00001500
Sanjoy Das2d161452015-11-18 06:23:38 +00001501 // The inliner does not know how to inline through calls with operand bundles
1502 // in general ...
1503 if (CS.hasOperandBundles()) {
David Majnemer3bb88c02015-12-15 21:27:27 +00001504 for (int i = 0, e = CS.getNumOperandBundles(); i != e; ++i) {
1505 uint32_t Tag = CS.getOperandBundleAt(i).getTagID();
1506 // ... but it knows how to inline through "deopt" operand bundles ...
1507 if (Tag == LLVMContext::OB_deopt)
1508 continue;
1509 // ... and "funclet" operand bundles.
1510 if (Tag == LLVMContext::OB_funclet)
1511 continue;
1512
Sanjoy Das2d161452015-11-18 06:23:38 +00001513 return false;
David Majnemer3bb88c02015-12-15 21:27:27 +00001514 }
Sanjoy Das2d161452015-11-18 06:23:38 +00001515 }
Sanjoy Das0a1bee82015-10-23 20:09:55 +00001516
Duncan Sandsaa31b922007-12-19 21:13:37 +00001517 // If the call to the callee cannot throw, set the 'nounwind' flag on any
1518 // calls that we inline.
1519 bool MarkNoUnwind = CS.doesNotThrow();
1520
Chris Lattner0cc265e2003-08-24 06:59:16 +00001521 BasicBlock *OrigBB = TheCall->getParent();
Chris Lattner530d4bf2003-05-29 15:11:31 +00001522 Function *Caller = OrigBB->getParent();
1523
Gordon Henriksenb969c592007-12-25 03:10:07 +00001524 // GC poses two hazards to inlining, which only occur when the callee has GC:
1525 // 1. If the caller has no GC, then the callee's GC must be propagated to the
1526 // caller.
1527 // 2. If the caller has a differing GC, it is invalid to inline.
Gordon Henriksend930f912008-08-17 18:44:35 +00001528 if (CalledFunc->hasGC()) {
1529 if (!Caller->hasGC())
1530 Caller->setGC(CalledFunc->getGC());
1531 else if (CalledFunc->getGC() != Caller->getGC())
Gordon Henriksenb969c592007-12-25 03:10:07 +00001532 return false;
1533 }
Duncan Sands7c8fb1a2008-09-05 12:37:12 +00001534
Benjamin Kramer4d2b8712011-12-02 18:37:31 +00001535 // Get the personality function from the callee if it contains a landing pad.
David Majnemer7fddecc2015-06-17 20:52:32 +00001536 Constant *CalledPersonality =
David Majnemereba62792015-10-13 22:08:17 +00001537 CalledFunc->hasPersonalityFn()
1538 ? CalledFunc->getPersonalityFn()->stripPointerCasts()
1539 : nullptr;
Benjamin Kramer4d2b8712011-12-02 18:37:31 +00001540
Bill Wendling55421f02011-08-14 08:01:36 +00001541 // Find the personality function used by the landing pads of the caller. If it
1542 // exists, then check to see that it matches the personality function used in
1543 // the callee.
David Majnemer7fddecc2015-06-17 20:52:32 +00001544 Constant *CallerPersonality =
David Majnemereba62792015-10-13 22:08:17 +00001545 Caller->hasPersonalityFn()
1546 ? Caller->getPersonalityFn()->stripPointerCasts()
1547 : nullptr;
David Majnemer7fddecc2015-06-17 20:52:32 +00001548 if (CalledPersonality) {
1549 if (!CallerPersonality)
1550 Caller->setPersonalityFn(CalledPersonality);
1551 // If the personality functions match, then we can perform the
1552 // inlining. Otherwise, we can't inline.
1553 // TODO: This isn't 100% true. Some personality functions are proper
1554 // supersets of others and can be used in place of the other.
1555 else if (CalledPersonality != CallerPersonality)
1556 return false;
Bill Wendlingce0c2292012-01-31 01:01:16 +00001557 }
Bill Wendling55421f02011-08-14 08:01:36 +00001558
David Majnemer8a1c45d2015-12-12 05:38:55 +00001559 // We need to figure out which funclet the callsite was in so that we may
1560 // properly nest the callee.
1561 Instruction *CallSiteEHPad = nullptr;
David Majnemer3bb88c02015-12-15 21:27:27 +00001562 if (CallerPersonality) {
1563 EHPersonality Personality = classifyEHPersonality(CallerPersonality);
David Majnemer8a1c45d2015-12-12 05:38:55 +00001564 if (isFuncletEHPersonality(Personality)) {
David Majnemer3bb88c02015-12-15 21:27:27 +00001565 Optional<OperandBundleUse> ParentFunclet =
1566 CS.getOperandBundle(LLVMContext::OB_funclet);
1567 if (ParentFunclet)
1568 CallSiteEHPad = cast<FuncletPadInst>(ParentFunclet->Inputs.front());
David Majnemer8a1c45d2015-12-12 05:38:55 +00001569
1570 // OK, the inlining site is legal. What about the target function?
1571
1572 if (CallSiteEHPad) {
1573 if (Personality == EHPersonality::MSVC_CXX) {
1574 // The MSVC personality cannot tolerate catches getting inlined into
1575 // cleanup funclets.
1576 if (isa<CleanupPadInst>(CallSiteEHPad)) {
1577 // Ok, the call site is within a cleanuppad. Let's check the callee
1578 // for catchpads.
1579 for (const BasicBlock &CalledBB : *CalledFunc) {
David Majnemer3bb88c02015-12-15 21:27:27 +00001580 if (isa<CatchSwitchInst>(CalledBB.getFirstNonPHI()))
David Majnemer8a1c45d2015-12-12 05:38:55 +00001581 return false;
1582 }
1583 }
1584 } else if (isAsynchronousEHPersonality(Personality)) {
1585 // SEH is even less tolerant, there may not be any sort of exceptional
1586 // funclet in the callee.
1587 for (const BasicBlock &CalledBB : *CalledFunc) {
1588 if (CalledBB.isEHPad())
1589 return false;
1590 }
1591 }
1592 }
1593 }
1594 }
1595
David Majnemer223538f2016-02-23 17:11:04 +00001596 // Determine if we are dealing with a call in an EHPad which does not unwind
1597 // to caller.
1598 bool EHPadForCallUnwindsLocally = false;
1599 if (CallSiteEHPad && CS.isCall()) {
1600 UnwindDestMemoTy FuncletUnwindMap;
1601 Value *CallSiteUnwindDestToken =
1602 getUnwindDestToken(CallSiteEHPad, FuncletUnwindMap);
1603
1604 EHPadForCallUnwindsLocally =
1605 CallSiteUnwindDestToken &&
1606 !isa<ConstantTokenNone>(CallSiteUnwindDestToken);
1607 }
1608
Chris Lattner9fc977e2004-02-04 01:41:09 +00001609 // Get an iterator to the last basic block in the function, which will have
1610 // the new function inlined after it.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001611 Function::iterator LastBlock = --Caller->end();
Chris Lattner9fc977e2004-02-04 01:41:09 +00001612
Chris Lattner18ef3fd2004-02-04 02:51:48 +00001613 // Make sure to capture all of the return instructions from the cloned
Chris Lattner530d4bf2003-05-29 15:11:31 +00001614 // function.
Chris Lattnerd84dbb32009-08-27 04:02:30 +00001615 SmallVector<ReturnInst*, 8> Returns;
Chris Lattner908d7952006-01-13 19:05:59 +00001616 ClonedCodeInfo InlinedFunctionInfo;
Dale Johannesen845e5822009-03-04 02:09:48 +00001617 Function::iterator FirstNewBlock;
Duncan Sandsaa31b922007-12-19 21:13:37 +00001618
Devang Patelb8f11de2010-06-23 23:55:51 +00001619 { // Scope to destroy VMap after cloning.
Rafael Espindola229e38f2010-10-13 01:36:30 +00001620 ValueToValueMapTy VMap;
Julien Lerouge957e91c2014-04-15 18:01:54 +00001621 // Keep a list of pair (dst, src) to emit byval initializations.
1622 SmallVector<std::pair<Value*, Value*>, 4> ByValInit;
Chris Lattnerbe853d72006-05-27 01:28:04 +00001623
Mehdi Amini46a43552015-03-04 18:43:29 +00001624 auto &DL = Caller->getParent()->getDataLayout();
1625
Dan Gohman3ada1e12008-06-20 17:11:32 +00001626 assert(CalledFunc->arg_size() == CS.arg_size() &&
Chris Lattner18ef3fd2004-02-04 02:51:48 +00001627 "No varargs calls can be inlined!");
Duncan Sands7c8fb1a2008-09-05 12:37:12 +00001628
Chris Lattner908117b2008-01-11 06:09:30 +00001629 // Calculate the vector of arguments to pass into the function cloner, which
1630 // matches up the formal to the actual argument values.
Chris Lattner18ef3fd2004-02-04 02:51:48 +00001631 CallSite::arg_iterator AI = CS.arg_begin();
Chris Lattner908117b2008-01-11 06:09:30 +00001632 unsigned ArgNo = 0;
Reid Kleckner45707d42017-03-16 22:59:15 +00001633 for (Function::arg_iterator I = CalledFunc->arg_begin(),
Chris Lattner908117b2008-01-11 06:09:30 +00001634 E = CalledFunc->arg_end(); I != E; ++I, ++AI, ++ArgNo) {
1635 Value *ActualArg = *AI;
Duncan Sands7c8fb1a2008-09-05 12:37:12 +00001636
Duncan Sands053c9872008-01-27 18:12:58 +00001637 // When byval arguments actually inlined, we need to make the copy implied
1638 // by them explicit. However, we don't do this if the callee is readonly
1639 // or readnone, because the copy would be unneeded: the callee doesn't
1640 // modify the struct.
Nick Lewycky612d70b2011-11-20 19:09:04 +00001641 if (CS.isByValArgument(ArgNo)) {
David Majnemer120f4a02013-11-03 12:22:13 +00001642 ActualArg = HandleByValArgument(ActualArg, TheCall, CalledFunc, IFI,
Reid Klecknerdd3f3ed2014-11-04 02:02:14 +00001643 CalledFunc->getParamAlignment(ArgNo+1));
Reid Kleckner9b2cc642014-04-21 20:48:47 +00001644 if (ActualArg != *AI)
Julien Lerouge957e91c2014-04-15 18:01:54 +00001645 ByValInit.push_back(std::make_pair(ActualArg, (Value*) *AI));
Chris Lattner908117b2008-01-11 06:09:30 +00001646 }
Duncan Sands7c8fb1a2008-09-05 12:37:12 +00001647
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001648 VMap[&*I] = ActualArg;
Chris Lattner908117b2008-01-11 06:09:30 +00001649 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001650
Hans Wennborg2d5841f2017-02-27 22:33:02 +00001651 // Add alignment assumptions if necessary. We do this before the inlined
1652 // instructions are actually cloned into the caller so that we can easily
1653 // check what will be known at the start of the inlined code.
1654 AddAlignmentAssumptions(CS, IFI);
Hal Finkel68dc3c72014-10-15 23:44:41 +00001655
Chris Lattnerbe853d72006-05-27 01:28:04 +00001656 // We want the inliner to prune the code as it copies. We would LOVE to
1657 // have no dead or constant instructions leftover after inlining occurs
1658 // (which can happen, e.g., because an argument was constant), but we'll be
1659 // happy with whatever the cloner can do.
Mehdi Amini46a43552015-03-04 18:43:29 +00001660 CloneAndPruneFunctionInto(Caller, CalledFunc, VMap,
Dan Gohmanca26f792010-08-26 15:41:53 +00001661 /*ModuleLevelChanges=*/false, Returns, ".i",
Easwaran Ramanb1bd3982016-03-08 00:36:35 +00001662 &InlinedFunctionInfo, TheCall);
Chris Lattner5de3b8b2006-07-12 18:29:36 +00001663 // Remember the first block that is newly cloned over.
1664 FirstNewBlock = LastBlock; ++FirstNewBlock;
Duncan Sands7c8fb1a2008-09-05 12:37:12 +00001665
Dehao Chene5930492017-03-20 16:40:44 +00001666 if (IFI.CallerBFI != nullptr && IFI.CalleeBFI != nullptr)
Easwaran Raman12585b02017-01-20 22:44:04 +00001667 // Update the BFI of blocks cloned into the caller.
1668 updateCallerBFI(OrigBB, VMap, IFI.CallerBFI, IFI.CalleeBFI,
1669 CalledFunc->front());
Dehao Chene5930492017-03-20 16:40:44 +00001670
1671 updateCallProfile(CalledFunc, VMap, CalledFunc->getEntryCount(), TheCall);
1672 // Update the profile count of callee.
1673 updateCalleeCount(IFI.CallerBFI, OrigBB, TheCall, CalledFunc);
Easwaran Raman12585b02017-01-20 22:44:04 +00001674
Julien Lerouge957e91c2014-04-15 18:01:54 +00001675 // Inject byval arguments initialization.
1676 for (std::pair<Value*, Value*> &Init : ByValInit)
1677 HandleByValArgumentInit(Init.first, Init.second, Caller->getParent(),
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001678 &*FirstNewBlock, IFI);
Julien Lerouge957e91c2014-04-15 18:01:54 +00001679
David Majnemer3bb88c02015-12-15 21:27:27 +00001680 Optional<OperandBundleUse> ParentDeopt =
1681 CS.getOperandBundle(LLVMContext::OB_deopt);
1682 if (ParentDeopt) {
Sanjoy Das2d161452015-11-18 06:23:38 +00001683 SmallVector<OperandBundleDef, 2> OpDefs;
1684
1685 for (auto &VH : InlinedFunctionInfo.OperandBundleCallSites) {
Sanjoy Dasab0626e2015-12-19 22:40:28 +00001686 Instruction *I = dyn_cast_or_null<Instruction>(VH);
1687 if (!I) continue; // instruction was DCE'd or RAUW'ed to undef
Sanjoy Das2d161452015-11-18 06:23:38 +00001688
1689 OpDefs.clear();
1690
1691 CallSite ICS(I);
1692 OpDefs.reserve(ICS.getNumOperandBundles());
1693
1694 for (unsigned i = 0, e = ICS.getNumOperandBundles(); i < e; ++i) {
1695 auto ChildOB = ICS.getOperandBundleAt(i);
1696 if (ChildOB.getTagID() != LLVMContext::OB_deopt) {
1697 // If the inlined call has other operand bundles, let them be
1698 OpDefs.emplace_back(ChildOB);
1699 continue;
1700 }
1701
1702 // It may be useful to separate this logic (of handling operand
1703 // bundles) out to a separate "policy" component if this gets crowded.
1704 // Prepend the parent's deoptimization continuation to the newly
1705 // inlined call's deoptimization continuation.
1706 std::vector<Value *> MergedDeoptArgs;
David Majnemer3bb88c02015-12-15 21:27:27 +00001707 MergedDeoptArgs.reserve(ParentDeopt->Inputs.size() +
Sanjoy Das2d161452015-11-18 06:23:38 +00001708 ChildOB.Inputs.size());
1709
1710 MergedDeoptArgs.insert(MergedDeoptArgs.end(),
David Majnemer3bb88c02015-12-15 21:27:27 +00001711 ParentDeopt->Inputs.begin(),
1712 ParentDeopt->Inputs.end());
Sanjoy Das2d161452015-11-18 06:23:38 +00001713 MergedDeoptArgs.insert(MergedDeoptArgs.end(), ChildOB.Inputs.begin(),
1714 ChildOB.Inputs.end());
1715
Sanjoy Das8da1f952015-12-08 03:50:32 +00001716 OpDefs.emplace_back("deopt", std::move(MergedDeoptArgs));
Sanjoy Das2d161452015-11-18 06:23:38 +00001717 }
1718
1719 Instruction *NewI = nullptr;
1720 if (isa<CallInst>(I))
1721 NewI = CallInst::Create(cast<CallInst>(I), OpDefs, I);
1722 else
1723 NewI = InvokeInst::Create(cast<InvokeInst>(I), OpDefs, I);
1724
1725 // Note: the RAUW does the appropriate fixup in VMap, so we need to do
1726 // this even if the call returns void.
1727 I->replaceAllUsesWith(NewI);
1728
1729 VH = nullptr;
1730 I->eraseFromParent();
1731 }
1732 }
1733
Chris Lattner5de3b8b2006-07-12 18:29:36 +00001734 // Update the callgraph if requested.
Chandler Carruth0ee8bb12016-12-27 01:24:50 +00001735 if (IFI.CG)
Devang Patelb8f11de2010-06-23 23:55:51 +00001736 UpdateCallGraphAfterInlining(CS, FirstNewBlock, VMap, IFI);
Devang Patel35797402011-07-08 18:01:31 +00001737
Andrea Di Biagio32d5aed2016-12-07 10:37:26 +00001738 // For 'nodebug' functions, the associated DISubprogram is always null.
1739 // Conservatively avoid propagating the callsite debug location to
1740 // instructions inlined from a function whose DISubprogram is not null.
Adrian Prantld4056502017-03-07 17:28:57 +00001741 fixupLineNumbers(Caller, FirstNewBlock, TheCall,
1742 CalledFunc->getSubprogram() != nullptr);
Hal Finkel94146652014-07-24 14:25:39 +00001743
1744 // Clone existing noalias metadata if necessary.
1745 CloneAliasScopeMetadata(CS, VMap);
Hal Finkelff0bcb62014-07-25 15:50:08 +00001746
1747 // Add noalias metadata if necessary.
Chandler Carruth7b560d42015-09-09 17:55:00 +00001748 AddAliasScopeMetadata(CS, VMap, DL, CalleeAAR);
Hal Finkel74c2f352014-09-07 12:44:26 +00001749
Hal Finkel50316d92016-04-28 23:00:04 +00001750 // Propagate llvm.mem.parallel_loop_access if necessary.
1751 PropagateParallelLoopAccessMetadata(CS, VMap);
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001752
1753 // Register any cloned assumptions.
1754 if (IFI.GetAssumptionCache)
1755 for (BasicBlock &NewBlock :
1756 make_range(FirstNewBlock->getIterator(), Caller->end()))
1757 for (Instruction &I : NewBlock) {
1758 if (auto *II = dyn_cast<IntrinsicInst>(&I))
1759 if (II->getIntrinsicID() == Intrinsic::assume)
1760 (*IFI.GetAssumptionCache)(*Caller).registerAssumption(II);
1761 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001762 }
Duncan Sands7c8fb1a2008-09-05 12:37:12 +00001763
Chris Lattner530d4bf2003-05-29 15:11:31 +00001764 // If there are any alloca instructions in the block that used to be the entry
1765 // block for the callee, move them to the entry block of the caller. First
1766 // calculate which instruction they should be inserted before. We insert the
1767 // instructions at the end of the current alloca list.
Chris Lattner257492c2006-01-13 18:16:48 +00001768 {
Chris Lattner0cc265e2003-08-24 06:59:16 +00001769 BasicBlock::iterator InsertPoint = Caller->begin()->begin();
Chris Lattner18ef3fd2004-02-04 02:51:48 +00001770 for (BasicBlock::iterator I = FirstNewBlock->begin(),
Chris Lattner5eef6ad2009-08-27 03:51:50 +00001771 E = FirstNewBlock->end(); I != E; ) {
1772 AllocaInst *AI = dyn_cast<AllocaInst>(I++);
Craig Topperf40110f2014-04-25 05:29:35 +00001773 if (!AI) continue;
Chris Lattner5eef6ad2009-08-27 03:51:50 +00001774
1775 // If the alloca is now dead, remove it. This often occurs due to code
1776 // specialization.
1777 if (AI->use_empty()) {
1778 AI->eraseFromParent();
1779 continue;
Chris Lattner6ef6d062006-09-13 19:23:57 +00001780 }
Chris Lattner5eef6ad2009-08-27 03:51:50 +00001781
Reid Kleckner6ee00a22016-08-12 22:23:04 +00001782 if (!allocaWouldBeStaticInEntry(AI))
Chris Lattner5eef6ad2009-08-27 03:51:50 +00001783 continue;
1784
Chris Lattnercd3af962010-12-06 07:43:04 +00001785 // Keep track of the static allocas that we inline into the caller.
Chris Lattner4ba01ec2010-04-22 23:07:58 +00001786 IFI.StaticAllocas.push_back(AI);
Chris Lattnerb1cba3f2009-08-27 04:20:52 +00001787
Chris Lattner5eef6ad2009-08-27 03:51:50 +00001788 // Scan for the block of allocas that we can move over, and move them
1789 // all at once.
1790 while (isa<AllocaInst>(I) &&
Reid Kleckner6ee00a22016-08-12 22:23:04 +00001791 allocaWouldBeStaticInEntry(cast<AllocaInst>(I))) {
Chris Lattner4ba01ec2010-04-22 23:07:58 +00001792 IFI.StaticAllocas.push_back(cast<AllocaInst>(I));
Chris Lattner5eef6ad2009-08-27 03:51:50 +00001793 ++I;
Chris Lattnerb1cba3f2009-08-27 04:20:52 +00001794 }
Chris Lattner5eef6ad2009-08-27 03:51:50 +00001795
1796 // Transfer all of the allocas over in a block. Using splice means
1797 // that the instructions aren't removed from the symbol table, then
1798 // reinserted.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001799 Caller->getEntryBlock().getInstList().splice(
1800 InsertPoint, FirstNewBlock->getInstList(), AI->getIterator(), I);
Chris Lattner5eef6ad2009-08-27 03:51:50 +00001801 }
Adrian Prantl4d365252015-01-30 01:55:25 +00001802 // Move any dbg.declares describing the allocas into the entry basic block.
Adrian Prantl3e2659e2015-01-30 19:37:48 +00001803 DIBuilder DIB(*Caller->getParent());
Adrian Prantl133e1022015-01-30 19:42:59 +00001804 for (auto &AI : IFI.StaticAllocas)
1805 replaceDbgDeclareForAlloca(AI, AI, DIB, /*Deref=*/false);
Chris Lattner0cc265e2003-08-24 06:59:16 +00001806 }
Chris Lattner530d4bf2003-05-29 15:11:31 +00001807
Sanjoy Dasb51325d2016-03-11 19:08:34 +00001808 bool InlinedMustTailCalls = false, InlinedDeoptimizeCalls = false;
Reid Klecknerf0915aa2014-05-15 20:11:28 +00001809 if (InlinedFunctionInfo.ContainsCalls) {
Reid Kleckner6af21242014-05-15 20:39:42 +00001810 CallInst::TailCallKind CallSiteTailKind = CallInst::TCK_None;
1811 if (CallInst *CI = dyn_cast<CallInst>(TheCall))
1812 CallSiteTailKind = CI->getTailCallKind();
1813
Reid Klecknerf0915aa2014-05-15 20:11:28 +00001814 for (Function::iterator BB = FirstNewBlock, E = Caller->end(); BB != E;
1815 ++BB) {
1816 for (Instruction &I : *BB) {
1817 CallInst *CI = dyn_cast<CallInst>(&I);
1818 if (!CI)
1819 continue;
1820
Sanjoy Dasb51325d2016-03-11 19:08:34 +00001821 if (Function *F = CI->getCalledFunction())
1822 InlinedDeoptimizeCalls |=
1823 F->getIntrinsicID() == Intrinsic::experimental_deoptimize;
1824
Reid Klecknerf0915aa2014-05-15 20:11:28 +00001825 // We need to reduce the strength of any inlined tail calls. For
1826 // musttail, we have to avoid introducing potential unbounded stack
1827 // growth. For example, if functions 'f' and 'g' are mutually recursive
1828 // with musttail, we can inline 'g' into 'f' so long as we preserve
1829 // musttail on the cloned call to 'f'. If either the inlined call site
1830 // or the cloned call site is *not* musttail, the program already has
1831 // one frame of stack growth, so it's safe to remove musttail. Here is
1832 // a table of example transformations:
1833 //
1834 // f -> musttail g -> musttail f ==> f -> musttail f
1835 // f -> musttail g -> tail f ==> f -> tail f
1836 // f -> g -> musttail f ==> f -> f
1837 // f -> g -> tail f ==> f -> f
1838 CallInst::TailCallKind ChildTCK = CI->getTailCallKind();
1839 ChildTCK = std::min(CallSiteTailKind, ChildTCK);
Reid Klecknerdd3f3ed2014-11-04 02:02:14 +00001840 CI->setTailCallKind(ChildTCK);
Reid Klecknerf0915aa2014-05-15 20:11:28 +00001841 InlinedMustTailCalls |= CI->isMustTailCall();
1842
1843 // Calls inlined through a 'nounwind' call site should be marked
1844 // 'nounwind'.
1845 if (MarkNoUnwind)
1846 CI->setDoesNotThrow();
1847 }
1848 }
1849 }
1850
Nick Lewyckya68ec832011-05-22 05:22:10 +00001851 // Leave lifetime markers for the static alloca's, scoping them to the
1852 // function we just inlined.
Chad Rosier07d37bc2012-02-25 02:56:01 +00001853 if (InsertLifetime && !IFI.StaticAllocas.empty()) {
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001854 IRBuilder<> builder(&FirstNewBlock->front());
Nick Lewyckya68ec832011-05-22 05:22:10 +00001855 for (unsigned ai = 0, ae = IFI.StaticAllocas.size(); ai != ae; ++ai) {
1856 AllocaInst *AI = IFI.StaticAllocas[ai];
Arnold Schwaighoferc9277f42016-09-09 22:40:27 +00001857 // Don't mark swifterror allocas. They can't have bitcast uses.
1858 if (AI->isSwiftError())
1859 continue;
Nick Lewyckya68ec832011-05-22 05:22:10 +00001860
1861 // If the alloca is already scoped to something smaller than the whole
1862 // function then there's no need to add redundant, less accurate markers.
1863 if (hasLifetimeMarkers(AI))
1864 continue;
1865
Alexey Samsonovcfd662f2012-11-13 07:15:32 +00001866 // Try to determine the size of the allocation.
Craig Topperf40110f2014-04-25 05:29:35 +00001867 ConstantInt *AllocaSize = nullptr;
Alexey Samsonovcfd662f2012-11-13 07:15:32 +00001868 if (ConstantInt *AIArraySize =
1869 dyn_cast<ConstantInt>(AI->getArraySize())) {
Mehdi Amini46a43552015-03-04 18:43:29 +00001870 auto &DL = Caller->getParent()->getDataLayout();
1871 Type *AllocaType = AI->getAllocatedType();
1872 uint64_t AllocaTypeSize = DL.getTypeAllocSize(AllocaType);
1873 uint64_t AllocaArraySize = AIArraySize->getLimitedValue();
Akira Hatanaka2cc2b632015-04-20 16:11:05 +00001874
1875 // Don't add markers for zero-sized allocas.
1876 if (AllocaArraySize == 0)
1877 continue;
1878
Mehdi Amini46a43552015-03-04 18:43:29 +00001879 // Check that array size doesn't saturate uint64_t and doesn't
1880 // overflow when it's multiplied by type size.
1881 if (AllocaArraySize != ~0ULL &&
1882 UINT64_MAX / AllocaArraySize >= AllocaTypeSize) {
1883 AllocaSize = ConstantInt::get(Type::getInt64Ty(AI->getContext()),
1884 AllocaArraySize * AllocaTypeSize);
Alexey Samsonovcfd662f2012-11-13 07:15:32 +00001885 }
1886 }
1887
1888 builder.CreateLifetimeStart(AI, AllocaSize);
Reid Kleckner900d46f2014-05-15 21:10:46 +00001889 for (ReturnInst *RI : Returns) {
Sanjoy Das18b92962016-04-01 02:51:26 +00001890 // Don't insert llvm.lifetime.end calls between a musttail or deoptimize
1891 // call and a return. The return kills all local allocas.
Reid Klecknere31acf22014-08-12 00:05:15 +00001892 if (InlinedMustTailCalls &&
1893 RI->getParent()->getTerminatingMustTailCall())
Reid Kleckner900d46f2014-05-15 21:10:46 +00001894 continue;
Sanjoy Das18b92962016-04-01 02:51:26 +00001895 if (InlinedDeoptimizeCalls &&
1896 RI->getParent()->getTerminatingDeoptimizeCall())
1897 continue;
Reid Klecknerf0915aa2014-05-15 20:11:28 +00001898 IRBuilder<>(RI).CreateLifetimeEnd(AI, AllocaSize);
Reid Kleckner900d46f2014-05-15 21:10:46 +00001899 }
Nick Lewyckya68ec832011-05-22 05:22:10 +00001900 }
1901 }
1902
Chris Lattner2be06072006-01-13 19:34:14 +00001903 // If the inlined code contained dynamic alloca instructions, wrap the inlined
1904 // code with llvm.stacksave/llvm.stackrestore intrinsics.
1905 if (InlinedFunctionInfo.ContainsDynamicAllocas) {
1906 Module *M = Caller->getParent();
Chris Lattner2be06072006-01-13 19:34:14 +00001907 // Get the two intrinsics we care about.
Chris Lattner88b36f12009-10-17 05:39:39 +00001908 Function *StackSave = Intrinsic::getDeclaration(M, Intrinsic::stacksave);
1909 Function *StackRestore=Intrinsic::getDeclaration(M,Intrinsic::stackrestore);
Chris Lattner5de3b8b2006-07-12 18:29:36 +00001910
Chris Lattner2be06072006-01-13 19:34:14 +00001911 // Insert the llvm.stacksave.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001912 CallInst *SavedPtr = IRBuilder<>(&*FirstNewBlock, FirstNewBlock->begin())
David Blaikieff6409d2015-05-18 22:13:54 +00001913 .CreateCall(StackSave, {}, "savedstack");
Duncan Sands7c8fb1a2008-09-05 12:37:12 +00001914
Chris Lattner2be06072006-01-13 19:34:14 +00001915 // Insert a call to llvm.stackrestore before any return instructions in the
1916 // inlined function.
Reid Kleckner900d46f2014-05-15 21:10:46 +00001917 for (ReturnInst *RI : Returns) {
Sanjoy Dasf83ab6d2016-04-01 02:51:30 +00001918 // Don't insert llvm.stackrestore calls between a musttail or deoptimize
1919 // call and a return. The return will restore the stack pointer.
Reid Klecknere31acf22014-08-12 00:05:15 +00001920 if (InlinedMustTailCalls && RI->getParent()->getTerminatingMustTailCall())
Reid Kleckner900d46f2014-05-15 21:10:46 +00001921 continue;
Sanjoy Dasf83ab6d2016-04-01 02:51:30 +00001922 if (InlinedDeoptimizeCalls && RI->getParent()->getTerminatingDeoptimizeCall())
1923 continue;
Reid Klecknerf0915aa2014-05-15 20:11:28 +00001924 IRBuilder<>(RI).CreateCall(StackRestore, SavedPtr);
Reid Kleckner900d46f2014-05-15 21:10:46 +00001925 }
Chris Lattner9f3dced2005-05-06 06:47:52 +00001926 }
1927
Joseph Tremouletb41632b2016-01-20 02:15:15 +00001928 // If we are inlining for an invoke instruction, we must make sure to rewrite
1929 // any call instructions into invoke instructions. This is sensitive to which
1930 // funclet pads were top-level in the inlinee, so must be done before
1931 // rewriting the "parent pad" links.
1932 if (auto *II = dyn_cast<InvokeInst>(TheCall)) {
1933 BasicBlock *UnwindDest = II->getUnwindDest();
1934 Instruction *FirstNonPHI = UnwindDest->getFirstNonPHI();
1935 if (isa<LandingPadInst>(FirstNonPHI)) {
1936 HandleInlinedLandingPad(II, &*FirstNewBlock, InlinedFunctionInfo);
1937 } else {
1938 HandleInlinedEHPad(II, &*FirstNewBlock, InlinedFunctionInfo);
1939 }
1940 }
1941
David Majnemer3bb88c02015-12-15 21:27:27 +00001942 // Update the lexical scopes of the new funclets and callsites.
1943 // Anything that had 'none' as its parent is now nested inside the callsite's
1944 // EHPad.
1945
David Majnemer8a1c45d2015-12-12 05:38:55 +00001946 if (CallSiteEHPad) {
1947 for (Function::iterator BB = FirstNewBlock->getIterator(),
1948 E = Caller->end();
1949 BB != E; ++BB) {
David Majnemer3bb88c02015-12-15 21:27:27 +00001950 // Add bundle operands to any top-level call sites.
1951 SmallVector<OperandBundleDef, 1> OpBundles;
1952 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E;) {
1953 Instruction *I = &*BBI++;
1954 CallSite CS(I);
1955 if (!CS)
1956 continue;
1957
1958 // Skip call sites which are nounwind intrinsics.
1959 auto *CalledFn =
1960 dyn_cast<Function>(CS.getCalledValue()->stripPointerCasts());
1961 if (CalledFn && CalledFn->isIntrinsic() && CS.doesNotThrow())
1962 continue;
1963
1964 // Skip call sites which already have a "funclet" bundle.
1965 if (CS.getOperandBundle(LLVMContext::OB_funclet))
1966 continue;
1967
1968 CS.getOperandBundlesAsDefs(OpBundles);
1969 OpBundles.emplace_back("funclet", CallSiteEHPad);
1970
1971 Instruction *NewInst;
1972 if (CS.isCall())
1973 NewInst = CallInst::Create(cast<CallInst>(I), OpBundles, I);
1974 else
1975 NewInst = InvokeInst::Create(cast<InvokeInst>(I), OpBundles, I);
David Majnemer3bb88c02015-12-15 21:27:27 +00001976 NewInst->takeName(I);
1977 I->replaceAllUsesWith(NewInst);
1978 I->eraseFromParent();
1979
1980 OpBundles.clear();
1981 }
1982
David Majnemer223538f2016-02-23 17:11:04 +00001983 // It is problematic if the inlinee has a cleanupret which unwinds to
1984 // caller and we inline it into a call site which doesn't unwind but into
1985 // an EH pad that does. Such an edge must be dynamically unreachable.
1986 // As such, we replace the cleanupret with unreachable.
1987 if (auto *CleanupRet = dyn_cast<CleanupReturnInst>(BB->getTerminator()))
1988 if (CleanupRet->unwindsToCaller() && EHPadForCallUnwindsLocally)
David Majnemere14e7bc2016-06-25 08:19:55 +00001989 changeToUnreachable(CleanupRet, /*UseLLVMTrap=*/false);
David Majnemer223538f2016-02-23 17:11:04 +00001990
David Majnemer8a1c45d2015-12-12 05:38:55 +00001991 Instruction *I = BB->getFirstNonPHI();
1992 if (!I->isEHPad())
1993 continue;
1994
David Majnemerbbfc7212015-12-14 18:34:23 +00001995 if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(I)) {
David Majnemer8a1c45d2015-12-12 05:38:55 +00001996 if (isa<ConstantTokenNone>(CatchSwitch->getParentPad()))
1997 CatchSwitch->setParentPad(CallSiteEHPad);
1998 } else {
1999 auto *FPI = cast<FuncletPadInst>(I);
2000 if (isa<ConstantTokenNone>(FPI->getParentPad()))
2001 FPI->setParentPad(CallSiteEHPad);
2002 }
2003 }
2004 }
2005
Sanjoy Dasb51325d2016-03-11 19:08:34 +00002006 if (InlinedDeoptimizeCalls) {
2007 // We need to at least remove the deoptimizing returns from the Return set,
2008 // so that the control flow from those returns does not get merged into the
2009 // caller (but terminate it instead). If the caller's return type does not
2010 // match the callee's return type, we also need to change the return type of
2011 // the intrinsic.
2012 if (Caller->getReturnType() == TheCall->getType()) {
2013 auto NewEnd = remove_if(Returns, [](ReturnInst *RI) {
2014 return RI->getParent()->getTerminatingDeoptimizeCall() != nullptr;
2015 });
2016 Returns.erase(NewEnd, Returns.end());
2017 } else {
2018 SmallVector<ReturnInst *, 8> NormalReturns;
2019 Function *NewDeoptIntrinsic = Intrinsic::getDeclaration(
2020 Caller->getParent(), Intrinsic::experimental_deoptimize,
2021 {Caller->getReturnType()});
2022
2023 for (ReturnInst *RI : Returns) {
2024 CallInst *DeoptCall = RI->getParent()->getTerminatingDeoptimizeCall();
2025 if (!DeoptCall) {
2026 NormalReturns.push_back(RI);
2027 continue;
2028 }
2029
Sanjoy Dase0aa4142016-05-12 01:17:38 +00002030 // The calling convention on the deoptimize call itself may be bogus,
2031 // since the code we're inlining may have undefined behavior (and may
2032 // never actually execute at runtime); but all
2033 // @llvm.experimental.deoptimize declarations have to have the same
2034 // calling convention in a well-formed module.
2035 auto CallingConv = DeoptCall->getCalledFunction()->getCallingConv();
2036 NewDeoptIntrinsic->setCallingConv(CallingConv);
Sanjoy Dasb51325d2016-03-11 19:08:34 +00002037 auto *CurBB = RI->getParent();
2038 RI->eraseFromParent();
2039
2040 SmallVector<Value *, 4> CallArgs(DeoptCall->arg_begin(),
2041 DeoptCall->arg_end());
2042
2043 SmallVector<OperandBundleDef, 1> OpBundles;
2044 DeoptCall->getOperandBundlesAsDefs(OpBundles);
2045 DeoptCall->eraseFromParent();
2046 assert(!OpBundles.empty() &&
2047 "Expected at least the deopt operand bundle");
2048
2049 IRBuilder<> Builder(CurBB);
Sanjoy Dasdd77e1e2016-04-09 00:22:59 +00002050 CallInst *NewDeoptCall =
Sanjoy Dasb51325d2016-03-11 19:08:34 +00002051 Builder.CreateCall(NewDeoptIntrinsic, CallArgs, OpBundles);
Sanjoy Dasdd77e1e2016-04-09 00:22:59 +00002052 NewDeoptCall->setCallingConv(CallingConv);
Sanjoy Dasb51325d2016-03-11 19:08:34 +00002053 if (NewDeoptCall->getType()->isVoidTy())
2054 Builder.CreateRetVoid();
2055 else
2056 Builder.CreateRet(NewDeoptCall);
2057 }
2058
2059 // Leave behind the normal returns so we can merge control flow.
2060 std::swap(Returns, NormalReturns);
2061 }
2062 }
2063
Reid Klecknerf0915aa2014-05-15 20:11:28 +00002064 // Handle any inlined musttail call sites. In order for a new call site to be
2065 // musttail, the source of the clone and the inlined call site must have been
2066 // musttail. Therefore it's safe to return without merging control into the
2067 // phi below.
2068 if (InlinedMustTailCalls) {
2069 // Check if we need to bitcast the result of any musttail calls.
2070 Type *NewRetTy = Caller->getReturnType();
2071 bool NeedBitCast = !TheCall->use_empty() && TheCall->getType() != NewRetTy;
2072
2073 // Handle the returns preceded by musttail calls separately.
2074 SmallVector<ReturnInst *, 8> NormalReturns;
2075 for (ReturnInst *RI : Returns) {
Reid Klecknere31acf22014-08-12 00:05:15 +00002076 CallInst *ReturnedMustTail =
2077 RI->getParent()->getTerminatingMustTailCall();
Reid Klecknerf0915aa2014-05-15 20:11:28 +00002078 if (!ReturnedMustTail) {
2079 NormalReturns.push_back(RI);
2080 continue;
2081 }
2082 if (!NeedBitCast)
2083 continue;
2084
2085 // Delete the old return and any preceding bitcast.
2086 BasicBlock *CurBB = RI->getParent();
2087 auto *OldCast = dyn_cast_or_null<BitCastInst>(RI->getReturnValue());
2088 RI->eraseFromParent();
2089 if (OldCast)
2090 OldCast->eraseFromParent();
2091
2092 // Insert a new bitcast and return with the right type.
2093 IRBuilder<> Builder(CurBB);
2094 Builder.CreateRet(Builder.CreateBitCast(ReturnedMustTail, NewRetTy));
2095 }
2096
2097 // Leave behind the normal returns so we can merge control flow.
2098 std::swap(Returns, NormalReturns);
2099 }
2100
Chandler Carruth0ee8bb12016-12-27 01:24:50 +00002101 // Now that all of the transforms on the inlined code have taken place but
2102 // before we splice the inlined code into the CFG and lose track of which
2103 // blocks were actually inlined, collect the call sites. We only do this if
2104 // call graph updates weren't requested, as those provide value handle based
2105 // tracking of inlined call sites instead.
2106 if (InlinedFunctionInfo.ContainsCalls && !IFI.CG) {
2107 // Otherwise just collect the raw call sites that were inlined.
2108 for (BasicBlock &NewBB :
2109 make_range(FirstNewBlock->getIterator(), Caller->end()))
2110 for (Instruction &I : NewBB)
2111 if (auto CS = CallSite(&I))
2112 IFI.InlinedCallSites.push_back(CS);
2113 }
2114
Chris Lattner0fa8c7c2004-02-04 04:17:06 +00002115 // If we cloned in _exactly one_ basic block, and if that block ends in a
2116 // return instruction, we splice the body of the inlined callee directly into
2117 // the calling basic block.
2118 if (Returns.size() == 1 && std::distance(FirstNewBlock, Caller->end()) == 1) {
2119 // Move all of the instructions right before the call.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002120 OrigBB->getInstList().splice(TheCall->getIterator(),
2121 FirstNewBlock->getInstList(),
Chris Lattner0fa8c7c2004-02-04 04:17:06 +00002122 FirstNewBlock->begin(), FirstNewBlock->end());
2123 // Remove the cloned basic block.
2124 Caller->getBasicBlockList().pop_back();
Misha Brukmanb1c93172005-04-21 23:48:37 +00002125
Chris Lattner0fa8c7c2004-02-04 04:17:06 +00002126 // If the call site was an invoke instruction, add a branch to the normal
2127 // destination.
Adrian Prantl15db52b2013-04-23 19:56:03 +00002128 if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall)) {
2129 BranchInst *NewBr = BranchInst::Create(II->getNormalDest(), TheCall);
2130 NewBr->setDebugLoc(Returns[0]->getDebugLoc());
2131 }
Chris Lattner0fa8c7c2004-02-04 04:17:06 +00002132
2133 // If the return instruction returned a value, replace uses of the call with
2134 // uses of the returned value.
Devang Patel841322b2008-03-04 21:15:15 +00002135 if (!TheCall->use_empty()) {
2136 ReturnInst *R = Returns[0];
Eli Friedman36b90262009-05-08 00:22:04 +00002137 if (TheCall == R->getReturnValue())
Owen Andersonb292b8c2009-07-30 23:03:37 +00002138 TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
Eli Friedman36b90262009-05-08 00:22:04 +00002139 else
2140 TheCall->replaceAllUsesWith(R->getReturnValue());
Devang Patel841322b2008-03-04 21:15:15 +00002141 }
Chris Lattner0fa8c7c2004-02-04 04:17:06 +00002142 // Since we are now done with the Call/Invoke, we can delete it.
Dan Gohman158ff2c2008-06-21 22:08:46 +00002143 TheCall->eraseFromParent();
Chris Lattner0fa8c7c2004-02-04 04:17:06 +00002144
2145 // Since we are now done with the return instruction, delete it also.
Dan Gohman158ff2c2008-06-21 22:08:46 +00002146 Returns[0]->eraseFromParent();
Chris Lattner0fa8c7c2004-02-04 04:17:06 +00002147
2148 // We are now done with the inlining.
2149 return true;
2150 }
2151
2152 // Otherwise, we have the normal case, of more than one block to inline or
2153 // multiple return sites.
2154
Chris Lattner18ef3fd2004-02-04 02:51:48 +00002155 // We want to clone the entire callee function into the hole between the
2156 // "starter" and "ender" blocks. How we accomplish this depends on whether
2157 // this is an invoke instruction or a call instruction.
2158 BasicBlock *AfterCallBB;
Craig Topperf40110f2014-04-25 05:29:35 +00002159 BranchInst *CreatedBranchToNormalDest = nullptr;
Chris Lattner18ef3fd2004-02-04 02:51:48 +00002160 if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall)) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00002161
Chris Lattner18ef3fd2004-02-04 02:51:48 +00002162 // Add an unconditional branch to make this look like the CallInst case...
Adrian Prantl15db52b2013-04-23 19:56:03 +00002163 CreatedBranchToNormalDest = BranchInst::Create(II->getNormalDest(), TheCall);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002164
Chris Lattner18ef3fd2004-02-04 02:51:48 +00002165 // Split the basic block. This guarantees that no PHI nodes will have to be
2166 // updated due to new incoming edges, and make the invoke case more
2167 // symmetric to the call case.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002168 AfterCallBB =
2169 OrigBB->splitBasicBlock(CreatedBranchToNormalDest->getIterator(),
2170 CalledFunc->getName() + ".exit");
Misha Brukmanb1c93172005-04-21 23:48:37 +00002171
Chris Lattner18ef3fd2004-02-04 02:51:48 +00002172 } else { // It's a call
Chris Lattner0fa8c7c2004-02-04 04:17:06 +00002173 // If this is a call instruction, we need to split the basic block that
2174 // the call lives in.
Chris Lattner18ef3fd2004-02-04 02:51:48 +00002175 //
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002176 AfterCallBB = OrigBB->splitBasicBlock(TheCall->getIterator(),
2177 CalledFunc->getName() + ".exit");
Chris Lattner18ef3fd2004-02-04 02:51:48 +00002178 }
2179
Easwaran Raman12585b02017-01-20 22:44:04 +00002180 if (IFI.CallerBFI) {
2181 // Copy original BB's block frequency to AfterCallBB
2182 IFI.CallerBFI->setBlockFreq(
2183 AfterCallBB, IFI.CallerBFI->getBlockFreq(OrigBB).getFrequency());
2184 }
2185
Chris Lattner0fa8c7c2004-02-04 04:17:06 +00002186 // Change the branch that used to go to AfterCallBB to branch to the first
2187 // basic block of the inlined function.
2188 //
2189 TerminatorInst *Br = OrigBB->getTerminator();
Misha Brukmanb1c93172005-04-21 23:48:37 +00002190 assert(Br && Br->getOpcode() == Instruction::Br &&
Chris Lattner0fa8c7c2004-02-04 04:17:06 +00002191 "splitBasicBlock broken!");
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002192 Br->setOperand(0, &*FirstNewBlock);
Chris Lattner0fa8c7c2004-02-04 04:17:06 +00002193
2194 // Now that the function is correct, make it a little bit nicer. In
2195 // particular, move the basic blocks inserted from the end of the function
2196 // into the space made by splitting the source basic block.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002197 Caller->getBasicBlockList().splice(AfterCallBB->getIterator(),
2198 Caller->getBasicBlockList(), FirstNewBlock,
2199 Caller->end());
Chris Lattner0fa8c7c2004-02-04 04:17:06 +00002200
Chris Lattner18ef3fd2004-02-04 02:51:48 +00002201 // Handle all of the return instructions that we just cloned in, and eliminate
2202 // any users of the original call/invoke instruction.
Chris Lattner229907c2011-07-18 04:54:35 +00002203 Type *RTy = CalledFunc->getReturnType();
Dan Gohman3b18fd72008-06-20 01:03:44 +00002204
Craig Topperf40110f2014-04-25 05:29:35 +00002205 PHINode *PHI = nullptr;
Dan Gohmanfa1211f2008-07-23 00:34:11 +00002206 if (Returns.size() > 1) {
Chris Lattner18ef3fd2004-02-04 02:51:48 +00002207 // The PHI node should go at the front of the new basic block to merge all
2208 // possible incoming values.
Chris Lattner18ef3fd2004-02-04 02:51:48 +00002209 if (!TheCall->use_empty()) {
Jay Foad52131342011-03-30 11:28:46 +00002210 PHI = PHINode::Create(RTy, Returns.size(), TheCall->getName(),
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002211 &AfterCallBB->front());
Dan Gohmanfa1211f2008-07-23 00:34:11 +00002212 // Anything that used the result of the function call should now use the
2213 // PHI node as their operand.
Duncan Sands7c8fb1a2008-09-05 12:37:12 +00002214 TheCall->replaceAllUsesWith(PHI);
Chris Lattner18ef3fd2004-02-04 02:51:48 +00002215 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002216
Gabor Greif5aa19222009-01-15 18:40:09 +00002217 // Loop over all of the return instructions adding entries to the PHI node
2218 // as appropriate.
Dan Gohmanfa1211f2008-07-23 00:34:11 +00002219 if (PHI) {
2220 for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
2221 ReturnInst *RI = Returns[i];
2222 assert(RI->getReturnValue()->getType() == PHI->getType() &&
2223 "Ret value not consistent in function!");
2224 PHI->addIncoming(RI->getReturnValue(), RI->getParent());
Devang Patel780b3ca62008-03-07 20:06:16 +00002225 }
2226 }
2227
Gabor Greif8c573f72009-01-16 23:08:50 +00002228 // Add a branch to the merge points and remove return instructions.
Richard Trieu624c2eb2013-04-30 22:45:10 +00002229 DebugLoc Loc;
Chris Lattner18ef3fd2004-02-04 02:51:48 +00002230 for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
Richard Trieu624c2eb2013-04-30 22:45:10 +00002231 ReturnInst *RI = Returns[i];
Adrian Prantl09416382013-04-30 17:08:16 +00002232 BranchInst* BI = BranchInst::Create(AfterCallBB, RI);
Richard Trieu624c2eb2013-04-30 22:45:10 +00002233 Loc = RI->getDebugLoc();
2234 BI->setDebugLoc(Loc);
Devang Patel64d0f072008-03-10 18:34:00 +00002235 RI->eraseFromParent();
Chris Lattner18ef3fd2004-02-04 02:51:48 +00002236 }
Adrian Prantl09416382013-04-30 17:08:16 +00002237 // We need to set the debug location to *somewhere* inside the
Adrian Prantl8beccf92013-04-30 17:33:32 +00002238 // inlined function. The line number may be nonsensical, but the
Adrian Prantl09416382013-04-30 17:08:16 +00002239 // instruction will at least be associated with the right
2240 // function.
2241 if (CreatedBranchToNormalDest)
Richard Trieu624c2eb2013-04-30 22:45:10 +00002242 CreatedBranchToNormalDest->setDebugLoc(Loc);
Devang Patel64d0f072008-03-10 18:34:00 +00002243 } else if (!Returns.empty()) {
2244 // Otherwise, if there is exactly one return value, just replace anything
2245 // using the return value of the call with the computed value.
Eli Friedman36b90262009-05-08 00:22:04 +00002246 if (!TheCall->use_empty()) {
2247 if (TheCall == Returns[0]->getReturnValue())
Owen Andersonb292b8c2009-07-30 23:03:37 +00002248 TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
Eli Friedman36b90262009-05-08 00:22:04 +00002249 else
2250 TheCall->replaceAllUsesWith(Returns[0]->getReturnValue());
2251 }
Duncan Sands7c8fb1a2008-09-05 12:37:12 +00002252
Jay Foad61ea0e42011-06-23 09:09:15 +00002253 // Update PHI nodes that use the ReturnBB to use the AfterCallBB.
2254 BasicBlock *ReturnBB = Returns[0]->getParent();
2255 ReturnBB->replaceAllUsesWith(AfterCallBB);
2256
Devang Patel64d0f072008-03-10 18:34:00 +00002257 // Splice the code from the return block into the block that it will return
2258 // to, which contains the code that was after the call.
Devang Patel64d0f072008-03-10 18:34:00 +00002259 AfterCallBB->getInstList().splice(AfterCallBB->begin(),
2260 ReturnBB->getInstList());
Duncan Sands7c8fb1a2008-09-05 12:37:12 +00002261
Adrian Prantl15db52b2013-04-23 19:56:03 +00002262 if (CreatedBranchToNormalDest)
2263 CreatedBranchToNormalDest->setDebugLoc(Returns[0]->getDebugLoc());
2264
Devang Patel64d0f072008-03-10 18:34:00 +00002265 // Delete the return instruction now and empty ReturnBB now.
2266 Returns[0]->eraseFromParent();
2267 ReturnBB->eraseFromParent();
Chris Lattner6e79e552004-10-17 23:21:07 +00002268 } else if (!TheCall->use_empty()) {
2269 // No returns, but something is using the return value of the call. Just
2270 // nuke the result.
Owen Andersonb292b8c2009-07-30 23:03:37 +00002271 TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
Chris Lattner18ef3fd2004-02-04 02:51:48 +00002272 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002273
Chris Lattner18ef3fd2004-02-04 02:51:48 +00002274 // Since we are now done with the Call/Invoke, we can delete it.
Chris Lattner6e79e552004-10-17 23:21:07 +00002275 TheCall->eraseFromParent();
Chris Lattner530d4bf2003-05-29 15:11:31 +00002276
Reid Klecknerf0915aa2014-05-15 20:11:28 +00002277 // If we inlined any musttail calls and the original return is now
2278 // unreachable, delete it. It can only contain a bitcast and ret.
Easwaran Ramanb1bd3982016-03-08 00:36:35 +00002279 if (InlinedMustTailCalls && pred_begin(AfterCallBB) == pred_end(AfterCallBB))
Reid Klecknerf0915aa2014-05-15 20:11:28 +00002280 AfterCallBB->eraseFromParent();
2281
Chris Lattnerfc3fe5c2003-08-24 04:06:56 +00002282 // We should always be able to fold the entry block of the function into the
2283 // single predecessor of the block...
Chris Lattner0328d752004-04-16 05:17:59 +00002284 assert(cast<BranchInst>(Br)->isUnconditional() && "splitBasicBlock broken!");
Chris Lattnerfc3fe5c2003-08-24 04:06:56 +00002285 BasicBlock *CalleeEntry = cast<BranchInst>(Br)->getSuccessor(0);
Chris Lattner0fa8c7c2004-02-04 04:17:06 +00002286
Chris Lattner0328d752004-04-16 05:17:59 +00002287 // Splice the code entry block into calling block, right before the
2288 // unconditional branch.
Eric Christopher96513122011-06-23 06:24:52 +00002289 CalleeEntry->replaceAllUsesWith(OrigBB); // Update PHI nodes
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002290 OrigBB->getInstList().splice(Br->getIterator(), CalleeEntry->getInstList());
Chris Lattner0328d752004-04-16 05:17:59 +00002291
2292 // Remove the unconditional branch.
2293 OrigBB->getInstList().erase(Br);
2294
2295 // Now we can remove the CalleeEntry block, which is now empty.
2296 Caller->getBasicBlockList().erase(CalleeEntry);
Duncan Sands7c8fb1a2008-09-05 12:37:12 +00002297
Duncan Sands9d9a4e22010-11-17 11:16:23 +00002298 // If we inserted a phi node, check to see if it has a single value (e.g. all
2299 // the entries are the same or undef). If so, remove the PHI so it doesn't
2300 // block other optimizations.
Bill Wendlingce0c2292012-01-31 01:01:16 +00002301 if (PHI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002302 AssumptionCache *AC =
2303 IFI.GetAssumptionCache ? &(*IFI.GetAssumptionCache)(*Caller) : nullptr;
Mehdi Amini46a43552015-03-04 18:43:29 +00002304 auto &DL = Caller->getParent()->getDataLayout();
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002305 if (Value *V = SimplifyInstruction(PHI, DL, nullptr, nullptr, AC)) {
Duncan Sands9d9a4e22010-11-17 11:16:23 +00002306 PHI->replaceAllUsesWith(V);
2307 PHI->eraseFromParent();
2308 }
Bill Wendlingce0c2292012-01-31 01:01:16 +00002309 }
Duncan Sands9d9a4e22010-11-17 11:16:23 +00002310
Chris Lattner530d4bf2003-05-29 15:11:31 +00002311 return true;
2312}