blob: b59868f80fbab163e790bb0586f7d810434c04f4 [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"
Owen Andersond672ecb2009-07-03 00:17:18 +000024#include "llvm/LLVMContext.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000025#include "llvm/Pass.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"
32#include "llvm/ADT/DenseMap.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000033#include "llvm/ADT/SmallSet.h"
Dan Gohman03ce0422009-02-13 17:45:12 +000034#include "llvm/Assembly/Writer.h"
Evan Cheng9bf12b52008-02-26 02:42:37 +000035#include "llvm/Support/CallSite.h"
Evan Chengab631522008-12-19 18:03:11 +000036#include "llvm/Support/CommandLine.h"
Evan Chengbdcb7262007-12-05 23:58:20 +000037#include "llvm/Support/Debug.h"
Chris Lattnerdd77df32007-04-13 20:30:56 +000038#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner088a1e82008-11-25 04:42:10 +000039#include "llvm/Support/PatternMatch.h"
Dan Gohman6c1980b2009-07-25 01:13:51 +000040#include "llvm/Support/raw_ostream.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000041using namespace llvm;
Chris Lattner088a1e82008-11-25 04:42:10 +000042using namespace llvm::PatternMatch;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000043
Evan Chengab631522008-12-19 18:03:11 +000044static cl::opt<bool> FactorCommonPreds("split-critical-paths-tweak",
45 cl::init(false), cl::Hidden);
46
Eric Christopher692bf6b2008-09-24 05:32:41 +000047namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +000048 class CodeGenPrepare : public FunctionPass {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000049 /// TLI - Keep a pointer of a TargetLowering to consult for determining
50 /// transformation profitability.
51 const TargetLowering *TLI;
Andreas Neustifterad809812009-09-16 09:26:52 +000052 ProfileInfo *PI;
Evan Chengab631522008-12-19 18:03:11 +000053
54 /// BackEdges - Keep a set of all the loop back edges.
55 ///
Mike Stumpfe095f32009-05-04 18:40:41 +000056 SmallSet<std::pair<const BasicBlock*, const BasicBlock*>, 8> BackEdges;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000057 public:
Nick Lewyckyecd94c82007-05-06 13:37:16 +000058 static char ID; // Pass identification, replacement for typeid
Dan Gohmanc2bbfc12007-08-01 15:32:29 +000059 explicit CodeGenPrepare(const TargetLowering *tli = 0)
Dan Gohmanae73dc12008-09-04 17:05:41 +000060 : FunctionPass(&ID), TLI(tli) {}
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000061 bool runOnFunction(Function &F);
Eric Christopher692bf6b2008-09-24 05:32:41 +000062
Andreas Neustifterad809812009-09-16 09:26:52 +000063 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
64 AU.addPreserved<ProfileInfo>();
65 }
66
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000067 private:
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +000068 bool EliminateMostlyEmptyBlocks(Function &F);
69 bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
70 void EliminateMostlyEmptyBlock(BasicBlock *BB);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000071 bool OptimizeBlock(BasicBlock &BB);
Chris Lattner88a5c832008-11-25 07:09:13 +000072 bool OptimizeMemoryInst(Instruction *I, Value *Addr, const Type *AccessTy,
73 DenseMap<Value*,Value*> &SunkAddrs);
Evan Cheng9bf12b52008-02-26 02:42:37 +000074 bool OptimizeInlineAsmInst(Instruction *I, CallSite CS,
75 DenseMap<Value*,Value*> &SunkAddrs);
Dan Gohmanb00f2362009-10-16 20:59:35 +000076 bool MoveExtToFormExtLoad(Instruction *I);
Evan Chengbdcb7262007-12-05 23:58:20 +000077 bool OptimizeExtUses(Instruction *I);
Mike Stumpfe095f32009-05-04 18:40:41 +000078 void findLoopBackEdges(const Function &F);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000079 };
80}
Devang Patel794fd752007-05-01 21:15:47 +000081
Devang Patel19974732007-05-03 01:11:54 +000082char CodeGenPrepare::ID = 0;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000083static RegisterPass<CodeGenPrepare> X("codegenprepare",
84 "Optimize for code generation");
85
86FunctionPass *llvm::createCodeGenPreparePass(const TargetLowering *TLI) {
87 return new CodeGenPrepare(TLI);
88}
89
Evan Chengab631522008-12-19 18:03:11 +000090/// findLoopBackEdges - Do a DFS walk to find loop back edges.
91///
Mike Stumpfe095f32009-05-04 18:40:41 +000092void CodeGenPrepare::findLoopBackEdges(const Function &F) {
93 SmallVector<std::pair<const BasicBlock*,const BasicBlock*>, 32> Edges;
94 FindFunctionBackedges(F, Edges);
95
96 BackEdges.insert(Edges.begin(), Edges.end());
Evan Chengab631522008-12-19 18:03:11 +000097}
98
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000099
100bool CodeGenPrepare::runOnFunction(Function &F) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000101 bool EverMadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000102
Andreas Neustifterad809812009-09-16 09:26:52 +0000103 PI = getAnalysisIfAvailable<ProfileInfo>();
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000104 // First pass, eliminate blocks that contain only PHI nodes and an
105 // unconditional branch.
106 EverMadeChange |= EliminateMostlyEmptyBlocks(F);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000107
Evan Cheng7e66c0d2009-01-05 21:17:27 +0000108 // Now find loop back edges.
109 findLoopBackEdges(F);
110
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000111 bool MadeChange = true;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000112 while (MadeChange) {
113 MadeChange = false;
114 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
115 MadeChange |= OptimizeBlock(*BB);
116 EverMadeChange |= MadeChange;
117 }
118 return EverMadeChange;
119}
120
Dale Johannesen2d697242009-03-27 01:13:37 +0000121/// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes,
122/// debug info directives, and an unconditional branch. Passes before isel
123/// (e.g. LSR/loopsimplify) often split edges in ways that are non-optimal for
124/// isel. Start by eliminating these blocks so we can split them the way we
125/// want them.
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000126bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
127 bool MadeChange = false;
128 // Note that this intentionally skips the entry block.
129 for (Function::iterator I = ++F.begin(), E = F.end(); I != E; ) {
130 BasicBlock *BB = I++;
131
132 // If this block doesn't end with an uncond branch, ignore it.
133 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
134 if (!BI || !BI->isUnconditional())
135 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000136
Dale Johannesen2d697242009-03-27 01:13:37 +0000137 // If the instruction before the branch (skipping debug info) isn't a phi
138 // node, then other stuff is happening here.
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000139 BasicBlock::iterator BBI = BI;
140 if (BBI != BB->begin()) {
141 --BBI;
Dale Johannesen2d697242009-03-27 01:13:37 +0000142 while (isa<DbgInfoIntrinsic>(BBI)) {
143 if (BBI == BB->begin())
144 break;
145 --BBI;
146 }
147 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
148 continue;
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000149 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000150
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000151 // Do not break infinite loops.
152 BasicBlock *DestBB = BI->getSuccessor(0);
153 if (DestBB == BB)
154 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000155
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000156 if (!CanMergeBlocks(BB, DestBB))
157 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000158
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000159 EliminateMostlyEmptyBlock(BB);
160 MadeChange = true;
161 }
162 return MadeChange;
163}
164
165/// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
166/// single uncond branch between them, and BB contains no other non-phi
167/// instructions.
168bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
169 const BasicBlock *DestBB) const {
170 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
171 // the successor. If there are more complex condition (e.g. preheaders),
172 // don't mess around with them.
173 BasicBlock::const_iterator BBI = BB->begin();
174 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
175 for (Value::use_const_iterator UI = PN->use_begin(), E = PN->use_end();
176 UI != E; ++UI) {
177 const Instruction *User = cast<Instruction>(*UI);
178 if (User->getParent() != DestBB || !isa<PHINode>(User))
179 return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000180 // If User is inside DestBB block and it is a PHINode then check
181 // incoming value. If incoming value is not from BB then this is
Devang Patel75abc1e2007-04-25 00:37:04 +0000182 // a complex condition (e.g. preheaders) we want to avoid here.
183 if (User->getParent() == DestBB) {
184 if (const PHINode *UPN = dyn_cast<PHINode>(User))
185 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
186 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
187 if (Insn && Insn->getParent() == BB &&
188 Insn->getParent() != UPN->getIncomingBlock(I))
189 return false;
190 }
191 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000192 }
193 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000194
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000195 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
196 // and DestBB may have conflicting incoming values for the block. If so, we
197 // can't merge the block.
198 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
199 if (!DestBBPN) return true; // no conflict.
Eric Christopher692bf6b2008-09-24 05:32:41 +0000200
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000201 // Collect the preds of BB.
Chris Lattnerf67f73a2007-11-06 22:07:40 +0000202 SmallPtrSet<const BasicBlock*, 16> BBPreds;
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000203 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
204 // It is faster to get preds from a PHI than with pred_iterator.
205 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
206 BBPreds.insert(BBPN->getIncomingBlock(i));
207 } else {
208 BBPreds.insert(pred_begin(BB), pred_end(BB));
209 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000210
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000211 // Walk the preds of DestBB.
212 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
213 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
214 if (BBPreds.count(Pred)) { // Common predecessor?
215 BBI = DestBB->begin();
216 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
217 const Value *V1 = PN->getIncomingValueForBlock(Pred);
218 const Value *V2 = PN->getIncomingValueForBlock(BB);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000219
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000220 // If V2 is a phi node in BB, look up what the mapped value will be.
221 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
222 if (V2PN->getParent() == BB)
223 V2 = V2PN->getIncomingValueForBlock(Pred);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000224
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000225 // If there is a conflict, bail out.
226 if (V1 != V2) return false;
227 }
228 }
229 }
230
231 return true;
232}
233
234
235/// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
236/// an unconditional branch in it.
237void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
238 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
239 BasicBlock *DestBB = BI->getSuccessor(0);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000240
Chris Lattnerbdff5482009-08-23 04:37:46 +0000241 DEBUG(errs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000242
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000243 // If the destination block has a single pred, then this is a trivial edge,
244 // just collapse it.
Chris Lattner9918fb52008-11-27 19:29:14 +0000245 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
Chris Lattnerf5102a02008-11-28 19:54:49 +0000246 if (SinglePred != DestBB) {
247 // Remember if SinglePred was the entry block of the function. If so, we
248 // will need to move BB back to the entry position.
249 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Andreas Neustifterad809812009-09-16 09:26:52 +0000250 MergeBasicBlockIntoOnlyPred(DestBB, this);
Chris Lattner9918fb52008-11-27 19:29:14 +0000251
Chris Lattnerf5102a02008-11-28 19:54:49 +0000252 if (isEntry && BB != &BB->getParent()->getEntryBlock())
253 BB->moveBefore(&BB->getParent()->getEntryBlock());
254
Chris Lattnerbdff5482009-08-23 04:37:46 +0000255 DEBUG(errs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerf5102a02008-11-28 19:54:49 +0000256 return;
257 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000258 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000259
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000260 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
261 // to handle the new incoming edges it is about to have.
262 PHINode *PN;
263 for (BasicBlock::iterator BBI = DestBB->begin();
264 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
265 // Remove the incoming value for BB, and remember it.
266 Value *InVal = PN->removeIncomingValue(BB, false);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000267
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000268 // Two options: either the InVal is a phi node defined in BB or it is some
269 // value that dominates BB.
270 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
271 if (InValPhi && InValPhi->getParent() == BB) {
272 // Add all of the input values of the input PHI as inputs of this phi.
273 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
274 PN->addIncoming(InValPhi->getIncomingValue(i),
275 InValPhi->getIncomingBlock(i));
276 } else {
277 // Otherwise, add one instance of the dominating value for each edge that
278 // we will be adding.
279 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
280 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
281 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
282 } else {
283 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
284 PN->addIncoming(InVal, *PI);
285 }
286 }
287 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000288
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000289 // The PHIs are now updated, change everything that refers to BB to use
290 // DestBB and remove BB.
291 BB->replaceAllUsesWith(DestBB);
Andreas Neustifterad809812009-09-16 09:26:52 +0000292 if (PI) {
293 PI->replaceAllUses(BB, DestBB);
294 PI->removeEdge(ProfileInfo::getEdge(BB, DestBB));
295 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000296 BB->eraseFromParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000297
Chris Lattnerbdff5482009-08-23 04:37:46 +0000298 DEBUG(errs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000299}
300
301
Chris Lattnerebe80752007-12-24 19:32:55 +0000302/// SplitEdgeNicely - Split the critical edge from TI to its specified
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000303/// successor if it will improve codegen. We only do this if the successor has
304/// phi nodes (otherwise critical edges are ok). If there is already another
305/// predecessor of the succ that is empty (and thus has no phi nodes), use it
306/// instead of introducing a new block.
Evan Chengab631522008-12-19 18:03:11 +0000307static void SplitEdgeNicely(TerminatorInst *TI, unsigned SuccNum,
Mike Stumpfe095f32009-05-04 18:40:41 +0000308 SmallSet<std::pair<const BasicBlock*,
309 const BasicBlock*>, 8> &BackEdges,
Evan Chengab631522008-12-19 18:03:11 +0000310 Pass *P) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000311 BasicBlock *TIBB = TI->getParent();
312 BasicBlock *Dest = TI->getSuccessor(SuccNum);
313 assert(isa<PHINode>(Dest->begin()) &&
314 "This should only be called if Dest has a PHI!");
Eric Christopher692bf6b2008-09-24 05:32:41 +0000315
Evan Chengfc0b80d2009-03-13 22:59:14 +0000316 // Do not split edges to EH landing pads.
317 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(TI)) {
318 if (Invoke->getSuccessor(1) == Dest)
319 return;
320 }
Chris Lattnera4b04212009-10-31 22:04:43 +0000321
Evan Chengfc0b80d2009-03-13 22:59:14 +0000322
Chris Lattnerebe80752007-12-24 19:32:55 +0000323 // As a hack, never split backedges of loops. Even though the copy for any
324 // PHIs inserted on the backedge would be dead for exits from the loop, we
325 // assume that the cost of *splitting* the backedge would be too high.
Evan Chengab631522008-12-19 18:03:11 +0000326 if (BackEdges.count(std::make_pair(TIBB, Dest)))
Chris Lattnerebe80752007-12-24 19:32:55 +0000327 return;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000328
Evan Chengab631522008-12-19 18:03:11 +0000329 if (!FactorCommonPreds) {
330 /// TIPHIValues - This array is lazily computed to determine the values of
331 /// PHIs in Dest that TI would provide.
332 SmallVector<Value*, 32> TIPHIValues;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000333
Evan Chengab631522008-12-19 18:03:11 +0000334 // Check to see if Dest has any blocks that can be used as a split edge for
335 // this terminator.
336 for (pred_iterator PI = pred_begin(Dest), E = pred_end(Dest); PI != E; ++PI) {
337 BasicBlock *Pred = *PI;
338 // To be usable, the pred has to end with an uncond branch to the dest.
339 BranchInst *PredBr = dyn_cast<BranchInst>(Pred->getTerminator());
Dale Johannesen6aae1d62009-03-26 01:15:07 +0000340 if (!PredBr || !PredBr->isUnconditional())
341 continue;
342 // Must be empty other than the branch and debug info.
343 BasicBlock::iterator I = Pred->begin();
344 while (isa<DbgInfoIntrinsic>(I))
345 I++;
346 if (dyn_cast<Instruction>(I) != PredBr)
347 continue;
348 // Cannot be the entry block; its label does not get emitted.
349 if (Pred == &(Dest->getParent()->getEntryBlock()))
Evan Chengab631522008-12-19 18:03:11 +0000350 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000351
Evan Chengab631522008-12-19 18:03:11 +0000352 // Finally, since we know that Dest has phi nodes in it, we have to make
Dale Johannesen6aae1d62009-03-26 01:15:07 +0000353 // sure that jumping to Pred will have the same effect as going to Dest in
Evan Chengab631522008-12-19 18:03:11 +0000354 // terms of PHI values.
355 PHINode *PN;
356 unsigned PHINo = 0;
357 bool FoundMatch = true;
358 for (BasicBlock::iterator I = Dest->begin();
359 (PN = dyn_cast<PHINode>(I)); ++I, ++PHINo) {
360 if (PHINo == TIPHIValues.size())
361 TIPHIValues.push_back(PN->getIncomingValueForBlock(TIBB));
Eric Christopher692bf6b2008-09-24 05:32:41 +0000362
Evan Chengab631522008-12-19 18:03:11 +0000363 // If the PHI entry doesn't work, we can't use this pred.
364 if (TIPHIValues[PHINo] != PN->getIncomingValueForBlock(Pred)) {
365 FoundMatch = false;
366 break;
367 }
368 }
369
370 // If we found a workable predecessor, change TI to branch to Succ.
371 if (FoundMatch) {
Andreas Neustifterad809812009-09-16 09:26:52 +0000372 ProfileInfo *PI = P->getAnalysisIfAvailable<ProfileInfo>();
373 if (PI)
374 PI->splitEdge(TIBB, Dest, Pred);
Evan Chengab631522008-12-19 18:03:11 +0000375 Dest->removePredecessor(TIBB);
376 TI->setSuccessor(SuccNum, Pred);
377 return;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000378 }
379 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000380
Evan Chengab631522008-12-19 18:03:11 +0000381 SplitCriticalEdge(TI, SuccNum, P, true);
382 return;
383 }
384
385 PHINode *PN;
386 SmallVector<Value*, 8> TIPHIValues;
387 for (BasicBlock::iterator I = Dest->begin();
388 (PN = dyn_cast<PHINode>(I)); ++I)
389 TIPHIValues.push_back(PN->getIncomingValueForBlock(TIBB));
390
391 SmallVector<BasicBlock*, 8> IdenticalPreds;
392 for (pred_iterator PI = pred_begin(Dest), E = pred_end(Dest); PI != E; ++PI) {
393 BasicBlock *Pred = *PI;
394 if (BackEdges.count(std::make_pair(Pred, Dest)))
395 continue;
396 if (PI == TIBB)
397 IdenticalPreds.push_back(Pred);
398 else {
399 bool Identical = true;
400 unsigned PHINo = 0;
401 for (BasicBlock::iterator I = Dest->begin();
402 (PN = dyn_cast<PHINode>(I)); ++I, ++PHINo)
403 if (TIPHIValues[PHINo] != PN->getIncomingValueForBlock(Pred)) {
404 Identical = false;
405 break;
406 }
407 if (Identical)
408 IdenticalPreds.push_back(Pred);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000409 }
410 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000411
Evan Chengab631522008-12-19 18:03:11 +0000412 assert(!IdenticalPreds.empty());
413 SplitBlockPredecessors(Dest, &IdenticalPreds[0], IdenticalPreds.size(),
414 ".critedge", P);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000415}
416
Evan Chengab631522008-12-19 18:03:11 +0000417
Chris Lattnerdd77df32007-04-13 20:30:56 +0000418/// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
Dan Gohmana119de82009-06-14 23:30:43 +0000419/// copy (e.g. it's casting from one pointer type to another, i32->i8 on PPC),
420/// sink it into user blocks to reduce the number of virtual
Dale Johannesence0b2372007-06-12 16:50:17 +0000421/// registers that must be created and coalesced.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000422///
423/// Return true if any changes are made.
Chris Lattner85fa13c2008-11-24 22:44:16 +0000424///
Chris Lattnerdd77df32007-04-13 20:30:56 +0000425static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
Eric Christopher692bf6b2008-09-24 05:32:41 +0000426 // If this is a noop copy,
Owen Andersone50ed302009-08-10 22:56:29 +0000427 EVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
428 EVT DstVT = TLI.getValueType(CI->getType());
Eric Christopher692bf6b2008-09-24 05:32:41 +0000429
Chris Lattnerdd77df32007-04-13 20:30:56 +0000430 // This is an fp<->int conversion?
Duncan Sands83ec4b62008-06-06 12:08:01 +0000431 if (SrcVT.isInteger() != DstVT.isInteger())
Chris Lattnerdd77df32007-04-13 20:30:56 +0000432 return false;
Duncan Sands8e4eb092008-06-08 20:54:56 +0000433
Chris Lattnerdd77df32007-04-13 20:30:56 +0000434 // If this is an extension, it will be a zero or sign extension, which
435 // isn't a noop.
Duncan Sands8e4eb092008-06-08 20:54:56 +0000436 if (SrcVT.bitsLT(DstVT)) return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000437
Chris Lattnerdd77df32007-04-13 20:30:56 +0000438 // If these values will be promoted, find out what they will be promoted
439 // to. This helps us consider truncates on PPC as noop copies when they
440 // are.
Owen Anderson23b9b192009-08-12 00:36:31 +0000441 if (TLI.getTypeAction(CI->getContext(), SrcVT) == TargetLowering::Promote)
442 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
443 if (TLI.getTypeAction(CI->getContext(), DstVT) == TargetLowering::Promote)
444 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000445
Chris Lattnerdd77df32007-04-13 20:30:56 +0000446 // If, after promotion, these are the same types, this is a noop copy.
447 if (SrcVT != DstVT)
448 return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000449
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000450 BasicBlock *DefBB = CI->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000451
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000452 /// InsertedCasts - Only insert a cast in each block once.
Dale Johannesence0b2372007-06-12 16:50:17 +0000453 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000454
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000455 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000456 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000457 UI != E; ) {
458 Use &TheUse = UI.getUse();
459 Instruction *User = cast<Instruction>(*UI);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000460
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000461 // Figure out which BB this cast is used in. For PHI's this is the
462 // appropriate predecessor block.
463 BasicBlock *UserBB = User->getParent();
464 if (PHINode *PN = dyn_cast<PHINode>(User)) {
Gabor Greifa36791d2009-01-23 19:40:15 +0000465 UserBB = PN->getIncomingBlock(UI);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000466 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000467
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000468 // Preincrement use iterator so we don't invalidate it.
469 ++UI;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000470
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000471 // If this user is in the same block as the cast, don't change the cast.
472 if (UserBB == DefBB) continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000473
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000474 // If we have already inserted a cast into this block, use it.
475 CastInst *&InsertedCast = InsertedCasts[UserBB];
476
477 if (!InsertedCast) {
Dan Gohman02dea8b2008-05-23 21:05:58 +0000478 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000479
480 InsertedCast =
481 CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000482 InsertPt);
483 MadeChange = true;
484 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000485
Dale Johannesence0b2372007-06-12 16:50:17 +0000486 // Replace a use of the cast with a use of the new cast.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000487 TheUse = InsertedCast;
488 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000489
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000490 // If we removed all uses, nuke the cast.
Duncan Sandse0038132008-01-20 16:51:46 +0000491 if (CI->use_empty()) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000492 CI->eraseFromParent();
Duncan Sandse0038132008-01-20 16:51:46 +0000493 MadeChange = true;
494 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000495
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000496 return MadeChange;
497}
498
Eric Christopher692bf6b2008-09-24 05:32:41 +0000499/// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
Dale Johannesence0b2372007-06-12 16:50:17 +0000500/// the number of virtual registers that must be created and coalesced. This is
Chris Lattner684b22d2007-08-02 16:53:43 +0000501/// a clear win except on targets with multiple condition code registers
502/// (PowerPC), where it might lose; some adjustment may be wanted there.
Dale Johannesence0b2372007-06-12 16:50:17 +0000503///
504/// Return true if any changes are made.
Chris Lattner85fa13c2008-11-24 22:44:16 +0000505static bool OptimizeCmpExpression(CmpInst *CI) {
Dale Johannesence0b2372007-06-12 16:50:17 +0000506 BasicBlock *DefBB = CI->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000507
Dale Johannesence0b2372007-06-12 16:50:17 +0000508 /// InsertedCmp - Only insert a cmp in each block once.
509 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000510
Dale Johannesence0b2372007-06-12 16:50:17 +0000511 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000512 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
Dale Johannesence0b2372007-06-12 16:50:17 +0000513 UI != E; ) {
514 Use &TheUse = UI.getUse();
515 Instruction *User = cast<Instruction>(*UI);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000516
Dale Johannesence0b2372007-06-12 16:50:17 +0000517 // Preincrement use iterator so we don't invalidate it.
518 ++UI;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000519
Dale Johannesence0b2372007-06-12 16:50:17 +0000520 // Don't bother for PHI nodes.
521 if (isa<PHINode>(User))
522 continue;
523
524 // Figure out which BB this cmp is used in.
525 BasicBlock *UserBB = User->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000526
Dale Johannesence0b2372007-06-12 16:50:17 +0000527 // If this user is in the same block as the cmp, don't change the cmp.
528 if (UserBB == DefBB) continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000529
Dale Johannesence0b2372007-06-12 16:50:17 +0000530 // If we have already inserted a cmp into this block, use it.
531 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
532
533 if (!InsertedCmp) {
Dan Gohman02dea8b2008-05-23 21:05:58 +0000534 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000535
536 InsertedCmp =
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000537 CmpInst::Create(CI->getOpcode(),
Owen Anderson333c4002009-07-09 23:48:35 +0000538 CI->getPredicate(), CI->getOperand(0),
Dale Johannesence0b2372007-06-12 16:50:17 +0000539 CI->getOperand(1), "", InsertPt);
540 MadeChange = true;
541 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000542
Dale Johannesence0b2372007-06-12 16:50:17 +0000543 // Replace a use of the cmp with a use of the new cmp.
544 TheUse = InsertedCmp;
545 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000546
Dale Johannesence0b2372007-06-12 16:50:17 +0000547 // If we removed all uses, nuke the cmp.
548 if (CI->use_empty())
549 CI->eraseFromParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000550
Dale Johannesence0b2372007-06-12 16:50:17 +0000551 return MadeChange;
552}
553
Chris Lattner88a5c832008-11-25 07:09:13 +0000554//===----------------------------------------------------------------------===//
Chris Lattner88a5c832008-11-25 07:09:13 +0000555// Memory Optimization
556//===----------------------------------------------------------------------===//
557
Chris Lattnerdd77df32007-04-13 20:30:56 +0000558/// IsNonLocalValue - Return true if the specified values are defined in a
559/// different basic block than BB.
560static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
561 if (Instruction *I = dyn_cast<Instruction>(V))
562 return I->getParent() != BB;
563 return false;
564}
565
Bob Wilson4a8ee232009-12-03 21:47:07 +0000566/// OptimizeMemoryInst - Load and Store Instructions often have
Chris Lattnerdd77df32007-04-13 20:30:56 +0000567/// addressing modes that can do significant amounts of computation. As such,
568/// instruction selection will try to get the load or store to do as much
569/// computation as possible for the program. The problem is that isel can only
570/// see within a single block. As such, we sink as much legal addressing mode
571/// stuff into the block as possible.
Chris Lattner88a5c832008-11-25 07:09:13 +0000572///
573/// This method is used to optimize both load/store and inline asms with memory
574/// operands.
Chris Lattner896617b2008-11-26 03:20:37 +0000575bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
Chris Lattner88a5c832008-11-25 07:09:13 +0000576 const Type *AccessTy,
577 DenseMap<Value*,Value*> &SunkAddrs) {
Chris Lattnerdd77df32007-04-13 20:30:56 +0000578 // Figure out what addressing mode will be built up for this operation.
579 SmallVector<Instruction*, 16> AddrModeInsts;
Chris Lattner896617b2008-11-26 03:20:37 +0000580 ExtAddrMode AddrMode = AddressingModeMatcher::Match(Addr, AccessTy,MemoryInst,
581 AddrModeInsts, *TLI);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000582
Chris Lattnerdd77df32007-04-13 20:30:56 +0000583 // Check to see if any of the instructions supersumed by this addr mode are
584 // non-local to I's BB.
585 bool AnyNonLocal = false;
586 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
Chris Lattner896617b2008-11-26 03:20:37 +0000587 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
Chris Lattnerdd77df32007-04-13 20:30:56 +0000588 AnyNonLocal = true;
589 break;
590 }
591 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000592
Chris Lattnerdd77df32007-04-13 20:30:56 +0000593 // If all the instructions matched are already in this BB, don't do anything.
594 if (!AnyNonLocal) {
Dan Gohman6c1980b2009-07-25 01:13:51 +0000595 DEBUG(errs() << "CGP: Found local addrmode: " << AddrMode << "\n");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000596 return false;
597 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000598
Chris Lattnerdd77df32007-04-13 20:30:56 +0000599 // Insert this computation right after this user. Since our caller is
600 // scanning from the top of the BB to the bottom, reuse of the expr are
601 // guaranteed to happen later.
Chris Lattner896617b2008-11-26 03:20:37 +0000602 BasicBlock::iterator InsertPt = MemoryInst;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000603
Chris Lattnerdd77df32007-04-13 20:30:56 +0000604 // Now that we determined the addressing expression we want to use and know
605 // that we have to sink it into this block. Check to see if we have already
606 // done this for some other load/store instr in this block. If so, reuse the
607 // computation.
608 Value *&SunkAddr = SunkAddrs[Addr];
609 if (SunkAddr) {
Dan Gohman6c1980b2009-07-25 01:13:51 +0000610 DEBUG(errs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
611 << *MemoryInst);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000612 if (SunkAddr->getType() != Addr->getType())
613 SunkAddr = new BitCastInst(SunkAddr, Addr->getType(), "tmp", InsertPt);
614 } else {
Dan Gohman6c1980b2009-07-25 01:13:51 +0000615 DEBUG(errs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
616 << *MemoryInst);
Owen Anderson1d0be152009-08-13 21:58:54 +0000617 const Type *IntPtrTy =
618 TLI->getTargetData()->getIntPtrType(AccessTy->getContext());
Eric Christopher692bf6b2008-09-24 05:32:41 +0000619
Chris Lattnerdd77df32007-04-13 20:30:56 +0000620 Value *Result = 0;
621 // Start with the scale value.
622 if (AddrMode.Scale) {
623 Value *V = AddrMode.ScaledReg;
624 if (V->getType() == IntPtrTy) {
625 // done.
626 } else if (isa<PointerType>(V->getType())) {
627 V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
628 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
629 cast<IntegerType>(V->getType())->getBitWidth()) {
630 V = new TruncInst(V, IntPtrTy, "sunkaddr", InsertPt);
631 } else {
632 V = new SExtInst(V, IntPtrTy, "sunkaddr", InsertPt);
633 }
634 if (AddrMode.Scale != 1)
Owen Andersoneed707b2009-07-24 23:12:02 +0000635 V = BinaryOperator::CreateMul(V, ConstantInt::get(IntPtrTy,
Owen Andersond672ecb2009-07-03 00:17:18 +0000636 AddrMode.Scale),
Chris Lattnerdd77df32007-04-13 20:30:56 +0000637 "sunkaddr", InsertPt);
638 Result = V;
639 }
640
641 // Add in the base register.
642 if (AddrMode.BaseReg) {
643 Value *V = AddrMode.BaseReg;
Dan Gohman8b0d4f62009-06-02 21:29:13 +0000644 if (isa<PointerType>(V->getType()))
Chris Lattnerdd77df32007-04-13 20:30:56 +0000645 V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
Dan Gohman8b0d4f62009-06-02 21:29:13 +0000646 if (V->getType() != IntPtrTy)
647 V = CastInst::CreateIntegerCast(V, IntPtrTy, /*isSigned=*/true,
648 "sunkaddr", InsertPt);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000649 if (Result)
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000650 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000651 else
652 Result = V;
653 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000654
Chris Lattnerdd77df32007-04-13 20:30:56 +0000655 // Add in the BaseGV if present.
656 if (AddrMode.BaseGV) {
657 Value *V = new PtrToIntInst(AddrMode.BaseGV, IntPtrTy, "sunkaddr",
658 InsertPt);
659 if (Result)
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000660 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000661 else
662 Result = V;
663 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000664
Chris Lattnerdd77df32007-04-13 20:30:56 +0000665 // Add in the Base Offset if present.
666 if (AddrMode.BaseOffs) {
Owen Andersoneed707b2009-07-24 23:12:02 +0000667 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000668 if (Result)
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000669 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000670 else
671 Result = V;
672 }
673
674 if (Result == 0)
Owen Andersona7235ea2009-07-31 20:28:14 +0000675 SunkAddr = Constant::getNullValue(Addr->getType());
Chris Lattnerdd77df32007-04-13 20:30:56 +0000676 else
677 SunkAddr = new IntToPtrInst(Result, Addr->getType(), "sunkaddr",InsertPt);
678 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000679
Chris Lattner896617b2008-11-26 03:20:37 +0000680 MemoryInst->replaceUsesOfWith(Addr, SunkAddr);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000681
Chris Lattnerdd77df32007-04-13 20:30:56 +0000682 if (Addr->use_empty())
Chris Lattner3481f242008-11-27 22:57:53 +0000683 RecursivelyDeleteTriviallyDeadInstructions(Addr);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000684 return true;
685}
686
Evan Cheng9bf12b52008-02-26 02:42:37 +0000687/// OptimizeInlineAsmInst - If there are any memory operands, use
Chris Lattner88a5c832008-11-25 07:09:13 +0000688/// OptimizeMemoryInst to sink their address computing into the block when
Evan Cheng9bf12b52008-02-26 02:42:37 +0000689/// possible / profitable.
690bool CodeGenPrepare::OptimizeInlineAsmInst(Instruction *I, CallSite CS,
691 DenseMap<Value*,Value*> &SunkAddrs) {
692 bool MadeChange = false;
693 InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
694
695 // Do a prepass over the constraints, canonicalizing them, and building up the
696 // ConstraintOperands list.
697 std::vector<InlineAsm::ConstraintInfo>
698 ConstraintInfos = IA->ParseConstraints();
699
700 /// ConstraintOperands - Information about all of the constraints.
701 std::vector<TargetLowering::AsmOperandInfo> ConstraintOperands;
702 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
703 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
704 ConstraintOperands.
705 push_back(TargetLowering::AsmOperandInfo(ConstraintInfos[i]));
706 TargetLowering::AsmOperandInfo &OpInfo = ConstraintOperands.back();
707
708 // Compute the value type for each operand.
709 switch (OpInfo.Type) {
710 case InlineAsm::isOutput:
711 if (OpInfo.isIndirect)
712 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
713 break;
714 case InlineAsm::isInput:
715 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
716 break;
717 case InlineAsm::isClobber:
718 // Nothing to do.
719 break;
720 }
721
722 // Compute the constraint code and ConstraintType to use.
Evan Chenga7e61462008-09-24 06:48:55 +0000723 TLI->ComputeConstraintToUse(OpInfo, SDValue(),
724 OpInfo.ConstraintType == TargetLowering::C_Memory);
Evan Cheng9bf12b52008-02-26 02:42:37 +0000725
Eli Friedman9ec80952008-02-26 18:37:49 +0000726 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
727 OpInfo.isIndirect) {
Evan Cheng9bf12b52008-02-26 02:42:37 +0000728 Value *OpVal = OpInfo.CallOperandVal;
Chris Lattner88a5c832008-11-25 07:09:13 +0000729 MadeChange |= OptimizeMemoryInst(I, OpVal, OpVal->getType(), SunkAddrs);
Evan Cheng9bf12b52008-02-26 02:42:37 +0000730 }
731 }
732
733 return MadeChange;
734}
735
Dan Gohmanb00f2362009-10-16 20:59:35 +0000736/// MoveExtToFormExtLoad - Move a zext or sext fed by a load into the same
737/// basic block as the load, unless conditions are unfavorable. This allows
738/// SelectionDAG to fold the extend into the load.
739///
740bool CodeGenPrepare::MoveExtToFormExtLoad(Instruction *I) {
741 // Look for a load being extended.
742 LoadInst *LI = dyn_cast<LoadInst>(I->getOperand(0));
743 if (!LI) return false;
744
745 // If they're already in the same block, there's nothing to do.
746 if (LI->getParent() == I->getParent())
747 return false;
748
749 // If the load has other users and the truncate is not free, this probably
750 // isn't worthwhile.
751 if (!LI->hasOneUse() &&
752 TLI && !TLI->isTruncateFree(I->getType(), LI->getType()))
753 return false;
754
755 // Check whether the target supports casts folded into loads.
756 unsigned LType;
757 if (isa<ZExtInst>(I))
758 LType = ISD::ZEXTLOAD;
759 else {
760 assert(isa<SExtInst>(I) && "Unexpected ext type!");
761 LType = ISD::SEXTLOAD;
762 }
763 if (TLI && !TLI->isLoadExtLegal(LType, TLI->getValueType(LI->getType())))
764 return false;
765
766 // Move the extend into the same block as the load, so that SelectionDAG
767 // can fold it.
768 I->removeFromParent();
769 I->insertAfter(LI);
770 return true;
771}
772
Evan Chengbdcb7262007-12-05 23:58:20 +0000773bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
774 BasicBlock *DefBB = I->getParent();
775
776 // If both result of the {s|z}xt and its source are live out, rewrite all
777 // other uses of the source with result of extension.
778 Value *Src = I->getOperand(0);
779 if (Src->hasOneUse())
780 return false;
781
Evan Cheng696e5c02007-12-13 07:50:36 +0000782 // Only do this xform if truncating is free.
Gabor Greif53bdbd72008-02-26 19:13:21 +0000783 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
Evan Chengf9785f92007-12-13 03:32:53 +0000784 return false;
785
Evan Cheng772de512007-12-12 00:51:06 +0000786 // Only safe to perform the optimization if the source is also defined in
Evan Cheng765dff22007-12-12 02:53:41 +0000787 // this block.
788 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
Evan Cheng772de512007-12-12 00:51:06 +0000789 return false;
790
Evan Chengbdcb7262007-12-05 23:58:20 +0000791 bool DefIsLiveOut = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000792 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
Evan Chengbdcb7262007-12-05 23:58:20 +0000793 UI != E; ++UI) {
794 Instruction *User = cast<Instruction>(*UI);
795
796 // Figure out which BB this ext is used in.
797 BasicBlock *UserBB = User->getParent();
798 if (UserBB == DefBB) continue;
799 DefIsLiveOut = true;
800 break;
801 }
802 if (!DefIsLiveOut)
803 return false;
804
Evan Cheng765dff22007-12-12 02:53:41 +0000805 // Make sure non of the uses are PHI nodes.
Eric Christopher692bf6b2008-09-24 05:32:41 +0000806 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
Evan Cheng765dff22007-12-12 02:53:41 +0000807 UI != E; ++UI) {
808 Instruction *User = cast<Instruction>(*UI);
Evan Chengf9785f92007-12-13 03:32:53 +0000809 BasicBlock *UserBB = User->getParent();
810 if (UserBB == DefBB) continue;
811 // Be conservative. We don't want this xform to end up introducing
812 // reloads just before load / store instructions.
813 if (isa<PHINode>(User) || isa<LoadInst>(User) || isa<StoreInst>(User))
Evan Cheng765dff22007-12-12 02:53:41 +0000814 return false;
815 }
816
Evan Chengbdcb7262007-12-05 23:58:20 +0000817 // InsertedTruncs - Only insert one trunc in each block once.
818 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
819
820 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000821 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
Evan Chengbdcb7262007-12-05 23:58:20 +0000822 UI != E; ++UI) {
823 Use &TheUse = UI.getUse();
824 Instruction *User = cast<Instruction>(*UI);
825
826 // Figure out which BB this ext is used in.
827 BasicBlock *UserBB = User->getParent();
828 if (UserBB == DefBB) continue;
829
830 // Both src and def are live in this block. Rewrite the use.
831 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
832
833 if (!InsertedTrunc) {
Dan Gohman02dea8b2008-05-23 21:05:58 +0000834 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000835
Evan Chengbdcb7262007-12-05 23:58:20 +0000836 InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
837 }
838
839 // Replace a use of the {s|z}ext source with a use of the result.
840 TheUse = InsertedTrunc;
841
842 MadeChange = true;
843 }
844
845 return MadeChange;
846}
847
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000848// In this pass we look for GEP and cast instructions that are used
849// across basic blocks and rewrite them to improve basic-block-at-a-time
850// selection.
851bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
852 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000853
Evan Chengab631522008-12-19 18:03:11 +0000854 // Split all critical edges where the dest block has a PHI.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000855 TerminatorInst *BBTI = BB.getTerminator();
Chris Lattnera4b04212009-10-31 22:04:43 +0000856 if (BBTI->getNumSuccessors() > 1 && !isa<IndirectBrInst>(BBTI)) {
Evan Chengab631522008-12-19 18:03:11 +0000857 for (unsigned i = 0, e = BBTI->getNumSuccessors(); i != e; ++i) {
858 BasicBlock *SuccBB = BBTI->getSuccessor(i);
859 if (isa<PHINode>(SuccBB->begin()) && isCriticalEdge(BBTI, i, true))
860 SplitEdgeNicely(BBTI, i, BackEdges, this);
861 }
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000862 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000863
Chris Lattnerdd77df32007-04-13 20:30:56 +0000864 // Keep track of non-local addresses that have been sunk into this block.
865 // This allows us to avoid inserting duplicate code for blocks with multiple
866 // load/stores of the same address.
867 DenseMap<Value*, Value*> SunkAddrs;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000868
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000869 for (BasicBlock::iterator BBI = BB.begin(), E = BB.end(); BBI != E; ) {
870 Instruction *I = BBI++;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000871
Chris Lattnerdd77df32007-04-13 20:30:56 +0000872 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000873 // If the source of the cast is a constant, then this should have
874 // already been constant folded. The only reason NOT to constant fold
875 // it is if something (e.g. LSR) was careful to place the constant
876 // evaluation in a block other than then one that uses it (e.g. to hoist
877 // the address of globals out of a loop). If this is the case, we don't
878 // want to forward-subst the cast.
879 if (isa<Constant>(CI->getOperand(0)))
880 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000881
Evan Chengbdcb7262007-12-05 23:58:20 +0000882 bool Change = false;
883 if (TLI) {
884 Change = OptimizeNoopCopyExpression(CI, *TLI);
885 MadeChange |= Change;
886 }
887
Dan Gohmanb00f2362009-10-16 20:59:35 +0000888 if (!Change && (isa<ZExtInst>(I) || isa<SExtInst>(I))) {
889 MadeChange |= MoveExtToFormExtLoad(I);
Evan Chengbdcb7262007-12-05 23:58:20 +0000890 MadeChange |= OptimizeExtUses(I);
Dan Gohmanb00f2362009-10-16 20:59:35 +0000891 }
Dale Johannesence0b2372007-06-12 16:50:17 +0000892 } else if (CmpInst *CI = dyn_cast<CmpInst>(I)) {
893 MadeChange |= OptimizeCmpExpression(CI);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000894 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
895 if (TLI)
Chris Lattner88a5c832008-11-25 07:09:13 +0000896 MadeChange |= OptimizeMemoryInst(I, I->getOperand(0), LI->getType(),
897 SunkAddrs);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000898 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
899 if (TLI)
Chris Lattner88a5c832008-11-25 07:09:13 +0000900 MadeChange |= OptimizeMemoryInst(I, SI->getOperand(1),
901 SI->getOperand(0)->getType(),
902 SunkAddrs);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000903 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Chris Lattnerf25646b2007-04-14 00:17:39 +0000904 if (GEPI->hasAllZeroIndices()) {
Chris Lattnerdd77df32007-04-13 20:30:56 +0000905 /// The GEP operand must be a pointer, so must its result -> BitCast
Eric Christopher692bf6b2008-09-24 05:32:41 +0000906 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
Chris Lattnerdd77df32007-04-13 20:30:56 +0000907 GEPI->getName(), GEPI);
908 GEPI->replaceAllUsesWith(NC);
909 GEPI->eraseFromParent();
910 MadeChange = true;
911 BBI = NC;
912 }
913 } else if (CallInst *CI = dyn_cast<CallInst>(I)) {
914 // If we found an inline asm expession, and if the target knows how to
915 // lower it to normal LLVM code, do so now.
Chris Lattner8850b362009-07-20 17:52:52 +0000916 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
917 if (TLI->ExpandInlineAsm(CI)) {
918 BBI = BB.begin();
919 // Avoid processing instructions out of order, which could cause
920 // reuse before a value is defined.
921 SunkAddrs.clear();
922 } else
923 // Sink address computing for memory operands into the block.
924 MadeChange |= OptimizeInlineAsmInst(I, &(*CI), SunkAddrs);
925 }
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000926 }
927 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000928
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000929 return MadeChange;
930}