blob: f661747d0d100f49d511e39ef9039eeefb947570 [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"
Evan Cheng9bf12b52008-02-26 02:42:37 +000021#include "llvm/InlineAsm.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000022#include "llvm/Instructions.h"
Dale Johannesen6aae1d62009-03-26 01:15:07 +000023#include "llvm/IntrinsicInst.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000024#include "llvm/Pass.h"
Cameron Zwarich80f6a502011-01-08 17:01:52 +000025#include "llvm/Analysis/Dominators.h"
Owen Andersond5f86842010-12-23 20:57:35 +000026#include "llvm/Analysis/InstructionSimplify.h"
Andreas Neustifterad809812009-09-16 09:26:52 +000027#include "llvm/Analysis/ProfileInfo.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000028#include "llvm/Target/TargetData.h"
29#include "llvm/Target/TargetLowering.h"
Evan Chenga1fd5b32009-02-20 18:24:38 +000030#include "llvm/Transforms/Utils/AddrModeMatcher.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000031#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattnerdd77df32007-04-13 20:30:56 +000032#include "llvm/Transforms/Utils/Local.h"
Eric Christopher040056f2010-03-11 02:41:03 +000033#include "llvm/Transforms/Utils/BuildLibCalls.h"
Chris Lattnerdd77df32007-04-13 20:30:56 +000034#include "llvm/ADT/DenseMap.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000035#include "llvm/ADT/SmallSet.h"
Jakob Stoklund Olesen7eb589d2010-09-30 20:51:52 +000036#include "llvm/ADT/Statistic.h"
Dan Gohman03ce0422009-02-13 17:45:12 +000037#include "llvm/Assembly/Writer.h"
Evan Cheng9bf12b52008-02-26 02:42:37 +000038#include "llvm/Support/CallSite.h"
Evan Chenge1bcb442010-08-17 01:34:49 +000039#include "llvm/Support/CommandLine.h"
Evan Chengbdcb7262007-12-05 23:58:20 +000040#include "llvm/Support/Debug.h"
Chris Lattnerdd77df32007-04-13 20:30:56 +000041#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner088a1e82008-11-25 04:42:10 +000042#include "llvm/Support/PatternMatch.h"
Dan Gohman6c1980b2009-07-25 01:13:51 +000043#include "llvm/Support/raw_ostream.h"
Eric Christopher040056f2010-03-11 02:41:03 +000044#include "llvm/Support/IRBuilder.h"
Chris Lattner94e8e0c2011-01-15 07:25:29 +000045#include "llvm/Support/ValueHandle.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000046using namespace llvm;
Chris Lattner088a1e82008-11-25 04:42:10 +000047using namespace llvm::PatternMatch;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000048
Cameron Zwarich31ff1332011-01-05 17:27:27 +000049STATISTIC(NumBlocksElim, "Number of blocks eliminated");
Evan Cheng485fafc2011-03-21 01:19:09 +000050STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated");
51STATISTIC(NumGEPsElim, "Number of GEPs converted to casts");
Cameron Zwarich31ff1332011-01-05 17:27:27 +000052STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "
53 "sunken Cmps");
54STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
55 "of sunken Casts");
56STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "
57 "computations were sunk");
Evan Cheng485fafc2011-03-21 01:19:09 +000058STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads");
59STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized");
60STATISTIC(NumRetsDup, "Number of return instructions duplicated");
Devang Patelf56ea612011-08-18 00:50:51 +000061STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved");
Jakob Stoklund Olesen7eb589d2010-09-30 20:51:52 +000062
Cameron Zwarich899eaa32011-03-11 21:52:04 +000063static cl::opt<bool> DisableBranchOpts(
64 "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
65 cl::desc("Disable branch optimizations in CodeGenPrepare"));
66
Eric Christopher692bf6b2008-09-24 05:32:41 +000067namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +000068 class CodeGenPrepare : public FunctionPass {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000069 /// TLI - Keep a pointer of a TargetLowering to consult for determining
70 /// transformation profitability.
71 const TargetLowering *TLI;
Cameron Zwarich80f6a502011-01-08 17:01:52 +000072 DominatorTree *DT;
Evan Cheng04149f72009-12-17 09:39:49 +000073 ProfileInfo *PFI;
Chris Lattner75796092011-01-15 07:14:54 +000074
75 /// CurInstIterator - As we scan instructions optimizing them, this is the
76 /// next instruction to optimize. Xforms that can invalidate this should
77 /// update it.
78 BasicBlock::iterator CurInstIterator;
Evan Chengab631522008-12-19 18:03:11 +000079
Evan Cheng485fafc2011-03-21 01:19:09 +000080 /// Keeps track of non-local addresses that have been sunk into a block.
81 /// This allows us to avoid inserting duplicate code for blocks with
82 /// multiple load/stores of the same address.
Cameron Zwarich8c3527e2011-01-06 00:42:50 +000083 DenseMap<Value*, Value*> SunkAddrs;
84
Devang Patel52e37df2011-03-24 15:35:25 +000085 /// ModifiedDT - If CFG is modified in anyway, dominator tree may need to
Evan Cheng485fafc2011-03-21 01:19:09 +000086 /// be updated.
Devang Patel52e37df2011-03-24 15:35:25 +000087 bool ModifiedDT;
Evan Cheng485fafc2011-03-21 01:19:09 +000088
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000089 public:
Nick Lewyckyecd94c82007-05-06 13:37:16 +000090 static char ID; // Pass identification, replacement for typeid
Dan Gohmanc2bbfc12007-08-01 15:32:29 +000091 explicit CodeGenPrepare(const TargetLowering *tli = 0)
Owen Anderson081c34b2010-10-19 17:21:58 +000092 : FunctionPass(ID), TLI(tli) {
93 initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
94 }
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000095 bool runOnFunction(Function &F);
Eric Christopher692bf6b2008-09-24 05:32:41 +000096
Andreas Neustifterad809812009-09-16 09:26:52 +000097 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Cameron Zwarich80f6a502011-01-08 17:01:52 +000098 AU.addPreserved<DominatorTree>();
Andreas Neustifterad809812009-09-16 09:26:52 +000099 AU.addPreserved<ProfileInfo>();
100 }
101
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000102 private:
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000103 bool EliminateMostlyEmptyBlocks(Function &F);
104 bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
105 void EliminateMostlyEmptyBlock(BasicBlock *BB);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000106 bool OptimizeBlock(BasicBlock &BB);
Cameron Zwarichc0611012011-01-06 02:37:26 +0000107 bool OptimizeInst(Instruction *I);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000108 bool OptimizeMemoryInst(Instruction *I, Value *Addr, Type *AccessTy);
Chris Lattner75796092011-01-15 07:14:54 +0000109 bool OptimizeInlineAsmInst(CallInst *CS);
Eric Christopher040056f2010-03-11 02:41:03 +0000110 bool OptimizeCallInst(CallInst *CI);
Dan Gohmanb00f2362009-10-16 20:59:35 +0000111 bool MoveExtToFormExtLoad(Instruction *I);
Evan Chengbdcb7262007-12-05 23:58:20 +0000112 bool OptimizeExtUses(Instruction *I);
Evan Cheng485fafc2011-03-21 01:19:09 +0000113 bool DupRetToEnableTailCallOpts(ReturnInst *RI);
Devang Patelf56ea612011-08-18 00:50:51 +0000114 bool PlaceDbgValues(Function &F);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000115 };
116}
Devang Patel794fd752007-05-01 21:15:47 +0000117
Devang Patel19974732007-05-03 01:11:54 +0000118char CodeGenPrepare::ID = 0;
Owen Andersond13db2c2010-07-21 22:09:45 +0000119INITIALIZE_PASS(CodeGenPrepare, "codegenprepare",
Owen Andersonce665bd2010-10-07 22:25:06 +0000120 "Optimize for code generation", false, false)
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000121
122FunctionPass *llvm::createCodeGenPreparePass(const TargetLowering *TLI) {
123 return new CodeGenPrepare(TLI);
124}
125
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000126bool CodeGenPrepare::runOnFunction(Function &F) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000127 bool EverMadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000128
Devang Patel52e37df2011-03-24 15:35:25 +0000129 ModifiedDT = false;
Cameron Zwarich80f6a502011-01-08 17:01:52 +0000130 DT = getAnalysisIfAvailable<DominatorTree>();
Evan Cheng04149f72009-12-17 09:39:49 +0000131 PFI = getAnalysisIfAvailable<ProfileInfo>();
Evan Cheng485fafc2011-03-21 01:19:09 +0000132
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000133 // First pass, eliminate blocks that contain only PHI nodes and an
134 // unconditional branch.
135 EverMadeChange |= EliminateMostlyEmptyBlocks(F);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000136
Devang Patelf56ea612011-08-18 00:50:51 +0000137 // llvm.dbg.value is far away from the value then iSel may not be able
138 // handle it properly. iSel will drop llvm.dbg.value if it can not
139 // find a node corresponding to the value.
140 EverMadeChange |= PlaceDbgValues(F);
141
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000142 bool MadeChange = true;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000143 while (MadeChange) {
144 MadeChange = false;
Evan Cheng485fafc2011-03-21 01:19:09 +0000145 for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
146 BasicBlock *BB = I++;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000147 MadeChange |= OptimizeBlock(*BB);
Evan Cheng485fafc2011-03-21 01:19:09 +0000148 }
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000149 EverMadeChange |= MadeChange;
150 }
Cameron Zwarich8c3527e2011-01-06 00:42:50 +0000151
152 SunkAddrs.clear();
153
Cameron Zwarich899eaa32011-03-11 21:52:04 +0000154 if (!DisableBranchOpts) {
155 MadeChange = false;
156 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
Frits van Bommel5649ba72011-05-22 16:24:18 +0000157 MadeChange |= ConstantFoldTerminator(BB, true);
Cameron Zwarich899eaa32011-03-11 21:52:04 +0000158
Evan Cheng485fafc2011-03-21 01:19:09 +0000159 if (MadeChange)
Devang Patel52e37df2011-03-24 15:35:25 +0000160 ModifiedDT = true;
Cameron Zwarich899eaa32011-03-11 21:52:04 +0000161 EverMadeChange |= MadeChange;
162 }
163
Devang Patel52e37df2011-03-24 15:35:25 +0000164 if (ModifiedDT && DT)
Evan Cheng485fafc2011-03-21 01:19:09 +0000165 DT->DT->recalculate(F);
166
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000167 return EverMadeChange;
168}
169
Dale Johannesen2d697242009-03-27 01:13:37 +0000170/// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes,
171/// debug info directives, and an unconditional branch. Passes before isel
172/// (e.g. LSR/loopsimplify) often split edges in ways that are non-optimal for
173/// isel. Start by eliminating these blocks so we can split them the way we
174/// want them.
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000175bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
176 bool MadeChange = false;
177 // Note that this intentionally skips the entry block.
178 for (Function::iterator I = ++F.begin(), E = F.end(); I != E; ) {
179 BasicBlock *BB = I++;
180
181 // If this block doesn't end with an uncond branch, ignore it.
182 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
183 if (!BI || !BI->isUnconditional())
184 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000185
Dale Johannesen2d697242009-03-27 01:13:37 +0000186 // If the instruction before the branch (skipping debug info) isn't a phi
187 // node, then other stuff is happening here.
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000188 BasicBlock::iterator BBI = BI;
189 if (BBI != BB->begin()) {
190 --BBI;
Dale Johannesen2d697242009-03-27 01:13:37 +0000191 while (isa<DbgInfoIntrinsic>(BBI)) {
192 if (BBI == BB->begin())
193 break;
194 --BBI;
195 }
196 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
197 continue;
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000198 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000199
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000200 // Do not break infinite loops.
201 BasicBlock *DestBB = BI->getSuccessor(0);
202 if (DestBB == BB)
203 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000204
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000205 if (!CanMergeBlocks(BB, DestBB))
206 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000207
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000208 EliminateMostlyEmptyBlock(BB);
209 MadeChange = true;
210 }
211 return MadeChange;
212}
213
214/// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
215/// single uncond branch between them, and BB contains no other non-phi
216/// instructions.
217bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
218 const BasicBlock *DestBB) const {
219 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
220 // the successor. If there are more complex condition (e.g. preheaders),
221 // don't mess around with them.
222 BasicBlock::const_iterator BBI = BB->begin();
223 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
Gabor Greif60ad7812010-03-25 23:06:16 +0000224 for (Value::const_use_iterator UI = PN->use_begin(), E = PN->use_end();
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000225 UI != E; ++UI) {
226 const Instruction *User = cast<Instruction>(*UI);
227 if (User->getParent() != DestBB || !isa<PHINode>(User))
228 return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000229 // If User is inside DestBB block and it is a PHINode then check
230 // incoming value. If incoming value is not from BB then this is
Devang Patel75abc1e2007-04-25 00:37:04 +0000231 // a complex condition (e.g. preheaders) we want to avoid here.
232 if (User->getParent() == DestBB) {
233 if (const PHINode *UPN = dyn_cast<PHINode>(User))
234 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
235 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
236 if (Insn && Insn->getParent() == BB &&
237 Insn->getParent() != UPN->getIncomingBlock(I))
238 return false;
239 }
240 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000241 }
242 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000243
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000244 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
245 // and DestBB may have conflicting incoming values for the block. If so, we
246 // can't merge the block.
247 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
248 if (!DestBBPN) return true; // no conflict.
Eric Christopher692bf6b2008-09-24 05:32:41 +0000249
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000250 // Collect the preds of BB.
Chris Lattnerf67f73a2007-11-06 22:07:40 +0000251 SmallPtrSet<const BasicBlock*, 16> BBPreds;
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000252 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
253 // It is faster to get preds from a PHI than with pred_iterator.
254 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
255 BBPreds.insert(BBPN->getIncomingBlock(i));
256 } else {
257 BBPreds.insert(pred_begin(BB), pred_end(BB));
258 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000259
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000260 // Walk the preds of DestBB.
261 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
262 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
263 if (BBPreds.count(Pred)) { // Common predecessor?
264 BBI = DestBB->begin();
265 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
266 const Value *V1 = PN->getIncomingValueForBlock(Pred);
267 const Value *V2 = PN->getIncomingValueForBlock(BB);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000268
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000269 // If V2 is a phi node in BB, look up what the mapped value will be.
270 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
271 if (V2PN->getParent() == BB)
272 V2 = V2PN->getIncomingValueForBlock(Pred);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000273
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000274 // If there is a conflict, bail out.
275 if (V1 != V2) return false;
276 }
277 }
278 }
279
280 return true;
281}
282
283
284/// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
285/// an unconditional branch in it.
286void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
287 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
288 BasicBlock *DestBB = BI->getSuccessor(0);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000289
David Greene68d67fd2010-01-05 01:27:11 +0000290 DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000291
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000292 // If the destination block has a single pred, then this is a trivial edge,
293 // just collapse it.
Chris Lattner9918fb52008-11-27 19:29:14 +0000294 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
Chris Lattnerf5102a02008-11-28 19:54:49 +0000295 if (SinglePred != DestBB) {
296 // Remember if SinglePred was the entry block of the function. If so, we
297 // will need to move BB back to the entry position.
298 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Andreas Neustifterad809812009-09-16 09:26:52 +0000299 MergeBasicBlockIntoOnlyPred(DestBB, this);
Chris Lattner9918fb52008-11-27 19:29:14 +0000300
Chris Lattnerf5102a02008-11-28 19:54:49 +0000301 if (isEntry && BB != &BB->getParent()->getEntryBlock())
302 BB->moveBefore(&BB->getParent()->getEntryBlock());
303
David Greene68d67fd2010-01-05 01:27:11 +0000304 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerf5102a02008-11-28 19:54:49 +0000305 return;
306 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000307 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000308
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000309 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
310 // to handle the new incoming edges it is about to have.
311 PHINode *PN;
312 for (BasicBlock::iterator BBI = DestBB->begin();
313 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
314 // Remove the incoming value for BB, and remember it.
315 Value *InVal = PN->removeIncomingValue(BB, false);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000316
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000317 // Two options: either the InVal is a phi node defined in BB or it is some
318 // value that dominates BB.
319 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
320 if (InValPhi && InValPhi->getParent() == BB) {
321 // Add all of the input values of the input PHI as inputs of this phi.
322 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
323 PN->addIncoming(InValPhi->getIncomingValue(i),
324 InValPhi->getIncomingBlock(i));
325 } else {
326 // Otherwise, add one instance of the dominating value for each edge that
327 // we will be adding.
328 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
329 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
330 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
331 } else {
332 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
333 PN->addIncoming(InVal, *PI);
334 }
335 }
336 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000337
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000338 // The PHIs are now updated, change everything that refers to BB to use
339 // DestBB and remove BB.
340 BB->replaceAllUsesWith(DestBB);
Devang Patel52e37df2011-03-24 15:35:25 +0000341 if (DT && !ModifiedDT) {
Cameron Zwarich80f6a502011-01-08 17:01:52 +0000342 BasicBlock *BBIDom = DT->getNode(BB)->getIDom()->getBlock();
343 BasicBlock *DestBBIDom = DT->getNode(DestBB)->getIDom()->getBlock();
344 BasicBlock *NewIDom = DT->findNearestCommonDominator(BBIDom, DestBBIDom);
345 DT->changeImmediateDominator(DestBB, NewIDom);
346 DT->eraseNode(BB);
347 }
Evan Cheng04149f72009-12-17 09:39:49 +0000348 if (PFI) {
349 PFI->replaceAllUses(BB, DestBB);
350 PFI->removeEdge(ProfileInfo::getEdge(BB, DestBB));
Andreas Neustifterad809812009-09-16 09:26:52 +0000351 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000352 BB->eraseFromParent();
Cameron Zwarich31ff1332011-01-05 17:27:27 +0000353 ++NumBlocksElim;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000354
David Greene68d67fd2010-01-05 01:27:11 +0000355 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000356}
357
Chris Lattnerdd77df32007-04-13 20:30:56 +0000358/// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
Dan Gohmana119de82009-06-14 23:30:43 +0000359/// copy (e.g. it's casting from one pointer type to another, i32->i8 on PPC),
360/// sink it into user blocks to reduce the number of virtual
Dale Johannesence0b2372007-06-12 16:50:17 +0000361/// registers that must be created and coalesced.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000362///
363/// Return true if any changes are made.
Chris Lattner85fa13c2008-11-24 22:44:16 +0000364///
Chris Lattnerdd77df32007-04-13 20:30:56 +0000365static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
Eric Christopher692bf6b2008-09-24 05:32:41 +0000366 // If this is a noop copy,
Owen Andersone50ed302009-08-10 22:56:29 +0000367 EVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
368 EVT DstVT = TLI.getValueType(CI->getType());
Eric Christopher692bf6b2008-09-24 05:32:41 +0000369
Chris Lattnerdd77df32007-04-13 20:30:56 +0000370 // This is an fp<->int conversion?
Duncan Sands83ec4b62008-06-06 12:08:01 +0000371 if (SrcVT.isInteger() != DstVT.isInteger())
Chris Lattnerdd77df32007-04-13 20:30:56 +0000372 return false;
Duncan Sands8e4eb092008-06-08 20:54:56 +0000373
Chris Lattnerdd77df32007-04-13 20:30:56 +0000374 // If this is an extension, it will be a zero or sign extension, which
375 // isn't a noop.
Duncan Sands8e4eb092008-06-08 20:54:56 +0000376 if (SrcVT.bitsLT(DstVT)) return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000377
Chris Lattnerdd77df32007-04-13 20:30:56 +0000378 // If these values will be promoted, find out what they will be promoted
379 // to. This helps us consider truncates on PPC as noop copies when they
380 // are.
Nadav Rotem0ccc12a2011-05-29 08:10:47 +0000381 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
382 TargetLowering::TypePromoteInteger)
Owen Anderson23b9b192009-08-12 00:36:31 +0000383 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
Nadav Rotem0ccc12a2011-05-29 08:10:47 +0000384 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
385 TargetLowering::TypePromoteInteger)
Owen Anderson23b9b192009-08-12 00:36:31 +0000386 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000387
Chris Lattnerdd77df32007-04-13 20:30:56 +0000388 // If, after promotion, these are the same types, this is a noop copy.
389 if (SrcVT != DstVT)
390 return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000391
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000392 BasicBlock *DefBB = CI->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000393
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000394 /// InsertedCasts - Only insert a cast in each block once.
Dale Johannesence0b2372007-06-12 16:50:17 +0000395 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000396
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000397 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000398 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000399 UI != E; ) {
400 Use &TheUse = UI.getUse();
401 Instruction *User = cast<Instruction>(*UI);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000402
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000403 // Figure out which BB this cast is used in. For PHI's this is the
404 // appropriate predecessor block.
405 BasicBlock *UserBB = User->getParent();
406 if (PHINode *PN = dyn_cast<PHINode>(User)) {
Gabor Greifa36791d2009-01-23 19:40:15 +0000407 UserBB = PN->getIncomingBlock(UI);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000408 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000409
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000410 // Preincrement use iterator so we don't invalidate it.
411 ++UI;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000412
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000413 // If this user is in the same block as the cast, don't change the cast.
414 if (UserBB == DefBB) continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000415
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000416 // If we have already inserted a cast into this block, use it.
417 CastInst *&InsertedCast = InsertedCasts[UserBB];
418
419 if (!InsertedCast) {
Bill Wendling5b6f42f2011-08-16 20:45:24 +0000420 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000421 InsertedCast =
422 CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000423 InsertPt);
424 MadeChange = true;
425 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000426
Dale Johannesence0b2372007-06-12 16:50:17 +0000427 // Replace a use of the cast with a use of the new cast.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000428 TheUse = InsertedCast;
Cameron Zwarich31ff1332011-01-05 17:27:27 +0000429 ++NumCastUses;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000430 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000431
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000432 // If we removed all uses, nuke the cast.
Duncan Sandse0038132008-01-20 16:51:46 +0000433 if (CI->use_empty()) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000434 CI->eraseFromParent();
Duncan Sandse0038132008-01-20 16:51:46 +0000435 MadeChange = true;
436 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000437
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000438 return MadeChange;
439}
440
Eric Christopher692bf6b2008-09-24 05:32:41 +0000441/// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
Dale Johannesence0b2372007-06-12 16:50:17 +0000442/// the number of virtual registers that must be created and coalesced. This is
Chris Lattner684b22d2007-08-02 16:53:43 +0000443/// a clear win except on targets with multiple condition code registers
444/// (PowerPC), where it might lose; some adjustment may be wanted there.
Dale Johannesence0b2372007-06-12 16:50:17 +0000445///
446/// Return true if any changes are made.
Chris Lattner85fa13c2008-11-24 22:44:16 +0000447static bool OptimizeCmpExpression(CmpInst *CI) {
Dale Johannesence0b2372007-06-12 16:50:17 +0000448 BasicBlock *DefBB = CI->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000449
Dale Johannesence0b2372007-06-12 16:50:17 +0000450 /// InsertedCmp - Only insert a cmp in each block once.
451 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000452
Dale Johannesence0b2372007-06-12 16:50:17 +0000453 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000454 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
Dale Johannesence0b2372007-06-12 16:50:17 +0000455 UI != E; ) {
456 Use &TheUse = UI.getUse();
457 Instruction *User = cast<Instruction>(*UI);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000458
Dale Johannesence0b2372007-06-12 16:50:17 +0000459 // Preincrement use iterator so we don't invalidate it.
460 ++UI;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000461
Dale Johannesence0b2372007-06-12 16:50:17 +0000462 // Don't bother for PHI nodes.
463 if (isa<PHINode>(User))
464 continue;
465
466 // Figure out which BB this cmp is used in.
467 BasicBlock *UserBB = User->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000468
Dale Johannesence0b2372007-06-12 16:50:17 +0000469 // If this user is in the same block as the cmp, don't change the cmp.
470 if (UserBB == DefBB) continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000471
Dale Johannesence0b2372007-06-12 16:50:17 +0000472 // If we have already inserted a cmp into this block, use it.
473 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
474
475 if (!InsertedCmp) {
Bill Wendling5b6f42f2011-08-16 20:45:24 +0000476 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000477 InsertedCmp =
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000478 CmpInst::Create(CI->getOpcode(),
Owen Anderson333c4002009-07-09 23:48:35 +0000479 CI->getPredicate(), CI->getOperand(0),
Dale Johannesence0b2372007-06-12 16:50:17 +0000480 CI->getOperand(1), "", InsertPt);
481 MadeChange = true;
482 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000483
Dale Johannesence0b2372007-06-12 16:50:17 +0000484 // Replace a use of the cmp with a use of the new cmp.
485 TheUse = InsertedCmp;
Cameron Zwarich31ff1332011-01-05 17:27:27 +0000486 ++NumCmpUses;
Dale Johannesence0b2372007-06-12 16:50:17 +0000487 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000488
Dale Johannesence0b2372007-06-12 16:50:17 +0000489 // If we removed all uses, nuke the cmp.
490 if (CI->use_empty())
491 CI->eraseFromParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000492
Dale Johannesence0b2372007-06-12 16:50:17 +0000493 return MadeChange;
494}
495
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000496namespace {
497class CodeGenPrepareFortifiedLibCalls : public SimplifyFortifiedLibCalls {
498protected:
499 void replaceCall(Value *With) {
500 CI->replaceAllUsesWith(With);
501 CI->eraseFromParent();
502 }
503 bool isFoldable(unsigned SizeCIOp, unsigned, bool) const {
Gabor Greifa6aac4c2010-07-16 09:38:02 +0000504 if (ConstantInt *SizeCI =
505 dyn_cast<ConstantInt>(CI->getArgOperand(SizeCIOp)))
506 return SizeCI->isAllOnesValue();
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000507 return false;
508 }
509};
510} // end anonymous namespace
511
Eric Christopher040056f2010-03-11 02:41:03 +0000512bool CodeGenPrepare::OptimizeCallInst(CallInst *CI) {
Chris Lattner75796092011-01-15 07:14:54 +0000513 BasicBlock *BB = CI->getParent();
514
515 // Lower inline assembly if we can.
516 // If we found an inline asm expession, and if the target knows how to
517 // lower it to normal LLVM code, do so now.
518 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
519 if (TLI->ExpandInlineAsm(CI)) {
520 // Avoid invalidating the iterator.
521 CurInstIterator = BB->begin();
522 // Avoid processing instructions out of order, which could cause
523 // reuse before a value is defined.
524 SunkAddrs.clear();
525 return true;
526 }
527 // Sink address computing for memory operands into the block.
528 if (OptimizeInlineAsmInst(CI))
529 return true;
530 }
531
Eric Christopher040056f2010-03-11 02:41:03 +0000532 // Lower all uses of llvm.objectsize.*
533 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
534 if (II && II->getIntrinsicID() == Intrinsic::objectsize) {
Gabor Greifde9f5452010-06-24 00:44:01 +0000535 bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000536 Type *ReturnTy = CI->getType();
Eric Christopher040056f2010-03-11 02:41:03 +0000537 Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
Chris Lattner94e8e0c2011-01-15 07:25:29 +0000538
539 // Substituting this can cause recursive simplifications, which can
540 // invalidate our iterator. Use a WeakVH to hold onto it in case this
541 // happens.
542 WeakVH IterHandle(CurInstIterator);
543
Cameron Zwarich680c9622011-03-24 04:52:04 +0000544 ReplaceAndSimplifyAllUses(CI, RetVal, TLI ? TLI->getTargetData() : 0,
Devang Patel52e37df2011-03-24 15:35:25 +0000545 ModifiedDT ? 0 : DT);
Chris Lattner94e8e0c2011-01-15 07:25:29 +0000546
547 // If the iterator instruction was recursively deleted, start over at the
548 // start of the block.
Chris Lattner435b4d22011-01-18 20:53:04 +0000549 if (IterHandle != CurInstIterator) {
Chris Lattner94e8e0c2011-01-15 07:25:29 +0000550 CurInstIterator = BB->begin();
Chris Lattner435b4d22011-01-18 20:53:04 +0000551 SunkAddrs.clear();
552 }
Eric Christopher040056f2010-03-11 02:41:03 +0000553 return true;
554 }
555
556 // From here on out we're working with named functions.
557 if (CI->getCalledFunction() == 0) return false;
Devang Patel97de92c2011-05-26 21:51:06 +0000558
Eric Christopher040056f2010-03-11 02:41:03 +0000559 // We'll need TargetData from here on out.
560 const TargetData *TD = TLI ? TLI->getTargetData() : 0;
561 if (!TD) return false;
562
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000563 // Lower all default uses of _chk calls. This is very similar
564 // to what InstCombineCalls does, but here we are only lowering calls
Eric Christopher040056f2010-03-11 02:41:03 +0000565 // that have the default "don't know" as the objectsize. Anything else
566 // should be left alone.
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000567 CodeGenPrepareFortifiedLibCalls Simplifier;
568 return Simplifier.fold(CI, TD);
Eric Christopher040056f2010-03-11 02:41:03 +0000569}
Chris Lattner94e8e0c2011-01-15 07:25:29 +0000570
Evan Cheng485fafc2011-03-21 01:19:09 +0000571/// DupRetToEnableTailCallOpts - Look for opportunities to duplicate return
572/// instructions to the predecessor to enable tail call optimizations. The
573/// case it is currently looking for is:
574/// bb0:
575/// %tmp0 = tail call i32 @f0()
576/// br label %return
577/// bb1:
578/// %tmp1 = tail call i32 @f1()
579/// br label %return
580/// bb2:
581/// %tmp2 = tail call i32 @f2()
582/// br label %return
583/// return:
584/// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
585/// ret i32 %retval
586///
587/// =>
588///
589/// bb0:
590/// %tmp0 = tail call i32 @f0()
591/// ret i32 %tmp0
592/// bb1:
593/// %tmp1 = tail call i32 @f1()
594/// ret i32 %tmp1
595/// bb2:
596/// %tmp2 = tail call i32 @f2()
597/// ret i32 %tmp2
598///
599bool CodeGenPrepare::DupRetToEnableTailCallOpts(ReturnInst *RI) {
Cameron Zwarich661a3902011-03-24 04:51:51 +0000600 if (!TLI)
601 return false;
602
Evan Cheng485fafc2011-03-21 01:19:09 +0000603 Value *V = RI->getReturnValue();
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000604 PHINode *PN = V ? dyn_cast<PHINode>(V) : NULL;
605 if (V && !PN)
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000606 return false;
Evan Cheng485fafc2011-03-21 01:19:09 +0000607
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000608 BasicBlock *BB = RI->getParent();
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000609 if (PN && PN->getParent() != BB)
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000610 return false;
Evan Cheng485fafc2011-03-21 01:19:09 +0000611
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000612 // It's not safe to eliminate the sign / zero extension of the return value.
613 // See llvm::isInTailCallPosition().
614 const Function *F = BB->getParent();
615 unsigned CallerRetAttr = F->getAttributes().getRetAttributes();
616 if ((CallerRetAttr & Attribute::ZExt) || (CallerRetAttr & Attribute::SExt))
617 return false;
Evan Cheng485fafc2011-03-21 01:19:09 +0000618
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000619 // Make sure there are no instructions between the PHI and return, or that the
620 // return is the first instruction in the block.
621 if (PN) {
622 BasicBlock::iterator BI = BB->begin();
623 do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
624 if (&*BI != RI)
625 return false;
626 } else {
Cameron Zwarich90354842011-03-24 16:34:59 +0000627 BasicBlock::iterator BI = BB->begin();
628 while (isa<DbgInfoIntrinsic>(BI)) ++BI;
629 if (&*BI != RI)
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000630 return false;
631 }
Evan Cheng485fafc2011-03-21 01:19:09 +0000632
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000633 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
634 /// call.
635 SmallVector<CallInst*, 4> TailCalls;
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000636 if (PN) {
637 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
638 CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
639 // Make sure the phi value is indeed produced by the tail call.
640 if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
641 TLI->mayBeEmittedAsTailCall(CI))
642 TailCalls.push_back(CI);
643 }
644 } else {
645 SmallPtrSet<BasicBlock*, 4> VisitedBBs;
646 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
647 if (!VisitedBBs.insert(*PI))
648 continue;
649
650 BasicBlock::InstListType &InstList = (*PI)->getInstList();
651 BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
652 BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
Cameron Zwarich90354842011-03-24 16:34:59 +0000653 do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
654 if (RI == RE)
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000655 continue;
Cameron Zwarich90354842011-03-24 16:34:59 +0000656
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000657 CallInst *CI = dyn_cast<CallInst>(&*RI);
Cameron Zwarichdc31cfe2011-03-24 15:54:11 +0000658 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI))
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000659 TailCalls.push_back(CI);
660 }
Evan Cheng485fafc2011-03-21 01:19:09 +0000661 }
662
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000663 bool Changed = false;
664 for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
665 CallInst *CI = TailCalls[i];
666 CallSite CS(CI);
667
668 // Conservatively require the attributes of the call to match those of the
669 // return. Ignore noalias because it doesn't affect the call sequence.
670 unsigned CalleeRetAttr = CS.getAttributes().getRetAttributes();
671 if ((CalleeRetAttr ^ CallerRetAttr) & ~Attribute::NoAlias)
672 continue;
673
674 // Make sure the call instruction is followed by an unconditional branch to
675 // the return block.
676 BasicBlock *CallBB = CI->getParent();
677 BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
678 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
679 continue;
680
681 // Duplicate the return into CallBB.
682 (void)FoldReturnIntoUncondBranch(RI, BB, CallBB);
Devang Patel52e37df2011-03-24 15:35:25 +0000683 ModifiedDT = Changed = true;
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000684 ++NumRetsDup;
685 }
686
687 // If we eliminated all predecessors of the block, delete the block now.
688 if (Changed && pred_begin(BB) == pred_end(BB))
689 BB->eraseFromParent();
690
691 return Changed;
Evan Cheng485fafc2011-03-21 01:19:09 +0000692}
693
Chris Lattner88a5c832008-11-25 07:09:13 +0000694//===----------------------------------------------------------------------===//
Chris Lattner88a5c832008-11-25 07:09:13 +0000695// Memory Optimization
696//===----------------------------------------------------------------------===//
697
Chris Lattnerdd77df32007-04-13 20:30:56 +0000698/// IsNonLocalValue - Return true if the specified values are defined in a
699/// different basic block than BB.
700static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
701 if (Instruction *I = dyn_cast<Instruction>(V))
702 return I->getParent() != BB;
703 return false;
704}
705
Bob Wilson4a8ee232009-12-03 21:47:07 +0000706/// OptimizeMemoryInst - Load and Store Instructions often have
Chris Lattnerdd77df32007-04-13 20:30:56 +0000707/// addressing modes that can do significant amounts of computation. As such,
708/// instruction selection will try to get the load or store to do as much
709/// computation as possible for the program. The problem is that isel can only
710/// see within a single block. As such, we sink as much legal addressing mode
711/// stuff into the block as possible.
Chris Lattner88a5c832008-11-25 07:09:13 +0000712///
713/// This method is used to optimize both load/store and inline asms with memory
714/// operands.
Chris Lattner896617b2008-11-26 03:20:37 +0000715bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000716 Type *AccessTy) {
Owen Anderson35bf4d62010-11-27 08:15:55 +0000717 Value *Repl = Addr;
718
Owen Andersond2f41742010-11-19 22:15:03 +0000719 // Try to collapse single-value PHI nodes. This is necessary to undo
720 // unprofitable PRE transformations.
Cameron Zwarich7cb4fa22011-01-03 06:33:01 +0000721 SmallVector<Value*, 8> worklist;
722 SmallPtrSet<Value*, 16> Visited;
Owen Anderson35bf4d62010-11-27 08:15:55 +0000723 worklist.push_back(Addr);
724
725 // Use a worklist to iteratively look through PHI nodes, and ensure that
726 // the addressing mode obtained from the non-PHI roots of the graph
727 // are equivalent.
728 Value *Consensus = 0;
Cameron Zwarich4c078f02011-03-01 21:13:53 +0000729 unsigned NumUsesConsensus = 0;
Cameron Zwarich7c8d3512011-03-05 08:12:26 +0000730 bool IsNumUsesConsensusValid = false;
Owen Anderson35bf4d62010-11-27 08:15:55 +0000731 SmallVector<Instruction*, 16> AddrModeInsts;
732 ExtAddrMode AddrMode;
733 while (!worklist.empty()) {
734 Value *V = worklist.back();
735 worklist.pop_back();
736
737 // Break use-def graph loops.
738 if (Visited.count(V)) {
739 Consensus = 0;
740 break;
Owen Andersond2f41742010-11-19 22:15:03 +0000741 }
742
Owen Anderson35bf4d62010-11-27 08:15:55 +0000743 Visited.insert(V);
744
745 // For a PHI node, push all of its incoming values.
746 if (PHINode *P = dyn_cast<PHINode>(V)) {
747 for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i)
748 worklist.push_back(P->getIncomingValue(i));
749 continue;
750 }
751
752 // For non-PHIs, determine the addressing mode being computed.
753 SmallVector<Instruction*, 16> NewAddrModeInsts;
754 ExtAddrMode NewAddrMode =
755 AddressingModeMatcher::Match(V, AccessTy,MemoryInst,
756 NewAddrModeInsts, *TLI);
Cameron Zwarich7c8d3512011-03-05 08:12:26 +0000757
758 // This check is broken into two cases with very similar code to avoid using
759 // getNumUses() as much as possible. Some values have a lot of uses, so
760 // calling getNumUses() unconditionally caused a significant compile-time
761 // regression.
762 if (!Consensus) {
763 Consensus = V;
764 AddrMode = NewAddrMode;
765 AddrModeInsts = NewAddrModeInsts;
766 continue;
767 } else if (NewAddrMode == AddrMode) {
768 if (!IsNumUsesConsensusValid) {
769 NumUsesConsensus = Consensus->getNumUses();
770 IsNumUsesConsensusValid = true;
771 }
772
773 // Ensure that the obtained addressing mode is equivalent to that obtained
774 // for all other roots of the PHI traversal. Also, when choosing one
775 // such root as representative, select the one with the most uses in order
776 // to keep the cost modeling heuristics in AddressingModeMatcher
777 // applicable.
Cameron Zwarich4c078f02011-03-01 21:13:53 +0000778 unsigned NumUses = V->getNumUses();
779 if (NumUses > NumUsesConsensus) {
Owen Anderson35bf4d62010-11-27 08:15:55 +0000780 Consensus = V;
Cameron Zwarich4c078f02011-03-01 21:13:53 +0000781 NumUsesConsensus = NumUses;
Owen Anderson35bf4d62010-11-27 08:15:55 +0000782 AddrModeInsts = NewAddrModeInsts;
783 }
784 continue;
785 }
786
787 Consensus = 0;
788 break;
Owen Andersond2f41742010-11-19 22:15:03 +0000789 }
790
Owen Anderson35bf4d62010-11-27 08:15:55 +0000791 // If the addressing mode couldn't be determined, or if multiple different
792 // ones were determined, bail out now.
793 if (!Consensus) return false;
794
Chris Lattnerdd77df32007-04-13 20:30:56 +0000795 // Check to see if any of the instructions supersumed by this addr mode are
796 // non-local to I's BB.
797 bool AnyNonLocal = false;
798 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
Chris Lattner896617b2008-11-26 03:20:37 +0000799 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
Chris Lattnerdd77df32007-04-13 20:30:56 +0000800 AnyNonLocal = true;
801 break;
802 }
803 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000804
Chris Lattnerdd77df32007-04-13 20:30:56 +0000805 // If all the instructions matched are already in this BB, don't do anything.
806 if (!AnyNonLocal) {
David Greene68d67fd2010-01-05 01:27:11 +0000807 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000808 return false;
809 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000810
Chris Lattnerdd77df32007-04-13 20:30:56 +0000811 // Insert this computation right after this user. Since our caller is
812 // scanning from the top of the BB to the bottom, reuse of the expr are
813 // guaranteed to happen later.
Devang Patel2048c372011-09-06 18:49:53 +0000814 IRBuilder<> Builder(MemoryInst);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000815
Chris Lattnerdd77df32007-04-13 20:30:56 +0000816 // Now that we determined the addressing expression we want to use and know
817 // that we have to sink it into this block. Check to see if we have already
818 // done this for some other load/store instr in this block. If so, reuse the
819 // computation.
820 Value *&SunkAddr = SunkAddrs[Addr];
821 if (SunkAddr) {
David Greene68d67fd2010-01-05 01:27:11 +0000822 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
Dan Gohman6c1980b2009-07-25 01:13:51 +0000823 << *MemoryInst);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000824 if (SunkAddr->getType() != Addr->getType())
Devang Patel2048c372011-09-06 18:49:53 +0000825 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType(), "tmp");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000826 } else {
David Greene68d67fd2010-01-05 01:27:11 +0000827 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Dan Gohman6c1980b2009-07-25 01:13:51 +0000828 << *MemoryInst);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000829 Type *IntPtrTy =
Owen Anderson1d0be152009-08-13 21:58:54 +0000830 TLI->getTargetData()->getIntPtrType(AccessTy->getContext());
Eric Christopher692bf6b2008-09-24 05:32:41 +0000831
Chris Lattnerdd77df32007-04-13 20:30:56 +0000832 Value *Result = 0;
Dan Gohmand8d0b6a2010-01-19 22:45:06 +0000833
834 // Start with the base register. Do this first so that subsequent address
835 // matching finds it last, which will prevent it from trying to match it
836 // as the scaled value in case it happens to be a mul. That would be
837 // problematic if we've sunk a different mul for the scale, because then
838 // we'd end up sinking both muls.
839 if (AddrMode.BaseReg) {
840 Value *V = AddrMode.BaseReg;
Duncan Sands1df98592010-02-16 11:11:14 +0000841 if (V->getType()->isPointerTy())
Devang Patel2048c372011-09-06 18:49:53 +0000842 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Dan Gohmand8d0b6a2010-01-19 22:45:06 +0000843 if (V->getType() != IntPtrTy)
Devang Patel2048c372011-09-06 18:49:53 +0000844 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
Dan Gohmand8d0b6a2010-01-19 22:45:06 +0000845 Result = V;
846 }
847
848 // Add the scale value.
Chris Lattnerdd77df32007-04-13 20:30:56 +0000849 if (AddrMode.Scale) {
850 Value *V = AddrMode.ScaledReg;
851 if (V->getType() == IntPtrTy) {
852 // done.
Duncan Sands1df98592010-02-16 11:11:14 +0000853 } else if (V->getType()->isPointerTy()) {
Devang Patel2048c372011-09-06 18:49:53 +0000854 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000855 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
856 cast<IntegerType>(V->getType())->getBitWidth()) {
Devang Patel2048c372011-09-06 18:49:53 +0000857 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000858 } else {
Devang Patel2048c372011-09-06 18:49:53 +0000859 V = Builder.CreateSExt(V, IntPtrTy, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000860 }
861 if (AddrMode.Scale != 1)
Devang Patel2048c372011-09-06 18:49:53 +0000862 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
863 "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000864 if (Result)
Devang Patel2048c372011-09-06 18:49:53 +0000865 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000866 else
867 Result = V;
868 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000869
Chris Lattnerdd77df32007-04-13 20:30:56 +0000870 // Add in the BaseGV if present.
871 if (AddrMode.BaseGV) {
Devang Patel2048c372011-09-06 18:49:53 +0000872 Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000873 if (Result)
Devang Patel2048c372011-09-06 18:49:53 +0000874 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000875 else
876 Result = V;
877 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000878
Chris Lattnerdd77df32007-04-13 20:30:56 +0000879 // Add in the Base Offset if present.
880 if (AddrMode.BaseOffs) {
Owen Andersoneed707b2009-07-24 23:12:02 +0000881 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000882 if (Result)
Devang Patel2048c372011-09-06 18:49:53 +0000883 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000884 else
885 Result = V;
886 }
887
888 if (Result == 0)
Owen Andersona7235ea2009-07-31 20:28:14 +0000889 SunkAddr = Constant::getNullValue(Addr->getType());
Chris Lattnerdd77df32007-04-13 20:30:56 +0000890 else
Devang Patel2048c372011-09-06 18:49:53 +0000891 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000892 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000893
Owen Andersond2f41742010-11-19 22:15:03 +0000894 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000895
Chris Lattner0403b472011-04-09 07:05:44 +0000896 // If we have no uses, recursively delete the value and all dead instructions
897 // using it.
Owen Andersond2f41742010-11-19 22:15:03 +0000898 if (Repl->use_empty()) {
Chris Lattner0403b472011-04-09 07:05:44 +0000899 // This can cause recursive deletion, which can invalidate our iterator.
900 // Use a WeakVH to hold onto it in case this happens.
901 WeakVH IterHandle(CurInstIterator);
902 BasicBlock *BB = CurInstIterator->getParent();
903
Owen Andersond2f41742010-11-19 22:15:03 +0000904 RecursivelyDeleteTriviallyDeadInstructions(Repl);
Chris Lattner0403b472011-04-09 07:05:44 +0000905
906 if (IterHandle != CurInstIterator) {
907 // If the iterator instruction was recursively deleted, start over at the
908 // start of the block.
909 CurInstIterator = BB->begin();
910 SunkAddrs.clear();
911 } else {
912 // This address is now available for reassignment, so erase the table
913 // entry; we don't want to match some completely different instruction.
914 SunkAddrs[Addr] = 0;
915 }
Dale Johannesen536d31b2010-03-31 20:37:15 +0000916 }
Cameron Zwarich31ff1332011-01-05 17:27:27 +0000917 ++NumMemoryInsts;
Chris Lattnerdd77df32007-04-13 20:30:56 +0000918 return true;
919}
920
Evan Cheng9bf12b52008-02-26 02:42:37 +0000921/// OptimizeInlineAsmInst - If there are any memory operands, use
Chris Lattner88a5c832008-11-25 07:09:13 +0000922/// OptimizeMemoryInst to sink their address computing into the block when
Evan Cheng9bf12b52008-02-26 02:42:37 +0000923/// possible / profitable.
Chris Lattner75796092011-01-15 07:14:54 +0000924bool CodeGenPrepare::OptimizeInlineAsmInst(CallInst *CS) {
Evan Cheng9bf12b52008-02-26 02:42:37 +0000925 bool MadeChange = false;
Evan Cheng9bf12b52008-02-26 02:42:37 +0000926
Chris Lattner75796092011-01-15 07:14:54 +0000927 TargetLowering::AsmOperandInfoVector
928 TargetConstraints = TLI->ParseConstraints(CS);
Dale Johannesen677c6ec2010-09-16 18:30:55 +0000929 unsigned ArgNo = 0;
John Thompsoneac6e1d2010-09-13 18:15:37 +0000930 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
931 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
932
Evan Cheng9bf12b52008-02-26 02:42:37 +0000933 // Compute the constraint code and ConstraintType to use.
Dale Johannesen1784d162010-06-25 21:55:36 +0000934 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Evan Cheng9bf12b52008-02-26 02:42:37 +0000935
Eli Friedman9ec80952008-02-26 18:37:49 +0000936 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
937 OpInfo.isIndirect) {
Chris Lattner75796092011-01-15 07:14:54 +0000938 Value *OpVal = CS->getArgOperand(ArgNo++);
Chris Lattner1a8943a2011-01-15 07:29:01 +0000939 MadeChange |= OptimizeMemoryInst(CS, OpVal, OpVal->getType());
Dale Johannesen677c6ec2010-09-16 18:30:55 +0000940 } else if (OpInfo.Type == InlineAsm::isInput)
941 ArgNo++;
Evan Cheng9bf12b52008-02-26 02:42:37 +0000942 }
943
944 return MadeChange;
945}
946
Dan Gohmanb00f2362009-10-16 20:59:35 +0000947/// MoveExtToFormExtLoad - Move a zext or sext fed by a load into the same
948/// basic block as the load, unless conditions are unfavorable. This allows
949/// SelectionDAG to fold the extend into the load.
950///
951bool CodeGenPrepare::MoveExtToFormExtLoad(Instruction *I) {
952 // Look for a load being extended.
953 LoadInst *LI = dyn_cast<LoadInst>(I->getOperand(0));
954 if (!LI) return false;
955
956 // If they're already in the same block, there's nothing to do.
957 if (LI->getParent() == I->getParent())
958 return false;
959
960 // If the load has other users and the truncate is not free, this probably
961 // isn't worthwhile.
962 if (!LI->hasOneUse() &&
Bob Wilsonec57a1a2010-09-22 18:44:56 +0000963 TLI && (TLI->isTypeLegal(TLI->getValueType(LI->getType())) ||
964 !TLI->isTypeLegal(TLI->getValueType(I->getType()))) &&
Bob Wilson71dc4d92010-09-21 21:54:27 +0000965 !TLI->isTruncateFree(I->getType(), LI->getType()))
Dan Gohmanb00f2362009-10-16 20:59:35 +0000966 return false;
967
968 // Check whether the target supports casts folded into loads.
969 unsigned LType;
970 if (isa<ZExtInst>(I))
971 LType = ISD::ZEXTLOAD;
972 else {
973 assert(isa<SExtInst>(I) && "Unexpected ext type!");
974 LType = ISD::SEXTLOAD;
975 }
976 if (TLI && !TLI->isLoadExtLegal(LType, TLI->getValueType(LI->getType())))
977 return false;
978
979 // Move the extend into the same block as the load, so that SelectionDAG
980 // can fold it.
981 I->removeFromParent();
982 I->insertAfter(LI);
Cameron Zwarich31ff1332011-01-05 17:27:27 +0000983 ++NumExtsMoved;
Dan Gohmanb00f2362009-10-16 20:59:35 +0000984 return true;
985}
986
Evan Chengbdcb7262007-12-05 23:58:20 +0000987bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
988 BasicBlock *DefBB = I->getParent();
989
Bob Wilson9120f5c2010-09-21 21:44:14 +0000990 // If the result of a {s|z}ext and its source are both live out, rewrite all
Evan Chengbdcb7262007-12-05 23:58:20 +0000991 // other uses of the source with result of extension.
992 Value *Src = I->getOperand(0);
993 if (Src->hasOneUse())
994 return false;
995
Evan Cheng696e5c02007-12-13 07:50:36 +0000996 // Only do this xform if truncating is free.
Gabor Greif53bdbd72008-02-26 19:13:21 +0000997 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
Evan Chengf9785f92007-12-13 03:32:53 +0000998 return false;
999
Evan Cheng772de512007-12-12 00:51:06 +00001000 // Only safe to perform the optimization if the source is also defined in
Evan Cheng765dff22007-12-12 02:53:41 +00001001 // this block.
1002 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
Evan Cheng772de512007-12-12 00:51:06 +00001003 return false;
1004
Evan Chengbdcb7262007-12-05 23:58:20 +00001005 bool DefIsLiveOut = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001006 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
Evan Chengbdcb7262007-12-05 23:58:20 +00001007 UI != E; ++UI) {
1008 Instruction *User = cast<Instruction>(*UI);
1009
1010 // Figure out which BB this ext is used in.
1011 BasicBlock *UserBB = User->getParent();
1012 if (UserBB == DefBB) continue;
1013 DefIsLiveOut = true;
1014 break;
1015 }
1016 if (!DefIsLiveOut)
1017 return false;
1018
Evan Cheng765dff22007-12-12 02:53:41 +00001019 // Make sure non of the uses are PHI nodes.
Eric Christopher692bf6b2008-09-24 05:32:41 +00001020 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
Evan Cheng765dff22007-12-12 02:53:41 +00001021 UI != E; ++UI) {
1022 Instruction *User = cast<Instruction>(*UI);
Evan Chengf9785f92007-12-13 03:32:53 +00001023 BasicBlock *UserBB = User->getParent();
1024 if (UserBB == DefBB) continue;
1025 // Be conservative. We don't want this xform to end up introducing
1026 // reloads just before load / store instructions.
1027 if (isa<PHINode>(User) || isa<LoadInst>(User) || isa<StoreInst>(User))
Evan Cheng765dff22007-12-12 02:53:41 +00001028 return false;
1029 }
1030
Evan Chengbdcb7262007-12-05 23:58:20 +00001031 // InsertedTruncs - Only insert one trunc in each block once.
1032 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
1033
1034 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001035 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
Evan Chengbdcb7262007-12-05 23:58:20 +00001036 UI != E; ++UI) {
1037 Use &TheUse = UI.getUse();
1038 Instruction *User = cast<Instruction>(*UI);
1039
1040 // Figure out which BB this ext is used in.
1041 BasicBlock *UserBB = User->getParent();
1042 if (UserBB == DefBB) continue;
1043
1044 // Both src and def are live in this block. Rewrite the use.
1045 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
1046
1047 if (!InsertedTrunc) {
Bill Wendling5b6f42f2011-08-16 20:45:24 +00001048 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Evan Chengbdcb7262007-12-05 23:58:20 +00001049 InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
1050 }
1051
1052 // Replace a use of the {s|z}ext source with a use of the result.
1053 TheUse = InsertedTrunc;
Cameron Zwarich31ff1332011-01-05 17:27:27 +00001054 ++NumExtUses;
Evan Chengbdcb7262007-12-05 23:58:20 +00001055 MadeChange = true;
1056 }
1057
1058 return MadeChange;
1059}
1060
Cameron Zwarichc0611012011-01-06 02:37:26 +00001061bool CodeGenPrepare::OptimizeInst(Instruction *I) {
Cameron Zwarichc0611012011-01-06 02:37:26 +00001062 if (PHINode *P = dyn_cast<PHINode>(I)) {
1063 // It is possible for very late stage optimizations (such as SimplifyCFG)
1064 // to introduce PHI nodes too late to be cleaned up. If we detect such a
1065 // trivial PHI, go ahead and zap it here.
1066 if (Value *V = SimplifyInstruction(P)) {
1067 P->replaceAllUsesWith(V);
1068 P->eraseFromParent();
1069 ++NumPHIsElim;
Chris Lattner1a8943a2011-01-15 07:29:01 +00001070 return true;
Cameron Zwarichc0611012011-01-06 02:37:26 +00001071 }
Chris Lattner1a8943a2011-01-15 07:29:01 +00001072 return false;
1073 }
1074
1075 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Cameron Zwarichc0611012011-01-06 02:37:26 +00001076 // If the source of the cast is a constant, then this should have
1077 // already been constant folded. The only reason NOT to constant fold
1078 // it is if something (e.g. LSR) was careful to place the constant
1079 // evaluation in a block other than then one that uses it (e.g. to hoist
1080 // the address of globals out of a loop). If this is the case, we don't
1081 // want to forward-subst the cast.
1082 if (isa<Constant>(CI->getOperand(0)))
1083 return false;
1084
Chris Lattner1a8943a2011-01-15 07:29:01 +00001085 if (TLI && OptimizeNoopCopyExpression(CI, *TLI))
1086 return true;
Cameron Zwarichc0611012011-01-06 02:37:26 +00001087
Chris Lattner1a8943a2011-01-15 07:29:01 +00001088 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
1089 bool MadeChange = MoveExtToFormExtLoad(I);
1090 return MadeChange | OptimizeExtUses(I);
Cameron Zwarichc0611012011-01-06 02:37:26 +00001091 }
Chris Lattner1a8943a2011-01-15 07:29:01 +00001092 return false;
1093 }
1094
1095 if (CmpInst *CI = dyn_cast<CmpInst>(I))
1096 return OptimizeCmpExpression(CI);
1097
1098 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Cameron Zwarichc0611012011-01-06 02:37:26 +00001099 if (TLI)
Chris Lattner1a8943a2011-01-15 07:29:01 +00001100 return OptimizeMemoryInst(I, I->getOperand(0), LI->getType());
1101 return false;
1102 }
1103
1104 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Cameron Zwarichc0611012011-01-06 02:37:26 +00001105 if (TLI)
Chris Lattner1a8943a2011-01-15 07:29:01 +00001106 return OptimizeMemoryInst(I, SI->getOperand(1),
1107 SI->getOperand(0)->getType());
1108 return false;
1109 }
1110
1111 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Cameron Zwarich865ae1a2011-01-06 02:44:52 +00001112 if (GEPI->hasAllZeroIndices()) {
1113 /// The GEP operand must be a pointer, so must its result -> BitCast
1114 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
1115 GEPI->getName(), GEPI);
1116 GEPI->replaceAllUsesWith(NC);
1117 GEPI->eraseFromParent();
1118 ++NumGEPsElim;
Cameron Zwarich865ae1a2011-01-06 02:44:52 +00001119 OptimizeInst(NC);
Chris Lattner1a8943a2011-01-15 07:29:01 +00001120 return true;
Cameron Zwarich865ae1a2011-01-06 02:44:52 +00001121 }
Chris Lattner1a8943a2011-01-15 07:29:01 +00001122 return false;
Cameron Zwarichc0611012011-01-06 02:37:26 +00001123 }
Chris Lattner1a8943a2011-01-15 07:29:01 +00001124
1125 if (CallInst *CI = dyn_cast<CallInst>(I))
1126 return OptimizeCallInst(CI);
Cameron Zwarichc0611012011-01-06 02:37:26 +00001127
Evan Cheng485fafc2011-03-21 01:19:09 +00001128 if (ReturnInst *RI = dyn_cast<ReturnInst>(I))
1129 return DupRetToEnableTailCallOpts(RI);
1130
Chris Lattner1a8943a2011-01-15 07:29:01 +00001131 return false;
Cameron Zwarichc0611012011-01-06 02:37:26 +00001132}
1133
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001134// In this pass we look for GEP and cast instructions that are used
1135// across basic blocks and rewrite them to improve basic-block-at-a-time
1136// selection.
1137bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
Cameron Zwarich8c3527e2011-01-06 00:42:50 +00001138 SunkAddrs.clear();
Cameron Zwarich56e37932011-03-02 03:31:46 +00001139 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001140
Chris Lattner75796092011-01-15 07:14:54 +00001141 CurInstIterator = BB.begin();
Chris Lattner94e8e0c2011-01-15 07:25:29 +00001142 for (BasicBlock::iterator E = BB.end(); CurInstIterator != E; )
1143 MadeChange |= OptimizeInst(CurInstIterator++);
Eric Christopher692bf6b2008-09-24 05:32:41 +00001144
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001145 return MadeChange;
1146}
Devang Patelf56ea612011-08-18 00:50:51 +00001147
1148// llvm.dbg.value is far away from the value then iSel may not be able
1149// handle it properly. iSel will drop llvm.dbg.value if it can not
1150// find a node corresponding to the value.
1151bool CodeGenPrepare::PlaceDbgValues(Function &F) {
1152 bool MadeChange = false;
1153 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
1154 Instruction *PrevNonDbgInst = NULL;
1155 for (BasicBlock::iterator BI = I->begin(), BE = I->end(); BI != BE;) {
1156 Instruction *Insn = BI; ++BI;
1157 DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
1158 if (!DVI) {
1159 PrevNonDbgInst = Insn;
1160 continue;
1161 }
1162
1163 Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
1164 if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
1165 DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
1166 DVI->removeFromParent();
1167 if (isa<PHINode>(VI))
1168 DVI->insertBefore(VI->getParent()->getFirstInsertionPt());
1169 else
1170 DVI->insertAfter(VI);
1171 MadeChange = true;
1172 ++NumDbgValueMoved;
1173 }
1174 }
1175 }
1176 return MadeChange;
1177}