blob: c90cb32b98b995694ef039489f1da8bd5db52b23 [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");
Cameron Zwarich073057f2011-01-05 17:47:38 +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");
58STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads");
59STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized");
Jakob Stoklund Olesen7eb589d2010-09-30 20:51:52 +000060
Eric Christopher692bf6b2008-09-24 05:32:41 +000061namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +000062 class CodeGenPrepare : public FunctionPass {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000063 /// TLI - Keep a pointer of a TargetLowering to consult for determining
64 /// transformation profitability.
65 const TargetLowering *TLI;
Cameron Zwarich80f6a502011-01-08 17:01:52 +000066 DominatorTree *DT;
Evan Cheng04149f72009-12-17 09:39:49 +000067 ProfileInfo *PFI;
Chris Lattner75796092011-01-15 07:14:54 +000068
69 /// CurInstIterator - As we scan instructions optimizing them, this is the
70 /// next instruction to optimize. Xforms that can invalidate this should
71 /// update it.
72 BasicBlock::iterator CurInstIterator;
Evan Chengab631522008-12-19 18:03:11 +000073
74 /// BackEdges - Keep a set of all the loop back edges.
75 ///
Mike Stumpfe095f32009-05-04 18:40:41 +000076 SmallSet<std::pair<const BasicBlock*, const BasicBlock*>, 8> BackEdges;
Cameron Zwarich8c3527e2011-01-06 00:42:50 +000077
78 // Keeps track of non-local addresses that have been sunk into a block. This
79 // allows us to avoid inserting duplicate code for blocks with multiple
80 // load/stores of the same address.
81 DenseMap<Value*, Value*> SunkAddrs;
82
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000083 public:
Nick Lewyckyecd94c82007-05-06 13:37:16 +000084 static char ID; // Pass identification, replacement for typeid
Dan Gohmanc2bbfc12007-08-01 15:32:29 +000085 explicit CodeGenPrepare(const TargetLowering *tli = 0)
Owen Anderson081c34b2010-10-19 17:21:58 +000086 : FunctionPass(ID), TLI(tli) {
87 initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
88 }
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000089 bool runOnFunction(Function &F);
Eric Christopher692bf6b2008-09-24 05:32:41 +000090
Andreas Neustifterad809812009-09-16 09:26:52 +000091 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Cameron Zwarich80f6a502011-01-08 17:01:52 +000092 AU.addPreserved<DominatorTree>();
Andreas Neustifterad809812009-09-16 09:26:52 +000093 AU.addPreserved<ProfileInfo>();
94 }
95
Dan Gohmanaa0e5232010-02-05 19:24:11 +000096 virtual void releaseMemory() {
97 BackEdges.clear();
98 }
99
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000100 private:
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000101 bool EliminateMostlyEmptyBlocks(Function &F);
102 bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
103 void EliminateMostlyEmptyBlock(BasicBlock *BB);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000104 bool OptimizeBlock(BasicBlock &BB);
Cameron Zwarichc0611012011-01-06 02:37:26 +0000105 bool OptimizeInst(Instruction *I);
Chris Lattner1a8943a2011-01-15 07:29:01 +0000106 bool OptimizeMemoryInst(Instruction *I, Value *Addr, const Type *AccessTy);
Chris Lattner75796092011-01-15 07:14:54 +0000107 bool OptimizeInlineAsmInst(CallInst *CS);
Eric Christopher040056f2010-03-11 02:41:03 +0000108 bool OptimizeCallInst(CallInst *CI);
Dan Gohmanb00f2362009-10-16 20:59:35 +0000109 bool MoveExtToFormExtLoad(Instruction *I);
Evan Chengbdcb7262007-12-05 23:58:20 +0000110 bool OptimizeExtUses(Instruction *I);
Mike Stumpfe095f32009-05-04 18:40:41 +0000111 void findLoopBackEdges(const Function &F);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000112 };
113}
Devang Patel794fd752007-05-01 21:15:47 +0000114
Devang Patel19974732007-05-03 01:11:54 +0000115char CodeGenPrepare::ID = 0;
Owen Andersond13db2c2010-07-21 22:09:45 +0000116INITIALIZE_PASS(CodeGenPrepare, "codegenprepare",
Owen Andersonce665bd2010-10-07 22:25:06 +0000117 "Optimize for code generation", false, false)
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000118
119FunctionPass *llvm::createCodeGenPreparePass(const TargetLowering *TLI) {
120 return new CodeGenPrepare(TLI);
121}
122
Evan Chengab631522008-12-19 18:03:11 +0000123/// findLoopBackEdges - Do a DFS walk to find loop back edges.
124///
Mike Stumpfe095f32009-05-04 18:40:41 +0000125void CodeGenPrepare::findLoopBackEdges(const Function &F) {
126 SmallVector<std::pair<const BasicBlock*,const BasicBlock*>, 32> Edges;
127 FindFunctionBackedges(F, Edges);
128
129 BackEdges.insert(Edges.begin(), Edges.end());
Evan Chengab631522008-12-19 18:03:11 +0000130}
131
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000132
133bool CodeGenPrepare::runOnFunction(Function &F) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000134 bool EverMadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000135
Cameron Zwarich80f6a502011-01-08 17:01:52 +0000136 DT = getAnalysisIfAvailable<DominatorTree>();
Evan Cheng04149f72009-12-17 09:39:49 +0000137 PFI = getAnalysisIfAvailable<ProfileInfo>();
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000138 // First pass, eliminate blocks that contain only PHI nodes and an
139 // unconditional branch.
140 EverMadeChange |= EliminateMostlyEmptyBlocks(F);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000141
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000142 bool MadeChange = true;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000143 while (MadeChange) {
144 MadeChange = false;
145 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
146 MadeChange |= OptimizeBlock(*BB);
147 EverMadeChange |= MadeChange;
148 }
Cameron Zwarich8c3527e2011-01-06 00:42:50 +0000149
150 SunkAddrs.clear();
151
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000152 return EverMadeChange;
153}
154
Dale Johannesen2d697242009-03-27 01:13:37 +0000155/// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes,
156/// debug info directives, and an unconditional branch. Passes before isel
157/// (e.g. LSR/loopsimplify) often split edges in ways that are non-optimal for
158/// isel. Start by eliminating these blocks so we can split them the way we
159/// want them.
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000160bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
161 bool MadeChange = false;
162 // Note that this intentionally skips the entry block.
163 for (Function::iterator I = ++F.begin(), E = F.end(); I != E; ) {
164 BasicBlock *BB = I++;
165
166 // If this block doesn't end with an uncond branch, ignore it.
167 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
168 if (!BI || !BI->isUnconditional())
169 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000170
Dale Johannesen2d697242009-03-27 01:13:37 +0000171 // If the instruction before the branch (skipping debug info) isn't a phi
172 // node, then other stuff is happening here.
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000173 BasicBlock::iterator BBI = BI;
174 if (BBI != BB->begin()) {
175 --BBI;
Dale Johannesen2d697242009-03-27 01:13:37 +0000176 while (isa<DbgInfoIntrinsic>(BBI)) {
177 if (BBI == BB->begin())
178 break;
179 --BBI;
180 }
181 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
182 continue;
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000183 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000184
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000185 // Do not break infinite loops.
186 BasicBlock *DestBB = BI->getSuccessor(0);
187 if (DestBB == BB)
188 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000189
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000190 if (!CanMergeBlocks(BB, DestBB))
191 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000192
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000193 EliminateMostlyEmptyBlock(BB);
194 MadeChange = true;
195 }
196 return MadeChange;
197}
198
199/// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
200/// single uncond branch between them, and BB contains no other non-phi
201/// instructions.
202bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
203 const BasicBlock *DestBB) const {
204 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
205 // the successor. If there are more complex condition (e.g. preheaders),
206 // don't mess around with them.
207 BasicBlock::const_iterator BBI = BB->begin();
208 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
Gabor Greif60ad7812010-03-25 23:06:16 +0000209 for (Value::const_use_iterator UI = PN->use_begin(), E = PN->use_end();
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000210 UI != E; ++UI) {
211 const Instruction *User = cast<Instruction>(*UI);
212 if (User->getParent() != DestBB || !isa<PHINode>(User))
213 return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000214 // If User is inside DestBB block and it is a PHINode then check
215 // incoming value. If incoming value is not from BB then this is
Devang Patel75abc1e2007-04-25 00:37:04 +0000216 // a complex condition (e.g. preheaders) we want to avoid here.
217 if (User->getParent() == DestBB) {
218 if (const PHINode *UPN = dyn_cast<PHINode>(User))
219 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
220 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
221 if (Insn && Insn->getParent() == BB &&
222 Insn->getParent() != UPN->getIncomingBlock(I))
223 return false;
224 }
225 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000226 }
227 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000228
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000229 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
230 // and DestBB may have conflicting incoming values for the block. If so, we
231 // can't merge the block.
232 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
233 if (!DestBBPN) return true; // no conflict.
Eric Christopher692bf6b2008-09-24 05:32:41 +0000234
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000235 // Collect the preds of BB.
Chris Lattnerf67f73a2007-11-06 22:07:40 +0000236 SmallPtrSet<const BasicBlock*, 16> BBPreds;
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000237 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
238 // It is faster to get preds from a PHI than with pred_iterator.
239 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
240 BBPreds.insert(BBPN->getIncomingBlock(i));
241 } else {
242 BBPreds.insert(pred_begin(BB), pred_end(BB));
243 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000244
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000245 // Walk the preds of DestBB.
246 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
247 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
248 if (BBPreds.count(Pred)) { // Common predecessor?
249 BBI = DestBB->begin();
250 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
251 const Value *V1 = PN->getIncomingValueForBlock(Pred);
252 const Value *V2 = PN->getIncomingValueForBlock(BB);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000253
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000254 // If V2 is a phi node in BB, look up what the mapped value will be.
255 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
256 if (V2PN->getParent() == BB)
257 V2 = V2PN->getIncomingValueForBlock(Pred);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000258
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000259 // If there is a conflict, bail out.
260 if (V1 != V2) return false;
261 }
262 }
263 }
264
265 return true;
266}
267
268
269/// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
270/// an unconditional branch in it.
271void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
272 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
273 BasicBlock *DestBB = BI->getSuccessor(0);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000274
David Greene68d67fd2010-01-05 01:27:11 +0000275 DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000276
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000277 // If the destination block has a single pred, then this is a trivial edge,
278 // just collapse it.
Chris Lattner9918fb52008-11-27 19:29:14 +0000279 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
Chris Lattnerf5102a02008-11-28 19:54:49 +0000280 if (SinglePred != DestBB) {
281 // Remember if SinglePred was the entry block of the function. If so, we
282 // will need to move BB back to the entry position.
283 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Andreas Neustifterad809812009-09-16 09:26:52 +0000284 MergeBasicBlockIntoOnlyPred(DestBB, this);
Chris Lattner9918fb52008-11-27 19:29:14 +0000285
Chris Lattnerf5102a02008-11-28 19:54:49 +0000286 if (isEntry && BB != &BB->getParent()->getEntryBlock())
287 BB->moveBefore(&BB->getParent()->getEntryBlock());
288
David Greene68d67fd2010-01-05 01:27:11 +0000289 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerf5102a02008-11-28 19:54:49 +0000290 return;
291 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000292 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000293
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000294 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
295 // to handle the new incoming edges it is about to have.
296 PHINode *PN;
297 for (BasicBlock::iterator BBI = DestBB->begin();
298 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
299 // Remove the incoming value for BB, and remember it.
300 Value *InVal = PN->removeIncomingValue(BB, false);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000301
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000302 // Two options: either the InVal is a phi node defined in BB or it is some
303 // value that dominates BB.
304 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
305 if (InValPhi && InValPhi->getParent() == BB) {
306 // Add all of the input values of the input PHI as inputs of this phi.
307 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
308 PN->addIncoming(InValPhi->getIncomingValue(i),
309 InValPhi->getIncomingBlock(i));
310 } else {
311 // Otherwise, add one instance of the dominating value for each edge that
312 // we will be adding.
313 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
314 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
315 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
316 } else {
317 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
318 PN->addIncoming(InVal, *PI);
319 }
320 }
321 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000322
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000323 // The PHIs are now updated, change everything that refers to BB to use
324 // DestBB and remove BB.
325 BB->replaceAllUsesWith(DestBB);
Cameron Zwarich80f6a502011-01-08 17:01:52 +0000326 if (DT) {
327 BasicBlock *BBIDom = DT->getNode(BB)->getIDom()->getBlock();
328 BasicBlock *DestBBIDom = DT->getNode(DestBB)->getIDom()->getBlock();
329 BasicBlock *NewIDom = DT->findNearestCommonDominator(BBIDom, DestBBIDom);
330 DT->changeImmediateDominator(DestBB, NewIDom);
331 DT->eraseNode(BB);
332 }
Evan Cheng04149f72009-12-17 09:39:49 +0000333 if (PFI) {
334 PFI->replaceAllUses(BB, DestBB);
335 PFI->removeEdge(ProfileInfo::getEdge(BB, DestBB));
Andreas Neustifterad809812009-09-16 09:26:52 +0000336 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000337 BB->eraseFromParent();
Cameron Zwarich31ff1332011-01-05 17:27:27 +0000338 ++NumBlocksElim;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000339
David Greene68d67fd2010-01-05 01:27:11 +0000340 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000341}
342
Chris Lattnerdd77df32007-04-13 20:30:56 +0000343/// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
Dan Gohmana119de82009-06-14 23:30:43 +0000344/// copy (e.g. it's casting from one pointer type to another, i32->i8 on PPC),
345/// sink it into user blocks to reduce the number of virtual
Dale Johannesence0b2372007-06-12 16:50:17 +0000346/// registers that must be created and coalesced.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000347///
348/// Return true if any changes are made.
Chris Lattner85fa13c2008-11-24 22:44:16 +0000349///
Chris Lattnerdd77df32007-04-13 20:30:56 +0000350static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
Eric Christopher692bf6b2008-09-24 05:32:41 +0000351 // If this is a noop copy,
Owen Andersone50ed302009-08-10 22:56:29 +0000352 EVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
353 EVT DstVT = TLI.getValueType(CI->getType());
Eric Christopher692bf6b2008-09-24 05:32:41 +0000354
Chris Lattnerdd77df32007-04-13 20:30:56 +0000355 // This is an fp<->int conversion?
Duncan Sands83ec4b62008-06-06 12:08:01 +0000356 if (SrcVT.isInteger() != DstVT.isInteger())
Chris Lattnerdd77df32007-04-13 20:30:56 +0000357 return false;
Duncan Sands8e4eb092008-06-08 20:54:56 +0000358
Chris Lattnerdd77df32007-04-13 20:30:56 +0000359 // If this is an extension, it will be a zero or sign extension, which
360 // isn't a noop.
Duncan Sands8e4eb092008-06-08 20:54:56 +0000361 if (SrcVT.bitsLT(DstVT)) return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000362
Chris Lattnerdd77df32007-04-13 20:30:56 +0000363 // If these values will be promoted, find out what they will be promoted
364 // to. This helps us consider truncates on PPC as noop copies when they
365 // are.
Chris Lattneraafe6262010-08-25 23:00:45 +0000366 if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote)
Owen Anderson23b9b192009-08-12 00:36:31 +0000367 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
Chris Lattneraafe6262010-08-25 23:00:45 +0000368 if (TLI.getTypeAction(DstVT) == TargetLowering::Promote)
Owen Anderson23b9b192009-08-12 00:36:31 +0000369 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000370
Chris Lattnerdd77df32007-04-13 20:30:56 +0000371 // If, after promotion, these are the same types, this is a noop copy.
372 if (SrcVT != DstVT)
373 return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000374
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000375 BasicBlock *DefBB = CI->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000376
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000377 /// InsertedCasts - Only insert a cast in each block once.
Dale Johannesence0b2372007-06-12 16:50:17 +0000378 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000379
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000380 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000381 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000382 UI != E; ) {
383 Use &TheUse = UI.getUse();
384 Instruction *User = cast<Instruction>(*UI);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000385
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000386 // Figure out which BB this cast is used in. For PHI's this is the
387 // appropriate predecessor block.
388 BasicBlock *UserBB = User->getParent();
389 if (PHINode *PN = dyn_cast<PHINode>(User)) {
Gabor Greifa36791d2009-01-23 19:40:15 +0000390 UserBB = PN->getIncomingBlock(UI);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000391 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000392
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000393 // Preincrement use iterator so we don't invalidate it.
394 ++UI;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000395
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000396 // If this user is in the same block as the cast, don't change the cast.
397 if (UserBB == DefBB) continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000398
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000399 // If we have already inserted a cast into this block, use it.
400 CastInst *&InsertedCast = InsertedCasts[UserBB];
401
402 if (!InsertedCast) {
Dan Gohman02dea8b2008-05-23 21:05:58 +0000403 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000404
405 InsertedCast =
406 CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000407 InsertPt);
408 MadeChange = true;
409 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000410
Dale Johannesence0b2372007-06-12 16:50:17 +0000411 // Replace a use of the cast with a use of the new cast.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000412 TheUse = InsertedCast;
Cameron Zwarich31ff1332011-01-05 17:27:27 +0000413 ++NumCastUses;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000414 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000415
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000416 // If we removed all uses, nuke the cast.
Duncan Sandse0038132008-01-20 16:51:46 +0000417 if (CI->use_empty()) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000418 CI->eraseFromParent();
Duncan Sandse0038132008-01-20 16:51:46 +0000419 MadeChange = true;
420 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000421
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000422 return MadeChange;
423}
424
Eric Christopher692bf6b2008-09-24 05:32:41 +0000425/// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
Dale Johannesence0b2372007-06-12 16:50:17 +0000426/// the number of virtual registers that must be created and coalesced. This is
Chris Lattner684b22d2007-08-02 16:53:43 +0000427/// a clear win except on targets with multiple condition code registers
428/// (PowerPC), where it might lose; some adjustment may be wanted there.
Dale Johannesence0b2372007-06-12 16:50:17 +0000429///
430/// Return true if any changes are made.
Chris Lattner85fa13c2008-11-24 22:44:16 +0000431static bool OptimizeCmpExpression(CmpInst *CI) {
Dale Johannesence0b2372007-06-12 16:50:17 +0000432 BasicBlock *DefBB = CI->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000433
Dale Johannesence0b2372007-06-12 16:50:17 +0000434 /// InsertedCmp - Only insert a cmp in each block once.
435 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000436
Dale Johannesence0b2372007-06-12 16:50:17 +0000437 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000438 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
Dale Johannesence0b2372007-06-12 16:50:17 +0000439 UI != E; ) {
440 Use &TheUse = UI.getUse();
441 Instruction *User = cast<Instruction>(*UI);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000442
Dale Johannesence0b2372007-06-12 16:50:17 +0000443 // Preincrement use iterator so we don't invalidate it.
444 ++UI;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000445
Dale Johannesence0b2372007-06-12 16:50:17 +0000446 // Don't bother for PHI nodes.
447 if (isa<PHINode>(User))
448 continue;
449
450 // Figure out which BB this cmp is used in.
451 BasicBlock *UserBB = User->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000452
Dale Johannesence0b2372007-06-12 16:50:17 +0000453 // If this user is in the same block as the cmp, don't change the cmp.
454 if (UserBB == DefBB) continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000455
Dale Johannesence0b2372007-06-12 16:50:17 +0000456 // If we have already inserted a cmp into this block, use it.
457 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
458
459 if (!InsertedCmp) {
Dan Gohman02dea8b2008-05-23 21:05:58 +0000460 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000461
462 InsertedCmp =
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000463 CmpInst::Create(CI->getOpcode(),
Owen Anderson333c4002009-07-09 23:48:35 +0000464 CI->getPredicate(), CI->getOperand(0),
Dale Johannesence0b2372007-06-12 16:50:17 +0000465 CI->getOperand(1), "", InsertPt);
466 MadeChange = true;
467 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000468
Dale Johannesence0b2372007-06-12 16:50:17 +0000469 // Replace a use of the cmp with a use of the new cmp.
470 TheUse = InsertedCmp;
Cameron Zwarich31ff1332011-01-05 17:27:27 +0000471 ++NumCmpUses;
Dale Johannesence0b2372007-06-12 16:50:17 +0000472 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000473
Dale Johannesence0b2372007-06-12 16:50:17 +0000474 // If we removed all uses, nuke the cmp.
475 if (CI->use_empty())
476 CI->eraseFromParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000477
Dale Johannesence0b2372007-06-12 16:50:17 +0000478 return MadeChange;
479}
480
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000481namespace {
482class CodeGenPrepareFortifiedLibCalls : public SimplifyFortifiedLibCalls {
483protected:
484 void replaceCall(Value *With) {
485 CI->replaceAllUsesWith(With);
486 CI->eraseFromParent();
487 }
488 bool isFoldable(unsigned SizeCIOp, unsigned, bool) const {
Gabor Greifa6aac4c2010-07-16 09:38:02 +0000489 if (ConstantInt *SizeCI =
490 dyn_cast<ConstantInt>(CI->getArgOperand(SizeCIOp)))
491 return SizeCI->isAllOnesValue();
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000492 return false;
493 }
494};
495} // end anonymous namespace
496
Eric Christopher040056f2010-03-11 02:41:03 +0000497bool CodeGenPrepare::OptimizeCallInst(CallInst *CI) {
Chris Lattner75796092011-01-15 07:14:54 +0000498 BasicBlock *BB = CI->getParent();
499
500 // Lower inline assembly if we can.
501 // If we found an inline asm expession, and if the target knows how to
502 // lower it to normal LLVM code, do so now.
503 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
504 if (TLI->ExpandInlineAsm(CI)) {
505 // Avoid invalidating the iterator.
506 CurInstIterator = BB->begin();
507 // Avoid processing instructions out of order, which could cause
508 // reuse before a value is defined.
509 SunkAddrs.clear();
510 return true;
511 }
512 // Sink address computing for memory operands into the block.
513 if (OptimizeInlineAsmInst(CI))
514 return true;
515 }
516
Eric Christopher040056f2010-03-11 02:41:03 +0000517 // Lower all uses of llvm.objectsize.*
518 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
519 if (II && II->getIntrinsicID() == Intrinsic::objectsize) {
Gabor Greifde9f5452010-06-24 00:44:01 +0000520 bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
Eric Christopher040056f2010-03-11 02:41:03 +0000521 const Type *ReturnTy = CI->getType();
522 Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
Chris Lattner94e8e0c2011-01-15 07:25:29 +0000523
524 // Substituting this can cause recursive simplifications, which can
525 // invalidate our iterator. Use a WeakVH to hold onto it in case this
526 // happens.
527 WeakVH IterHandle(CurInstIterator);
528
529 ReplaceAndSimplifyAllUses(CI, RetVal, TLI ? TLI->getTargetData() : 0, DT);
530
531 // If the iterator instruction was recursively deleted, start over at the
532 // start of the block.
Chris Lattner435b4d22011-01-18 20:53:04 +0000533 if (IterHandle != CurInstIterator) {
Chris Lattner94e8e0c2011-01-15 07:25:29 +0000534 CurInstIterator = BB->begin();
Chris Lattner435b4d22011-01-18 20:53:04 +0000535 SunkAddrs.clear();
536 }
Eric Christopher040056f2010-03-11 02:41:03 +0000537 return true;
538 }
539
540 // From here on out we're working with named functions.
541 if (CI->getCalledFunction() == 0) return false;
542
543 // We'll need TargetData from here on out.
544 const TargetData *TD = TLI ? TLI->getTargetData() : 0;
545 if (!TD) return false;
546
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000547 // Lower all default uses of _chk calls. This is very similar
548 // to what InstCombineCalls does, but here we are only lowering calls
Eric Christopher040056f2010-03-11 02:41:03 +0000549 // that have the default "don't know" as the objectsize. Anything else
550 // should be left alone.
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000551 CodeGenPrepareFortifiedLibCalls Simplifier;
552 return Simplifier.fold(CI, TD);
Eric Christopher040056f2010-03-11 02:41:03 +0000553}
Chris Lattner94e8e0c2011-01-15 07:25:29 +0000554
Chris Lattner88a5c832008-11-25 07:09:13 +0000555//===----------------------------------------------------------------------===//
Chris Lattner88a5c832008-11-25 07:09:13 +0000556// Memory Optimization
557//===----------------------------------------------------------------------===//
558
Chris Lattnerdd77df32007-04-13 20:30:56 +0000559/// IsNonLocalValue - Return true if the specified values are defined in a
560/// different basic block than BB.
561static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
562 if (Instruction *I = dyn_cast<Instruction>(V))
563 return I->getParent() != BB;
564 return false;
565}
566
Bob Wilson4a8ee232009-12-03 21:47:07 +0000567/// OptimizeMemoryInst - Load and Store Instructions often have
Chris Lattnerdd77df32007-04-13 20:30:56 +0000568/// addressing modes that can do significant amounts of computation. As such,
569/// instruction selection will try to get the load or store to do as much
570/// computation as possible for the program. The problem is that isel can only
571/// see within a single block. As such, we sink as much legal addressing mode
572/// stuff into the block as possible.
Chris Lattner88a5c832008-11-25 07:09:13 +0000573///
574/// This method is used to optimize both load/store and inline asms with memory
575/// operands.
Chris Lattner896617b2008-11-26 03:20:37 +0000576bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
Chris Lattner1a8943a2011-01-15 07:29:01 +0000577 const Type *AccessTy) {
Owen Anderson35bf4d62010-11-27 08:15:55 +0000578 Value *Repl = Addr;
579
Owen Andersond2f41742010-11-19 22:15:03 +0000580 // Try to collapse single-value PHI nodes. This is necessary to undo
581 // unprofitable PRE transformations.
Cameron Zwarich7cb4fa22011-01-03 06:33:01 +0000582 SmallVector<Value*, 8> worklist;
583 SmallPtrSet<Value*, 16> Visited;
Owen Anderson35bf4d62010-11-27 08:15:55 +0000584 worklist.push_back(Addr);
585
586 // Use a worklist to iteratively look through PHI nodes, and ensure that
587 // the addressing mode obtained from the non-PHI roots of the graph
588 // are equivalent.
589 Value *Consensus = 0;
Cameron Zwarich4c078f02011-03-01 21:13:53 +0000590 unsigned NumUsesConsensus = 0;
Owen Anderson35bf4d62010-11-27 08:15:55 +0000591 SmallVector<Instruction*, 16> AddrModeInsts;
592 ExtAddrMode AddrMode;
593 while (!worklist.empty()) {
594 Value *V = worklist.back();
595 worklist.pop_back();
596
597 // Break use-def graph loops.
598 if (Visited.count(V)) {
599 Consensus = 0;
600 break;
Owen Andersond2f41742010-11-19 22:15:03 +0000601 }
602
Owen Anderson35bf4d62010-11-27 08:15:55 +0000603 Visited.insert(V);
604
605 // For a PHI node, push all of its incoming values.
606 if (PHINode *P = dyn_cast<PHINode>(V)) {
607 for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i)
608 worklist.push_back(P->getIncomingValue(i));
609 continue;
610 }
611
612 // For non-PHIs, determine the addressing mode being computed.
613 SmallVector<Instruction*, 16> NewAddrModeInsts;
614 ExtAddrMode NewAddrMode =
615 AddressingModeMatcher::Match(V, AccessTy,MemoryInst,
616 NewAddrModeInsts, *TLI);
617
618 // Ensure that the obtained addressing mode is equivalent to that obtained
619 // for all other roots of the PHI traversal. Also, when choosing one
620 // such root as representative, select the one with the most uses in order
621 // to keep the cost modeling heuristics in AddressingModeMatcher applicable.
622 if (!Consensus || NewAddrMode == AddrMode) {
Cameron Zwarich4c078f02011-03-01 21:13:53 +0000623 unsigned NumUses = V->getNumUses();
624 if (NumUses > NumUsesConsensus) {
Owen Anderson35bf4d62010-11-27 08:15:55 +0000625 Consensus = V;
Cameron Zwarich4c078f02011-03-01 21:13:53 +0000626 NumUsesConsensus = NumUses;
Owen Anderson35bf4d62010-11-27 08:15:55 +0000627 AddrMode = NewAddrMode;
628 AddrModeInsts = NewAddrModeInsts;
629 }
630 continue;
631 }
632
633 Consensus = 0;
634 break;
Owen Andersond2f41742010-11-19 22:15:03 +0000635 }
636
Owen Anderson35bf4d62010-11-27 08:15:55 +0000637 // If the addressing mode couldn't be determined, or if multiple different
638 // ones were determined, bail out now.
639 if (!Consensus) return false;
640
Chris Lattnerdd77df32007-04-13 20:30:56 +0000641 // Check to see if any of the instructions supersumed by this addr mode are
642 // non-local to I's BB.
643 bool AnyNonLocal = false;
644 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
Chris Lattner896617b2008-11-26 03:20:37 +0000645 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
Chris Lattnerdd77df32007-04-13 20:30:56 +0000646 AnyNonLocal = true;
647 break;
648 }
649 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000650
Chris Lattnerdd77df32007-04-13 20:30:56 +0000651 // If all the instructions matched are already in this BB, don't do anything.
652 if (!AnyNonLocal) {
David Greene68d67fd2010-01-05 01:27:11 +0000653 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000654 return false;
655 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000656
Chris Lattnerdd77df32007-04-13 20:30:56 +0000657 // Insert this computation right after this user. Since our caller is
658 // scanning from the top of the BB to the bottom, reuse of the expr are
659 // guaranteed to happen later.
Chris Lattner896617b2008-11-26 03:20:37 +0000660 BasicBlock::iterator InsertPt = MemoryInst;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000661
Chris Lattnerdd77df32007-04-13 20:30:56 +0000662 // Now that we determined the addressing expression we want to use and know
663 // that we have to sink it into this block. Check to see if we have already
664 // done this for some other load/store instr in this block. If so, reuse the
665 // computation.
666 Value *&SunkAddr = SunkAddrs[Addr];
667 if (SunkAddr) {
David Greene68d67fd2010-01-05 01:27:11 +0000668 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
Dan Gohman6c1980b2009-07-25 01:13:51 +0000669 << *MemoryInst);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000670 if (SunkAddr->getType() != Addr->getType())
671 SunkAddr = new BitCastInst(SunkAddr, Addr->getType(), "tmp", InsertPt);
672 } else {
David Greene68d67fd2010-01-05 01:27:11 +0000673 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Dan Gohman6c1980b2009-07-25 01:13:51 +0000674 << *MemoryInst);
Owen Anderson1d0be152009-08-13 21:58:54 +0000675 const Type *IntPtrTy =
676 TLI->getTargetData()->getIntPtrType(AccessTy->getContext());
Eric Christopher692bf6b2008-09-24 05:32:41 +0000677
Chris Lattnerdd77df32007-04-13 20:30:56 +0000678 Value *Result = 0;
Dan Gohmand8d0b6a2010-01-19 22:45:06 +0000679
680 // Start with the base register. Do this first so that subsequent address
681 // matching finds it last, which will prevent it from trying to match it
682 // as the scaled value in case it happens to be a mul. That would be
683 // problematic if we've sunk a different mul for the scale, because then
684 // we'd end up sinking both muls.
685 if (AddrMode.BaseReg) {
686 Value *V = AddrMode.BaseReg;
Duncan Sands1df98592010-02-16 11:11:14 +0000687 if (V->getType()->isPointerTy())
Dan Gohmand8d0b6a2010-01-19 22:45:06 +0000688 V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
689 if (V->getType() != IntPtrTy)
690 V = CastInst::CreateIntegerCast(V, IntPtrTy, /*isSigned=*/true,
691 "sunkaddr", InsertPt);
692 Result = V;
693 }
694
695 // Add the scale value.
Chris Lattnerdd77df32007-04-13 20:30:56 +0000696 if (AddrMode.Scale) {
697 Value *V = AddrMode.ScaledReg;
698 if (V->getType() == IntPtrTy) {
699 // done.
Duncan Sands1df98592010-02-16 11:11:14 +0000700 } else if (V->getType()->isPointerTy()) {
Chris Lattnerdd77df32007-04-13 20:30:56 +0000701 V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
702 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
703 cast<IntegerType>(V->getType())->getBitWidth()) {
704 V = new TruncInst(V, IntPtrTy, "sunkaddr", InsertPt);
705 } else {
706 V = new SExtInst(V, IntPtrTy, "sunkaddr", InsertPt);
707 }
708 if (AddrMode.Scale != 1)
Owen Andersoneed707b2009-07-24 23:12:02 +0000709 V = BinaryOperator::CreateMul(V, ConstantInt::get(IntPtrTy,
Owen Andersond672ecb2009-07-03 00:17:18 +0000710 AddrMode.Scale),
Chris Lattnerdd77df32007-04-13 20:30:56 +0000711 "sunkaddr", InsertPt);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000712 if (Result)
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000713 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000714 else
715 Result = V;
716 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000717
Chris Lattnerdd77df32007-04-13 20:30:56 +0000718 // Add in the BaseGV if present.
719 if (AddrMode.BaseGV) {
720 Value *V = new PtrToIntInst(AddrMode.BaseGV, IntPtrTy, "sunkaddr",
721 InsertPt);
722 if (Result)
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000723 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000724 else
725 Result = V;
726 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000727
Chris Lattnerdd77df32007-04-13 20:30:56 +0000728 // Add in the Base Offset if present.
729 if (AddrMode.BaseOffs) {
Owen Andersoneed707b2009-07-24 23:12:02 +0000730 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000731 if (Result)
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000732 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000733 else
734 Result = V;
735 }
736
737 if (Result == 0)
Owen Andersona7235ea2009-07-31 20:28:14 +0000738 SunkAddr = Constant::getNullValue(Addr->getType());
Chris Lattnerdd77df32007-04-13 20:30:56 +0000739 else
740 SunkAddr = new IntToPtrInst(Result, Addr->getType(), "sunkaddr",InsertPt);
741 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000742
Owen Andersond2f41742010-11-19 22:15:03 +0000743 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000744
Owen Andersond2f41742010-11-19 22:15:03 +0000745 if (Repl->use_empty()) {
746 RecursivelyDeleteTriviallyDeadInstructions(Repl);
Dale Johannesen536d31b2010-03-31 20:37:15 +0000747 // This address is now available for reassignment, so erase the table entry;
748 // we don't want to match some completely different instruction.
749 SunkAddrs[Addr] = 0;
750 }
Cameron Zwarich31ff1332011-01-05 17:27:27 +0000751 ++NumMemoryInsts;
Chris Lattnerdd77df32007-04-13 20:30:56 +0000752 return true;
753}
754
Evan Cheng9bf12b52008-02-26 02:42:37 +0000755/// OptimizeInlineAsmInst - If there are any memory operands, use
Chris Lattner88a5c832008-11-25 07:09:13 +0000756/// OptimizeMemoryInst to sink their address computing into the block when
Evan Cheng9bf12b52008-02-26 02:42:37 +0000757/// possible / profitable.
Chris Lattner75796092011-01-15 07:14:54 +0000758bool CodeGenPrepare::OptimizeInlineAsmInst(CallInst *CS) {
Evan Cheng9bf12b52008-02-26 02:42:37 +0000759 bool MadeChange = false;
Evan Cheng9bf12b52008-02-26 02:42:37 +0000760
Chris Lattner75796092011-01-15 07:14:54 +0000761 TargetLowering::AsmOperandInfoVector
762 TargetConstraints = TLI->ParseConstraints(CS);
Dale Johannesen677c6ec2010-09-16 18:30:55 +0000763 unsigned ArgNo = 0;
John Thompsoneac6e1d2010-09-13 18:15:37 +0000764 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
765 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
766
Evan Cheng9bf12b52008-02-26 02:42:37 +0000767 // Compute the constraint code and ConstraintType to use.
Dale Johannesen1784d162010-06-25 21:55:36 +0000768 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Evan Cheng9bf12b52008-02-26 02:42:37 +0000769
Eli Friedman9ec80952008-02-26 18:37:49 +0000770 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
771 OpInfo.isIndirect) {
Chris Lattner75796092011-01-15 07:14:54 +0000772 Value *OpVal = CS->getArgOperand(ArgNo++);
Chris Lattner1a8943a2011-01-15 07:29:01 +0000773 MadeChange |= OptimizeMemoryInst(CS, OpVal, OpVal->getType());
Dale Johannesen677c6ec2010-09-16 18:30:55 +0000774 } else if (OpInfo.Type == InlineAsm::isInput)
775 ArgNo++;
Evan Cheng9bf12b52008-02-26 02:42:37 +0000776 }
777
778 return MadeChange;
779}
780
Dan Gohmanb00f2362009-10-16 20:59:35 +0000781/// MoveExtToFormExtLoad - Move a zext or sext fed by a load into the same
782/// basic block as the load, unless conditions are unfavorable. This allows
783/// SelectionDAG to fold the extend into the load.
784///
785bool CodeGenPrepare::MoveExtToFormExtLoad(Instruction *I) {
786 // Look for a load being extended.
787 LoadInst *LI = dyn_cast<LoadInst>(I->getOperand(0));
788 if (!LI) return false;
789
790 // If they're already in the same block, there's nothing to do.
791 if (LI->getParent() == I->getParent())
792 return false;
793
794 // If the load has other users and the truncate is not free, this probably
795 // isn't worthwhile.
796 if (!LI->hasOneUse() &&
Bob Wilsonec57a1a2010-09-22 18:44:56 +0000797 TLI && (TLI->isTypeLegal(TLI->getValueType(LI->getType())) ||
798 !TLI->isTypeLegal(TLI->getValueType(I->getType()))) &&
Bob Wilson71dc4d92010-09-21 21:54:27 +0000799 !TLI->isTruncateFree(I->getType(), LI->getType()))
Dan Gohmanb00f2362009-10-16 20:59:35 +0000800 return false;
801
802 // Check whether the target supports casts folded into loads.
803 unsigned LType;
804 if (isa<ZExtInst>(I))
805 LType = ISD::ZEXTLOAD;
806 else {
807 assert(isa<SExtInst>(I) && "Unexpected ext type!");
808 LType = ISD::SEXTLOAD;
809 }
810 if (TLI && !TLI->isLoadExtLegal(LType, TLI->getValueType(LI->getType())))
811 return false;
812
813 // Move the extend into the same block as the load, so that SelectionDAG
814 // can fold it.
815 I->removeFromParent();
816 I->insertAfter(LI);
Cameron Zwarich31ff1332011-01-05 17:27:27 +0000817 ++NumExtsMoved;
Dan Gohmanb00f2362009-10-16 20:59:35 +0000818 return true;
819}
820
Evan Chengbdcb7262007-12-05 23:58:20 +0000821bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
822 BasicBlock *DefBB = I->getParent();
823
Bob Wilson9120f5c2010-09-21 21:44:14 +0000824 // If the result of a {s|z}ext and its source are both live out, rewrite all
Evan Chengbdcb7262007-12-05 23:58:20 +0000825 // other uses of the source with result of extension.
826 Value *Src = I->getOperand(0);
827 if (Src->hasOneUse())
828 return false;
829
Evan Cheng696e5c02007-12-13 07:50:36 +0000830 // Only do this xform if truncating is free.
Gabor Greif53bdbd72008-02-26 19:13:21 +0000831 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
Evan Chengf9785f92007-12-13 03:32:53 +0000832 return false;
833
Evan Cheng772de512007-12-12 00:51:06 +0000834 // Only safe to perform the optimization if the source is also defined in
Evan Cheng765dff22007-12-12 02:53:41 +0000835 // this block.
836 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
Evan Cheng772de512007-12-12 00:51:06 +0000837 return false;
838
Evan Chengbdcb7262007-12-05 23:58:20 +0000839 bool DefIsLiveOut = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000840 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
Evan Chengbdcb7262007-12-05 23:58:20 +0000841 UI != E; ++UI) {
842 Instruction *User = cast<Instruction>(*UI);
843
844 // Figure out which BB this ext is used in.
845 BasicBlock *UserBB = User->getParent();
846 if (UserBB == DefBB) continue;
847 DefIsLiveOut = true;
848 break;
849 }
850 if (!DefIsLiveOut)
851 return false;
852
Evan Cheng765dff22007-12-12 02:53:41 +0000853 // Make sure non of the uses are PHI nodes.
Eric Christopher692bf6b2008-09-24 05:32:41 +0000854 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
Evan Cheng765dff22007-12-12 02:53:41 +0000855 UI != E; ++UI) {
856 Instruction *User = cast<Instruction>(*UI);
Evan Chengf9785f92007-12-13 03:32:53 +0000857 BasicBlock *UserBB = User->getParent();
858 if (UserBB == DefBB) continue;
859 // Be conservative. We don't want this xform to end up introducing
860 // reloads just before load / store instructions.
861 if (isa<PHINode>(User) || isa<LoadInst>(User) || isa<StoreInst>(User))
Evan Cheng765dff22007-12-12 02:53:41 +0000862 return false;
863 }
864
Evan Chengbdcb7262007-12-05 23:58:20 +0000865 // InsertedTruncs - Only insert one trunc in each block once.
866 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
867
868 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000869 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
Evan Chengbdcb7262007-12-05 23:58:20 +0000870 UI != E; ++UI) {
871 Use &TheUse = UI.getUse();
872 Instruction *User = cast<Instruction>(*UI);
873
874 // Figure out which BB this ext is used in.
875 BasicBlock *UserBB = User->getParent();
876 if (UserBB == DefBB) continue;
877
878 // Both src and def are live in this block. Rewrite the use.
879 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
880
881 if (!InsertedTrunc) {
Dan Gohman02dea8b2008-05-23 21:05:58 +0000882 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000883
Evan Chengbdcb7262007-12-05 23:58:20 +0000884 InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
885 }
886
887 // Replace a use of the {s|z}ext source with a use of the result.
888 TheUse = InsertedTrunc;
Cameron Zwarich31ff1332011-01-05 17:27:27 +0000889 ++NumExtUses;
Evan Chengbdcb7262007-12-05 23:58:20 +0000890 MadeChange = true;
891 }
892
893 return MadeChange;
894}
895
Cameron Zwarichc0611012011-01-06 02:37:26 +0000896bool CodeGenPrepare::OptimizeInst(Instruction *I) {
Cameron Zwarichc0611012011-01-06 02:37:26 +0000897 if (PHINode *P = dyn_cast<PHINode>(I)) {
898 // It is possible for very late stage optimizations (such as SimplifyCFG)
899 // to introduce PHI nodes too late to be cleaned up. If we detect such a
900 // trivial PHI, go ahead and zap it here.
901 if (Value *V = SimplifyInstruction(P)) {
902 P->replaceAllUsesWith(V);
903 P->eraseFromParent();
904 ++NumPHIsElim;
Chris Lattner1a8943a2011-01-15 07:29:01 +0000905 return true;
Cameron Zwarichc0611012011-01-06 02:37:26 +0000906 }
Chris Lattner1a8943a2011-01-15 07:29:01 +0000907 return false;
908 }
909
910 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Cameron Zwarichc0611012011-01-06 02:37:26 +0000911 // If the source of the cast is a constant, then this should have
912 // already been constant folded. The only reason NOT to constant fold
913 // it is if something (e.g. LSR) was careful to place the constant
914 // evaluation in a block other than then one that uses it (e.g. to hoist
915 // the address of globals out of a loop). If this is the case, we don't
916 // want to forward-subst the cast.
917 if (isa<Constant>(CI->getOperand(0)))
918 return false;
919
Chris Lattner1a8943a2011-01-15 07:29:01 +0000920 if (TLI && OptimizeNoopCopyExpression(CI, *TLI))
921 return true;
Cameron Zwarichc0611012011-01-06 02:37:26 +0000922
Chris Lattner1a8943a2011-01-15 07:29:01 +0000923 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
924 bool MadeChange = MoveExtToFormExtLoad(I);
925 return MadeChange | OptimizeExtUses(I);
Cameron Zwarichc0611012011-01-06 02:37:26 +0000926 }
Chris Lattner1a8943a2011-01-15 07:29:01 +0000927 return false;
928 }
929
930 if (CmpInst *CI = dyn_cast<CmpInst>(I))
931 return OptimizeCmpExpression(CI);
932
933 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Cameron Zwarichc0611012011-01-06 02:37:26 +0000934 if (TLI)
Chris Lattner1a8943a2011-01-15 07:29:01 +0000935 return OptimizeMemoryInst(I, I->getOperand(0), LI->getType());
936 return false;
937 }
938
939 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Cameron Zwarichc0611012011-01-06 02:37:26 +0000940 if (TLI)
Chris Lattner1a8943a2011-01-15 07:29:01 +0000941 return OptimizeMemoryInst(I, SI->getOperand(1),
942 SI->getOperand(0)->getType());
943 return false;
944 }
945
946 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Cameron Zwarich865ae1a2011-01-06 02:44:52 +0000947 if (GEPI->hasAllZeroIndices()) {
948 /// The GEP operand must be a pointer, so must its result -> BitCast
949 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
950 GEPI->getName(), GEPI);
951 GEPI->replaceAllUsesWith(NC);
952 GEPI->eraseFromParent();
953 ++NumGEPsElim;
Cameron Zwarich865ae1a2011-01-06 02:44:52 +0000954 OptimizeInst(NC);
Chris Lattner1a8943a2011-01-15 07:29:01 +0000955 return true;
Cameron Zwarich865ae1a2011-01-06 02:44:52 +0000956 }
Chris Lattner1a8943a2011-01-15 07:29:01 +0000957 return false;
Cameron Zwarichc0611012011-01-06 02:37:26 +0000958 }
Chris Lattner1a8943a2011-01-15 07:29:01 +0000959
960 if (CallInst *CI = dyn_cast<CallInst>(I))
961 return OptimizeCallInst(CI);
Cameron Zwarichc0611012011-01-06 02:37:26 +0000962
Chris Lattner1a8943a2011-01-15 07:29:01 +0000963 return false;
Cameron Zwarichc0611012011-01-06 02:37:26 +0000964}
965
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000966// In this pass we look for GEP and cast instructions that are used
967// across basic blocks and rewrite them to improve basic-block-at-a-time
968// selection.
969bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
Cameron Zwarich8c3527e2011-01-06 00:42:50 +0000970 SunkAddrs.clear();
Cameron Zwarich56e37932011-03-02 03:31:46 +0000971 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000972
Chris Lattner75796092011-01-15 07:14:54 +0000973 CurInstIterator = BB.begin();
Chris Lattner94e8e0c2011-01-15 07:25:29 +0000974 for (BasicBlock::iterator E = BB.end(); CurInstIterator != E; )
975 MadeChange |= OptimizeInst(CurInstIterator++);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000976
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000977 return MadeChange;
978}