blob: b8900ac3d77387eb9e5af4d0a4e2b430f708a372 [file] [log] [blame]
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001//===- CodeGenPrepare.cpp - Prepare a function for code generation --------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This pass munges the code in the input function to better prepare it for
Gordon Henriksena8a118b2008-05-08 17:46:35 +000011// SelectionDAG-based code generation. This works around limitations in it's
12// basic-block-at-a-time approach. It should eventually be removed.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000013//
14//===----------------------------------------------------------------------===//
15
16#define DEBUG_TYPE "codegenprepare"
17#include "llvm/Transforms/Scalar.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000018#include "llvm/ADT/DenseMap.h"
19#include "llvm/ADT/SmallSet.h"
20#include "llvm/ADT/Statistic.h"
21#include "llvm/Analysis/DominatorInternals.h"
22#include "llvm/Analysis/Dominators.h"
23#include "llvm/Analysis/InstructionSimplify.h"
24#include "llvm/Analysis/ProfileInfo.h"
25#include "llvm/Assembly/Writer.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000026#include "llvm/Constants.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000027#include "llvm/DataLayout.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000028#include "llvm/DerivedTypes.h"
29#include "llvm/Function.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000030#include "llvm/IRBuilder.h"
Evan Cheng9bf12b52008-02-26 02:42:37 +000031#include "llvm/InlineAsm.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000032#include "llvm/Instructions.h"
Dale Johannesen6aae1d62009-03-26 01:15:07 +000033#include "llvm/IntrinsicInst.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000034#include "llvm/Pass.h"
Evan Cheng9bf12b52008-02-26 02:42:37 +000035#include "llvm/Support/CallSite.h"
Evan Chenge1bcb442010-08-17 01:34:49 +000036#include "llvm/Support/CommandLine.h"
Evan Chengbdcb7262007-12-05 23:58:20 +000037#include "llvm/Support/Debug.h"
Chris Lattnerdd77df32007-04-13 20:30:56 +000038#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner088a1e82008-11-25 04:42:10 +000039#include "llvm/Support/PatternMatch.h"
Chris Lattner94e8e0c2011-01-15 07:25:29 +000040#include "llvm/Support/ValueHandle.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000041#include "llvm/Support/raw_ostream.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000042#include "llvm/Target/TargetLibraryInfo.h"
43#include "llvm/Target/TargetLowering.h"
44#include "llvm/Transforms/Utils/AddrModeMatcher.h"
45#include "llvm/Transforms/Utils/BasicBlockUtils.h"
46#include "llvm/Transforms/Utils/BuildLibCalls.h"
Preston Gurd2e2efd92012-09-04 18:22:17 +000047#include "llvm/Transforms/Utils/BypassSlowDivision.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000048#include "llvm/Transforms/Utils/Local.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000049using namespace llvm;
Chris Lattner088a1e82008-11-25 04:42:10 +000050using namespace llvm::PatternMatch;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000051
Cameron Zwarich31ff1332011-01-05 17:27:27 +000052STATISTIC(NumBlocksElim, "Number of blocks eliminated");
Evan Cheng485fafc2011-03-21 01:19:09 +000053STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated");
54STATISTIC(NumGEPsElim, "Number of GEPs converted to casts");
Cameron Zwarich31ff1332011-01-05 17:27:27 +000055STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "
56 "sunken Cmps");
57STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
58 "of sunken Casts");
59STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "
60 "computations were sunk");
Evan Cheng485fafc2011-03-21 01:19:09 +000061STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads");
62STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized");
63STATISTIC(NumRetsDup, "Number of return instructions duplicated");
Devang Patelf56ea612011-08-18 00:50:51 +000064STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved");
Benjamin Kramer59957502012-05-05 12:49:22 +000065STATISTIC(NumSelectsExpanded, "Number of selects turned into branches");
Jakob Stoklund Olesen7eb589d2010-09-30 20:51:52 +000066
Cameron Zwarich899eaa32011-03-11 21:52:04 +000067static cl::opt<bool> DisableBranchOpts(
68 "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
69 cl::desc("Disable branch optimizations in CodeGenPrepare"));
70
Benjamin Kramer77c4ef82012-05-06 14:25:16 +000071static cl::opt<bool> DisableSelectToBranch(
72 "disable-cgp-select2branch", cl::Hidden, cl::init(false),
73 cl::desc("Disable select to branch conversion."));
Benjamin Kramer59957502012-05-05 12:49:22 +000074
Eric Christopher692bf6b2008-09-24 05:32:41 +000075namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +000076 class CodeGenPrepare : public FunctionPass {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000077 /// TLI - Keep a pointer of a TargetLowering to consult for determining
78 /// transformation profitability.
79 const TargetLowering *TLI;
Chad Rosier618c1db2011-12-01 03:08:23 +000080 const TargetLibraryInfo *TLInfo;
Cameron Zwarich80f6a502011-01-08 17:01:52 +000081 DominatorTree *DT;
Evan Cheng04149f72009-12-17 09:39:49 +000082 ProfileInfo *PFI;
Nadav Rotema94d6e82012-07-24 10:51:42 +000083
Chris Lattner75796092011-01-15 07:14:54 +000084 /// CurInstIterator - As we scan instructions optimizing them, this is the
85 /// next instruction to optimize. Xforms that can invalidate this should
86 /// update it.
87 BasicBlock::iterator CurInstIterator;
Evan Chengab631522008-12-19 18:03:11 +000088
Evan Cheng485fafc2011-03-21 01:19:09 +000089 /// Keeps track of non-local addresses that have been sunk into a block.
90 /// This allows us to avoid inserting duplicate code for blocks with
91 /// multiple load/stores of the same address.
Cameron Zwarich8c3527e2011-01-06 00:42:50 +000092 DenseMap<Value*, Value*> SunkAddrs;
93
Devang Patel52e37df2011-03-24 15:35:25 +000094 /// ModifiedDT - If CFG is modified in anyway, dominator tree may need to
Evan Cheng485fafc2011-03-21 01:19:09 +000095 /// be updated.
Devang Patel52e37df2011-03-24 15:35:25 +000096 bool ModifiedDT;
Evan Cheng485fafc2011-03-21 01:19:09 +000097
Benjamin Kramer59957502012-05-05 12:49:22 +000098 /// OptSize - True if optimizing for size.
99 bool OptSize;
100
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000101 public:
Nick Lewyckyecd94c82007-05-06 13:37:16 +0000102 static char ID; // Pass identification, replacement for typeid
Dan Gohmanc2bbfc12007-08-01 15:32:29 +0000103 explicit CodeGenPrepare(const TargetLowering *tli = 0)
Owen Anderson081c34b2010-10-19 17:21:58 +0000104 : FunctionPass(ID), TLI(tli) {
105 initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
106 }
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000107 bool runOnFunction(Function &F);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000108
Evan Chenga16422f2012-12-21 01:48:14 +0000109 const char *getPassName() const { return "CodeGen Prepare"; }
110
Andreas Neustifterad809812009-09-16 09:26:52 +0000111 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Cameron Zwarich80f6a502011-01-08 17:01:52 +0000112 AU.addPreserved<DominatorTree>();
Andreas Neustifterad809812009-09-16 09:26:52 +0000113 AU.addPreserved<ProfileInfo>();
Chad Rosier618c1db2011-12-01 03:08:23 +0000114 AU.addRequired<TargetLibraryInfo>();
Andreas Neustifterad809812009-09-16 09:26:52 +0000115 }
116
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000117 private:
Nadav Rotem3e883732012-08-14 05:19:07 +0000118 bool EliminateFallThrough(Function &F);
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000119 bool EliminateMostlyEmptyBlocks(Function &F);
120 bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
121 void EliminateMostlyEmptyBlock(BasicBlock *BB);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000122 bool OptimizeBlock(BasicBlock &BB);
Cameron Zwarichc0611012011-01-06 02:37:26 +0000123 bool OptimizeInst(Instruction *I);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000124 bool OptimizeMemoryInst(Instruction *I, Value *Addr, Type *AccessTy);
Chris Lattner75796092011-01-15 07:14:54 +0000125 bool OptimizeInlineAsmInst(CallInst *CS);
Eric Christopher040056f2010-03-11 02:41:03 +0000126 bool OptimizeCallInst(CallInst *CI);
Dan Gohmanb00f2362009-10-16 20:59:35 +0000127 bool MoveExtToFormExtLoad(Instruction *I);
Evan Chengbdcb7262007-12-05 23:58:20 +0000128 bool OptimizeExtUses(Instruction *I);
Benjamin Kramer59957502012-05-05 12:49:22 +0000129 bool OptimizeSelectInst(SelectInst *SI);
Benjamin Kramer4ccb49a2012-11-23 19:17:06 +0000130 bool DupRetToEnableTailCallOpts(BasicBlock *BB);
Devang Patelf56ea612011-08-18 00:50:51 +0000131 bool PlaceDbgValues(Function &F);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000132 };
133}
Devang Patel794fd752007-05-01 21:15:47 +0000134
Devang Patel19974732007-05-03 01:11:54 +0000135char CodeGenPrepare::ID = 0;
Chad Rosier618c1db2011-12-01 03:08:23 +0000136INITIALIZE_PASS_BEGIN(CodeGenPrepare, "codegenprepare",
137 "Optimize for code generation", false, false)
138INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
139INITIALIZE_PASS_END(CodeGenPrepare, "codegenprepare",
Owen Andersonce665bd2010-10-07 22:25:06 +0000140 "Optimize for code generation", false, false)
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000141
142FunctionPass *llvm::createCodeGenPreparePass(const TargetLowering *TLI) {
143 return new CodeGenPrepare(TLI);
144}
145
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000146bool CodeGenPrepare::runOnFunction(Function &F) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000147 bool EverMadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000148
Devang Patel52e37df2011-03-24 15:35:25 +0000149 ModifiedDT = false;
Chad Rosier618c1db2011-12-01 03:08:23 +0000150 TLInfo = &getAnalysis<TargetLibraryInfo>();
Cameron Zwarich80f6a502011-01-08 17:01:52 +0000151 DT = getAnalysisIfAvailable<DominatorTree>();
Evan Cheng04149f72009-12-17 09:39:49 +0000152 PFI = getAnalysisIfAvailable<ProfileInfo>();
Bill Wendling034b94b2012-12-19 07:18:57 +0000153 OptSize = F.getFnAttributes().hasAttribute(Attribute::OptimizeForSize);
Evan Cheng485fafc2011-03-21 01:19:09 +0000154
Preston Gurd2e2efd92012-09-04 18:22:17 +0000155 /// This optimization identifies DIV instructions that can be
156 /// profitably bypassed and carried out with a shorter, faster divide.
157 if (TLI && TLI->isSlowDivBypassed()) {
Preston Gurd8d662b52012-10-04 21:33:40 +0000158 const DenseMap<unsigned int, unsigned int> &BypassWidths =
159 TLI->getBypassSlowDivWidths();
Evan Cheng911908d2012-09-14 21:25:34 +0000160 for (Function::iterator I = F.begin(); I != F.end(); I++)
Preston Gurd8d662b52012-10-04 21:33:40 +0000161 EverMadeChange |= bypassSlowDivision(F, I, BypassWidths);
Preston Gurd2e2efd92012-09-04 18:22:17 +0000162 }
163
164 // Eliminate blocks that contain only PHI nodes and an
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000165 // unconditional branch.
166 EverMadeChange |= EliminateMostlyEmptyBlocks(F);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000167
Devang Patelf56ea612011-08-18 00:50:51 +0000168 // llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotema94d6e82012-07-24 10:51:42 +0000169 // handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patelf56ea612011-08-18 00:50:51 +0000170 // find a node corresponding to the value.
171 EverMadeChange |= PlaceDbgValues(F);
172
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000173 bool MadeChange = true;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000174 while (MadeChange) {
175 MadeChange = false;
Hans Wennborg93ba1332012-09-19 07:48:16 +0000176 for (Function::iterator I = F.begin(); I != F.end(); ) {
Evan Cheng485fafc2011-03-21 01:19:09 +0000177 BasicBlock *BB = I++;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000178 MadeChange |= OptimizeBlock(*BB);
Evan Cheng485fafc2011-03-21 01:19:09 +0000179 }
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000180 EverMadeChange |= MadeChange;
181 }
Cameron Zwarich8c3527e2011-01-06 00:42:50 +0000182
183 SunkAddrs.clear();
184
Cameron Zwarich899eaa32011-03-11 21:52:04 +0000185 if (!DisableBranchOpts) {
186 MadeChange = false;
Bill Wendlinge3e394d2012-03-04 10:46:01 +0000187 SmallPtrSet<BasicBlock*, 8> WorkList;
188 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
189 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
Frits van Bommel5649ba72011-05-22 16:24:18 +0000190 MadeChange |= ConstantFoldTerminator(BB, true);
Bill Wendlinge3e394d2012-03-04 10:46:01 +0000191 if (!MadeChange) continue;
192
193 for (SmallVectorImpl<BasicBlock*>::iterator
194 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
195 if (pred_begin(*II) == pred_end(*II))
196 WorkList.insert(*II);
197 }
198
Bill Wendlingbf2ad732012-11-28 23:23:48 +0000199 // Delete the dead blocks and any of their dead successors.
Bill Wendling1c211642012-12-06 00:30:20 +0000200 MadeChange |= !WorkList.empty();
Bill Wendlingbf2ad732012-11-28 23:23:48 +0000201 while (!WorkList.empty()) {
202 BasicBlock *BB = *WorkList.begin();
203 WorkList.erase(BB);
204 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
205
206 DeleteDeadBlock(BB);
207
208 for (SmallVectorImpl<BasicBlock*>::iterator
209 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
210 if (pred_begin(*II) == pred_end(*II))
211 WorkList.insert(*II);
212 }
Cameron Zwarich899eaa32011-03-11 21:52:04 +0000213
Nadav Rotem3e883732012-08-14 05:19:07 +0000214 // Merge pairs of basic blocks with unconditional branches, connected by
215 // a single edge.
216 if (EverMadeChange || MadeChange)
217 MadeChange |= EliminateFallThrough(F);
218
Evan Cheng485fafc2011-03-21 01:19:09 +0000219 if (MadeChange)
Devang Patel52e37df2011-03-24 15:35:25 +0000220 ModifiedDT = true;
Cameron Zwarich899eaa32011-03-11 21:52:04 +0000221 EverMadeChange |= MadeChange;
222 }
223
Devang Patel52e37df2011-03-24 15:35:25 +0000224 if (ModifiedDT && DT)
Evan Cheng485fafc2011-03-21 01:19:09 +0000225 DT->DT->recalculate(F);
226
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000227 return EverMadeChange;
228}
229
Nadav Rotem3e883732012-08-14 05:19:07 +0000230/// EliminateFallThrough - Merge basic blocks which are connected
231/// by a single edge, where one of the basic blocks has a single successor
232/// pointing to the other basic block, which has a single predecessor.
233bool CodeGenPrepare::EliminateFallThrough(Function &F) {
234 bool Changed = false;
235 // Scan all of the blocks in the function, except for the entry block.
236 for (Function::iterator I = ++F.begin(), E = F.end(); I != E; ) {
237 BasicBlock *BB = I++;
238 // If the destination block has a single pred, then this is a trivial
239 // edge, just collapse it.
240 BasicBlock *SinglePred = BB->getSinglePredecessor();
241
Evan Cheng46597072012-09-28 23:58:57 +0000242 // Don't merge if BB's address is taken.
243 if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue;
Nadav Rotem3e883732012-08-14 05:19:07 +0000244
245 BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
246 if (Term && !Term->isConditional()) {
247 Changed = true;
Michael Liao787ed032012-08-21 05:55:22 +0000248 DEBUG(dbgs() << "To merge:\n"<< *SinglePred << "\n\n\n");
Nadav Rotem3e883732012-08-14 05:19:07 +0000249 // Remember if SinglePred was the entry block of the function.
250 // If so, we will need to move BB back to the entry position.
251 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
252 MergeBasicBlockIntoOnlyPred(BB, this);
253
254 if (isEntry && BB != &BB->getParent()->getEntryBlock())
255 BB->moveBefore(&BB->getParent()->getEntryBlock());
256
257 // We have erased a block. Update the iterator.
258 I = BB;
Nadav Rotem3e883732012-08-14 05:19:07 +0000259 }
260 }
261 return Changed;
262}
263
Dale Johannesen2d697242009-03-27 01:13:37 +0000264/// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes,
265/// debug info directives, and an unconditional branch. Passes before isel
266/// (e.g. LSR/loopsimplify) often split edges in ways that are non-optimal for
267/// isel. Start by eliminating these blocks so we can split them the way we
268/// want them.
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000269bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
270 bool MadeChange = false;
271 // Note that this intentionally skips the entry block.
272 for (Function::iterator I = ++F.begin(), E = F.end(); I != E; ) {
273 BasicBlock *BB = I++;
274
275 // If this block doesn't end with an uncond branch, ignore it.
276 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
277 if (!BI || !BI->isUnconditional())
278 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000279
Dale Johannesen2d697242009-03-27 01:13:37 +0000280 // If the instruction before the branch (skipping debug info) isn't a phi
281 // node, then other stuff is happening here.
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000282 BasicBlock::iterator BBI = BI;
283 if (BBI != BB->begin()) {
284 --BBI;
Dale Johannesen2d697242009-03-27 01:13:37 +0000285 while (isa<DbgInfoIntrinsic>(BBI)) {
286 if (BBI == BB->begin())
287 break;
288 --BBI;
289 }
290 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
291 continue;
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000292 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000293
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000294 // Do not break infinite loops.
295 BasicBlock *DestBB = BI->getSuccessor(0);
296 if (DestBB == BB)
297 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000298
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000299 if (!CanMergeBlocks(BB, DestBB))
300 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000301
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000302 EliminateMostlyEmptyBlock(BB);
303 MadeChange = true;
304 }
305 return MadeChange;
306}
307
308/// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
309/// single uncond branch between them, and BB contains no other non-phi
310/// instructions.
311bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
312 const BasicBlock *DestBB) const {
313 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
314 // the successor. If there are more complex condition (e.g. preheaders),
315 // don't mess around with them.
316 BasicBlock::const_iterator BBI = BB->begin();
317 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
Gabor Greif60ad7812010-03-25 23:06:16 +0000318 for (Value::const_use_iterator UI = PN->use_begin(), E = PN->use_end();
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000319 UI != E; ++UI) {
320 const Instruction *User = cast<Instruction>(*UI);
321 if (User->getParent() != DestBB || !isa<PHINode>(User))
322 return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000323 // If User is inside DestBB block and it is a PHINode then check
324 // incoming value. If incoming value is not from BB then this is
Devang Patel75abc1e2007-04-25 00:37:04 +0000325 // a complex condition (e.g. preheaders) we want to avoid here.
326 if (User->getParent() == DestBB) {
327 if (const PHINode *UPN = dyn_cast<PHINode>(User))
328 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
329 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
330 if (Insn && Insn->getParent() == BB &&
331 Insn->getParent() != UPN->getIncomingBlock(I))
332 return false;
333 }
334 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000335 }
336 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000337
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000338 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
339 // and DestBB may have conflicting incoming values for the block. If so, we
340 // can't merge the block.
341 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
342 if (!DestBBPN) return true; // no conflict.
Eric Christopher692bf6b2008-09-24 05:32:41 +0000343
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000344 // Collect the preds of BB.
Chris Lattnerf67f73a2007-11-06 22:07:40 +0000345 SmallPtrSet<const BasicBlock*, 16> BBPreds;
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000346 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
347 // It is faster to get preds from a PHI than with pred_iterator.
348 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
349 BBPreds.insert(BBPN->getIncomingBlock(i));
350 } else {
351 BBPreds.insert(pred_begin(BB), pred_end(BB));
352 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000353
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000354 // Walk the preds of DestBB.
355 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
356 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
357 if (BBPreds.count(Pred)) { // Common predecessor?
358 BBI = DestBB->begin();
359 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
360 const Value *V1 = PN->getIncomingValueForBlock(Pred);
361 const Value *V2 = PN->getIncomingValueForBlock(BB);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000362
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000363 // If V2 is a phi node in BB, look up what the mapped value will be.
364 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
365 if (V2PN->getParent() == BB)
366 V2 = V2PN->getIncomingValueForBlock(Pred);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000367
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000368 // If there is a conflict, bail out.
369 if (V1 != V2) return false;
370 }
371 }
372 }
373
374 return true;
375}
376
377
378/// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
379/// an unconditional branch in it.
380void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
381 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
382 BasicBlock *DestBB = BI->getSuccessor(0);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000383
David Greene68d67fd2010-01-05 01:27:11 +0000384 DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000385
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000386 // If the destination block has a single pred, then this is a trivial edge,
387 // just collapse it.
Chris Lattner9918fb52008-11-27 19:29:14 +0000388 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
Chris Lattnerf5102a02008-11-28 19:54:49 +0000389 if (SinglePred != DestBB) {
390 // Remember if SinglePred was the entry block of the function. If so, we
391 // will need to move BB back to the entry position.
392 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Andreas Neustifterad809812009-09-16 09:26:52 +0000393 MergeBasicBlockIntoOnlyPred(DestBB, this);
Chris Lattner9918fb52008-11-27 19:29:14 +0000394
Chris Lattnerf5102a02008-11-28 19:54:49 +0000395 if (isEntry && BB != &BB->getParent()->getEntryBlock())
396 BB->moveBefore(&BB->getParent()->getEntryBlock());
Nadav Rotema94d6e82012-07-24 10:51:42 +0000397
David Greene68d67fd2010-01-05 01:27:11 +0000398 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerf5102a02008-11-28 19:54:49 +0000399 return;
400 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000401 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000402
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000403 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
404 // to handle the new incoming edges it is about to have.
405 PHINode *PN;
406 for (BasicBlock::iterator BBI = DestBB->begin();
407 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
408 // Remove the incoming value for BB, and remember it.
409 Value *InVal = PN->removeIncomingValue(BB, false);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000410
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000411 // Two options: either the InVal is a phi node defined in BB or it is some
412 // value that dominates BB.
413 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
414 if (InValPhi && InValPhi->getParent() == BB) {
415 // Add all of the input values of the input PHI as inputs of this phi.
416 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
417 PN->addIncoming(InValPhi->getIncomingValue(i),
418 InValPhi->getIncomingBlock(i));
419 } else {
420 // Otherwise, add one instance of the dominating value for each edge that
421 // we will be adding.
422 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
423 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
424 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
425 } else {
426 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
427 PN->addIncoming(InVal, *PI);
428 }
429 }
430 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000431
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000432 // The PHIs are now updated, change everything that refers to BB to use
433 // DestBB and remove BB.
434 BB->replaceAllUsesWith(DestBB);
Devang Patel52e37df2011-03-24 15:35:25 +0000435 if (DT && !ModifiedDT) {
Cameron Zwarich80f6a502011-01-08 17:01:52 +0000436 BasicBlock *BBIDom = DT->getNode(BB)->getIDom()->getBlock();
437 BasicBlock *DestBBIDom = DT->getNode(DestBB)->getIDom()->getBlock();
438 BasicBlock *NewIDom = DT->findNearestCommonDominator(BBIDom, DestBBIDom);
439 DT->changeImmediateDominator(DestBB, NewIDom);
440 DT->eraseNode(BB);
441 }
Evan Cheng04149f72009-12-17 09:39:49 +0000442 if (PFI) {
443 PFI->replaceAllUses(BB, DestBB);
444 PFI->removeEdge(ProfileInfo::getEdge(BB, DestBB));
Andreas Neustifterad809812009-09-16 09:26:52 +0000445 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000446 BB->eraseFromParent();
Cameron Zwarich31ff1332011-01-05 17:27:27 +0000447 ++NumBlocksElim;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000448
David Greene68d67fd2010-01-05 01:27:11 +0000449 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000450}
451
Chris Lattnerdd77df32007-04-13 20:30:56 +0000452/// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
Dan Gohmana119de82009-06-14 23:30:43 +0000453/// copy (e.g. it's casting from one pointer type to another, i32->i8 on PPC),
454/// sink it into user blocks to reduce the number of virtual
Dale Johannesence0b2372007-06-12 16:50:17 +0000455/// registers that must be created and coalesced.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000456///
457/// Return true if any changes are made.
Chris Lattner85fa13c2008-11-24 22:44:16 +0000458///
Chris Lattnerdd77df32007-04-13 20:30:56 +0000459static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
Eric Christopher692bf6b2008-09-24 05:32:41 +0000460 // If this is a noop copy,
Owen Andersone50ed302009-08-10 22:56:29 +0000461 EVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
462 EVT DstVT = TLI.getValueType(CI->getType());
Eric Christopher692bf6b2008-09-24 05:32:41 +0000463
Chris Lattnerdd77df32007-04-13 20:30:56 +0000464 // This is an fp<->int conversion?
Duncan Sands83ec4b62008-06-06 12:08:01 +0000465 if (SrcVT.isInteger() != DstVT.isInteger())
Chris Lattnerdd77df32007-04-13 20:30:56 +0000466 return false;
Duncan Sands8e4eb092008-06-08 20:54:56 +0000467
Chris Lattnerdd77df32007-04-13 20:30:56 +0000468 // If this is an extension, it will be a zero or sign extension, which
469 // isn't a noop.
Duncan Sands8e4eb092008-06-08 20:54:56 +0000470 if (SrcVT.bitsLT(DstVT)) return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000471
Chris Lattnerdd77df32007-04-13 20:30:56 +0000472 // If these values will be promoted, find out what they will be promoted
473 // to. This helps us consider truncates on PPC as noop copies when they
474 // are.
Nadav Rotem0ccc12a2011-05-29 08:10:47 +0000475 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
476 TargetLowering::TypePromoteInteger)
Owen Anderson23b9b192009-08-12 00:36:31 +0000477 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
Nadav Rotem0ccc12a2011-05-29 08:10:47 +0000478 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
479 TargetLowering::TypePromoteInteger)
Owen Anderson23b9b192009-08-12 00:36:31 +0000480 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000481
Chris Lattnerdd77df32007-04-13 20:30:56 +0000482 // If, after promotion, these are the same types, this is a noop copy.
483 if (SrcVT != DstVT)
484 return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000485
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000486 BasicBlock *DefBB = CI->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000487
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000488 /// InsertedCasts - Only insert a cast in each block once.
Dale Johannesence0b2372007-06-12 16:50:17 +0000489 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000490
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000491 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000492 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000493 UI != E; ) {
494 Use &TheUse = UI.getUse();
495 Instruction *User = cast<Instruction>(*UI);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000496
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000497 // Figure out which BB this cast is used in. For PHI's this is the
498 // appropriate predecessor block.
499 BasicBlock *UserBB = User->getParent();
500 if (PHINode *PN = dyn_cast<PHINode>(User)) {
Gabor Greifa36791d2009-01-23 19:40:15 +0000501 UserBB = PN->getIncomingBlock(UI);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000502 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000503
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000504 // Preincrement use iterator so we don't invalidate it.
505 ++UI;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000506
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000507 // If this user is in the same block as the cast, don't change the cast.
508 if (UserBB == DefBB) continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000509
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000510 // If we have already inserted a cast into this block, use it.
511 CastInst *&InsertedCast = InsertedCasts[UserBB];
512
513 if (!InsertedCast) {
Bill Wendling5b6f42f2011-08-16 20:45:24 +0000514 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000515 InsertedCast =
516 CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000517 InsertPt);
518 MadeChange = true;
519 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000520
Dale Johannesence0b2372007-06-12 16:50:17 +0000521 // Replace a use of the cast with a use of the new cast.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000522 TheUse = InsertedCast;
Cameron Zwarich31ff1332011-01-05 17:27:27 +0000523 ++NumCastUses;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000524 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000525
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000526 // If we removed all uses, nuke the cast.
Duncan Sandse0038132008-01-20 16:51:46 +0000527 if (CI->use_empty()) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000528 CI->eraseFromParent();
Duncan Sandse0038132008-01-20 16:51:46 +0000529 MadeChange = true;
530 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000531
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000532 return MadeChange;
533}
534
Eric Christopher692bf6b2008-09-24 05:32:41 +0000535/// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
Dale Johannesence0b2372007-06-12 16:50:17 +0000536/// the number of virtual registers that must be created and coalesced. This is
Chris Lattner684b22d2007-08-02 16:53:43 +0000537/// a clear win except on targets with multiple condition code registers
538/// (PowerPC), where it might lose; some adjustment may be wanted there.
Dale Johannesence0b2372007-06-12 16:50:17 +0000539///
540/// Return true if any changes are made.
Chris Lattner85fa13c2008-11-24 22:44:16 +0000541static bool OptimizeCmpExpression(CmpInst *CI) {
Dale Johannesence0b2372007-06-12 16:50:17 +0000542 BasicBlock *DefBB = CI->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000543
Dale Johannesence0b2372007-06-12 16:50:17 +0000544 /// InsertedCmp - Only insert a cmp in each block once.
545 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000546
Dale Johannesence0b2372007-06-12 16:50:17 +0000547 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000548 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
Dale Johannesence0b2372007-06-12 16:50:17 +0000549 UI != E; ) {
550 Use &TheUse = UI.getUse();
551 Instruction *User = cast<Instruction>(*UI);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000552
Dale Johannesence0b2372007-06-12 16:50:17 +0000553 // Preincrement use iterator so we don't invalidate it.
554 ++UI;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000555
Dale Johannesence0b2372007-06-12 16:50:17 +0000556 // Don't bother for PHI nodes.
557 if (isa<PHINode>(User))
558 continue;
559
560 // Figure out which BB this cmp is used in.
561 BasicBlock *UserBB = User->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000562
Dale Johannesence0b2372007-06-12 16:50:17 +0000563 // If this user is in the same block as the cmp, don't change the cmp.
564 if (UserBB == DefBB) continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000565
Dale Johannesence0b2372007-06-12 16:50:17 +0000566 // If we have already inserted a cmp into this block, use it.
567 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
568
569 if (!InsertedCmp) {
Bill Wendling5b6f42f2011-08-16 20:45:24 +0000570 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000571 InsertedCmp =
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000572 CmpInst::Create(CI->getOpcode(),
Owen Anderson333c4002009-07-09 23:48:35 +0000573 CI->getPredicate(), CI->getOperand(0),
Dale Johannesence0b2372007-06-12 16:50:17 +0000574 CI->getOperand(1), "", InsertPt);
575 MadeChange = true;
576 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000577
Dale Johannesence0b2372007-06-12 16:50:17 +0000578 // Replace a use of the cmp with a use of the new cmp.
579 TheUse = InsertedCmp;
Cameron Zwarich31ff1332011-01-05 17:27:27 +0000580 ++NumCmpUses;
Dale Johannesence0b2372007-06-12 16:50:17 +0000581 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000582
Dale Johannesence0b2372007-06-12 16:50:17 +0000583 // If we removed all uses, nuke the cmp.
584 if (CI->use_empty())
585 CI->eraseFromParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000586
Dale Johannesence0b2372007-06-12 16:50:17 +0000587 return MadeChange;
588}
589
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000590namespace {
591class CodeGenPrepareFortifiedLibCalls : public SimplifyFortifiedLibCalls {
592protected:
593 void replaceCall(Value *With) {
594 CI->replaceAllUsesWith(With);
595 CI->eraseFromParent();
596 }
597 bool isFoldable(unsigned SizeCIOp, unsigned, bool) const {
Gabor Greifa6aac4c2010-07-16 09:38:02 +0000598 if (ConstantInt *SizeCI =
599 dyn_cast<ConstantInt>(CI->getArgOperand(SizeCIOp)))
600 return SizeCI->isAllOnesValue();
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000601 return false;
602 }
603};
604} // end anonymous namespace
605
Eric Christopher040056f2010-03-11 02:41:03 +0000606bool CodeGenPrepare::OptimizeCallInst(CallInst *CI) {
Chris Lattner75796092011-01-15 07:14:54 +0000607 BasicBlock *BB = CI->getParent();
Nadav Rotema94d6e82012-07-24 10:51:42 +0000608
Chris Lattner75796092011-01-15 07:14:54 +0000609 // Lower inline assembly if we can.
610 // If we found an inline asm expession, and if the target knows how to
611 // lower it to normal LLVM code, do so now.
612 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
613 if (TLI->ExpandInlineAsm(CI)) {
614 // Avoid invalidating the iterator.
615 CurInstIterator = BB->begin();
616 // Avoid processing instructions out of order, which could cause
617 // reuse before a value is defined.
618 SunkAddrs.clear();
619 return true;
620 }
621 // Sink address computing for memory operands into the block.
622 if (OptimizeInlineAsmInst(CI))
623 return true;
624 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000625
Eric Christopher040056f2010-03-11 02:41:03 +0000626 // Lower all uses of llvm.objectsize.*
627 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
628 if (II && II->getIntrinsicID() == Intrinsic::objectsize) {
Gabor Greifde9f5452010-06-24 00:44:01 +0000629 bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000630 Type *ReturnTy = CI->getType();
Nadav Rotema94d6e82012-07-24 10:51:42 +0000631 Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
632
Chris Lattner94e8e0c2011-01-15 07:25:29 +0000633 // Substituting this can cause recursive simplifications, which can
634 // invalidate our iterator. Use a WeakVH to hold onto it in case this
635 // happens.
636 WeakVH IterHandle(CurInstIterator);
Nadav Rotema94d6e82012-07-24 10:51:42 +0000637
Micah Villmow3574eca2012-10-08 16:38:25 +0000638 replaceAndRecursivelySimplify(CI, RetVal, TLI ? TLI->getDataLayout() : 0,
Chandler Carruth6b980542012-03-24 21:11:24 +0000639 TLInfo, ModifiedDT ? 0 : DT);
Chris Lattner94e8e0c2011-01-15 07:25:29 +0000640
641 // If the iterator instruction was recursively deleted, start over at the
642 // start of the block.
Chris Lattner435b4d22011-01-18 20:53:04 +0000643 if (IterHandle != CurInstIterator) {
Chris Lattner94e8e0c2011-01-15 07:25:29 +0000644 CurInstIterator = BB->begin();
Chris Lattner435b4d22011-01-18 20:53:04 +0000645 SunkAddrs.clear();
646 }
Eric Christopher040056f2010-03-11 02:41:03 +0000647 return true;
648 }
649
Pete Cooperf210b682012-03-13 20:59:56 +0000650 if (II && TLI) {
651 SmallVector<Value*, 2> PtrOps;
652 Type *AccessTy;
653 if (TLI->GetAddrModeArguments(II, PtrOps, AccessTy))
654 while (!PtrOps.empty())
655 if (OptimizeMemoryInst(II, PtrOps.pop_back_val(), AccessTy))
656 return true;
657 }
658
Eric Christopher040056f2010-03-11 02:41:03 +0000659 // From here on out we're working with named functions.
660 if (CI->getCalledFunction() == 0) return false;
Devang Patel97de92c2011-05-26 21:51:06 +0000661
Micah Villmow3574eca2012-10-08 16:38:25 +0000662 // We'll need DataLayout from here on out.
663 const DataLayout *TD = TLI ? TLI->getDataLayout() : 0;
Eric Christopher040056f2010-03-11 02:41:03 +0000664 if (!TD) return false;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000665
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000666 // Lower all default uses of _chk calls. This is very similar
667 // to what InstCombineCalls does, but here we are only lowering calls
Eric Christopher040056f2010-03-11 02:41:03 +0000668 // that have the default "don't know" as the objectsize. Anything else
669 // should be left alone.
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000670 CodeGenPrepareFortifiedLibCalls Simplifier;
Nuno Lopes51004df2012-07-25 16:46:31 +0000671 return Simplifier.fold(CI, TD, TLInfo);
Eric Christopher040056f2010-03-11 02:41:03 +0000672}
Chris Lattner94e8e0c2011-01-15 07:25:29 +0000673
Evan Cheng485fafc2011-03-21 01:19:09 +0000674/// DupRetToEnableTailCallOpts - Look for opportunities to duplicate return
675/// instructions to the predecessor to enable tail call optimizations. The
676/// case it is currently looking for is:
Dmitri Gribenko2d9eb722012-09-13 12:34:29 +0000677/// @code
Evan Cheng485fafc2011-03-21 01:19:09 +0000678/// bb0:
679/// %tmp0 = tail call i32 @f0()
680/// br label %return
681/// bb1:
682/// %tmp1 = tail call i32 @f1()
683/// br label %return
684/// bb2:
685/// %tmp2 = tail call i32 @f2()
686/// br label %return
687/// return:
688/// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
689/// ret i32 %retval
Dmitri Gribenko2d9eb722012-09-13 12:34:29 +0000690/// @endcode
Evan Cheng485fafc2011-03-21 01:19:09 +0000691///
692/// =>
693///
Dmitri Gribenko2d9eb722012-09-13 12:34:29 +0000694/// @code
Evan Cheng485fafc2011-03-21 01:19:09 +0000695/// bb0:
696/// %tmp0 = tail call i32 @f0()
697/// ret i32 %tmp0
698/// bb1:
699/// %tmp1 = tail call i32 @f1()
700/// ret i32 %tmp1
701/// bb2:
702/// %tmp2 = tail call i32 @f2()
703/// ret i32 %tmp2
Dmitri Gribenko2d9eb722012-09-13 12:34:29 +0000704/// @endcode
Benjamin Kramer4ccb49a2012-11-23 19:17:06 +0000705bool CodeGenPrepare::DupRetToEnableTailCallOpts(BasicBlock *BB) {
Cameron Zwarich661a3902011-03-24 04:51:51 +0000706 if (!TLI)
707 return false;
708
Benjamin Kramer4ccb49a2012-11-23 19:17:06 +0000709 ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
710 if (!RI)
711 return false;
712
Evan Cheng9c777a42012-07-27 21:21:26 +0000713 PHINode *PN = 0;
714 BitCastInst *BCI = 0;
Evan Cheng485fafc2011-03-21 01:19:09 +0000715 Value *V = RI->getReturnValue();
Evan Cheng9c777a42012-07-27 21:21:26 +0000716 if (V) {
717 BCI = dyn_cast<BitCastInst>(V);
718 if (BCI)
719 V = BCI->getOperand(0);
720
721 PN = dyn_cast<PHINode>(V);
722 if (!PN)
723 return false;
724 }
Evan Cheng485fafc2011-03-21 01:19:09 +0000725
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000726 if (PN && PN->getParent() != BB)
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000727 return false;
Evan Cheng485fafc2011-03-21 01:19:09 +0000728
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000729 // It's not safe to eliminate the sign / zero extension of the return value.
730 // See llvm::isInTailCallPosition().
731 const Function *F = BB->getParent();
Bill Wendling034b94b2012-12-19 07:18:57 +0000732 Attribute CallerRetAttr = F->getAttributes().getRetAttributes();
733 if (CallerRetAttr.hasAttribute(Attribute::ZExt) ||
734 CallerRetAttr.hasAttribute(Attribute::SExt))
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000735 return false;
Evan Cheng485fafc2011-03-21 01:19:09 +0000736
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000737 // Make sure there are no instructions between the PHI and return, or that the
738 // return is the first instruction in the block.
739 if (PN) {
740 BasicBlock::iterator BI = BB->begin();
741 do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
Evan Cheng9c777a42012-07-27 21:21:26 +0000742 if (&*BI == BCI)
743 // Also skip over the bitcast.
744 ++BI;
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000745 if (&*BI != RI)
746 return false;
747 } else {
Cameron Zwarich90354842011-03-24 16:34:59 +0000748 BasicBlock::iterator BI = BB->begin();
749 while (isa<DbgInfoIntrinsic>(BI)) ++BI;
750 if (&*BI != RI)
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000751 return false;
752 }
Evan Cheng485fafc2011-03-21 01:19:09 +0000753
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000754 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
755 /// call.
756 SmallVector<CallInst*, 4> TailCalls;
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000757 if (PN) {
758 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
759 CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
760 // Make sure the phi value is indeed produced by the tail call.
761 if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
762 TLI->mayBeEmittedAsTailCall(CI))
763 TailCalls.push_back(CI);
764 }
765 } else {
766 SmallPtrSet<BasicBlock*, 4> VisitedBBs;
767 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
768 if (!VisitedBBs.insert(*PI))
769 continue;
770
771 BasicBlock::InstListType &InstList = (*PI)->getInstList();
772 BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
773 BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
Cameron Zwarich90354842011-03-24 16:34:59 +0000774 do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
775 if (RI == RE)
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000776 continue;
Cameron Zwarich90354842011-03-24 16:34:59 +0000777
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000778 CallInst *CI = dyn_cast<CallInst>(&*RI);
Cameron Zwarichdc31cfe2011-03-24 15:54:11 +0000779 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI))
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000780 TailCalls.push_back(CI);
781 }
Evan Cheng485fafc2011-03-21 01:19:09 +0000782 }
783
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000784 bool Changed = false;
785 for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
786 CallInst *CI = TailCalls[i];
787 CallSite CS(CI);
788
789 // Conservatively require the attributes of the call to match those of the
790 // return. Ignore noalias because it doesn't affect the call sequence.
Bill Wendling034b94b2012-12-19 07:18:57 +0000791 Attribute CalleeRetAttr = CS.getAttributes().getRetAttributes();
Bill Wendling702cc912012-10-15 20:35:56 +0000792 if (AttrBuilder(CalleeRetAttr).
Bill Wendling034b94b2012-12-19 07:18:57 +0000793 removeAttribute(Attribute::NoAlias) !=
Bill Wendling702cc912012-10-15 20:35:56 +0000794 AttrBuilder(CallerRetAttr).
Bill Wendling034b94b2012-12-19 07:18:57 +0000795 removeAttribute(Attribute::NoAlias))
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000796 continue;
797
798 // Make sure the call instruction is followed by an unconditional branch to
799 // the return block.
800 BasicBlock *CallBB = CI->getParent();
801 BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
802 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
803 continue;
804
805 // Duplicate the return into CallBB.
806 (void)FoldReturnIntoUncondBranch(RI, BB, CallBB);
Devang Patel52e37df2011-03-24 15:35:25 +0000807 ModifiedDT = Changed = true;
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000808 ++NumRetsDup;
809 }
810
811 // If we eliminated all predecessors of the block, delete the block now.
Evan Cheng46597072012-09-28 23:58:57 +0000812 if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000813 BB->eraseFromParent();
814
815 return Changed;
Evan Cheng485fafc2011-03-21 01:19:09 +0000816}
817
Chris Lattner88a5c832008-11-25 07:09:13 +0000818//===----------------------------------------------------------------------===//
Chris Lattner88a5c832008-11-25 07:09:13 +0000819// Memory Optimization
820//===----------------------------------------------------------------------===//
821
Chris Lattnerdd77df32007-04-13 20:30:56 +0000822/// IsNonLocalValue - Return true if the specified values are defined in a
823/// different basic block than BB.
824static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
825 if (Instruction *I = dyn_cast<Instruction>(V))
826 return I->getParent() != BB;
827 return false;
828}
829
Bob Wilson4a8ee232009-12-03 21:47:07 +0000830/// OptimizeMemoryInst - Load and Store Instructions often have
Chris Lattnerdd77df32007-04-13 20:30:56 +0000831/// addressing modes that can do significant amounts of computation. As such,
832/// instruction selection will try to get the load or store to do as much
833/// computation as possible for the program. The problem is that isel can only
834/// see within a single block. As such, we sink as much legal addressing mode
835/// stuff into the block as possible.
Chris Lattner88a5c832008-11-25 07:09:13 +0000836///
837/// This method is used to optimize both load/store and inline asms with memory
838/// operands.
Chris Lattner896617b2008-11-26 03:20:37 +0000839bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000840 Type *AccessTy) {
Owen Anderson35bf4d62010-11-27 08:15:55 +0000841 Value *Repl = Addr;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000842
843 // Try to collapse single-value PHI nodes. This is necessary to undo
Owen Andersond2f41742010-11-19 22:15:03 +0000844 // unprofitable PRE transformations.
Cameron Zwarich7cb4fa22011-01-03 06:33:01 +0000845 SmallVector<Value*, 8> worklist;
846 SmallPtrSet<Value*, 16> Visited;
Owen Anderson35bf4d62010-11-27 08:15:55 +0000847 worklist.push_back(Addr);
Nadav Rotema94d6e82012-07-24 10:51:42 +0000848
Owen Anderson35bf4d62010-11-27 08:15:55 +0000849 // Use a worklist to iteratively look through PHI nodes, and ensure that
850 // the addressing mode obtained from the non-PHI roots of the graph
851 // are equivalent.
852 Value *Consensus = 0;
Cameron Zwarich4c078f02011-03-01 21:13:53 +0000853 unsigned NumUsesConsensus = 0;
Cameron Zwarich7c8d3512011-03-05 08:12:26 +0000854 bool IsNumUsesConsensusValid = false;
Owen Anderson35bf4d62010-11-27 08:15:55 +0000855 SmallVector<Instruction*, 16> AddrModeInsts;
856 ExtAddrMode AddrMode;
857 while (!worklist.empty()) {
858 Value *V = worklist.back();
859 worklist.pop_back();
Nadav Rotema94d6e82012-07-24 10:51:42 +0000860
Owen Anderson35bf4d62010-11-27 08:15:55 +0000861 // Break use-def graph loops.
Nick Lewycky48105282011-09-29 23:40:12 +0000862 if (!Visited.insert(V)) {
Owen Anderson35bf4d62010-11-27 08:15:55 +0000863 Consensus = 0;
864 break;
Owen Andersond2f41742010-11-19 22:15:03 +0000865 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000866
Owen Anderson35bf4d62010-11-27 08:15:55 +0000867 // For a PHI node, push all of its incoming values.
868 if (PHINode *P = dyn_cast<PHINode>(V)) {
869 for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i)
870 worklist.push_back(P->getIncomingValue(i));
871 continue;
872 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000873
Owen Anderson35bf4d62010-11-27 08:15:55 +0000874 // For non-PHIs, determine the addressing mode being computed.
875 SmallVector<Instruction*, 16> NewAddrModeInsts;
876 ExtAddrMode NewAddrMode =
Nick Lewycky48105282011-09-29 23:40:12 +0000877 AddressingModeMatcher::Match(V, AccessTy, MemoryInst,
Owen Anderson35bf4d62010-11-27 08:15:55 +0000878 NewAddrModeInsts, *TLI);
Cameron Zwarich7c8d3512011-03-05 08:12:26 +0000879
880 // This check is broken into two cases with very similar code to avoid using
881 // getNumUses() as much as possible. Some values have a lot of uses, so
882 // calling getNumUses() unconditionally caused a significant compile-time
883 // regression.
884 if (!Consensus) {
885 Consensus = V;
886 AddrMode = NewAddrMode;
887 AddrModeInsts = NewAddrModeInsts;
888 continue;
889 } else if (NewAddrMode == AddrMode) {
890 if (!IsNumUsesConsensusValid) {
891 NumUsesConsensus = Consensus->getNumUses();
892 IsNumUsesConsensusValid = true;
893 }
894
895 // Ensure that the obtained addressing mode is equivalent to that obtained
896 // for all other roots of the PHI traversal. Also, when choosing one
897 // such root as representative, select the one with the most uses in order
898 // to keep the cost modeling heuristics in AddressingModeMatcher
899 // applicable.
Cameron Zwarich4c078f02011-03-01 21:13:53 +0000900 unsigned NumUses = V->getNumUses();
901 if (NumUses > NumUsesConsensus) {
Owen Anderson35bf4d62010-11-27 08:15:55 +0000902 Consensus = V;
Cameron Zwarich4c078f02011-03-01 21:13:53 +0000903 NumUsesConsensus = NumUses;
Owen Anderson35bf4d62010-11-27 08:15:55 +0000904 AddrModeInsts = NewAddrModeInsts;
905 }
906 continue;
907 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000908
Owen Anderson35bf4d62010-11-27 08:15:55 +0000909 Consensus = 0;
910 break;
Owen Andersond2f41742010-11-19 22:15:03 +0000911 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000912
Owen Anderson35bf4d62010-11-27 08:15:55 +0000913 // If the addressing mode couldn't be determined, or if multiple different
914 // ones were determined, bail out now.
915 if (!Consensus) return false;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000916
Chris Lattnerdd77df32007-04-13 20:30:56 +0000917 // Check to see if any of the instructions supersumed by this addr mode are
918 // non-local to I's BB.
919 bool AnyNonLocal = false;
920 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
Chris Lattner896617b2008-11-26 03:20:37 +0000921 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
Chris Lattnerdd77df32007-04-13 20:30:56 +0000922 AnyNonLocal = true;
923 break;
924 }
925 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000926
Chris Lattnerdd77df32007-04-13 20:30:56 +0000927 // If all the instructions matched are already in this BB, don't do anything.
928 if (!AnyNonLocal) {
David Greene68d67fd2010-01-05 01:27:11 +0000929 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000930 return false;
931 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000932
Chris Lattnerdd77df32007-04-13 20:30:56 +0000933 // Insert this computation right after this user. Since our caller is
934 // scanning from the top of the BB to the bottom, reuse of the expr are
935 // guaranteed to happen later.
Devang Patel2048c372011-09-06 18:49:53 +0000936 IRBuilder<> Builder(MemoryInst);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000937
Chris Lattnerdd77df32007-04-13 20:30:56 +0000938 // Now that we determined the addressing expression we want to use and know
939 // that we have to sink it into this block. Check to see if we have already
940 // done this for some other load/store instr in this block. If so, reuse the
941 // computation.
942 Value *&SunkAddr = SunkAddrs[Addr];
943 if (SunkAddr) {
David Greene68d67fd2010-01-05 01:27:11 +0000944 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
Dan Gohman6c1980b2009-07-25 01:13:51 +0000945 << *MemoryInst);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000946 if (SunkAddr->getType() != Addr->getType())
Benjamin Kramera9390a42011-09-27 20:39:19 +0000947 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
Chris Lattnerdd77df32007-04-13 20:30:56 +0000948 } else {
David Greene68d67fd2010-01-05 01:27:11 +0000949 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Dan Gohman6c1980b2009-07-25 01:13:51 +0000950 << *MemoryInst);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000951 Type *IntPtrTy =
Chandler Carruthece6c6b2012-11-01 08:07:29 +0000952 TLI->getDataLayout()->getIntPtrType(AccessTy->getContext());
Eric Christopher692bf6b2008-09-24 05:32:41 +0000953
Chris Lattnerdd77df32007-04-13 20:30:56 +0000954 Value *Result = 0;
Dan Gohmand8d0b6a2010-01-19 22:45:06 +0000955
956 // Start with the base register. Do this first so that subsequent address
957 // matching finds it last, which will prevent it from trying to match it
958 // as the scaled value in case it happens to be a mul. That would be
959 // problematic if we've sunk a different mul for the scale, because then
960 // we'd end up sinking both muls.
961 if (AddrMode.BaseReg) {
962 Value *V = AddrMode.BaseReg;
Duncan Sands1df98592010-02-16 11:11:14 +0000963 if (V->getType()->isPointerTy())
Devang Patel2048c372011-09-06 18:49:53 +0000964 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Dan Gohmand8d0b6a2010-01-19 22:45:06 +0000965 if (V->getType() != IntPtrTy)
Devang Patel2048c372011-09-06 18:49:53 +0000966 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
Dan Gohmand8d0b6a2010-01-19 22:45:06 +0000967 Result = V;
968 }
969
970 // Add the scale value.
Chris Lattnerdd77df32007-04-13 20:30:56 +0000971 if (AddrMode.Scale) {
972 Value *V = AddrMode.ScaledReg;
973 if (V->getType() == IntPtrTy) {
974 // done.
Duncan Sands1df98592010-02-16 11:11:14 +0000975 } else if (V->getType()->isPointerTy()) {
Devang Patel2048c372011-09-06 18:49:53 +0000976 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000977 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
978 cast<IntegerType>(V->getType())->getBitWidth()) {
Devang Patel2048c372011-09-06 18:49:53 +0000979 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000980 } else {
Devang Patel2048c372011-09-06 18:49:53 +0000981 V = Builder.CreateSExt(V, IntPtrTy, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000982 }
983 if (AddrMode.Scale != 1)
Devang Patel2048c372011-09-06 18:49:53 +0000984 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
985 "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000986 if (Result)
Devang Patel2048c372011-09-06 18:49:53 +0000987 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000988 else
989 Result = V;
990 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000991
Chris Lattnerdd77df32007-04-13 20:30:56 +0000992 // Add in the BaseGV if present.
993 if (AddrMode.BaseGV) {
Devang Patel2048c372011-09-06 18:49:53 +0000994 Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000995 if (Result)
Devang Patel2048c372011-09-06 18:49:53 +0000996 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000997 else
998 Result = V;
999 }
Eric Christopher692bf6b2008-09-24 05:32:41 +00001000
Chris Lattnerdd77df32007-04-13 20:30:56 +00001001 // Add in the Base Offset if present.
1002 if (AddrMode.BaseOffs) {
Owen Andersoneed707b2009-07-24 23:12:02 +00001003 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
Chris Lattnerdd77df32007-04-13 20:30:56 +00001004 if (Result)
Devang Patel2048c372011-09-06 18:49:53 +00001005 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +00001006 else
1007 Result = V;
1008 }
1009
1010 if (Result == 0)
Owen Andersona7235ea2009-07-31 20:28:14 +00001011 SunkAddr = Constant::getNullValue(Addr->getType());
Chris Lattnerdd77df32007-04-13 20:30:56 +00001012 else
Devang Patel2048c372011-09-06 18:49:53 +00001013 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +00001014 }
Eric Christopher692bf6b2008-09-24 05:32:41 +00001015
Owen Andersond2f41742010-11-19 22:15:03 +00001016 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
Eric Christopher692bf6b2008-09-24 05:32:41 +00001017
Chris Lattner0403b472011-04-09 07:05:44 +00001018 // If we have no uses, recursively delete the value and all dead instructions
1019 // using it.
Owen Andersond2f41742010-11-19 22:15:03 +00001020 if (Repl->use_empty()) {
Chris Lattner0403b472011-04-09 07:05:44 +00001021 // This can cause recursive deletion, which can invalidate our iterator.
1022 // Use a WeakVH to hold onto it in case this happens.
1023 WeakVH IterHandle(CurInstIterator);
1024 BasicBlock *BB = CurInstIterator->getParent();
Nadav Rotema94d6e82012-07-24 10:51:42 +00001025
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +00001026 RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
Chris Lattner0403b472011-04-09 07:05:44 +00001027
1028 if (IterHandle != CurInstIterator) {
1029 // If the iterator instruction was recursively deleted, start over at the
1030 // start of the block.
1031 CurInstIterator = BB->begin();
1032 SunkAddrs.clear();
1033 } else {
1034 // This address is now available for reassignment, so erase the table
1035 // entry; we don't want to match some completely different instruction.
1036 SunkAddrs[Addr] = 0;
Nadav Rotema94d6e82012-07-24 10:51:42 +00001037 }
Dale Johannesen536d31b2010-03-31 20:37:15 +00001038 }
Cameron Zwarich31ff1332011-01-05 17:27:27 +00001039 ++NumMemoryInsts;
Chris Lattnerdd77df32007-04-13 20:30:56 +00001040 return true;
1041}
1042
Evan Cheng9bf12b52008-02-26 02:42:37 +00001043/// OptimizeInlineAsmInst - If there are any memory operands, use
Chris Lattner88a5c832008-11-25 07:09:13 +00001044/// OptimizeMemoryInst to sink their address computing into the block when
Evan Cheng9bf12b52008-02-26 02:42:37 +00001045/// possible / profitable.
Chris Lattner75796092011-01-15 07:14:54 +00001046bool CodeGenPrepare::OptimizeInlineAsmInst(CallInst *CS) {
Evan Cheng9bf12b52008-02-26 02:42:37 +00001047 bool MadeChange = false;
Evan Cheng9bf12b52008-02-26 02:42:37 +00001048
Nadav Rotema94d6e82012-07-24 10:51:42 +00001049 TargetLowering::AsmOperandInfoVector
Chris Lattner75796092011-01-15 07:14:54 +00001050 TargetConstraints = TLI->ParseConstraints(CS);
Dale Johannesen677c6ec2010-09-16 18:30:55 +00001051 unsigned ArgNo = 0;
John Thompsoneac6e1d2010-09-13 18:15:37 +00001052 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
1053 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Nadav Rotema94d6e82012-07-24 10:51:42 +00001054
Evan Cheng9bf12b52008-02-26 02:42:37 +00001055 // Compute the constraint code and ConstraintType to use.
Dale Johannesen1784d162010-06-25 21:55:36 +00001056 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Evan Cheng9bf12b52008-02-26 02:42:37 +00001057
Eli Friedman9ec80952008-02-26 18:37:49 +00001058 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
1059 OpInfo.isIndirect) {
Chris Lattner75796092011-01-15 07:14:54 +00001060 Value *OpVal = CS->getArgOperand(ArgNo++);
Chris Lattner1a8943a2011-01-15 07:29:01 +00001061 MadeChange |= OptimizeMemoryInst(CS, OpVal, OpVal->getType());
Dale Johannesen677c6ec2010-09-16 18:30:55 +00001062 } else if (OpInfo.Type == InlineAsm::isInput)
1063 ArgNo++;
Evan Cheng9bf12b52008-02-26 02:42:37 +00001064 }
1065
1066 return MadeChange;
1067}
1068
Dan Gohmanb00f2362009-10-16 20:59:35 +00001069/// MoveExtToFormExtLoad - Move a zext or sext fed by a load into the same
1070/// basic block as the load, unless conditions are unfavorable. This allows
1071/// SelectionDAG to fold the extend into the load.
1072///
1073bool CodeGenPrepare::MoveExtToFormExtLoad(Instruction *I) {
1074 // Look for a load being extended.
1075 LoadInst *LI = dyn_cast<LoadInst>(I->getOperand(0));
1076 if (!LI) return false;
1077
1078 // If they're already in the same block, there's nothing to do.
1079 if (LI->getParent() == I->getParent())
1080 return false;
1081
1082 // If the load has other users and the truncate is not free, this probably
1083 // isn't worthwhile.
1084 if (!LI->hasOneUse() &&
Bob Wilsonec57a1a2010-09-22 18:44:56 +00001085 TLI && (TLI->isTypeLegal(TLI->getValueType(LI->getType())) ||
1086 !TLI->isTypeLegal(TLI->getValueType(I->getType()))) &&
Bob Wilson71dc4d92010-09-21 21:54:27 +00001087 !TLI->isTruncateFree(I->getType(), LI->getType()))
Dan Gohmanb00f2362009-10-16 20:59:35 +00001088 return false;
1089
1090 // Check whether the target supports casts folded into loads.
1091 unsigned LType;
1092 if (isa<ZExtInst>(I))
1093 LType = ISD::ZEXTLOAD;
1094 else {
1095 assert(isa<SExtInst>(I) && "Unexpected ext type!");
1096 LType = ISD::SEXTLOAD;
1097 }
Patrik Hagglund34525f92012-12-11 11:14:33 +00001098 if (TLI && !TLI->isLoadExtLegal(LType, TLI->getValueType(LI->getType())))
Dan Gohmanb00f2362009-10-16 20:59:35 +00001099 return false;
1100
1101 // Move the extend into the same block as the load, so that SelectionDAG
1102 // can fold it.
1103 I->removeFromParent();
1104 I->insertAfter(LI);
Cameron Zwarich31ff1332011-01-05 17:27:27 +00001105 ++NumExtsMoved;
Dan Gohmanb00f2362009-10-16 20:59:35 +00001106 return true;
1107}
1108
Evan Chengbdcb7262007-12-05 23:58:20 +00001109bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
1110 BasicBlock *DefBB = I->getParent();
1111
Bob Wilson9120f5c2010-09-21 21:44:14 +00001112 // If the result of a {s|z}ext and its source are both live out, rewrite all
Evan Chengbdcb7262007-12-05 23:58:20 +00001113 // other uses of the source with result of extension.
1114 Value *Src = I->getOperand(0);
1115 if (Src->hasOneUse())
1116 return false;
1117
Evan Cheng696e5c02007-12-13 07:50:36 +00001118 // Only do this xform if truncating is free.
Gabor Greif53bdbd72008-02-26 19:13:21 +00001119 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
Evan Chengf9785f92007-12-13 03:32:53 +00001120 return false;
1121
Evan Cheng772de512007-12-12 00:51:06 +00001122 // Only safe to perform the optimization if the source is also defined in
Evan Cheng765dff22007-12-12 02:53:41 +00001123 // this block.
1124 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
Evan Cheng772de512007-12-12 00:51:06 +00001125 return false;
1126
Evan Chengbdcb7262007-12-05 23:58:20 +00001127 bool DefIsLiveOut = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001128 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
Evan Chengbdcb7262007-12-05 23:58:20 +00001129 UI != E; ++UI) {
1130 Instruction *User = cast<Instruction>(*UI);
1131
1132 // Figure out which BB this ext is used in.
1133 BasicBlock *UserBB = User->getParent();
1134 if (UserBB == DefBB) continue;
1135 DefIsLiveOut = true;
1136 break;
1137 }
1138 if (!DefIsLiveOut)
1139 return false;
1140
Evan Cheng765dff22007-12-12 02:53:41 +00001141 // Make sure non of the uses are PHI nodes.
Eric Christopher692bf6b2008-09-24 05:32:41 +00001142 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
Evan Cheng765dff22007-12-12 02:53:41 +00001143 UI != E; ++UI) {
1144 Instruction *User = cast<Instruction>(*UI);
Evan Chengf9785f92007-12-13 03:32:53 +00001145 BasicBlock *UserBB = User->getParent();
1146 if (UserBB == DefBB) continue;
1147 // Be conservative. We don't want this xform to end up introducing
1148 // reloads just before load / store instructions.
1149 if (isa<PHINode>(User) || isa<LoadInst>(User) || isa<StoreInst>(User))
Evan Cheng765dff22007-12-12 02:53:41 +00001150 return false;
1151 }
1152
Evan Chengbdcb7262007-12-05 23:58:20 +00001153 // InsertedTruncs - Only insert one trunc in each block once.
1154 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
1155
1156 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001157 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
Evan Chengbdcb7262007-12-05 23:58:20 +00001158 UI != E; ++UI) {
1159 Use &TheUse = UI.getUse();
1160 Instruction *User = cast<Instruction>(*UI);
1161
1162 // Figure out which BB this ext is used in.
1163 BasicBlock *UserBB = User->getParent();
1164 if (UserBB == DefBB) continue;
1165
1166 // Both src and def are live in this block. Rewrite the use.
1167 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
1168
1169 if (!InsertedTrunc) {
Bill Wendling5b6f42f2011-08-16 20:45:24 +00001170 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Evan Chengbdcb7262007-12-05 23:58:20 +00001171 InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
1172 }
1173
1174 // Replace a use of the {s|z}ext source with a use of the result.
1175 TheUse = InsertedTrunc;
Cameron Zwarich31ff1332011-01-05 17:27:27 +00001176 ++NumExtUses;
Evan Chengbdcb7262007-12-05 23:58:20 +00001177 MadeChange = true;
1178 }
1179
1180 return MadeChange;
1181}
1182
Benjamin Kramer59957502012-05-05 12:49:22 +00001183/// isFormingBranchFromSelectProfitable - Returns true if a SelectInst should be
1184/// turned into an explicit branch.
1185static bool isFormingBranchFromSelectProfitable(SelectInst *SI) {
1186 // FIXME: This should use the same heuristics as IfConversion to determine
1187 // whether a select is better represented as a branch. This requires that
1188 // branch probability metadata is preserved for the select, which is not the
1189 // case currently.
1190
1191 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
1192
1193 // If the branch is predicted right, an out of order CPU can avoid blocking on
1194 // the compare. Emit cmovs on compares with a memory operand as branches to
1195 // avoid stalls on the load from memory. If the compare has more than one use
1196 // there's probably another cmov or setcc around so it's not worth emitting a
1197 // branch.
1198 if (!Cmp)
1199 return false;
1200
1201 Value *CmpOp0 = Cmp->getOperand(0);
1202 Value *CmpOp1 = Cmp->getOperand(1);
1203
1204 // We check that the memory operand has one use to avoid uses of the loaded
1205 // value directly after the compare, making branches unprofitable.
1206 return Cmp->hasOneUse() &&
1207 ((isa<LoadInst>(CmpOp0) && CmpOp0->hasOneUse()) ||
1208 (isa<LoadInst>(CmpOp1) && CmpOp1->hasOneUse()));
1209}
1210
1211
Nadav Rotem9f40cb32012-09-02 12:10:19 +00001212/// If we have a SelectInst that will likely profit from branch prediction,
1213/// turn it into a branch.
Benjamin Kramer59957502012-05-05 12:49:22 +00001214bool CodeGenPrepare::OptimizeSelectInst(SelectInst *SI) {
Nadav Rotem9f40cb32012-09-02 12:10:19 +00001215 bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
1216
1217 // Can we convert the 'select' to CF ?
1218 if (DisableSelectToBranch || OptSize || !TLI || VectorCond)
Benjamin Kramer59957502012-05-05 12:49:22 +00001219 return false;
1220
Nadav Rotem9f40cb32012-09-02 12:10:19 +00001221 TargetLowering::SelectSupportKind SelectKind;
1222 if (VectorCond)
1223 SelectKind = TargetLowering::VectorMaskSelect;
1224 else if (SI->getType()->isVectorTy())
1225 SelectKind = TargetLowering::ScalarCondVectorVal;
1226 else
1227 SelectKind = TargetLowering::ScalarValSelect;
1228
1229 // Do we have efficient codegen support for this kind of 'selects' ?
1230 if (TLI->isSelectSupported(SelectKind)) {
1231 // We have efficient codegen support for the select instruction.
1232 // Check if it is profitable to keep this 'select'.
1233 if (!TLI->isPredictableSelectExpensive() ||
1234 !isFormingBranchFromSelectProfitable(SI))
1235 return false;
1236 }
Benjamin Kramer59957502012-05-05 12:49:22 +00001237
1238 ModifiedDT = true;
1239
1240 // First, we split the block containing the select into 2 blocks.
1241 BasicBlock *StartBlock = SI->getParent();
1242 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(SI));
1243 BasicBlock *NextBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
1244
1245 // Create a new block serving as the landing pad for the branch.
1246 BasicBlock *SmallBlock = BasicBlock::Create(SI->getContext(), "select.mid",
1247 NextBlock->getParent(), NextBlock);
1248
1249 // Move the unconditional branch from the block with the select in it into our
1250 // landing pad block.
1251 StartBlock->getTerminator()->eraseFromParent();
1252 BranchInst::Create(NextBlock, SmallBlock);
1253
1254 // Insert the real conditional branch based on the original condition.
1255 BranchInst::Create(NextBlock, SmallBlock, SI->getCondition(), SI);
1256
1257 // The select itself is replaced with a PHI Node.
1258 PHINode *PN = PHINode::Create(SI->getType(), 2, "", NextBlock->begin());
1259 PN->takeName(SI);
1260 PN->addIncoming(SI->getTrueValue(), StartBlock);
1261 PN->addIncoming(SI->getFalseValue(), SmallBlock);
1262 SI->replaceAllUsesWith(PN);
1263 SI->eraseFromParent();
1264
1265 // Instruct OptimizeBlock to skip to the next block.
1266 CurInstIterator = StartBlock->end();
1267 ++NumSelectsExpanded;
1268 return true;
1269}
1270
Cameron Zwarichc0611012011-01-06 02:37:26 +00001271bool CodeGenPrepare::OptimizeInst(Instruction *I) {
Cameron Zwarichc0611012011-01-06 02:37:26 +00001272 if (PHINode *P = dyn_cast<PHINode>(I)) {
1273 // It is possible for very late stage optimizations (such as SimplifyCFG)
1274 // to introduce PHI nodes too late to be cleaned up. If we detect such a
1275 // trivial PHI, go ahead and zap it here.
1276 if (Value *V = SimplifyInstruction(P)) {
1277 P->replaceAllUsesWith(V);
1278 P->eraseFromParent();
1279 ++NumPHIsElim;
Chris Lattner1a8943a2011-01-15 07:29:01 +00001280 return true;
Cameron Zwarichc0611012011-01-06 02:37:26 +00001281 }
Chris Lattner1a8943a2011-01-15 07:29:01 +00001282 return false;
1283 }
Nadav Rotema94d6e82012-07-24 10:51:42 +00001284
Chris Lattner1a8943a2011-01-15 07:29:01 +00001285 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Cameron Zwarichc0611012011-01-06 02:37:26 +00001286 // If the source of the cast is a constant, then this should have
1287 // already been constant folded. The only reason NOT to constant fold
1288 // it is if something (e.g. LSR) was careful to place the constant
1289 // evaluation in a block other than then one that uses it (e.g. to hoist
1290 // the address of globals out of a loop). If this is the case, we don't
1291 // want to forward-subst the cast.
1292 if (isa<Constant>(CI->getOperand(0)))
1293 return false;
1294
Chris Lattner1a8943a2011-01-15 07:29:01 +00001295 if (TLI && OptimizeNoopCopyExpression(CI, *TLI))
1296 return true;
Cameron Zwarichc0611012011-01-06 02:37:26 +00001297
Chris Lattner1a8943a2011-01-15 07:29:01 +00001298 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
1299 bool MadeChange = MoveExtToFormExtLoad(I);
1300 return MadeChange | OptimizeExtUses(I);
Cameron Zwarichc0611012011-01-06 02:37:26 +00001301 }
Chris Lattner1a8943a2011-01-15 07:29:01 +00001302 return false;
1303 }
Nadav Rotema94d6e82012-07-24 10:51:42 +00001304
Chris Lattner1a8943a2011-01-15 07:29:01 +00001305 if (CmpInst *CI = dyn_cast<CmpInst>(I))
1306 return OptimizeCmpExpression(CI);
Nadav Rotema94d6e82012-07-24 10:51:42 +00001307
Chris Lattner1a8943a2011-01-15 07:29:01 +00001308 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Cameron Zwarichc0611012011-01-06 02:37:26 +00001309 if (TLI)
Hans Wennborg04d7d132012-10-30 11:23:25 +00001310 return OptimizeMemoryInst(I, I->getOperand(0), LI->getType());
1311 return false;
Chris Lattner1a8943a2011-01-15 07:29:01 +00001312 }
Nadav Rotema94d6e82012-07-24 10:51:42 +00001313
Chris Lattner1a8943a2011-01-15 07:29:01 +00001314 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Cameron Zwarichc0611012011-01-06 02:37:26 +00001315 if (TLI)
Chris Lattner1a8943a2011-01-15 07:29:01 +00001316 return OptimizeMemoryInst(I, SI->getOperand(1),
1317 SI->getOperand(0)->getType());
1318 return false;
1319 }
Nadav Rotema94d6e82012-07-24 10:51:42 +00001320
Chris Lattner1a8943a2011-01-15 07:29:01 +00001321 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Cameron Zwarich865ae1a2011-01-06 02:44:52 +00001322 if (GEPI->hasAllZeroIndices()) {
1323 /// The GEP operand must be a pointer, so must its result -> BitCast
1324 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
1325 GEPI->getName(), GEPI);
1326 GEPI->replaceAllUsesWith(NC);
1327 GEPI->eraseFromParent();
1328 ++NumGEPsElim;
Cameron Zwarich865ae1a2011-01-06 02:44:52 +00001329 OptimizeInst(NC);
Chris Lattner1a8943a2011-01-15 07:29:01 +00001330 return true;
Cameron Zwarich865ae1a2011-01-06 02:44:52 +00001331 }
Chris Lattner1a8943a2011-01-15 07:29:01 +00001332 return false;
Cameron Zwarichc0611012011-01-06 02:37:26 +00001333 }
Nadav Rotema94d6e82012-07-24 10:51:42 +00001334
Chris Lattner1a8943a2011-01-15 07:29:01 +00001335 if (CallInst *CI = dyn_cast<CallInst>(I))
1336 return OptimizeCallInst(CI);
Cameron Zwarichc0611012011-01-06 02:37:26 +00001337
Benjamin Kramer59957502012-05-05 12:49:22 +00001338 if (SelectInst *SI = dyn_cast<SelectInst>(I))
1339 return OptimizeSelectInst(SI);
1340
Chris Lattner1a8943a2011-01-15 07:29:01 +00001341 return false;
Cameron Zwarichc0611012011-01-06 02:37:26 +00001342}
1343
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001344// In this pass we look for GEP and cast instructions that are used
1345// across basic blocks and rewrite them to improve basic-block-at-a-time
1346// selection.
1347bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
Cameron Zwarich8c3527e2011-01-06 00:42:50 +00001348 SunkAddrs.clear();
Cameron Zwarich56e37932011-03-02 03:31:46 +00001349 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001350
Chris Lattner75796092011-01-15 07:14:54 +00001351 CurInstIterator = BB.begin();
Hans Wennborg93ba1332012-09-19 07:48:16 +00001352 while (CurInstIterator != BB.end())
Chris Lattner94e8e0c2011-01-15 07:25:29 +00001353 MadeChange |= OptimizeInst(CurInstIterator++);
Eric Christopher692bf6b2008-09-24 05:32:41 +00001354
Benjamin Kramer4ccb49a2012-11-23 19:17:06 +00001355 MadeChange |= DupRetToEnableTailCallOpts(&BB);
1356
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001357 return MadeChange;
1358}
Devang Patelf56ea612011-08-18 00:50:51 +00001359
1360// llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotema94d6e82012-07-24 10:51:42 +00001361// handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patelf56ea612011-08-18 00:50:51 +00001362// find a node corresponding to the value.
1363bool CodeGenPrepare::PlaceDbgValues(Function &F) {
1364 bool MadeChange = false;
1365 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
1366 Instruction *PrevNonDbgInst = NULL;
1367 for (BasicBlock::iterator BI = I->begin(), BE = I->end(); BI != BE;) {
1368 Instruction *Insn = BI; ++BI;
1369 DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
1370 if (!DVI) {
1371 PrevNonDbgInst = Insn;
1372 continue;
1373 }
1374
1375 Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
1376 if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
1377 DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
1378 DVI->removeFromParent();
1379 if (isa<PHINode>(VI))
1380 DVI->insertBefore(VI->getParent()->getFirstInsertionPt());
1381 else
1382 DVI->insertAfter(VI);
1383 MadeChange = true;
1384 ++NumDbgValueMoved;
1385 }
1386 }
1387 }
1388 return MadeChange;
1389}