blob: b608a5535edcde5d8e56353d34e157b40a547c6a [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"
18#include "llvm/Constants.h"
19#include "llvm/DerivedTypes.h"
20#include "llvm/Function.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000021#include "llvm/IRBuilder.h"
Evan Cheng9bf12b52008-02-26 02:42:37 +000022#include "llvm/InlineAsm.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000023#include "llvm/Instructions.h"
Dale Johannesen6aae1d62009-03-26 01:15:07 +000024#include "llvm/IntrinsicInst.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000025#include "llvm/Pass.h"
Chris Lattnerdd77df32007-04-13 20:30:56 +000026#include "llvm/ADT/DenseMap.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000027#include "llvm/ADT/SmallSet.h"
Jakob Stoklund Olesen7eb589d2010-09-30 20:51:52 +000028#include "llvm/ADT/Statistic.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000029#include "llvm/Analysis/Dominators.h"
Richard Smithc1f7ae12012-10-23 06:19:46 +000030#include "llvm/Analysis/DominatorInternals.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000031#include "llvm/Analysis/InstructionSimplify.h"
32#include "llvm/Analysis/ProfileInfo.h"
Dan Gohman03ce0422009-02-13 17:45:12 +000033#include "llvm/Assembly/Writer.h"
Evan Cheng9bf12b52008-02-26 02:42:37 +000034#include "llvm/Support/CallSite.h"
Evan Chenge1bcb442010-08-17 01:34:49 +000035#include "llvm/Support/CommandLine.h"
Evan Chengbdcb7262007-12-05 23:58:20 +000036#include "llvm/Support/Debug.h"
Chris Lattnerdd77df32007-04-13 20:30:56 +000037#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner088a1e82008-11-25 04:42:10 +000038#include "llvm/Support/PatternMatch.h"
Chris Lattner94e8e0c2011-01-15 07:25:29 +000039#include "llvm/Support/ValueHandle.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000040#include "llvm/Support/raw_ostream.h"
Micah Villmow3574eca2012-10-08 16:38:25 +000041#include "llvm/DataLayout.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
Andreas Neustifterad809812009-09-16 09:26:52 +0000109 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Cameron Zwarich80f6a502011-01-08 17:01:52 +0000110 AU.addPreserved<DominatorTree>();
Andreas Neustifterad809812009-09-16 09:26:52 +0000111 AU.addPreserved<ProfileInfo>();
Chad Rosier618c1db2011-12-01 03:08:23 +0000112 AU.addRequired<TargetLibraryInfo>();
Andreas Neustifterad809812009-09-16 09:26:52 +0000113 }
114
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000115 private:
Nadav Rotem3e883732012-08-14 05:19:07 +0000116 bool EliminateFallThrough(Function &F);
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000117 bool EliminateMostlyEmptyBlocks(Function &F);
118 bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
119 void EliminateMostlyEmptyBlock(BasicBlock *BB);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000120 bool OptimizeBlock(BasicBlock &BB);
Cameron Zwarichc0611012011-01-06 02:37:26 +0000121 bool OptimizeInst(Instruction *I);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000122 bool OptimizeMemoryInst(Instruction *I, Value *Addr, Type *AccessTy);
Chris Lattner75796092011-01-15 07:14:54 +0000123 bool OptimizeInlineAsmInst(CallInst *CS);
Eric Christopher040056f2010-03-11 02:41:03 +0000124 bool OptimizeCallInst(CallInst *CI);
Dan Gohmanb00f2362009-10-16 20:59:35 +0000125 bool MoveExtToFormExtLoad(Instruction *I);
Evan Chengbdcb7262007-12-05 23:58:20 +0000126 bool OptimizeExtUses(Instruction *I);
Benjamin Kramer59957502012-05-05 12:49:22 +0000127 bool OptimizeSelectInst(SelectInst *SI);
Benjamin Kramer4ccb49a2012-11-23 19:17:06 +0000128 bool DupRetToEnableTailCallOpts(BasicBlock *BB);
Devang Patelf56ea612011-08-18 00:50:51 +0000129 bool PlaceDbgValues(Function &F);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000130 };
131}
Devang Patel794fd752007-05-01 21:15:47 +0000132
Devang Patel19974732007-05-03 01:11:54 +0000133char CodeGenPrepare::ID = 0;
Chad Rosier618c1db2011-12-01 03:08:23 +0000134INITIALIZE_PASS_BEGIN(CodeGenPrepare, "codegenprepare",
135 "Optimize for code generation", false, false)
136INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
137INITIALIZE_PASS_END(CodeGenPrepare, "codegenprepare",
Owen Andersonce665bd2010-10-07 22:25:06 +0000138 "Optimize for code generation", false, false)
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000139
140FunctionPass *llvm::createCodeGenPreparePass(const TargetLowering *TLI) {
141 return new CodeGenPrepare(TLI);
142}
143
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000144bool CodeGenPrepare::runOnFunction(Function &F) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000145 bool EverMadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000146
Devang Patel52e37df2011-03-24 15:35:25 +0000147 ModifiedDT = false;
Chad Rosier618c1db2011-12-01 03:08:23 +0000148 TLInfo = &getAnalysis<TargetLibraryInfo>();
Cameron Zwarich80f6a502011-01-08 17:01:52 +0000149 DT = getAnalysisIfAvailable<DominatorTree>();
Evan Cheng04149f72009-12-17 09:39:49 +0000150 PFI = getAnalysisIfAvailable<ProfileInfo>();
Bill Wendling67658342012-10-09 07:45:08 +0000151 OptSize = F.getFnAttributes().hasAttribute(Attributes::OptimizeForSize);
Evan Cheng485fafc2011-03-21 01:19:09 +0000152
Preston Gurd2e2efd92012-09-04 18:22:17 +0000153 /// This optimization identifies DIV instructions that can be
154 /// profitably bypassed and carried out with a shorter, faster divide.
155 if (TLI && TLI->isSlowDivBypassed()) {
Preston Gurd8d662b52012-10-04 21:33:40 +0000156 const DenseMap<unsigned int, unsigned int> &BypassWidths =
157 TLI->getBypassSlowDivWidths();
Evan Cheng911908d2012-09-14 21:25:34 +0000158 for (Function::iterator I = F.begin(); I != F.end(); I++)
Preston Gurd8d662b52012-10-04 21:33:40 +0000159 EverMadeChange |= bypassSlowDivision(F, I, BypassWidths);
Preston Gurd2e2efd92012-09-04 18:22:17 +0000160 }
161
162 // Eliminate blocks that contain only PHI nodes and an
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000163 // unconditional branch.
164 EverMadeChange |= EliminateMostlyEmptyBlocks(F);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000165
Devang Patelf56ea612011-08-18 00:50:51 +0000166 // llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotema94d6e82012-07-24 10:51:42 +0000167 // handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patelf56ea612011-08-18 00:50:51 +0000168 // find a node corresponding to the value.
169 EverMadeChange |= PlaceDbgValues(F);
170
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000171 bool MadeChange = true;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000172 while (MadeChange) {
173 MadeChange = false;
Hans Wennborg93ba1332012-09-19 07:48:16 +0000174 for (Function::iterator I = F.begin(); I != F.end(); ) {
Evan Cheng485fafc2011-03-21 01:19:09 +0000175 BasicBlock *BB = I++;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000176 MadeChange |= OptimizeBlock(*BB);
Evan Cheng485fafc2011-03-21 01:19:09 +0000177 }
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000178 EverMadeChange |= MadeChange;
179 }
Cameron Zwarich8c3527e2011-01-06 00:42:50 +0000180
181 SunkAddrs.clear();
182
Cameron Zwarich899eaa32011-03-11 21:52:04 +0000183 if (!DisableBranchOpts) {
184 MadeChange = false;
Bill Wendlinge3e394d2012-03-04 10:46:01 +0000185 SmallPtrSet<BasicBlock*, 8> WorkList;
186 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
187 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
Frits van Bommel5649ba72011-05-22 16:24:18 +0000188 MadeChange |= ConstantFoldTerminator(BB, true);
Bill Wendlinge3e394d2012-03-04 10:46:01 +0000189 if (!MadeChange) continue;
190
191 for (SmallVectorImpl<BasicBlock*>::iterator
192 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
193 if (pred_begin(*II) == pred_end(*II))
194 WorkList.insert(*II);
195 }
196
Bill Wendling8dd2e5b2012-08-15 21:18:10 +0000197 for (SmallPtrSet<BasicBlock*, 8>::iterator
198 I = WorkList.begin(), E = WorkList.end(); I != E; ++I)
199 DeleteDeadBlock(*I);
Cameron Zwarich899eaa32011-03-11 21:52:04 +0000200
Nadav Rotem3e883732012-08-14 05:19:07 +0000201 // Merge pairs of basic blocks with unconditional branches, connected by
202 // a single edge.
203 if (EverMadeChange || MadeChange)
204 MadeChange |= EliminateFallThrough(F);
205
Evan Cheng485fafc2011-03-21 01:19:09 +0000206 if (MadeChange)
Devang Patel52e37df2011-03-24 15:35:25 +0000207 ModifiedDT = true;
Cameron Zwarich899eaa32011-03-11 21:52:04 +0000208 EverMadeChange |= MadeChange;
209 }
210
Devang Patel52e37df2011-03-24 15:35:25 +0000211 if (ModifiedDT && DT)
Evan Cheng485fafc2011-03-21 01:19:09 +0000212 DT->DT->recalculate(F);
213
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000214 return EverMadeChange;
215}
216
Nadav Rotem3e883732012-08-14 05:19:07 +0000217/// EliminateFallThrough - Merge basic blocks which are connected
218/// by a single edge, where one of the basic blocks has a single successor
219/// pointing to the other basic block, which has a single predecessor.
220bool CodeGenPrepare::EliminateFallThrough(Function &F) {
221 bool Changed = false;
222 // Scan all of the blocks in the function, except for the entry block.
223 for (Function::iterator I = ++F.begin(), E = F.end(); I != E; ) {
224 BasicBlock *BB = I++;
225 // If the destination block has a single pred, then this is a trivial
226 // edge, just collapse it.
227 BasicBlock *SinglePred = BB->getSinglePredecessor();
228
Evan Cheng46597072012-09-28 23:58:57 +0000229 // Don't merge if BB's address is taken.
230 if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue;
Nadav Rotem3e883732012-08-14 05:19:07 +0000231
232 BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
233 if (Term && !Term->isConditional()) {
234 Changed = true;
Michael Liao787ed032012-08-21 05:55:22 +0000235 DEBUG(dbgs() << "To merge:\n"<< *SinglePred << "\n\n\n");
Nadav Rotem3e883732012-08-14 05:19:07 +0000236 // Remember if SinglePred was the entry block of the function.
237 // If so, we will need to move BB back to the entry position.
238 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
239 MergeBasicBlockIntoOnlyPred(BB, this);
240
241 if (isEntry && BB != &BB->getParent()->getEntryBlock())
242 BB->moveBefore(&BB->getParent()->getEntryBlock());
243
244 // We have erased a block. Update the iterator.
245 I = BB;
Nadav Rotem3e883732012-08-14 05:19:07 +0000246 }
247 }
248 return Changed;
249}
250
Dale Johannesen2d697242009-03-27 01:13:37 +0000251/// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes,
252/// debug info directives, and an unconditional branch. Passes before isel
253/// (e.g. LSR/loopsimplify) often split edges in ways that are non-optimal for
254/// isel. Start by eliminating these blocks so we can split them the way we
255/// want them.
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000256bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
257 bool MadeChange = false;
258 // Note that this intentionally skips the entry block.
259 for (Function::iterator I = ++F.begin(), E = F.end(); I != E; ) {
260 BasicBlock *BB = I++;
261
262 // If this block doesn't end with an uncond branch, ignore it.
263 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
264 if (!BI || !BI->isUnconditional())
265 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000266
Dale Johannesen2d697242009-03-27 01:13:37 +0000267 // If the instruction before the branch (skipping debug info) isn't a phi
268 // node, then other stuff is happening here.
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000269 BasicBlock::iterator BBI = BI;
270 if (BBI != BB->begin()) {
271 --BBI;
Dale Johannesen2d697242009-03-27 01:13:37 +0000272 while (isa<DbgInfoIntrinsic>(BBI)) {
273 if (BBI == BB->begin())
274 break;
275 --BBI;
276 }
277 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
278 continue;
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000279 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000280
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000281 // Do not break infinite loops.
282 BasicBlock *DestBB = BI->getSuccessor(0);
283 if (DestBB == BB)
284 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000285
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000286 if (!CanMergeBlocks(BB, DestBB))
287 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000288
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000289 EliminateMostlyEmptyBlock(BB);
290 MadeChange = true;
291 }
292 return MadeChange;
293}
294
295/// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
296/// single uncond branch between them, and BB contains no other non-phi
297/// instructions.
298bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
299 const BasicBlock *DestBB) const {
300 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
301 // the successor. If there are more complex condition (e.g. preheaders),
302 // don't mess around with them.
303 BasicBlock::const_iterator BBI = BB->begin();
304 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
Gabor Greif60ad7812010-03-25 23:06:16 +0000305 for (Value::const_use_iterator UI = PN->use_begin(), E = PN->use_end();
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000306 UI != E; ++UI) {
307 const Instruction *User = cast<Instruction>(*UI);
308 if (User->getParent() != DestBB || !isa<PHINode>(User))
309 return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000310 // If User is inside DestBB block and it is a PHINode then check
311 // incoming value. If incoming value is not from BB then this is
Devang Patel75abc1e2007-04-25 00:37:04 +0000312 // a complex condition (e.g. preheaders) we want to avoid here.
313 if (User->getParent() == DestBB) {
314 if (const PHINode *UPN = dyn_cast<PHINode>(User))
315 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
316 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
317 if (Insn && Insn->getParent() == BB &&
318 Insn->getParent() != UPN->getIncomingBlock(I))
319 return false;
320 }
321 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000322 }
323 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000324
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000325 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
326 // and DestBB may have conflicting incoming values for the block. If so, we
327 // can't merge the block.
328 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
329 if (!DestBBPN) return true; // no conflict.
Eric Christopher692bf6b2008-09-24 05:32:41 +0000330
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000331 // Collect the preds of BB.
Chris Lattnerf67f73a2007-11-06 22:07:40 +0000332 SmallPtrSet<const BasicBlock*, 16> BBPreds;
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000333 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
334 // It is faster to get preds from a PHI than with pred_iterator.
335 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
336 BBPreds.insert(BBPN->getIncomingBlock(i));
337 } else {
338 BBPreds.insert(pred_begin(BB), pred_end(BB));
339 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000340
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000341 // Walk the preds of DestBB.
342 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
343 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
344 if (BBPreds.count(Pred)) { // Common predecessor?
345 BBI = DestBB->begin();
346 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
347 const Value *V1 = PN->getIncomingValueForBlock(Pred);
348 const Value *V2 = PN->getIncomingValueForBlock(BB);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000349
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000350 // If V2 is a phi node in BB, look up what the mapped value will be.
351 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
352 if (V2PN->getParent() == BB)
353 V2 = V2PN->getIncomingValueForBlock(Pred);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000354
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000355 // If there is a conflict, bail out.
356 if (V1 != V2) return false;
357 }
358 }
359 }
360
361 return true;
362}
363
364
365/// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
366/// an unconditional branch in it.
367void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
368 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
369 BasicBlock *DestBB = BI->getSuccessor(0);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000370
David Greene68d67fd2010-01-05 01:27:11 +0000371 DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000372
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000373 // If the destination block has a single pred, then this is a trivial edge,
374 // just collapse it.
Chris Lattner9918fb52008-11-27 19:29:14 +0000375 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
Chris Lattnerf5102a02008-11-28 19:54:49 +0000376 if (SinglePred != DestBB) {
377 // Remember if SinglePred was the entry block of the function. If so, we
378 // will need to move BB back to the entry position.
379 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Andreas Neustifterad809812009-09-16 09:26:52 +0000380 MergeBasicBlockIntoOnlyPred(DestBB, this);
Chris Lattner9918fb52008-11-27 19:29:14 +0000381
Chris Lattnerf5102a02008-11-28 19:54:49 +0000382 if (isEntry && BB != &BB->getParent()->getEntryBlock())
383 BB->moveBefore(&BB->getParent()->getEntryBlock());
Nadav Rotema94d6e82012-07-24 10:51:42 +0000384
David Greene68d67fd2010-01-05 01:27:11 +0000385 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerf5102a02008-11-28 19:54:49 +0000386 return;
387 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000388 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000389
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000390 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
391 // to handle the new incoming edges it is about to have.
392 PHINode *PN;
393 for (BasicBlock::iterator BBI = DestBB->begin();
394 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
395 // Remove the incoming value for BB, and remember it.
396 Value *InVal = PN->removeIncomingValue(BB, false);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000397
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000398 // Two options: either the InVal is a phi node defined in BB or it is some
399 // value that dominates BB.
400 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
401 if (InValPhi && InValPhi->getParent() == BB) {
402 // Add all of the input values of the input PHI as inputs of this phi.
403 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
404 PN->addIncoming(InValPhi->getIncomingValue(i),
405 InValPhi->getIncomingBlock(i));
406 } else {
407 // Otherwise, add one instance of the dominating value for each edge that
408 // we will be adding.
409 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
410 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
411 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
412 } else {
413 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
414 PN->addIncoming(InVal, *PI);
415 }
416 }
417 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000418
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000419 // The PHIs are now updated, change everything that refers to BB to use
420 // DestBB and remove BB.
421 BB->replaceAllUsesWith(DestBB);
Devang Patel52e37df2011-03-24 15:35:25 +0000422 if (DT && !ModifiedDT) {
Cameron Zwarich80f6a502011-01-08 17:01:52 +0000423 BasicBlock *BBIDom = DT->getNode(BB)->getIDom()->getBlock();
424 BasicBlock *DestBBIDom = DT->getNode(DestBB)->getIDom()->getBlock();
425 BasicBlock *NewIDom = DT->findNearestCommonDominator(BBIDom, DestBBIDom);
426 DT->changeImmediateDominator(DestBB, NewIDom);
427 DT->eraseNode(BB);
428 }
Evan Cheng04149f72009-12-17 09:39:49 +0000429 if (PFI) {
430 PFI->replaceAllUses(BB, DestBB);
431 PFI->removeEdge(ProfileInfo::getEdge(BB, DestBB));
Andreas Neustifterad809812009-09-16 09:26:52 +0000432 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000433 BB->eraseFromParent();
Cameron Zwarich31ff1332011-01-05 17:27:27 +0000434 ++NumBlocksElim;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000435
David Greene68d67fd2010-01-05 01:27:11 +0000436 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000437}
438
Chris Lattnerdd77df32007-04-13 20:30:56 +0000439/// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
Dan Gohmana119de82009-06-14 23:30:43 +0000440/// copy (e.g. it's casting from one pointer type to another, i32->i8 on PPC),
441/// sink it into user blocks to reduce the number of virtual
Dale Johannesence0b2372007-06-12 16:50:17 +0000442/// registers that must be created and coalesced.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000443///
444/// Return true if any changes are made.
Chris Lattner85fa13c2008-11-24 22:44:16 +0000445///
Chris Lattnerdd77df32007-04-13 20:30:56 +0000446static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
Eric Christopher692bf6b2008-09-24 05:32:41 +0000447 // If this is a noop copy,
Owen Andersone50ed302009-08-10 22:56:29 +0000448 EVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
449 EVT DstVT = TLI.getValueType(CI->getType());
Eric Christopher692bf6b2008-09-24 05:32:41 +0000450
Chris Lattnerdd77df32007-04-13 20:30:56 +0000451 // This is an fp<->int conversion?
Duncan Sands83ec4b62008-06-06 12:08:01 +0000452 if (SrcVT.isInteger() != DstVT.isInteger())
Chris Lattnerdd77df32007-04-13 20:30:56 +0000453 return false;
Duncan Sands8e4eb092008-06-08 20:54:56 +0000454
Chris Lattnerdd77df32007-04-13 20:30:56 +0000455 // If this is an extension, it will be a zero or sign extension, which
456 // isn't a noop.
Duncan Sands8e4eb092008-06-08 20:54:56 +0000457 if (SrcVT.bitsLT(DstVT)) return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000458
Chris Lattnerdd77df32007-04-13 20:30:56 +0000459 // If these values will be promoted, find out what they will be promoted
460 // to. This helps us consider truncates on PPC as noop copies when they
461 // are.
Nadav Rotem0ccc12a2011-05-29 08:10:47 +0000462 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
463 TargetLowering::TypePromoteInteger)
Owen Anderson23b9b192009-08-12 00:36:31 +0000464 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
Nadav Rotem0ccc12a2011-05-29 08:10:47 +0000465 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
466 TargetLowering::TypePromoteInteger)
Owen Anderson23b9b192009-08-12 00:36:31 +0000467 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000468
Chris Lattnerdd77df32007-04-13 20:30:56 +0000469 // If, after promotion, these are the same types, this is a noop copy.
470 if (SrcVT != DstVT)
471 return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000472
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000473 BasicBlock *DefBB = CI->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000474
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000475 /// InsertedCasts - Only insert a cast in each block once.
Dale Johannesence0b2372007-06-12 16:50:17 +0000476 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000477
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000478 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000479 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000480 UI != E; ) {
481 Use &TheUse = UI.getUse();
482 Instruction *User = cast<Instruction>(*UI);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000483
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000484 // Figure out which BB this cast is used in. For PHI's this is the
485 // appropriate predecessor block.
486 BasicBlock *UserBB = User->getParent();
487 if (PHINode *PN = dyn_cast<PHINode>(User)) {
Gabor Greifa36791d2009-01-23 19:40:15 +0000488 UserBB = PN->getIncomingBlock(UI);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000489 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000490
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000491 // Preincrement use iterator so we don't invalidate it.
492 ++UI;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000493
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000494 // If this user is in the same block as the cast, don't change the cast.
495 if (UserBB == DefBB) continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000496
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000497 // If we have already inserted a cast into this block, use it.
498 CastInst *&InsertedCast = InsertedCasts[UserBB];
499
500 if (!InsertedCast) {
Bill Wendling5b6f42f2011-08-16 20:45:24 +0000501 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000502 InsertedCast =
503 CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000504 InsertPt);
505 MadeChange = true;
506 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000507
Dale Johannesence0b2372007-06-12 16:50:17 +0000508 // Replace a use of the cast with a use of the new cast.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000509 TheUse = InsertedCast;
Cameron Zwarich31ff1332011-01-05 17:27:27 +0000510 ++NumCastUses;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000511 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000512
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000513 // If we removed all uses, nuke the cast.
Duncan Sandse0038132008-01-20 16:51:46 +0000514 if (CI->use_empty()) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000515 CI->eraseFromParent();
Duncan Sandse0038132008-01-20 16:51:46 +0000516 MadeChange = true;
517 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000518
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000519 return MadeChange;
520}
521
Eric Christopher692bf6b2008-09-24 05:32:41 +0000522/// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
Dale Johannesence0b2372007-06-12 16:50:17 +0000523/// the number of virtual registers that must be created and coalesced. This is
Chris Lattner684b22d2007-08-02 16:53:43 +0000524/// a clear win except on targets with multiple condition code registers
525/// (PowerPC), where it might lose; some adjustment may be wanted there.
Dale Johannesence0b2372007-06-12 16:50:17 +0000526///
527/// Return true if any changes are made.
Chris Lattner85fa13c2008-11-24 22:44:16 +0000528static bool OptimizeCmpExpression(CmpInst *CI) {
Dale Johannesence0b2372007-06-12 16:50:17 +0000529 BasicBlock *DefBB = CI->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000530
Dale Johannesence0b2372007-06-12 16:50:17 +0000531 /// InsertedCmp - Only insert a cmp in each block once.
532 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000533
Dale Johannesence0b2372007-06-12 16:50:17 +0000534 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000535 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
Dale Johannesence0b2372007-06-12 16:50:17 +0000536 UI != E; ) {
537 Use &TheUse = UI.getUse();
538 Instruction *User = cast<Instruction>(*UI);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000539
Dale Johannesence0b2372007-06-12 16:50:17 +0000540 // Preincrement use iterator so we don't invalidate it.
541 ++UI;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000542
Dale Johannesence0b2372007-06-12 16:50:17 +0000543 // Don't bother for PHI nodes.
544 if (isa<PHINode>(User))
545 continue;
546
547 // Figure out which BB this cmp is used in.
548 BasicBlock *UserBB = User->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000549
Dale Johannesence0b2372007-06-12 16:50:17 +0000550 // If this user is in the same block as the cmp, don't change the cmp.
551 if (UserBB == DefBB) continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000552
Dale Johannesence0b2372007-06-12 16:50:17 +0000553 // If we have already inserted a cmp into this block, use it.
554 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
555
556 if (!InsertedCmp) {
Bill Wendling5b6f42f2011-08-16 20:45:24 +0000557 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000558 InsertedCmp =
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000559 CmpInst::Create(CI->getOpcode(),
Owen Anderson333c4002009-07-09 23:48:35 +0000560 CI->getPredicate(), CI->getOperand(0),
Dale Johannesence0b2372007-06-12 16:50:17 +0000561 CI->getOperand(1), "", InsertPt);
562 MadeChange = true;
563 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000564
Dale Johannesence0b2372007-06-12 16:50:17 +0000565 // Replace a use of the cmp with a use of the new cmp.
566 TheUse = InsertedCmp;
Cameron Zwarich31ff1332011-01-05 17:27:27 +0000567 ++NumCmpUses;
Dale Johannesence0b2372007-06-12 16:50:17 +0000568 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000569
Dale Johannesence0b2372007-06-12 16:50:17 +0000570 // If we removed all uses, nuke the cmp.
571 if (CI->use_empty())
572 CI->eraseFromParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000573
Dale Johannesence0b2372007-06-12 16:50:17 +0000574 return MadeChange;
575}
576
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000577namespace {
578class CodeGenPrepareFortifiedLibCalls : public SimplifyFortifiedLibCalls {
579protected:
580 void replaceCall(Value *With) {
581 CI->replaceAllUsesWith(With);
582 CI->eraseFromParent();
583 }
584 bool isFoldable(unsigned SizeCIOp, unsigned, bool) const {
Gabor Greifa6aac4c2010-07-16 09:38:02 +0000585 if (ConstantInt *SizeCI =
586 dyn_cast<ConstantInt>(CI->getArgOperand(SizeCIOp)))
587 return SizeCI->isAllOnesValue();
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000588 return false;
589 }
590};
591} // end anonymous namespace
592
Eric Christopher040056f2010-03-11 02:41:03 +0000593bool CodeGenPrepare::OptimizeCallInst(CallInst *CI) {
Chris Lattner75796092011-01-15 07:14:54 +0000594 BasicBlock *BB = CI->getParent();
Nadav Rotema94d6e82012-07-24 10:51:42 +0000595
Chris Lattner75796092011-01-15 07:14:54 +0000596 // Lower inline assembly if we can.
597 // If we found an inline asm expession, and if the target knows how to
598 // lower it to normal LLVM code, do so now.
599 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
600 if (TLI->ExpandInlineAsm(CI)) {
601 // Avoid invalidating the iterator.
602 CurInstIterator = BB->begin();
603 // Avoid processing instructions out of order, which could cause
604 // reuse before a value is defined.
605 SunkAddrs.clear();
606 return true;
607 }
608 // Sink address computing for memory operands into the block.
609 if (OptimizeInlineAsmInst(CI))
610 return true;
611 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000612
Eric Christopher040056f2010-03-11 02:41:03 +0000613 // Lower all uses of llvm.objectsize.*
614 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
615 if (II && II->getIntrinsicID() == Intrinsic::objectsize) {
Gabor Greifde9f5452010-06-24 00:44:01 +0000616 bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000617 Type *ReturnTy = CI->getType();
Nadav Rotema94d6e82012-07-24 10:51:42 +0000618 Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
619
Chris Lattner94e8e0c2011-01-15 07:25:29 +0000620 // Substituting this can cause recursive simplifications, which can
621 // invalidate our iterator. Use a WeakVH to hold onto it in case this
622 // happens.
623 WeakVH IterHandle(CurInstIterator);
Nadav Rotema94d6e82012-07-24 10:51:42 +0000624
Micah Villmow3574eca2012-10-08 16:38:25 +0000625 replaceAndRecursivelySimplify(CI, RetVal, TLI ? TLI->getDataLayout() : 0,
Chandler Carruth6b980542012-03-24 21:11:24 +0000626 TLInfo, ModifiedDT ? 0 : DT);
Chris Lattner94e8e0c2011-01-15 07:25:29 +0000627
628 // If the iterator instruction was recursively deleted, start over at the
629 // start of the block.
Chris Lattner435b4d22011-01-18 20:53:04 +0000630 if (IterHandle != CurInstIterator) {
Chris Lattner94e8e0c2011-01-15 07:25:29 +0000631 CurInstIterator = BB->begin();
Chris Lattner435b4d22011-01-18 20:53:04 +0000632 SunkAddrs.clear();
633 }
Eric Christopher040056f2010-03-11 02:41:03 +0000634 return true;
635 }
636
Pete Cooperf210b682012-03-13 20:59:56 +0000637 if (II && TLI) {
638 SmallVector<Value*, 2> PtrOps;
639 Type *AccessTy;
640 if (TLI->GetAddrModeArguments(II, PtrOps, AccessTy))
641 while (!PtrOps.empty())
642 if (OptimizeMemoryInst(II, PtrOps.pop_back_val(), AccessTy))
643 return true;
644 }
645
Eric Christopher040056f2010-03-11 02:41:03 +0000646 // From here on out we're working with named functions.
647 if (CI->getCalledFunction() == 0) return false;
Devang Patel97de92c2011-05-26 21:51:06 +0000648
Micah Villmow3574eca2012-10-08 16:38:25 +0000649 // We'll need DataLayout from here on out.
650 const DataLayout *TD = TLI ? TLI->getDataLayout() : 0;
Eric Christopher040056f2010-03-11 02:41:03 +0000651 if (!TD) return false;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000652
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000653 // Lower all default uses of _chk calls. This is very similar
654 // to what InstCombineCalls does, but here we are only lowering calls
Eric Christopher040056f2010-03-11 02:41:03 +0000655 // that have the default "don't know" as the objectsize. Anything else
656 // should be left alone.
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000657 CodeGenPrepareFortifiedLibCalls Simplifier;
Nuno Lopes51004df2012-07-25 16:46:31 +0000658 return Simplifier.fold(CI, TD, TLInfo);
Eric Christopher040056f2010-03-11 02:41:03 +0000659}
Chris Lattner94e8e0c2011-01-15 07:25:29 +0000660
Evan Cheng485fafc2011-03-21 01:19:09 +0000661/// DupRetToEnableTailCallOpts - Look for opportunities to duplicate return
662/// instructions to the predecessor to enable tail call optimizations. The
663/// case it is currently looking for is:
Dmitri Gribenko2d9eb722012-09-13 12:34:29 +0000664/// @code
Evan Cheng485fafc2011-03-21 01:19:09 +0000665/// bb0:
666/// %tmp0 = tail call i32 @f0()
667/// br label %return
668/// bb1:
669/// %tmp1 = tail call i32 @f1()
670/// br label %return
671/// bb2:
672/// %tmp2 = tail call i32 @f2()
673/// br label %return
674/// return:
675/// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
676/// ret i32 %retval
Dmitri Gribenko2d9eb722012-09-13 12:34:29 +0000677/// @endcode
Evan Cheng485fafc2011-03-21 01:19:09 +0000678///
679/// =>
680///
Dmitri Gribenko2d9eb722012-09-13 12:34:29 +0000681/// @code
Evan Cheng485fafc2011-03-21 01:19:09 +0000682/// bb0:
683/// %tmp0 = tail call i32 @f0()
684/// ret i32 %tmp0
685/// bb1:
686/// %tmp1 = tail call i32 @f1()
687/// ret i32 %tmp1
688/// bb2:
689/// %tmp2 = tail call i32 @f2()
690/// ret i32 %tmp2
Dmitri Gribenko2d9eb722012-09-13 12:34:29 +0000691/// @endcode
Benjamin Kramer4ccb49a2012-11-23 19:17:06 +0000692bool CodeGenPrepare::DupRetToEnableTailCallOpts(BasicBlock *BB) {
Cameron Zwarich661a3902011-03-24 04:51:51 +0000693 if (!TLI)
694 return false;
695
Benjamin Kramer4ccb49a2012-11-23 19:17:06 +0000696 ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
697 if (!RI)
698 return false;
699
Evan Cheng9c777a42012-07-27 21:21:26 +0000700 PHINode *PN = 0;
701 BitCastInst *BCI = 0;
Evan Cheng485fafc2011-03-21 01:19:09 +0000702 Value *V = RI->getReturnValue();
Evan Cheng9c777a42012-07-27 21:21:26 +0000703 if (V) {
704 BCI = dyn_cast<BitCastInst>(V);
705 if (BCI)
706 V = BCI->getOperand(0);
707
708 PN = dyn_cast<PHINode>(V);
709 if (!PN)
710 return false;
711 }
Evan Cheng485fafc2011-03-21 01:19:09 +0000712
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000713 if (PN && PN->getParent() != BB)
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000714 return false;
Evan Cheng485fafc2011-03-21 01:19:09 +0000715
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000716 // It's not safe to eliminate the sign / zero extension of the return value.
717 // See llvm::isInTailCallPosition().
718 const Function *F = BB->getParent();
Kostya Serebryany164b86b2012-01-20 17:56:17 +0000719 Attributes CallerRetAttr = F->getAttributes().getRetAttributes();
Bill Wendling67658342012-10-09 07:45:08 +0000720 if (CallerRetAttr.hasAttribute(Attributes::ZExt) ||
721 CallerRetAttr.hasAttribute(Attributes::SExt))
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000722 return false;
Evan Cheng485fafc2011-03-21 01:19:09 +0000723
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000724 // Make sure there are no instructions between the PHI and return, or that the
725 // return is the first instruction in the block.
726 if (PN) {
727 BasicBlock::iterator BI = BB->begin();
728 do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
Evan Cheng9c777a42012-07-27 21:21:26 +0000729 if (&*BI == BCI)
730 // Also skip over the bitcast.
731 ++BI;
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000732 if (&*BI != RI)
733 return false;
734 } else {
Cameron Zwarich90354842011-03-24 16:34:59 +0000735 BasicBlock::iterator BI = BB->begin();
736 while (isa<DbgInfoIntrinsic>(BI)) ++BI;
737 if (&*BI != RI)
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000738 return false;
739 }
Evan Cheng485fafc2011-03-21 01:19:09 +0000740
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000741 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
742 /// call.
743 SmallVector<CallInst*, 4> TailCalls;
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000744 if (PN) {
745 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
746 CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
747 // Make sure the phi value is indeed produced by the tail call.
748 if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
749 TLI->mayBeEmittedAsTailCall(CI))
750 TailCalls.push_back(CI);
751 }
752 } else {
753 SmallPtrSet<BasicBlock*, 4> VisitedBBs;
754 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
755 if (!VisitedBBs.insert(*PI))
756 continue;
757
758 BasicBlock::InstListType &InstList = (*PI)->getInstList();
759 BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
760 BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
Cameron Zwarich90354842011-03-24 16:34:59 +0000761 do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
762 if (RI == RE)
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000763 continue;
Cameron Zwarich90354842011-03-24 16:34:59 +0000764
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000765 CallInst *CI = dyn_cast<CallInst>(&*RI);
Cameron Zwarichdc31cfe2011-03-24 15:54:11 +0000766 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI))
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000767 TailCalls.push_back(CI);
768 }
Evan Cheng485fafc2011-03-21 01:19:09 +0000769 }
770
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000771 bool Changed = false;
772 for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
773 CallInst *CI = TailCalls[i];
774 CallSite CS(CI);
775
776 // Conservatively require the attributes of the call to match those of the
777 // return. Ignore noalias because it doesn't affect the call sequence.
Kostya Serebryany164b86b2012-01-20 17:56:17 +0000778 Attributes CalleeRetAttr = CS.getAttributes().getRetAttributes();
Bill Wendling702cc912012-10-15 20:35:56 +0000779 if (AttrBuilder(CalleeRetAttr).
Bill Wendling3756e702012-10-14 06:56:13 +0000780 removeAttribute(Attributes::NoAlias) !=
Bill Wendling702cc912012-10-15 20:35:56 +0000781 AttrBuilder(CallerRetAttr).
Bill Wendling3756e702012-10-14 06:56:13 +0000782 removeAttribute(Attributes::NoAlias))
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000783 continue;
784
785 // Make sure the call instruction is followed by an unconditional branch to
786 // the return block.
787 BasicBlock *CallBB = CI->getParent();
788 BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
789 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
790 continue;
791
792 // Duplicate the return into CallBB.
793 (void)FoldReturnIntoUncondBranch(RI, BB, CallBB);
Devang Patel52e37df2011-03-24 15:35:25 +0000794 ModifiedDT = Changed = true;
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000795 ++NumRetsDup;
796 }
797
798 // If we eliminated all predecessors of the block, delete the block now.
Evan Cheng46597072012-09-28 23:58:57 +0000799 if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000800 BB->eraseFromParent();
801
802 return Changed;
Evan Cheng485fafc2011-03-21 01:19:09 +0000803}
804
Chris Lattner88a5c832008-11-25 07:09:13 +0000805//===----------------------------------------------------------------------===//
Chris Lattner88a5c832008-11-25 07:09:13 +0000806// Memory Optimization
807//===----------------------------------------------------------------------===//
808
Chris Lattnerdd77df32007-04-13 20:30:56 +0000809/// IsNonLocalValue - Return true if the specified values are defined in a
810/// different basic block than BB.
811static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
812 if (Instruction *I = dyn_cast<Instruction>(V))
813 return I->getParent() != BB;
814 return false;
815}
816
Bob Wilson4a8ee232009-12-03 21:47:07 +0000817/// OptimizeMemoryInst - Load and Store Instructions often have
Chris Lattnerdd77df32007-04-13 20:30:56 +0000818/// addressing modes that can do significant amounts of computation. As such,
819/// instruction selection will try to get the load or store to do as much
820/// computation as possible for the program. The problem is that isel can only
821/// see within a single block. As such, we sink as much legal addressing mode
822/// stuff into the block as possible.
Chris Lattner88a5c832008-11-25 07:09:13 +0000823///
824/// This method is used to optimize both load/store and inline asms with memory
825/// operands.
Chris Lattner896617b2008-11-26 03:20:37 +0000826bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000827 Type *AccessTy) {
Owen Anderson35bf4d62010-11-27 08:15:55 +0000828 Value *Repl = Addr;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000829
830 // Try to collapse single-value PHI nodes. This is necessary to undo
Owen Andersond2f41742010-11-19 22:15:03 +0000831 // unprofitable PRE transformations.
Cameron Zwarich7cb4fa22011-01-03 06:33:01 +0000832 SmallVector<Value*, 8> worklist;
833 SmallPtrSet<Value*, 16> Visited;
Owen Anderson35bf4d62010-11-27 08:15:55 +0000834 worklist.push_back(Addr);
Nadav Rotema94d6e82012-07-24 10:51:42 +0000835
Owen Anderson35bf4d62010-11-27 08:15:55 +0000836 // Use a worklist to iteratively look through PHI nodes, and ensure that
837 // the addressing mode obtained from the non-PHI roots of the graph
838 // are equivalent.
839 Value *Consensus = 0;
Cameron Zwarich4c078f02011-03-01 21:13:53 +0000840 unsigned NumUsesConsensus = 0;
Cameron Zwarich7c8d3512011-03-05 08:12:26 +0000841 bool IsNumUsesConsensusValid = false;
Owen Anderson35bf4d62010-11-27 08:15:55 +0000842 SmallVector<Instruction*, 16> AddrModeInsts;
843 ExtAddrMode AddrMode;
844 while (!worklist.empty()) {
845 Value *V = worklist.back();
846 worklist.pop_back();
Nadav Rotema94d6e82012-07-24 10:51:42 +0000847
Owen Anderson35bf4d62010-11-27 08:15:55 +0000848 // Break use-def graph loops.
Nick Lewycky48105282011-09-29 23:40:12 +0000849 if (!Visited.insert(V)) {
Owen Anderson35bf4d62010-11-27 08:15:55 +0000850 Consensus = 0;
851 break;
Owen Andersond2f41742010-11-19 22:15:03 +0000852 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000853
Owen Anderson35bf4d62010-11-27 08:15:55 +0000854 // For a PHI node, push all of its incoming values.
855 if (PHINode *P = dyn_cast<PHINode>(V)) {
856 for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i)
857 worklist.push_back(P->getIncomingValue(i));
858 continue;
859 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000860
Owen Anderson35bf4d62010-11-27 08:15:55 +0000861 // For non-PHIs, determine the addressing mode being computed.
862 SmallVector<Instruction*, 16> NewAddrModeInsts;
863 ExtAddrMode NewAddrMode =
Nick Lewycky48105282011-09-29 23:40:12 +0000864 AddressingModeMatcher::Match(V, AccessTy, MemoryInst,
Owen Anderson35bf4d62010-11-27 08:15:55 +0000865 NewAddrModeInsts, *TLI);
Cameron Zwarich7c8d3512011-03-05 08:12:26 +0000866
867 // This check is broken into two cases with very similar code to avoid using
868 // getNumUses() as much as possible. Some values have a lot of uses, so
869 // calling getNumUses() unconditionally caused a significant compile-time
870 // regression.
871 if (!Consensus) {
872 Consensus = V;
873 AddrMode = NewAddrMode;
874 AddrModeInsts = NewAddrModeInsts;
875 continue;
876 } else if (NewAddrMode == AddrMode) {
877 if (!IsNumUsesConsensusValid) {
878 NumUsesConsensus = Consensus->getNumUses();
879 IsNumUsesConsensusValid = true;
880 }
881
882 // Ensure that the obtained addressing mode is equivalent to that obtained
883 // for all other roots of the PHI traversal. Also, when choosing one
884 // such root as representative, select the one with the most uses in order
885 // to keep the cost modeling heuristics in AddressingModeMatcher
886 // applicable.
Cameron Zwarich4c078f02011-03-01 21:13:53 +0000887 unsigned NumUses = V->getNumUses();
888 if (NumUses > NumUsesConsensus) {
Owen Anderson35bf4d62010-11-27 08:15:55 +0000889 Consensus = V;
Cameron Zwarich4c078f02011-03-01 21:13:53 +0000890 NumUsesConsensus = NumUses;
Owen Anderson35bf4d62010-11-27 08:15:55 +0000891 AddrModeInsts = NewAddrModeInsts;
892 }
893 continue;
894 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000895
Owen Anderson35bf4d62010-11-27 08:15:55 +0000896 Consensus = 0;
897 break;
Owen Andersond2f41742010-11-19 22:15:03 +0000898 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000899
Owen Anderson35bf4d62010-11-27 08:15:55 +0000900 // If the addressing mode couldn't be determined, or if multiple different
901 // ones were determined, bail out now.
902 if (!Consensus) return false;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000903
Chris Lattnerdd77df32007-04-13 20:30:56 +0000904 // Check to see if any of the instructions supersumed by this addr mode are
905 // non-local to I's BB.
906 bool AnyNonLocal = false;
907 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
Chris Lattner896617b2008-11-26 03:20:37 +0000908 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
Chris Lattnerdd77df32007-04-13 20:30:56 +0000909 AnyNonLocal = true;
910 break;
911 }
912 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000913
Chris Lattnerdd77df32007-04-13 20:30:56 +0000914 // If all the instructions matched are already in this BB, don't do anything.
915 if (!AnyNonLocal) {
David Greene68d67fd2010-01-05 01:27:11 +0000916 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000917 return false;
918 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000919
Chris Lattnerdd77df32007-04-13 20:30:56 +0000920 // Insert this computation right after this user. Since our caller is
921 // scanning from the top of the BB to the bottom, reuse of the expr are
922 // guaranteed to happen later.
Devang Patel2048c372011-09-06 18:49:53 +0000923 IRBuilder<> Builder(MemoryInst);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000924
Chris Lattnerdd77df32007-04-13 20:30:56 +0000925 // Now that we determined the addressing expression we want to use and know
926 // that we have to sink it into this block. Check to see if we have already
927 // done this for some other load/store instr in this block. If so, reuse the
928 // computation.
929 Value *&SunkAddr = SunkAddrs[Addr];
930 if (SunkAddr) {
David Greene68d67fd2010-01-05 01:27:11 +0000931 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
Dan Gohman6c1980b2009-07-25 01:13:51 +0000932 << *MemoryInst);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000933 if (SunkAddr->getType() != Addr->getType())
Benjamin Kramera9390a42011-09-27 20:39:19 +0000934 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
Chris Lattnerdd77df32007-04-13 20:30:56 +0000935 } else {
David Greene68d67fd2010-01-05 01:27:11 +0000936 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Dan Gohman6c1980b2009-07-25 01:13:51 +0000937 << *MemoryInst);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000938 Type *IntPtrTy =
Chandler Carruthece6c6b2012-11-01 08:07:29 +0000939 TLI->getDataLayout()->getIntPtrType(AccessTy->getContext());
Eric Christopher692bf6b2008-09-24 05:32:41 +0000940
Chris Lattnerdd77df32007-04-13 20:30:56 +0000941 Value *Result = 0;
Dan Gohmand8d0b6a2010-01-19 22:45:06 +0000942
943 // Start with the base register. Do this first so that subsequent address
944 // matching finds it last, which will prevent it from trying to match it
945 // as the scaled value in case it happens to be a mul. That would be
946 // problematic if we've sunk a different mul for the scale, because then
947 // we'd end up sinking both muls.
948 if (AddrMode.BaseReg) {
949 Value *V = AddrMode.BaseReg;
Duncan Sands1df98592010-02-16 11:11:14 +0000950 if (V->getType()->isPointerTy())
Devang Patel2048c372011-09-06 18:49:53 +0000951 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Dan Gohmand8d0b6a2010-01-19 22:45:06 +0000952 if (V->getType() != IntPtrTy)
Devang Patel2048c372011-09-06 18:49:53 +0000953 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
Dan Gohmand8d0b6a2010-01-19 22:45:06 +0000954 Result = V;
955 }
956
957 // Add the scale value.
Chris Lattnerdd77df32007-04-13 20:30:56 +0000958 if (AddrMode.Scale) {
959 Value *V = AddrMode.ScaledReg;
960 if (V->getType() == IntPtrTy) {
961 // done.
Duncan Sands1df98592010-02-16 11:11:14 +0000962 } else if (V->getType()->isPointerTy()) {
Devang Patel2048c372011-09-06 18:49:53 +0000963 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000964 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
965 cast<IntegerType>(V->getType())->getBitWidth()) {
Devang Patel2048c372011-09-06 18:49:53 +0000966 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000967 } else {
Devang Patel2048c372011-09-06 18:49:53 +0000968 V = Builder.CreateSExt(V, IntPtrTy, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000969 }
970 if (AddrMode.Scale != 1)
Devang Patel2048c372011-09-06 18:49:53 +0000971 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
972 "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000973 if (Result)
Devang Patel2048c372011-09-06 18:49:53 +0000974 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000975 else
976 Result = V;
977 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000978
Chris Lattnerdd77df32007-04-13 20:30:56 +0000979 // Add in the BaseGV if present.
980 if (AddrMode.BaseGV) {
Devang Patel2048c372011-09-06 18:49:53 +0000981 Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000982 if (Result)
Devang Patel2048c372011-09-06 18:49:53 +0000983 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000984 else
985 Result = V;
986 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000987
Chris Lattnerdd77df32007-04-13 20:30:56 +0000988 // Add in the Base Offset if present.
989 if (AddrMode.BaseOffs) {
Owen Andersoneed707b2009-07-24 23:12:02 +0000990 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000991 if (Result)
Devang Patel2048c372011-09-06 18:49:53 +0000992 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000993 else
994 Result = V;
995 }
996
997 if (Result == 0)
Owen Andersona7235ea2009-07-31 20:28:14 +0000998 SunkAddr = Constant::getNullValue(Addr->getType());
Chris Lattnerdd77df32007-04-13 20:30:56 +0000999 else
Devang Patel2048c372011-09-06 18:49:53 +00001000 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +00001001 }
Eric Christopher692bf6b2008-09-24 05:32:41 +00001002
Owen Andersond2f41742010-11-19 22:15:03 +00001003 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
Eric Christopher692bf6b2008-09-24 05:32:41 +00001004
Chris Lattner0403b472011-04-09 07:05:44 +00001005 // If we have no uses, recursively delete the value and all dead instructions
1006 // using it.
Owen Andersond2f41742010-11-19 22:15:03 +00001007 if (Repl->use_empty()) {
Chris Lattner0403b472011-04-09 07:05:44 +00001008 // This can cause recursive deletion, which can invalidate our iterator.
1009 // Use a WeakVH to hold onto it in case this happens.
1010 WeakVH IterHandle(CurInstIterator);
1011 BasicBlock *BB = CurInstIterator->getParent();
Nadav Rotema94d6e82012-07-24 10:51:42 +00001012
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +00001013 RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
Chris Lattner0403b472011-04-09 07:05:44 +00001014
1015 if (IterHandle != CurInstIterator) {
1016 // If the iterator instruction was recursively deleted, start over at the
1017 // start of the block.
1018 CurInstIterator = BB->begin();
1019 SunkAddrs.clear();
1020 } else {
1021 // This address is now available for reassignment, so erase the table
1022 // entry; we don't want to match some completely different instruction.
1023 SunkAddrs[Addr] = 0;
Nadav Rotema94d6e82012-07-24 10:51:42 +00001024 }
Dale Johannesen536d31b2010-03-31 20:37:15 +00001025 }
Cameron Zwarich31ff1332011-01-05 17:27:27 +00001026 ++NumMemoryInsts;
Chris Lattnerdd77df32007-04-13 20:30:56 +00001027 return true;
1028}
1029
Evan Cheng9bf12b52008-02-26 02:42:37 +00001030/// OptimizeInlineAsmInst - If there are any memory operands, use
Chris Lattner88a5c832008-11-25 07:09:13 +00001031/// OptimizeMemoryInst to sink their address computing into the block when
Evan Cheng9bf12b52008-02-26 02:42:37 +00001032/// possible / profitable.
Chris Lattner75796092011-01-15 07:14:54 +00001033bool CodeGenPrepare::OptimizeInlineAsmInst(CallInst *CS) {
Evan Cheng9bf12b52008-02-26 02:42:37 +00001034 bool MadeChange = false;
Evan Cheng9bf12b52008-02-26 02:42:37 +00001035
Nadav Rotema94d6e82012-07-24 10:51:42 +00001036 TargetLowering::AsmOperandInfoVector
Chris Lattner75796092011-01-15 07:14:54 +00001037 TargetConstraints = TLI->ParseConstraints(CS);
Dale Johannesen677c6ec2010-09-16 18:30:55 +00001038 unsigned ArgNo = 0;
John Thompsoneac6e1d2010-09-13 18:15:37 +00001039 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
1040 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Nadav Rotema94d6e82012-07-24 10:51:42 +00001041
Evan Cheng9bf12b52008-02-26 02:42:37 +00001042 // Compute the constraint code and ConstraintType to use.
Dale Johannesen1784d162010-06-25 21:55:36 +00001043 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Evan Cheng9bf12b52008-02-26 02:42:37 +00001044
Eli Friedman9ec80952008-02-26 18:37:49 +00001045 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
1046 OpInfo.isIndirect) {
Chris Lattner75796092011-01-15 07:14:54 +00001047 Value *OpVal = CS->getArgOperand(ArgNo++);
Chris Lattner1a8943a2011-01-15 07:29:01 +00001048 MadeChange |= OptimizeMemoryInst(CS, OpVal, OpVal->getType());
Dale Johannesen677c6ec2010-09-16 18:30:55 +00001049 } else if (OpInfo.Type == InlineAsm::isInput)
1050 ArgNo++;
Evan Cheng9bf12b52008-02-26 02:42:37 +00001051 }
1052
1053 return MadeChange;
1054}
1055
Dan Gohmanb00f2362009-10-16 20:59:35 +00001056/// MoveExtToFormExtLoad - Move a zext or sext fed by a load into the same
1057/// basic block as the load, unless conditions are unfavorable. This allows
1058/// SelectionDAG to fold the extend into the load.
1059///
1060bool CodeGenPrepare::MoveExtToFormExtLoad(Instruction *I) {
1061 // Look for a load being extended.
1062 LoadInst *LI = dyn_cast<LoadInst>(I->getOperand(0));
1063 if (!LI) return false;
1064
1065 // If they're already in the same block, there's nothing to do.
1066 if (LI->getParent() == I->getParent())
1067 return false;
1068
1069 // If the load has other users and the truncate is not free, this probably
1070 // isn't worthwhile.
1071 if (!LI->hasOneUse() &&
Bob Wilsonec57a1a2010-09-22 18:44:56 +00001072 TLI && (TLI->isTypeLegal(TLI->getValueType(LI->getType())) ||
1073 !TLI->isTypeLegal(TLI->getValueType(I->getType()))) &&
Bob Wilson71dc4d92010-09-21 21:54:27 +00001074 !TLI->isTruncateFree(I->getType(), LI->getType()))
Dan Gohmanb00f2362009-10-16 20:59:35 +00001075 return false;
1076
1077 // Check whether the target supports casts folded into loads.
1078 unsigned LType;
1079 if (isa<ZExtInst>(I))
1080 LType = ISD::ZEXTLOAD;
1081 else {
1082 assert(isa<SExtInst>(I) && "Unexpected ext type!");
1083 LType = ISD::SEXTLOAD;
1084 }
1085 if (TLI && !TLI->isLoadExtLegal(LType, TLI->getValueType(LI->getType())))
1086 return false;
1087
1088 // Move the extend into the same block as the load, so that SelectionDAG
1089 // can fold it.
1090 I->removeFromParent();
1091 I->insertAfter(LI);
Cameron Zwarich31ff1332011-01-05 17:27:27 +00001092 ++NumExtsMoved;
Dan Gohmanb00f2362009-10-16 20:59:35 +00001093 return true;
1094}
1095
Evan Chengbdcb7262007-12-05 23:58:20 +00001096bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
1097 BasicBlock *DefBB = I->getParent();
1098
Bob Wilson9120f5c2010-09-21 21:44:14 +00001099 // If the result of a {s|z}ext and its source are both live out, rewrite all
Evan Chengbdcb7262007-12-05 23:58:20 +00001100 // other uses of the source with result of extension.
1101 Value *Src = I->getOperand(0);
1102 if (Src->hasOneUse())
1103 return false;
1104
Evan Cheng696e5c02007-12-13 07:50:36 +00001105 // Only do this xform if truncating is free.
Gabor Greif53bdbd72008-02-26 19:13:21 +00001106 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
Evan Chengf9785f92007-12-13 03:32:53 +00001107 return false;
1108
Evan Cheng772de512007-12-12 00:51:06 +00001109 // Only safe to perform the optimization if the source is also defined in
Evan Cheng765dff22007-12-12 02:53:41 +00001110 // this block.
1111 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
Evan Cheng772de512007-12-12 00:51:06 +00001112 return false;
1113
Evan Chengbdcb7262007-12-05 23:58:20 +00001114 bool DefIsLiveOut = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001115 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
Evan Chengbdcb7262007-12-05 23:58:20 +00001116 UI != E; ++UI) {
1117 Instruction *User = cast<Instruction>(*UI);
1118
1119 // Figure out which BB this ext is used in.
1120 BasicBlock *UserBB = User->getParent();
1121 if (UserBB == DefBB) continue;
1122 DefIsLiveOut = true;
1123 break;
1124 }
1125 if (!DefIsLiveOut)
1126 return false;
1127
Evan Cheng765dff22007-12-12 02:53:41 +00001128 // Make sure non of the uses are PHI nodes.
Eric Christopher692bf6b2008-09-24 05:32:41 +00001129 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
Evan Cheng765dff22007-12-12 02:53:41 +00001130 UI != E; ++UI) {
1131 Instruction *User = cast<Instruction>(*UI);
Evan Chengf9785f92007-12-13 03:32:53 +00001132 BasicBlock *UserBB = User->getParent();
1133 if (UserBB == DefBB) continue;
1134 // Be conservative. We don't want this xform to end up introducing
1135 // reloads just before load / store instructions.
1136 if (isa<PHINode>(User) || isa<LoadInst>(User) || isa<StoreInst>(User))
Evan Cheng765dff22007-12-12 02:53:41 +00001137 return false;
1138 }
1139
Evan Chengbdcb7262007-12-05 23:58:20 +00001140 // InsertedTruncs - Only insert one trunc in each block once.
1141 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
1142
1143 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001144 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
Evan Chengbdcb7262007-12-05 23:58:20 +00001145 UI != E; ++UI) {
1146 Use &TheUse = UI.getUse();
1147 Instruction *User = cast<Instruction>(*UI);
1148
1149 // Figure out which BB this ext is used in.
1150 BasicBlock *UserBB = User->getParent();
1151 if (UserBB == DefBB) continue;
1152
1153 // Both src and def are live in this block. Rewrite the use.
1154 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
1155
1156 if (!InsertedTrunc) {
Bill Wendling5b6f42f2011-08-16 20:45:24 +00001157 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Evan Chengbdcb7262007-12-05 23:58:20 +00001158 InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
1159 }
1160
1161 // Replace a use of the {s|z}ext source with a use of the result.
1162 TheUse = InsertedTrunc;
Cameron Zwarich31ff1332011-01-05 17:27:27 +00001163 ++NumExtUses;
Evan Chengbdcb7262007-12-05 23:58:20 +00001164 MadeChange = true;
1165 }
1166
1167 return MadeChange;
1168}
1169
Benjamin Kramer59957502012-05-05 12:49:22 +00001170/// isFormingBranchFromSelectProfitable - Returns true if a SelectInst should be
1171/// turned into an explicit branch.
1172static bool isFormingBranchFromSelectProfitable(SelectInst *SI) {
1173 // FIXME: This should use the same heuristics as IfConversion to determine
1174 // whether a select is better represented as a branch. This requires that
1175 // branch probability metadata is preserved for the select, which is not the
1176 // case currently.
1177
1178 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
1179
1180 // If the branch is predicted right, an out of order CPU can avoid blocking on
1181 // the compare. Emit cmovs on compares with a memory operand as branches to
1182 // avoid stalls on the load from memory. If the compare has more than one use
1183 // there's probably another cmov or setcc around so it's not worth emitting a
1184 // branch.
1185 if (!Cmp)
1186 return false;
1187
1188 Value *CmpOp0 = Cmp->getOperand(0);
1189 Value *CmpOp1 = Cmp->getOperand(1);
1190
1191 // We check that the memory operand has one use to avoid uses of the loaded
1192 // value directly after the compare, making branches unprofitable.
1193 return Cmp->hasOneUse() &&
1194 ((isa<LoadInst>(CmpOp0) && CmpOp0->hasOneUse()) ||
1195 (isa<LoadInst>(CmpOp1) && CmpOp1->hasOneUse()));
1196}
1197
1198
Nadav Rotem9f40cb32012-09-02 12:10:19 +00001199/// If we have a SelectInst that will likely profit from branch prediction,
1200/// turn it into a branch.
Benjamin Kramer59957502012-05-05 12:49:22 +00001201bool CodeGenPrepare::OptimizeSelectInst(SelectInst *SI) {
Nadav Rotem9f40cb32012-09-02 12:10:19 +00001202 bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
1203
1204 // Can we convert the 'select' to CF ?
1205 if (DisableSelectToBranch || OptSize || !TLI || VectorCond)
Benjamin Kramer59957502012-05-05 12:49:22 +00001206 return false;
1207
Nadav Rotem9f40cb32012-09-02 12:10:19 +00001208 TargetLowering::SelectSupportKind SelectKind;
1209 if (VectorCond)
1210 SelectKind = TargetLowering::VectorMaskSelect;
1211 else if (SI->getType()->isVectorTy())
1212 SelectKind = TargetLowering::ScalarCondVectorVal;
1213 else
1214 SelectKind = TargetLowering::ScalarValSelect;
1215
1216 // Do we have efficient codegen support for this kind of 'selects' ?
1217 if (TLI->isSelectSupported(SelectKind)) {
1218 // We have efficient codegen support for the select instruction.
1219 // Check if it is profitable to keep this 'select'.
1220 if (!TLI->isPredictableSelectExpensive() ||
1221 !isFormingBranchFromSelectProfitable(SI))
1222 return false;
1223 }
Benjamin Kramer59957502012-05-05 12:49:22 +00001224
1225 ModifiedDT = true;
1226
1227 // First, we split the block containing the select into 2 blocks.
1228 BasicBlock *StartBlock = SI->getParent();
1229 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(SI));
1230 BasicBlock *NextBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
1231
1232 // Create a new block serving as the landing pad for the branch.
1233 BasicBlock *SmallBlock = BasicBlock::Create(SI->getContext(), "select.mid",
1234 NextBlock->getParent(), NextBlock);
1235
1236 // Move the unconditional branch from the block with the select in it into our
1237 // landing pad block.
1238 StartBlock->getTerminator()->eraseFromParent();
1239 BranchInst::Create(NextBlock, SmallBlock);
1240
1241 // Insert the real conditional branch based on the original condition.
1242 BranchInst::Create(NextBlock, SmallBlock, SI->getCondition(), SI);
1243
1244 // The select itself is replaced with a PHI Node.
1245 PHINode *PN = PHINode::Create(SI->getType(), 2, "", NextBlock->begin());
1246 PN->takeName(SI);
1247 PN->addIncoming(SI->getTrueValue(), StartBlock);
1248 PN->addIncoming(SI->getFalseValue(), SmallBlock);
1249 SI->replaceAllUsesWith(PN);
1250 SI->eraseFromParent();
1251
1252 // Instruct OptimizeBlock to skip to the next block.
1253 CurInstIterator = StartBlock->end();
1254 ++NumSelectsExpanded;
1255 return true;
1256}
1257
Cameron Zwarichc0611012011-01-06 02:37:26 +00001258bool CodeGenPrepare::OptimizeInst(Instruction *I) {
Cameron Zwarichc0611012011-01-06 02:37:26 +00001259 if (PHINode *P = dyn_cast<PHINode>(I)) {
1260 // It is possible for very late stage optimizations (such as SimplifyCFG)
1261 // to introduce PHI nodes too late to be cleaned up. If we detect such a
1262 // trivial PHI, go ahead and zap it here.
1263 if (Value *V = SimplifyInstruction(P)) {
1264 P->replaceAllUsesWith(V);
1265 P->eraseFromParent();
1266 ++NumPHIsElim;
Chris Lattner1a8943a2011-01-15 07:29:01 +00001267 return true;
Cameron Zwarichc0611012011-01-06 02:37:26 +00001268 }
Chris Lattner1a8943a2011-01-15 07:29:01 +00001269 return false;
1270 }
Nadav Rotema94d6e82012-07-24 10:51:42 +00001271
Chris Lattner1a8943a2011-01-15 07:29:01 +00001272 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Cameron Zwarichc0611012011-01-06 02:37:26 +00001273 // If the source of the cast is a constant, then this should have
1274 // already been constant folded. The only reason NOT to constant fold
1275 // it is if something (e.g. LSR) was careful to place the constant
1276 // evaluation in a block other than then one that uses it (e.g. to hoist
1277 // the address of globals out of a loop). If this is the case, we don't
1278 // want to forward-subst the cast.
1279 if (isa<Constant>(CI->getOperand(0)))
1280 return false;
1281
Chris Lattner1a8943a2011-01-15 07:29:01 +00001282 if (TLI && OptimizeNoopCopyExpression(CI, *TLI))
1283 return true;
Cameron Zwarichc0611012011-01-06 02:37:26 +00001284
Chris Lattner1a8943a2011-01-15 07:29:01 +00001285 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
1286 bool MadeChange = MoveExtToFormExtLoad(I);
1287 return MadeChange | OptimizeExtUses(I);
Cameron Zwarichc0611012011-01-06 02:37:26 +00001288 }
Chris Lattner1a8943a2011-01-15 07:29:01 +00001289 return false;
1290 }
Nadav Rotema94d6e82012-07-24 10:51:42 +00001291
Chris Lattner1a8943a2011-01-15 07:29:01 +00001292 if (CmpInst *CI = dyn_cast<CmpInst>(I))
1293 return OptimizeCmpExpression(CI);
Nadav Rotema94d6e82012-07-24 10:51:42 +00001294
Chris Lattner1a8943a2011-01-15 07:29:01 +00001295 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Cameron Zwarichc0611012011-01-06 02:37:26 +00001296 if (TLI)
Hans Wennborg04d7d132012-10-30 11:23:25 +00001297 return OptimizeMemoryInst(I, I->getOperand(0), LI->getType());
1298 return false;
Chris Lattner1a8943a2011-01-15 07:29:01 +00001299 }
Nadav Rotema94d6e82012-07-24 10:51:42 +00001300
Chris Lattner1a8943a2011-01-15 07:29:01 +00001301 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Cameron Zwarichc0611012011-01-06 02:37:26 +00001302 if (TLI)
Chris Lattner1a8943a2011-01-15 07:29:01 +00001303 return OptimizeMemoryInst(I, SI->getOperand(1),
1304 SI->getOperand(0)->getType());
1305 return false;
1306 }
Nadav Rotema94d6e82012-07-24 10:51:42 +00001307
Chris Lattner1a8943a2011-01-15 07:29:01 +00001308 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Cameron Zwarich865ae1a2011-01-06 02:44:52 +00001309 if (GEPI->hasAllZeroIndices()) {
1310 /// The GEP operand must be a pointer, so must its result -> BitCast
1311 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
1312 GEPI->getName(), GEPI);
1313 GEPI->replaceAllUsesWith(NC);
1314 GEPI->eraseFromParent();
1315 ++NumGEPsElim;
Cameron Zwarich865ae1a2011-01-06 02:44:52 +00001316 OptimizeInst(NC);
Chris Lattner1a8943a2011-01-15 07:29:01 +00001317 return true;
Cameron Zwarich865ae1a2011-01-06 02:44:52 +00001318 }
Chris Lattner1a8943a2011-01-15 07:29:01 +00001319 return false;
Cameron Zwarichc0611012011-01-06 02:37:26 +00001320 }
Nadav Rotema94d6e82012-07-24 10:51:42 +00001321
Chris Lattner1a8943a2011-01-15 07:29:01 +00001322 if (CallInst *CI = dyn_cast<CallInst>(I))
1323 return OptimizeCallInst(CI);
Cameron Zwarichc0611012011-01-06 02:37:26 +00001324
Benjamin Kramer59957502012-05-05 12:49:22 +00001325 if (SelectInst *SI = dyn_cast<SelectInst>(I))
1326 return OptimizeSelectInst(SI);
1327
Chris Lattner1a8943a2011-01-15 07:29:01 +00001328 return false;
Cameron Zwarichc0611012011-01-06 02:37:26 +00001329}
1330
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001331// In this pass we look for GEP and cast instructions that are used
1332// across basic blocks and rewrite them to improve basic-block-at-a-time
1333// selection.
1334bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
Cameron Zwarich8c3527e2011-01-06 00:42:50 +00001335 SunkAddrs.clear();
Cameron Zwarich56e37932011-03-02 03:31:46 +00001336 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001337
Chris Lattner75796092011-01-15 07:14:54 +00001338 CurInstIterator = BB.begin();
Hans Wennborg93ba1332012-09-19 07:48:16 +00001339 while (CurInstIterator != BB.end())
Chris Lattner94e8e0c2011-01-15 07:25:29 +00001340 MadeChange |= OptimizeInst(CurInstIterator++);
Eric Christopher692bf6b2008-09-24 05:32:41 +00001341
Benjamin Kramer4ccb49a2012-11-23 19:17:06 +00001342 MadeChange |= DupRetToEnableTailCallOpts(&BB);
1343
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001344 return MadeChange;
1345}
Devang Patelf56ea612011-08-18 00:50:51 +00001346
1347// llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotema94d6e82012-07-24 10:51:42 +00001348// handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patelf56ea612011-08-18 00:50:51 +00001349// find a node corresponding to the value.
1350bool CodeGenPrepare::PlaceDbgValues(Function &F) {
1351 bool MadeChange = false;
1352 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
1353 Instruction *PrevNonDbgInst = NULL;
1354 for (BasicBlock::iterator BI = I->begin(), BE = I->end(); BI != BE;) {
1355 Instruction *Insn = BI; ++BI;
1356 DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
1357 if (!DVI) {
1358 PrevNonDbgInst = Insn;
1359 continue;
1360 }
1361
1362 Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
1363 if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
1364 DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
1365 DVI->removeFromParent();
1366 if (isa<PHINode>(VI))
1367 DVI->insertBefore(VI->getParent()->getFirstInsertionPt());
1368 else
1369 DVI->insertAfter(VI);
1370 MadeChange = true;
1371 ++NumDbgValueMoved;
1372 }
1373 }
1374 }
1375 return MadeChange;
1376}