blob: e3e634339e2be41cbb02842daf41afcb4f29c890 [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"
Owen Andersond5f86842010-12-23 20:57:35 +000025#include "llvm/Analysis/InstructionSimplify.h"
Andreas Neustifterad809812009-09-16 09:26:52 +000026#include "llvm/Analysis/ProfileInfo.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000027#include "llvm/Target/TargetData.h"
28#include "llvm/Target/TargetLowering.h"
Evan Chenga1fd5b32009-02-20 18:24:38 +000029#include "llvm/Transforms/Utils/AddrModeMatcher.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000030#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattnerdd77df32007-04-13 20:30:56 +000031#include "llvm/Transforms/Utils/Local.h"
Eric Christopher040056f2010-03-11 02:41:03 +000032#include "llvm/Transforms/Utils/BuildLibCalls.h"
Chris Lattnerdd77df32007-04-13 20:30:56 +000033#include "llvm/ADT/DenseMap.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000034#include "llvm/ADT/SmallSet.h"
Jakob Stoklund Olesen7eb589d2010-09-30 20:51:52 +000035#include "llvm/ADT/Statistic.h"
Dan Gohman03ce0422009-02-13 17:45:12 +000036#include "llvm/Assembly/Writer.h"
Evan Cheng9bf12b52008-02-26 02:42:37 +000037#include "llvm/Support/CallSite.h"
Evan Chenge1bcb442010-08-17 01:34:49 +000038#include "llvm/Support/CommandLine.h"
Evan Chengbdcb7262007-12-05 23:58:20 +000039#include "llvm/Support/Debug.h"
Chris Lattnerdd77df32007-04-13 20:30:56 +000040#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner088a1e82008-11-25 04:42:10 +000041#include "llvm/Support/PatternMatch.h"
Dan Gohman6c1980b2009-07-25 01:13:51 +000042#include "llvm/Support/raw_ostream.h"
Eric Christopher040056f2010-03-11 02:41:03 +000043#include "llvm/Support/IRBuilder.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000044using namespace llvm;
Chris Lattner088a1e82008-11-25 04:42:10 +000045using namespace llvm::PatternMatch;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000046
Cameron Zwarich31ff1332011-01-05 17:27:27 +000047STATISTIC(NumBlocksElim, "Number of blocks eliminated");
Cameron Zwarich073057f2011-01-05 17:47:38 +000048STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated");
49STATISTIC(NumGEPsElim, "Number of GEPs converted to casts");
Cameron Zwarich31ff1332011-01-05 17:27:27 +000050STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "
51 "sunken Cmps");
52STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
53 "of sunken Casts");
54STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "
55 "computations were sunk");
56STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads");
57STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized");
Jakob Stoklund Olesen7eb589d2010-09-30 20:51:52 +000058
Evan Chenge1bcb442010-08-17 01:34:49 +000059static cl::opt<bool>
60CriticalEdgeSplit("cgp-critical-edge-splitting",
61 cl::desc("Split critical edges during codegen prepare"),
Jakob Stoklund Olesen7eb589d2010-09-30 20:51:52 +000062 cl::init(false), cl::Hidden);
Evan Chenge1bcb442010-08-17 01:34:49 +000063
Eric Christopher692bf6b2008-09-24 05:32:41 +000064namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +000065 class CodeGenPrepare : public FunctionPass {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000066 /// TLI - Keep a pointer of a TargetLowering to consult for determining
67 /// transformation profitability.
68 const TargetLowering *TLI;
Evan Cheng04149f72009-12-17 09:39:49 +000069 ProfileInfo *PFI;
Evan Chengab631522008-12-19 18:03:11 +000070
71 /// BackEdges - Keep a set of all the loop back edges.
72 ///
Mike Stumpfe095f32009-05-04 18:40:41 +000073 SmallSet<std::pair<const BasicBlock*, const BasicBlock*>, 8> BackEdges;
Cameron Zwarich8c3527e2011-01-06 00:42:50 +000074
75 // Keeps track of non-local addresses that have been sunk into a block. This
76 // allows us to avoid inserting duplicate code for blocks with multiple
77 // load/stores of the same address.
78 DenseMap<Value*, Value*> SunkAddrs;
79
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000080 public:
Nick Lewyckyecd94c82007-05-06 13:37:16 +000081 static char ID; // Pass identification, replacement for typeid
Dan Gohmanc2bbfc12007-08-01 15:32:29 +000082 explicit CodeGenPrepare(const TargetLowering *tli = 0)
Owen Anderson081c34b2010-10-19 17:21:58 +000083 : FunctionPass(ID), TLI(tli) {
84 initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
85 }
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000086 bool runOnFunction(Function &F);
Eric Christopher692bf6b2008-09-24 05:32:41 +000087
Andreas Neustifterad809812009-09-16 09:26:52 +000088 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
89 AU.addPreserved<ProfileInfo>();
90 }
91
Dan Gohmanaa0e5232010-02-05 19:24:11 +000092 virtual void releaseMemory() {
93 BackEdges.clear();
94 }
95
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000096 private:
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +000097 bool EliminateMostlyEmptyBlocks(Function &F);
98 bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
99 void EliminateMostlyEmptyBlock(BasicBlock *BB);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000100 bool OptimizeBlock(BasicBlock &BB);
Cameron Zwarichc0611012011-01-06 02:37:26 +0000101 bool OptimizeInst(Instruction *I);
Chris Lattner88a5c832008-11-25 07:09:13 +0000102 bool OptimizeMemoryInst(Instruction *I, Value *Addr, const Type *AccessTy,
103 DenseMap<Value*,Value*> &SunkAddrs);
Evan Cheng9bf12b52008-02-26 02:42:37 +0000104 bool OptimizeInlineAsmInst(Instruction *I, CallSite CS,
105 DenseMap<Value*,Value*> &SunkAddrs);
Eric Christopher040056f2010-03-11 02:41:03 +0000106 bool OptimizeCallInst(CallInst *CI);
Dan Gohmanb00f2362009-10-16 20:59:35 +0000107 bool MoveExtToFormExtLoad(Instruction *I);
Evan Chengbdcb7262007-12-05 23:58:20 +0000108 bool OptimizeExtUses(Instruction *I);
Mike Stumpfe095f32009-05-04 18:40:41 +0000109 void findLoopBackEdges(const Function &F);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000110 };
111}
Devang Patel794fd752007-05-01 21:15:47 +0000112
Devang Patel19974732007-05-03 01:11:54 +0000113char CodeGenPrepare::ID = 0;
Owen Andersond13db2c2010-07-21 22:09:45 +0000114INITIALIZE_PASS(CodeGenPrepare, "codegenprepare",
Owen Andersonce665bd2010-10-07 22:25:06 +0000115 "Optimize for code generation", false, false)
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000116
117FunctionPass *llvm::createCodeGenPreparePass(const TargetLowering *TLI) {
118 return new CodeGenPrepare(TLI);
119}
120
Evan Chengab631522008-12-19 18:03:11 +0000121/// findLoopBackEdges - Do a DFS walk to find loop back edges.
122///
Mike Stumpfe095f32009-05-04 18:40:41 +0000123void CodeGenPrepare::findLoopBackEdges(const Function &F) {
124 SmallVector<std::pair<const BasicBlock*,const BasicBlock*>, 32> Edges;
125 FindFunctionBackedges(F, Edges);
126
127 BackEdges.insert(Edges.begin(), Edges.end());
Evan Chengab631522008-12-19 18:03:11 +0000128}
129
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000130
131bool CodeGenPrepare::runOnFunction(Function &F) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000132 bool EverMadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000133
Evan Cheng04149f72009-12-17 09:39:49 +0000134 PFI = getAnalysisIfAvailable<ProfileInfo>();
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000135 // First pass, eliminate blocks that contain only PHI nodes and an
136 // unconditional branch.
137 EverMadeChange |= EliminateMostlyEmptyBlocks(F);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000138
Cameron Zwarich95bb0042011-01-04 04:43:31 +0000139 // Now find loop back edges, but only if they are being used to decide which
140 // critical edges to split.
141 if (CriticalEdgeSplit)
142 findLoopBackEdges(F);
Evan Cheng7e66c0d2009-01-05 21:17:27 +0000143
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000144 bool MadeChange = true;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000145 while (MadeChange) {
146 MadeChange = false;
147 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
148 MadeChange |= OptimizeBlock(*BB);
149 EverMadeChange |= MadeChange;
150 }
Cameron Zwarich8c3527e2011-01-06 00:42:50 +0000151
152 SunkAddrs.clear();
153
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000154 return EverMadeChange;
155}
156
Dale Johannesen2d697242009-03-27 01:13:37 +0000157/// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes,
158/// debug info directives, and an unconditional branch. Passes before isel
159/// (e.g. LSR/loopsimplify) often split edges in ways that are non-optimal for
160/// isel. Start by eliminating these blocks so we can split them the way we
161/// want them.
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000162bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
163 bool MadeChange = false;
164 // Note that this intentionally skips the entry block.
165 for (Function::iterator I = ++F.begin(), E = F.end(); I != E; ) {
166 BasicBlock *BB = I++;
167
168 // If this block doesn't end with an uncond branch, ignore it.
169 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
170 if (!BI || !BI->isUnconditional())
171 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000172
Dale Johannesen2d697242009-03-27 01:13:37 +0000173 // If the instruction before the branch (skipping debug info) isn't a phi
174 // node, then other stuff is happening here.
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000175 BasicBlock::iterator BBI = BI;
176 if (BBI != BB->begin()) {
177 --BBI;
Dale Johannesen2d697242009-03-27 01:13:37 +0000178 while (isa<DbgInfoIntrinsic>(BBI)) {
179 if (BBI == BB->begin())
180 break;
181 --BBI;
182 }
183 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
184 continue;
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000185 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000186
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000187 // Do not break infinite loops.
188 BasicBlock *DestBB = BI->getSuccessor(0);
189 if (DestBB == BB)
190 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000191
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000192 if (!CanMergeBlocks(BB, DestBB))
193 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000194
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000195 EliminateMostlyEmptyBlock(BB);
196 MadeChange = true;
197 }
198 return MadeChange;
199}
200
201/// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
202/// single uncond branch between them, and BB contains no other non-phi
203/// instructions.
204bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
205 const BasicBlock *DestBB) const {
206 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
207 // the successor. If there are more complex condition (e.g. preheaders),
208 // don't mess around with them.
209 BasicBlock::const_iterator BBI = BB->begin();
210 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
Gabor Greif60ad7812010-03-25 23:06:16 +0000211 for (Value::const_use_iterator UI = PN->use_begin(), E = PN->use_end();
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000212 UI != E; ++UI) {
213 const Instruction *User = cast<Instruction>(*UI);
214 if (User->getParent() != DestBB || !isa<PHINode>(User))
215 return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000216 // If User is inside DestBB block and it is a PHINode then check
217 // incoming value. If incoming value is not from BB then this is
Devang Patel75abc1e2007-04-25 00:37:04 +0000218 // a complex condition (e.g. preheaders) we want to avoid here.
219 if (User->getParent() == DestBB) {
220 if (const PHINode *UPN = dyn_cast<PHINode>(User))
221 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
222 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
223 if (Insn && Insn->getParent() == BB &&
224 Insn->getParent() != UPN->getIncomingBlock(I))
225 return false;
226 }
227 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000228 }
229 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000230
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000231 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
232 // and DestBB may have conflicting incoming values for the block. If so, we
233 // can't merge the block.
234 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
235 if (!DestBBPN) return true; // no conflict.
Eric Christopher692bf6b2008-09-24 05:32:41 +0000236
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000237 // Collect the preds of BB.
Chris Lattnerf67f73a2007-11-06 22:07:40 +0000238 SmallPtrSet<const BasicBlock*, 16> BBPreds;
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000239 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
240 // It is faster to get preds from a PHI than with pred_iterator.
241 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
242 BBPreds.insert(BBPN->getIncomingBlock(i));
243 } else {
244 BBPreds.insert(pred_begin(BB), pred_end(BB));
245 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000246
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000247 // Walk the preds of DestBB.
248 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
249 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
250 if (BBPreds.count(Pred)) { // Common predecessor?
251 BBI = DestBB->begin();
252 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
253 const Value *V1 = PN->getIncomingValueForBlock(Pred);
254 const Value *V2 = PN->getIncomingValueForBlock(BB);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000255
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000256 // If V2 is a phi node in BB, look up what the mapped value will be.
257 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
258 if (V2PN->getParent() == BB)
259 V2 = V2PN->getIncomingValueForBlock(Pred);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000260
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000261 // If there is a conflict, bail out.
262 if (V1 != V2) return false;
263 }
264 }
265 }
266
267 return true;
268}
269
270
271/// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
272/// an unconditional branch in it.
273void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
274 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
275 BasicBlock *DestBB = BI->getSuccessor(0);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000276
David Greene68d67fd2010-01-05 01:27:11 +0000277 DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000278
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000279 // If the destination block has a single pred, then this is a trivial edge,
280 // just collapse it.
Chris Lattner9918fb52008-11-27 19:29:14 +0000281 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
Chris Lattnerf5102a02008-11-28 19:54:49 +0000282 if (SinglePred != DestBB) {
283 // Remember if SinglePred was the entry block of the function. If so, we
284 // will need to move BB back to the entry position.
285 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Andreas Neustifterad809812009-09-16 09:26:52 +0000286 MergeBasicBlockIntoOnlyPred(DestBB, this);
Chris Lattner9918fb52008-11-27 19:29:14 +0000287
Chris Lattnerf5102a02008-11-28 19:54:49 +0000288 if (isEntry && BB != &BB->getParent()->getEntryBlock())
289 BB->moveBefore(&BB->getParent()->getEntryBlock());
290
David Greene68d67fd2010-01-05 01:27:11 +0000291 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerf5102a02008-11-28 19:54:49 +0000292 return;
293 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000294 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000295
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000296 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
297 // to handle the new incoming edges it is about to have.
298 PHINode *PN;
299 for (BasicBlock::iterator BBI = DestBB->begin();
300 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
301 // Remove the incoming value for BB, and remember it.
302 Value *InVal = PN->removeIncomingValue(BB, false);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000303
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000304 // Two options: either the InVal is a phi node defined in BB or it is some
305 // value that dominates BB.
306 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
307 if (InValPhi && InValPhi->getParent() == BB) {
308 // Add all of the input values of the input PHI as inputs of this phi.
309 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
310 PN->addIncoming(InValPhi->getIncomingValue(i),
311 InValPhi->getIncomingBlock(i));
312 } else {
313 // Otherwise, add one instance of the dominating value for each edge that
314 // we will be adding.
315 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
316 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
317 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
318 } else {
319 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
320 PN->addIncoming(InVal, *PI);
321 }
322 }
323 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000324
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000325 // The PHIs are now updated, change everything that refers to BB to use
326 // DestBB and remove BB.
327 BB->replaceAllUsesWith(DestBB);
Evan Cheng04149f72009-12-17 09:39:49 +0000328 if (PFI) {
329 PFI->replaceAllUses(BB, DestBB);
330 PFI->removeEdge(ProfileInfo::getEdge(BB, DestBB));
Andreas Neustifterad809812009-09-16 09:26:52 +0000331 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000332 BB->eraseFromParent();
Cameron Zwarich31ff1332011-01-05 17:27:27 +0000333 ++NumBlocksElim;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000334
David Greene68d67fd2010-01-05 01:27:11 +0000335 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000336}
337
Chris Lattner98d5c312010-02-13 05:35:08 +0000338/// FindReusablePredBB - Check all of the predecessors of the block DestPHI
339/// lives in to see if there is a block that we can reuse as a critical edge
340/// from TIBB.
341static BasicBlock *FindReusablePredBB(PHINode *DestPHI, BasicBlock *TIBB) {
342 BasicBlock *Dest = DestPHI->getParent();
343
344 /// TIPHIValues - This array is lazily computed to determine the values of
345 /// PHIs in Dest that TI would provide.
346 SmallVector<Value*, 32> TIPHIValues;
347
348 /// TIBBEntryNo - This is a cache to speed up pred queries for TIBB.
349 unsigned TIBBEntryNo = 0;
350
351 // Check to see if Dest has any blocks that can be used as a split edge for
352 // this terminator.
353 for (unsigned pi = 0, e = DestPHI->getNumIncomingValues(); pi != e; ++pi) {
354 BasicBlock *Pred = DestPHI->getIncomingBlock(pi);
355 // To be usable, the pred has to end with an uncond branch to the dest.
356 BranchInst *PredBr = dyn_cast<BranchInst>(Pred->getTerminator());
357 if (!PredBr || !PredBr->isUnconditional())
358 continue;
359 // Must be empty other than the branch and debug info.
360 BasicBlock::iterator I = Pred->begin();
361 while (isa<DbgInfoIntrinsic>(I))
362 I++;
363 if (&*I != PredBr)
364 continue;
365 // Cannot be the entry block; its label does not get emitted.
366 if (Pred == &Dest->getParent()->getEntryBlock())
367 continue;
368
369 // Finally, since we know that Dest has phi nodes in it, we have to make
370 // sure that jumping to Pred will have the same effect as going to Dest in
371 // terms of PHI values.
372 PHINode *PN;
373 unsigned PHINo = 0;
374 unsigned PredEntryNo = pi;
375
376 bool FoundMatch = true;
377 for (BasicBlock::iterator I = Dest->begin();
378 (PN = dyn_cast<PHINode>(I)); ++I, ++PHINo) {
379 if (PHINo == TIPHIValues.size()) {
380 if (PN->getIncomingBlock(TIBBEntryNo) != TIBB)
381 TIBBEntryNo = PN->getBasicBlockIndex(TIBB);
382 TIPHIValues.push_back(PN->getIncomingValue(TIBBEntryNo));
383 }
384
385 // If the PHI entry doesn't work, we can't use this pred.
386 if (PN->getIncomingBlock(PredEntryNo) != Pred)
387 PredEntryNo = PN->getBasicBlockIndex(Pred);
388
389 if (TIPHIValues[PHINo] != PN->getIncomingValue(PredEntryNo)) {
390 FoundMatch = false;
391 break;
392 }
393 }
394
395 // If we found a workable predecessor, change TI to branch to Succ.
396 if (FoundMatch)
397 return Pred;
398 }
399 return 0;
400}
401
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000402
Chris Lattnerebe80752007-12-24 19:32:55 +0000403/// SplitEdgeNicely - Split the critical edge from TI to its specified
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000404/// successor if it will improve codegen. We only do this if the successor has
405/// phi nodes (otherwise critical edges are ok). If there is already another
406/// predecessor of the succ that is empty (and thus has no phi nodes), use it
407/// instead of introducing a new block.
Evan Chengab631522008-12-19 18:03:11 +0000408static void SplitEdgeNicely(TerminatorInst *TI, unsigned SuccNum,
Mike Stumpfe095f32009-05-04 18:40:41 +0000409 SmallSet<std::pair<const BasicBlock*,
410 const BasicBlock*>, 8> &BackEdges,
Evan Chengab631522008-12-19 18:03:11 +0000411 Pass *P) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000412 BasicBlock *TIBB = TI->getParent();
413 BasicBlock *Dest = TI->getSuccessor(SuccNum);
414 assert(isa<PHINode>(Dest->begin()) &&
415 "This should only be called if Dest has a PHI!");
Chris Lattner3f65b5e2010-02-13 04:04:42 +0000416 PHINode *DestPHI = cast<PHINode>(Dest->begin());
Eric Christopher692bf6b2008-09-24 05:32:41 +0000417
Evan Chengfc0b80d2009-03-13 22:59:14 +0000418 // Do not split edges to EH landing pads.
Chris Lattner3f65b5e2010-02-13 04:04:42 +0000419 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(TI))
Evan Chengfc0b80d2009-03-13 22:59:14 +0000420 if (Invoke->getSuccessor(1) == Dest)
421 return;
Evan Chengfc0b80d2009-03-13 22:59:14 +0000422
Chris Lattnerebe80752007-12-24 19:32:55 +0000423 // As a hack, never split backedges of loops. Even though the copy for any
424 // PHIs inserted on the backedge would be dead for exits from the loop, we
425 // assume that the cost of *splitting* the backedge would be too high.
Evan Chengab631522008-12-19 18:03:11 +0000426 if (BackEdges.count(std::make_pair(TIBB, Dest)))
Chris Lattnerebe80752007-12-24 19:32:55 +0000427 return;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000428
Chris Lattnerc09687b2010-02-13 19:07:06 +0000429 if (BasicBlock *ReuseBB = FindReusablePredBB(DestPHI, TIBB)) {
430 ProfileInfo *PFI = P->getAnalysisIfAvailable<ProfileInfo>();
431 if (PFI)
432 PFI->splitEdge(TIBB, Dest, ReuseBB);
433 Dest->removePredecessor(TIBB);
434 TI->setSuccessor(SuccNum, ReuseBB);
Evan Chengab631522008-12-19 18:03:11 +0000435 return;
436 }
437
Chris Lattnerc09687b2010-02-13 19:07:06 +0000438 SplitCriticalEdge(TI, SuccNum, P, true);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000439}
440
Evan Chengab631522008-12-19 18:03:11 +0000441
Chris Lattnerdd77df32007-04-13 20:30:56 +0000442/// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
Dan Gohmana119de82009-06-14 23:30:43 +0000443/// copy (e.g. it's casting from one pointer type to another, i32->i8 on PPC),
444/// sink it into user blocks to reduce the number of virtual
Dale Johannesence0b2372007-06-12 16:50:17 +0000445/// registers that must be created and coalesced.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000446///
447/// Return true if any changes are made.
Chris Lattner85fa13c2008-11-24 22:44:16 +0000448///
Chris Lattnerdd77df32007-04-13 20:30:56 +0000449static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
Eric Christopher692bf6b2008-09-24 05:32:41 +0000450 // If this is a noop copy,
Owen Andersone50ed302009-08-10 22:56:29 +0000451 EVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
452 EVT DstVT = TLI.getValueType(CI->getType());
Eric Christopher692bf6b2008-09-24 05:32:41 +0000453
Chris Lattnerdd77df32007-04-13 20:30:56 +0000454 // This is an fp<->int conversion?
Duncan Sands83ec4b62008-06-06 12:08:01 +0000455 if (SrcVT.isInteger() != DstVT.isInteger())
Chris Lattnerdd77df32007-04-13 20:30:56 +0000456 return false;
Duncan Sands8e4eb092008-06-08 20:54:56 +0000457
Chris Lattnerdd77df32007-04-13 20:30:56 +0000458 // If this is an extension, it will be a zero or sign extension, which
459 // isn't a noop.
Duncan Sands8e4eb092008-06-08 20:54:56 +0000460 if (SrcVT.bitsLT(DstVT)) return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000461
Chris Lattnerdd77df32007-04-13 20:30:56 +0000462 // If these values will be promoted, find out what they will be promoted
463 // to. This helps us consider truncates on PPC as noop copies when they
464 // are.
Chris Lattneraafe6262010-08-25 23:00:45 +0000465 if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote)
Owen Anderson23b9b192009-08-12 00:36:31 +0000466 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
Chris Lattneraafe6262010-08-25 23:00:45 +0000467 if (TLI.getTypeAction(DstVT) == TargetLowering::Promote)
Owen Anderson23b9b192009-08-12 00:36:31 +0000468 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000469
Chris Lattnerdd77df32007-04-13 20:30:56 +0000470 // If, after promotion, these are the same types, this is a noop copy.
471 if (SrcVT != DstVT)
472 return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000473
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000474 BasicBlock *DefBB = CI->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000475
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000476 /// InsertedCasts - Only insert a cast in each block once.
Dale Johannesence0b2372007-06-12 16:50:17 +0000477 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000478
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000479 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000480 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000481 UI != E; ) {
482 Use &TheUse = UI.getUse();
483 Instruction *User = cast<Instruction>(*UI);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000484
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000485 // Figure out which BB this cast is used in. For PHI's this is the
486 // appropriate predecessor block.
487 BasicBlock *UserBB = User->getParent();
488 if (PHINode *PN = dyn_cast<PHINode>(User)) {
Gabor Greifa36791d2009-01-23 19:40:15 +0000489 UserBB = PN->getIncomingBlock(UI);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000490 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000491
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000492 // Preincrement use iterator so we don't invalidate it.
493 ++UI;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000494
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000495 // If this user is in the same block as the cast, don't change the cast.
496 if (UserBB == DefBB) continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000497
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000498 // If we have already inserted a cast into this block, use it.
499 CastInst *&InsertedCast = InsertedCasts[UserBB];
500
501 if (!InsertedCast) {
Dan Gohman02dea8b2008-05-23 21:05:58 +0000502 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000503
504 InsertedCast =
505 CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000506 InsertPt);
507 MadeChange = true;
508 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000509
Dale Johannesence0b2372007-06-12 16:50:17 +0000510 // Replace a use of the cast with a use of the new cast.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000511 TheUse = InsertedCast;
Cameron Zwarich31ff1332011-01-05 17:27:27 +0000512 ++NumCastUses;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000513 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000514
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000515 // If we removed all uses, nuke the cast.
Duncan Sandse0038132008-01-20 16:51:46 +0000516 if (CI->use_empty()) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000517 CI->eraseFromParent();
Duncan Sandse0038132008-01-20 16:51:46 +0000518 MadeChange = true;
519 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000520
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000521 return MadeChange;
522}
523
Eric Christopher692bf6b2008-09-24 05:32:41 +0000524/// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
Dale Johannesence0b2372007-06-12 16:50:17 +0000525/// the number of virtual registers that must be created and coalesced. This is
Chris Lattner684b22d2007-08-02 16:53:43 +0000526/// a clear win except on targets with multiple condition code registers
527/// (PowerPC), where it might lose; some adjustment may be wanted there.
Dale Johannesence0b2372007-06-12 16:50:17 +0000528///
529/// Return true if any changes are made.
Chris Lattner85fa13c2008-11-24 22:44:16 +0000530static bool OptimizeCmpExpression(CmpInst *CI) {
Dale Johannesence0b2372007-06-12 16:50:17 +0000531 BasicBlock *DefBB = CI->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000532
Dale Johannesence0b2372007-06-12 16:50:17 +0000533 /// InsertedCmp - Only insert a cmp in each block once.
534 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000535
Dale Johannesence0b2372007-06-12 16:50:17 +0000536 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000537 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
Dale Johannesence0b2372007-06-12 16:50:17 +0000538 UI != E; ) {
539 Use &TheUse = UI.getUse();
540 Instruction *User = cast<Instruction>(*UI);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000541
Dale Johannesence0b2372007-06-12 16:50:17 +0000542 // Preincrement use iterator so we don't invalidate it.
543 ++UI;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000544
Dale Johannesence0b2372007-06-12 16:50:17 +0000545 // Don't bother for PHI nodes.
546 if (isa<PHINode>(User))
547 continue;
548
549 // Figure out which BB this cmp is used in.
550 BasicBlock *UserBB = User->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000551
Dale Johannesence0b2372007-06-12 16:50:17 +0000552 // If this user is in the same block as the cmp, don't change the cmp.
553 if (UserBB == DefBB) continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000554
Dale Johannesence0b2372007-06-12 16:50:17 +0000555 // If we have already inserted a cmp into this block, use it.
556 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
557
558 if (!InsertedCmp) {
Dan Gohman02dea8b2008-05-23 21:05:58 +0000559 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000560
561 InsertedCmp =
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000562 CmpInst::Create(CI->getOpcode(),
Owen Anderson333c4002009-07-09 23:48:35 +0000563 CI->getPredicate(), CI->getOperand(0),
Dale Johannesence0b2372007-06-12 16:50:17 +0000564 CI->getOperand(1), "", InsertPt);
565 MadeChange = true;
566 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000567
Dale Johannesence0b2372007-06-12 16:50:17 +0000568 // Replace a use of the cmp with a use of the new cmp.
569 TheUse = InsertedCmp;
Cameron Zwarich31ff1332011-01-05 17:27:27 +0000570 ++NumCmpUses;
Dale Johannesence0b2372007-06-12 16:50:17 +0000571 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000572
Dale Johannesence0b2372007-06-12 16:50:17 +0000573 // If we removed all uses, nuke the cmp.
574 if (CI->use_empty())
575 CI->eraseFromParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000576
Dale Johannesence0b2372007-06-12 16:50:17 +0000577 return MadeChange;
578}
579
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000580namespace {
581class CodeGenPrepareFortifiedLibCalls : public SimplifyFortifiedLibCalls {
582protected:
583 void replaceCall(Value *With) {
584 CI->replaceAllUsesWith(With);
585 CI->eraseFromParent();
586 }
587 bool isFoldable(unsigned SizeCIOp, unsigned, bool) const {
Gabor Greifa6aac4c2010-07-16 09:38:02 +0000588 if (ConstantInt *SizeCI =
589 dyn_cast<ConstantInt>(CI->getArgOperand(SizeCIOp)))
590 return SizeCI->isAllOnesValue();
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000591 return false;
592 }
593};
594} // end anonymous namespace
595
Eric Christopher040056f2010-03-11 02:41:03 +0000596bool CodeGenPrepare::OptimizeCallInst(CallInst *CI) {
Eric Christopher040056f2010-03-11 02:41:03 +0000597 // Lower all uses of llvm.objectsize.*
598 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
599 if (II && II->getIntrinsicID() == Intrinsic::objectsize) {
Gabor Greifde9f5452010-06-24 00:44:01 +0000600 bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
Eric Christopher040056f2010-03-11 02:41:03 +0000601 const Type *ReturnTy = CI->getType();
602 Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
603 CI->replaceAllUsesWith(RetVal);
604 CI->eraseFromParent();
605 return true;
606 }
607
608 // From here on out we're working with named functions.
609 if (CI->getCalledFunction() == 0) return false;
610
611 // We'll need TargetData from here on out.
612 const TargetData *TD = TLI ? TLI->getTargetData() : 0;
613 if (!TD) return false;
614
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000615 // Lower all default uses of _chk calls. This is very similar
616 // to what InstCombineCalls does, but here we are only lowering calls
Eric Christopher040056f2010-03-11 02:41:03 +0000617 // that have the default "don't know" as the objectsize. Anything else
618 // should be left alone.
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000619 CodeGenPrepareFortifiedLibCalls Simplifier;
620 return Simplifier.fold(CI, TD);
Eric Christopher040056f2010-03-11 02:41:03 +0000621}
Chris Lattner88a5c832008-11-25 07:09:13 +0000622//===----------------------------------------------------------------------===//
Chris Lattner88a5c832008-11-25 07:09:13 +0000623// Memory Optimization
624//===----------------------------------------------------------------------===//
625
Chris Lattnerdd77df32007-04-13 20:30:56 +0000626/// IsNonLocalValue - Return true if the specified values are defined in a
627/// different basic block than BB.
628static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
629 if (Instruction *I = dyn_cast<Instruction>(V))
630 return I->getParent() != BB;
631 return false;
632}
633
Bob Wilson4a8ee232009-12-03 21:47:07 +0000634/// OptimizeMemoryInst - Load and Store Instructions often have
Chris Lattnerdd77df32007-04-13 20:30:56 +0000635/// addressing modes that can do significant amounts of computation. As such,
636/// instruction selection will try to get the load or store to do as much
637/// computation as possible for the program. The problem is that isel can only
638/// see within a single block. As such, we sink as much legal addressing mode
639/// stuff into the block as possible.
Chris Lattner88a5c832008-11-25 07:09:13 +0000640///
641/// This method is used to optimize both load/store and inline asms with memory
642/// operands.
Chris Lattner896617b2008-11-26 03:20:37 +0000643bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
Chris Lattner88a5c832008-11-25 07:09:13 +0000644 const Type *AccessTy,
645 DenseMap<Value*,Value*> &SunkAddrs) {
Owen Anderson35bf4d62010-11-27 08:15:55 +0000646 Value *Repl = Addr;
647
Owen Andersond2f41742010-11-19 22:15:03 +0000648 // Try to collapse single-value PHI nodes. This is necessary to undo
649 // unprofitable PRE transformations.
Cameron Zwarich7cb4fa22011-01-03 06:33:01 +0000650 SmallVector<Value*, 8> worklist;
651 SmallPtrSet<Value*, 16> Visited;
Owen Anderson35bf4d62010-11-27 08:15:55 +0000652 worklist.push_back(Addr);
653
654 // Use a worklist to iteratively look through PHI nodes, and ensure that
655 // the addressing mode obtained from the non-PHI roots of the graph
656 // are equivalent.
657 Value *Consensus = 0;
658 unsigned NumUses = 0;
659 SmallVector<Instruction*, 16> AddrModeInsts;
660 ExtAddrMode AddrMode;
661 while (!worklist.empty()) {
662 Value *V = worklist.back();
663 worklist.pop_back();
664
665 // Break use-def graph loops.
666 if (Visited.count(V)) {
667 Consensus = 0;
668 break;
Owen Andersond2f41742010-11-19 22:15:03 +0000669 }
670
Owen Anderson35bf4d62010-11-27 08:15:55 +0000671 Visited.insert(V);
672
673 // For a PHI node, push all of its incoming values.
674 if (PHINode *P = dyn_cast<PHINode>(V)) {
675 for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i)
676 worklist.push_back(P->getIncomingValue(i));
677 continue;
678 }
679
680 // For non-PHIs, determine the addressing mode being computed.
681 SmallVector<Instruction*, 16> NewAddrModeInsts;
682 ExtAddrMode NewAddrMode =
683 AddressingModeMatcher::Match(V, AccessTy,MemoryInst,
684 NewAddrModeInsts, *TLI);
685
686 // Ensure that the obtained addressing mode is equivalent to that obtained
687 // for all other roots of the PHI traversal. Also, when choosing one
688 // such root as representative, select the one with the most uses in order
689 // to keep the cost modeling heuristics in AddressingModeMatcher applicable.
690 if (!Consensus || NewAddrMode == AddrMode) {
691 if (V->getNumUses() > NumUses) {
692 Consensus = V;
693 NumUses = V->getNumUses();
694 AddrMode = NewAddrMode;
695 AddrModeInsts = NewAddrModeInsts;
696 }
697 continue;
698 }
699
700 Consensus = 0;
701 break;
Owen Andersond2f41742010-11-19 22:15:03 +0000702 }
703
Owen Anderson35bf4d62010-11-27 08:15:55 +0000704 // If the addressing mode couldn't be determined, or if multiple different
705 // ones were determined, bail out now.
706 if (!Consensus) return false;
707
Chris Lattnerdd77df32007-04-13 20:30:56 +0000708 // Check to see if any of the instructions supersumed by this addr mode are
709 // non-local to I's BB.
710 bool AnyNonLocal = false;
711 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
Chris Lattner896617b2008-11-26 03:20:37 +0000712 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
Chris Lattnerdd77df32007-04-13 20:30:56 +0000713 AnyNonLocal = true;
714 break;
715 }
716 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000717
Chris Lattnerdd77df32007-04-13 20:30:56 +0000718 // If all the instructions matched are already in this BB, don't do anything.
719 if (!AnyNonLocal) {
David Greene68d67fd2010-01-05 01:27:11 +0000720 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000721 return false;
722 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000723
Chris Lattnerdd77df32007-04-13 20:30:56 +0000724 // Insert this computation right after this user. Since our caller is
725 // scanning from the top of the BB to the bottom, reuse of the expr are
726 // guaranteed to happen later.
Chris Lattner896617b2008-11-26 03:20:37 +0000727 BasicBlock::iterator InsertPt = MemoryInst;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000728
Chris Lattnerdd77df32007-04-13 20:30:56 +0000729 // Now that we determined the addressing expression we want to use and know
730 // that we have to sink it into this block. Check to see if we have already
731 // done this for some other load/store instr in this block. If so, reuse the
732 // computation.
733 Value *&SunkAddr = SunkAddrs[Addr];
734 if (SunkAddr) {
David Greene68d67fd2010-01-05 01:27:11 +0000735 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
Dan Gohman6c1980b2009-07-25 01:13:51 +0000736 << *MemoryInst);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000737 if (SunkAddr->getType() != Addr->getType())
738 SunkAddr = new BitCastInst(SunkAddr, Addr->getType(), "tmp", InsertPt);
739 } else {
David Greene68d67fd2010-01-05 01:27:11 +0000740 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Dan Gohman6c1980b2009-07-25 01:13:51 +0000741 << *MemoryInst);
Owen Anderson1d0be152009-08-13 21:58:54 +0000742 const Type *IntPtrTy =
743 TLI->getTargetData()->getIntPtrType(AccessTy->getContext());
Eric Christopher692bf6b2008-09-24 05:32:41 +0000744
Chris Lattnerdd77df32007-04-13 20:30:56 +0000745 Value *Result = 0;
Dan Gohmand8d0b6a2010-01-19 22:45:06 +0000746
747 // Start with the base register. Do this first so that subsequent address
748 // matching finds it last, which will prevent it from trying to match it
749 // as the scaled value in case it happens to be a mul. That would be
750 // problematic if we've sunk a different mul for the scale, because then
751 // we'd end up sinking both muls.
752 if (AddrMode.BaseReg) {
753 Value *V = AddrMode.BaseReg;
Duncan Sands1df98592010-02-16 11:11:14 +0000754 if (V->getType()->isPointerTy())
Dan Gohmand8d0b6a2010-01-19 22:45:06 +0000755 V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
756 if (V->getType() != IntPtrTy)
757 V = CastInst::CreateIntegerCast(V, IntPtrTy, /*isSigned=*/true,
758 "sunkaddr", InsertPt);
759 Result = V;
760 }
761
762 // Add the scale value.
Chris Lattnerdd77df32007-04-13 20:30:56 +0000763 if (AddrMode.Scale) {
764 Value *V = AddrMode.ScaledReg;
765 if (V->getType() == IntPtrTy) {
766 // done.
Duncan Sands1df98592010-02-16 11:11:14 +0000767 } else if (V->getType()->isPointerTy()) {
Chris Lattnerdd77df32007-04-13 20:30:56 +0000768 V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
769 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
770 cast<IntegerType>(V->getType())->getBitWidth()) {
771 V = new TruncInst(V, IntPtrTy, "sunkaddr", InsertPt);
772 } else {
773 V = new SExtInst(V, IntPtrTy, "sunkaddr", InsertPt);
774 }
775 if (AddrMode.Scale != 1)
Owen Andersoneed707b2009-07-24 23:12:02 +0000776 V = BinaryOperator::CreateMul(V, ConstantInt::get(IntPtrTy,
Owen Andersond672ecb2009-07-03 00:17:18 +0000777 AddrMode.Scale),
Chris Lattnerdd77df32007-04-13 20:30:56 +0000778 "sunkaddr", InsertPt);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000779 if (Result)
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000780 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000781 else
782 Result = V;
783 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000784
Chris Lattnerdd77df32007-04-13 20:30:56 +0000785 // Add in the BaseGV if present.
786 if (AddrMode.BaseGV) {
787 Value *V = new PtrToIntInst(AddrMode.BaseGV, IntPtrTy, "sunkaddr",
788 InsertPt);
789 if (Result)
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000790 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000791 else
792 Result = V;
793 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000794
Chris Lattnerdd77df32007-04-13 20:30:56 +0000795 // Add in the Base Offset if present.
796 if (AddrMode.BaseOffs) {
Owen Andersoneed707b2009-07-24 23:12:02 +0000797 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000798 if (Result)
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000799 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000800 else
801 Result = V;
802 }
803
804 if (Result == 0)
Owen Andersona7235ea2009-07-31 20:28:14 +0000805 SunkAddr = Constant::getNullValue(Addr->getType());
Chris Lattnerdd77df32007-04-13 20:30:56 +0000806 else
807 SunkAddr = new IntToPtrInst(Result, Addr->getType(), "sunkaddr",InsertPt);
808 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000809
Owen Andersond2f41742010-11-19 22:15:03 +0000810 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000811
Owen Andersond2f41742010-11-19 22:15:03 +0000812 if (Repl->use_empty()) {
813 RecursivelyDeleteTriviallyDeadInstructions(Repl);
Dale Johannesen536d31b2010-03-31 20:37:15 +0000814 // This address is now available for reassignment, so erase the table entry;
815 // we don't want to match some completely different instruction.
816 SunkAddrs[Addr] = 0;
817 }
Cameron Zwarich31ff1332011-01-05 17:27:27 +0000818 ++NumMemoryInsts;
Chris Lattnerdd77df32007-04-13 20:30:56 +0000819 return true;
820}
821
Evan Cheng9bf12b52008-02-26 02:42:37 +0000822/// OptimizeInlineAsmInst - If there are any memory operands, use
Chris Lattner88a5c832008-11-25 07:09:13 +0000823/// OptimizeMemoryInst to sink their address computing into the block when
Evan Cheng9bf12b52008-02-26 02:42:37 +0000824/// possible / profitable.
825bool CodeGenPrepare::OptimizeInlineAsmInst(Instruction *I, CallSite CS,
826 DenseMap<Value*,Value*> &SunkAddrs) {
827 bool MadeChange = false;
Evan Cheng9bf12b52008-02-26 02:42:37 +0000828
John Thompson44ab89e2010-10-29 17:29:13 +0000829 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI->ParseConstraints(CS);
Dale Johannesen677c6ec2010-09-16 18:30:55 +0000830 unsigned ArgNo = 0;
John Thompsoneac6e1d2010-09-13 18:15:37 +0000831 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
832 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
833
Evan Cheng9bf12b52008-02-26 02:42:37 +0000834 // Compute the constraint code and ConstraintType to use.
Dale Johannesen1784d162010-06-25 21:55:36 +0000835 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Evan Cheng9bf12b52008-02-26 02:42:37 +0000836
Eli Friedman9ec80952008-02-26 18:37:49 +0000837 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
838 OpInfo.isIndirect) {
Dale Johannesen677c6ec2010-09-16 18:30:55 +0000839 Value *OpVal = const_cast<Value *>(CS.getArgument(ArgNo++));
Chris Lattner88a5c832008-11-25 07:09:13 +0000840 MadeChange |= OptimizeMemoryInst(I, OpVal, OpVal->getType(), SunkAddrs);
Dale Johannesen677c6ec2010-09-16 18:30:55 +0000841 } else if (OpInfo.Type == InlineAsm::isInput)
842 ArgNo++;
Evan Cheng9bf12b52008-02-26 02:42:37 +0000843 }
844
845 return MadeChange;
846}
847
Dan Gohmanb00f2362009-10-16 20:59:35 +0000848/// MoveExtToFormExtLoad - Move a zext or sext fed by a load into the same
849/// basic block as the load, unless conditions are unfavorable. This allows
850/// SelectionDAG to fold the extend into the load.
851///
852bool CodeGenPrepare::MoveExtToFormExtLoad(Instruction *I) {
853 // Look for a load being extended.
854 LoadInst *LI = dyn_cast<LoadInst>(I->getOperand(0));
855 if (!LI) return false;
856
857 // If they're already in the same block, there's nothing to do.
858 if (LI->getParent() == I->getParent())
859 return false;
860
861 // If the load has other users and the truncate is not free, this probably
862 // isn't worthwhile.
863 if (!LI->hasOneUse() &&
Bob Wilsonec57a1a2010-09-22 18:44:56 +0000864 TLI && (TLI->isTypeLegal(TLI->getValueType(LI->getType())) ||
865 !TLI->isTypeLegal(TLI->getValueType(I->getType()))) &&
Bob Wilson71dc4d92010-09-21 21:54:27 +0000866 !TLI->isTruncateFree(I->getType(), LI->getType()))
Dan Gohmanb00f2362009-10-16 20:59:35 +0000867 return false;
868
869 // Check whether the target supports casts folded into loads.
870 unsigned LType;
871 if (isa<ZExtInst>(I))
872 LType = ISD::ZEXTLOAD;
873 else {
874 assert(isa<SExtInst>(I) && "Unexpected ext type!");
875 LType = ISD::SEXTLOAD;
876 }
877 if (TLI && !TLI->isLoadExtLegal(LType, TLI->getValueType(LI->getType())))
878 return false;
879
880 // Move the extend into the same block as the load, so that SelectionDAG
881 // can fold it.
882 I->removeFromParent();
883 I->insertAfter(LI);
Cameron Zwarich31ff1332011-01-05 17:27:27 +0000884 ++NumExtsMoved;
Dan Gohmanb00f2362009-10-16 20:59:35 +0000885 return true;
886}
887
Evan Chengbdcb7262007-12-05 23:58:20 +0000888bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
889 BasicBlock *DefBB = I->getParent();
890
Bob Wilson9120f5c2010-09-21 21:44:14 +0000891 // If the result of a {s|z}ext and its source are both live out, rewrite all
Evan Chengbdcb7262007-12-05 23:58:20 +0000892 // other uses of the source with result of extension.
893 Value *Src = I->getOperand(0);
894 if (Src->hasOneUse())
895 return false;
896
Evan Cheng696e5c02007-12-13 07:50:36 +0000897 // Only do this xform if truncating is free.
Gabor Greif53bdbd72008-02-26 19:13:21 +0000898 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
Evan Chengf9785f92007-12-13 03:32:53 +0000899 return false;
900
Evan Cheng772de512007-12-12 00:51:06 +0000901 // Only safe to perform the optimization if the source is also defined in
Evan Cheng765dff22007-12-12 02:53:41 +0000902 // this block.
903 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
Evan Cheng772de512007-12-12 00:51:06 +0000904 return false;
905
Evan Chengbdcb7262007-12-05 23:58:20 +0000906 bool DefIsLiveOut = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000907 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
Evan Chengbdcb7262007-12-05 23:58:20 +0000908 UI != E; ++UI) {
909 Instruction *User = cast<Instruction>(*UI);
910
911 // Figure out which BB this ext is used in.
912 BasicBlock *UserBB = User->getParent();
913 if (UserBB == DefBB) continue;
914 DefIsLiveOut = true;
915 break;
916 }
917 if (!DefIsLiveOut)
918 return false;
919
Evan Cheng765dff22007-12-12 02:53:41 +0000920 // Make sure non of the uses are PHI nodes.
Eric Christopher692bf6b2008-09-24 05:32:41 +0000921 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
Evan Cheng765dff22007-12-12 02:53:41 +0000922 UI != E; ++UI) {
923 Instruction *User = cast<Instruction>(*UI);
Evan Chengf9785f92007-12-13 03:32:53 +0000924 BasicBlock *UserBB = User->getParent();
925 if (UserBB == DefBB) continue;
926 // Be conservative. We don't want this xform to end up introducing
927 // reloads just before load / store instructions.
928 if (isa<PHINode>(User) || isa<LoadInst>(User) || isa<StoreInst>(User))
Evan Cheng765dff22007-12-12 02:53:41 +0000929 return false;
930 }
931
Evan Chengbdcb7262007-12-05 23:58:20 +0000932 // InsertedTruncs - Only insert one trunc in each block once.
933 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
934
935 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000936 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
Evan Chengbdcb7262007-12-05 23:58:20 +0000937 UI != E; ++UI) {
938 Use &TheUse = UI.getUse();
939 Instruction *User = cast<Instruction>(*UI);
940
941 // Figure out which BB this ext is used in.
942 BasicBlock *UserBB = User->getParent();
943 if (UserBB == DefBB) continue;
944
945 // Both src and def are live in this block. Rewrite the use.
946 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
947
948 if (!InsertedTrunc) {
Dan Gohman02dea8b2008-05-23 21:05:58 +0000949 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000950
Evan Chengbdcb7262007-12-05 23:58:20 +0000951 InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
952 }
953
954 // Replace a use of the {s|z}ext source with a use of the result.
955 TheUse = InsertedTrunc;
Cameron Zwarich31ff1332011-01-05 17:27:27 +0000956 ++NumExtUses;
Evan Chengbdcb7262007-12-05 23:58:20 +0000957 MadeChange = true;
958 }
959
960 return MadeChange;
961}
962
Cameron Zwarichc0611012011-01-06 02:37:26 +0000963bool CodeGenPrepare::OptimizeInst(Instruction *I) {
964 bool MadeChange = false;
965
966 if (PHINode *P = dyn_cast<PHINode>(I)) {
967 // It is possible for very late stage optimizations (such as SimplifyCFG)
968 // to introduce PHI nodes too late to be cleaned up. If we detect such a
969 // trivial PHI, go ahead and zap it here.
970 if (Value *V = SimplifyInstruction(P)) {
971 P->replaceAllUsesWith(V);
972 P->eraseFromParent();
973 ++NumPHIsElim;
974 }
975 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
976 // If the source of the cast is a constant, then this should have
977 // already been constant folded. The only reason NOT to constant fold
978 // it is if something (e.g. LSR) was careful to place the constant
979 // evaluation in a block other than then one that uses it (e.g. to hoist
980 // the address of globals out of a loop). If this is the case, we don't
981 // want to forward-subst the cast.
982 if (isa<Constant>(CI->getOperand(0)))
983 return false;
984
985 bool Change = false;
986 if (TLI) {
987 Change = OptimizeNoopCopyExpression(CI, *TLI);
988 MadeChange |= Change;
989 }
990
991 if (!Change && (isa<ZExtInst>(I) || isa<SExtInst>(I))) {
992 MadeChange |= MoveExtToFormExtLoad(I);
993 MadeChange |= OptimizeExtUses(I);
994 }
995 } else if (CmpInst *CI = dyn_cast<CmpInst>(I)) {
996 MadeChange |= OptimizeCmpExpression(CI);
997 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
998 if (TLI)
999 MadeChange |= OptimizeMemoryInst(I, I->getOperand(0), LI->getType(),
1000 SunkAddrs);
1001 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
1002 if (TLI)
1003 MadeChange |= OptimizeMemoryInst(I, SI->getOperand(1),
1004 SI->getOperand(0)->getType(),
1005 SunkAddrs);
Cameron Zwarich865ae1a2011-01-06 02:44:52 +00001006 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
1007 if (GEPI->hasAllZeroIndices()) {
1008 /// The GEP operand must be a pointer, so must its result -> BitCast
1009 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
1010 GEPI->getName(), GEPI);
1011 GEPI->replaceAllUsesWith(NC);
1012 GEPI->eraseFromParent();
1013 ++NumGEPsElim;
1014 MadeChange = true;
1015 OptimizeInst(NC);
1016 }
Cameron Zwarich6cf34ab2011-01-06 02:56:42 +00001017 } else if (CallInst *CI = dyn_cast<CallInst>(I)) {
1018 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
1019 // Sink address computing for memory operands into the block.
1020 MadeChange |= OptimizeInlineAsmInst(I, &(*CI), SunkAddrs);
1021 } else {
1022 MadeChange |= OptimizeCallInst(CI);
1023 }
Cameron Zwarichc0611012011-01-06 02:37:26 +00001024 }
1025
1026 return MadeChange;
1027}
1028
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001029// In this pass we look for GEP and cast instructions that are used
1030// across basic blocks and rewrite them to improve basic-block-at-a-time
1031// selection.
1032bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
1033 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001034
Evan Chengab631522008-12-19 18:03:11 +00001035 // Split all critical edges where the dest block has a PHI.
Evan Chenge1bcb442010-08-17 01:34:49 +00001036 if (CriticalEdgeSplit) {
1037 TerminatorInst *BBTI = BB.getTerminator();
1038 if (BBTI->getNumSuccessors() > 1 && !isa<IndirectBrInst>(BBTI)) {
1039 for (unsigned i = 0, e = BBTI->getNumSuccessors(); i != e; ++i) {
1040 BasicBlock *SuccBB = BBTI->getSuccessor(i);
1041 if (isa<PHINode>(SuccBB->begin()) && isCriticalEdge(BBTI, i, true))
1042 SplitEdgeNicely(BBTI, i, BackEdges, this);
1043 }
Evan Chengab631522008-12-19 18:03:11 +00001044 }
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001045 }
Eric Christopher692bf6b2008-09-24 05:32:41 +00001046
Cameron Zwarich8c3527e2011-01-06 00:42:50 +00001047 SunkAddrs.clear();
Eric Christopher692bf6b2008-09-24 05:32:41 +00001048
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001049 for (BasicBlock::iterator BBI = BB.begin(), E = BB.end(); BBI != E; ) {
1050 Instruction *I = BBI++;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001051
Cameron Zwarich865ae1a2011-01-06 02:44:52 +00001052 if (CallInst *CI = dyn_cast<CallInst>(I)) {
Chris Lattnerdd77df32007-04-13 20:30:56 +00001053 // If we found an inline asm expession, and if the target knows how to
1054 // lower it to normal LLVM code, do so now.
Chris Lattner8850b362009-07-20 17:52:52 +00001055 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
1056 if (TLI->ExpandInlineAsm(CI)) {
1057 BBI = BB.begin();
1058 // Avoid processing instructions out of order, which could cause
1059 // reuse before a value is defined.
1060 SunkAddrs.clear();
1061 } else
1062 // Sink address computing for memory operands into the block.
1063 MadeChange |= OptimizeInlineAsmInst(I, &(*CI), SunkAddrs);
Eric Christopher040056f2010-03-11 02:41:03 +00001064 } else {
1065 // Other CallInst optimizations that don't need to muck with the
1066 // enclosing iterator here.
1067 MadeChange |= OptimizeCallInst(CI);
Chris Lattner8850b362009-07-20 17:52:52 +00001068 }
Cameron Zwarichc0611012011-01-06 02:37:26 +00001069 } else {
1070 MadeChange |= OptimizeInst(I);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001071 }
1072 }
Eric Christopher692bf6b2008-09-24 05:32:41 +00001073
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001074 return MadeChange;
1075}