blob: b8664b0d4a1ca4c0ddc1a473ec6d4327945d81b3 [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"
23#include "llvm/Pass.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000024#include "llvm/Target/TargetAsmInfo.h"
25#include "llvm/Target/TargetData.h"
26#include "llvm/Target/TargetLowering.h"
27#include "llvm/Target/TargetMachine.h"
28#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattnerdd77df32007-04-13 20:30:56 +000029#include "llvm/Transforms/Utils/Local.h"
30#include "llvm/ADT/DenseMap.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000031#include "llvm/ADT/SmallSet.h"
Evan Cheng9bf12b52008-02-26 02:42:37 +000032#include "llvm/Support/CallSite.h"
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +000033#include "llvm/Support/Compiler.h"
Evan Chengbdcb7262007-12-05 23:58:20 +000034#include "llvm/Support/Debug.h"
Chris Lattnerdd77df32007-04-13 20:30:56 +000035#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000036using namespace llvm;
37
Eric Christopher692bf6b2008-09-24 05:32:41 +000038namespace {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000039 class VISIBILITY_HIDDEN CodeGenPrepare : public FunctionPass {
40 /// TLI - Keep a pointer of a TargetLowering to consult for determining
41 /// transformation profitability.
42 const TargetLowering *TLI;
43 public:
Nick Lewyckyecd94c82007-05-06 13:37:16 +000044 static char ID; // Pass identification, replacement for typeid
Dan Gohmanc2bbfc12007-08-01 15:32:29 +000045 explicit CodeGenPrepare(const TargetLowering *tli = 0)
Dan Gohmanae73dc12008-09-04 17:05:41 +000046 : FunctionPass(&ID), TLI(tli) {}
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000047 bool runOnFunction(Function &F);
Eric Christopher692bf6b2008-09-24 05:32:41 +000048
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000049 private:
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +000050 bool EliminateMostlyEmptyBlocks(Function &F);
51 bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
52 void EliminateMostlyEmptyBlock(BasicBlock *BB);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000053 bool OptimizeBlock(BasicBlock &BB);
Chris Lattnerdd77df32007-04-13 20:30:56 +000054 bool OptimizeLoadStoreInst(Instruction *I, Value *Addr,
55 const Type *AccessTy,
56 DenseMap<Value*,Value*> &SunkAddrs);
Evan Cheng9bf12b52008-02-26 02:42:37 +000057 bool OptimizeInlineAsmInst(Instruction *I, CallSite CS,
58 DenseMap<Value*,Value*> &SunkAddrs);
Evan Chengbdcb7262007-12-05 23:58:20 +000059 bool OptimizeExtUses(Instruction *I);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000060 };
61}
Devang Patel794fd752007-05-01 21:15:47 +000062
Devang Patel19974732007-05-03 01:11:54 +000063char CodeGenPrepare::ID = 0;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000064static RegisterPass<CodeGenPrepare> X("codegenprepare",
65 "Optimize for code generation");
66
67FunctionPass *llvm::createCodeGenPreparePass(const TargetLowering *TLI) {
68 return new CodeGenPrepare(TLI);
69}
70
71
72bool CodeGenPrepare::runOnFunction(Function &F) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000073 bool EverMadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +000074
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +000075 // First pass, eliminate blocks that contain only PHI nodes and an
76 // unconditional branch.
77 EverMadeChange |= EliminateMostlyEmptyBlocks(F);
Eric Christopher692bf6b2008-09-24 05:32:41 +000078
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +000079 bool MadeChange = true;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000080 while (MadeChange) {
81 MadeChange = false;
82 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
83 MadeChange |= OptimizeBlock(*BB);
84 EverMadeChange |= MadeChange;
85 }
86 return EverMadeChange;
87}
88
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +000089/// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes
Eric Christopher692bf6b2008-09-24 05:32:41 +000090/// and an unconditional branch. Passes before isel (e.g. LSR/loopsimplify)
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +000091/// often split edges in ways that are non-optimal for isel. Start by
92/// eliminating these blocks so we can split them the way we want them.
93bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
94 bool MadeChange = false;
95 // Note that this intentionally skips the entry block.
96 for (Function::iterator I = ++F.begin(), E = F.end(); I != E; ) {
97 BasicBlock *BB = I++;
98
99 // If this block doesn't end with an uncond branch, ignore it.
100 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
101 if (!BI || !BI->isUnconditional())
102 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000103
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000104 // If the instruction before the branch isn't a phi node, then other stuff
105 // is happening here.
106 BasicBlock::iterator BBI = BI;
107 if (BBI != BB->begin()) {
108 --BBI;
109 if (!isa<PHINode>(BBI)) continue;
110 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000111
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000112 // Do not break infinite loops.
113 BasicBlock *DestBB = BI->getSuccessor(0);
114 if (DestBB == BB)
115 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000116
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000117 if (!CanMergeBlocks(BB, DestBB))
118 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000119
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000120 EliminateMostlyEmptyBlock(BB);
121 MadeChange = true;
122 }
123 return MadeChange;
124}
125
126/// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
127/// single uncond branch between them, and BB contains no other non-phi
128/// instructions.
129bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
130 const BasicBlock *DestBB) const {
131 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
132 // the successor. If there are more complex condition (e.g. preheaders),
133 // don't mess around with them.
134 BasicBlock::const_iterator BBI = BB->begin();
135 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
136 for (Value::use_const_iterator UI = PN->use_begin(), E = PN->use_end();
137 UI != E; ++UI) {
138 const Instruction *User = cast<Instruction>(*UI);
139 if (User->getParent() != DestBB || !isa<PHINode>(User))
140 return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000141 // If User is inside DestBB block and it is a PHINode then check
142 // incoming value. If incoming value is not from BB then this is
Devang Patel75abc1e2007-04-25 00:37:04 +0000143 // a complex condition (e.g. preheaders) we want to avoid here.
144 if (User->getParent() == DestBB) {
145 if (const PHINode *UPN = dyn_cast<PHINode>(User))
146 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
147 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
148 if (Insn && Insn->getParent() == BB &&
149 Insn->getParent() != UPN->getIncomingBlock(I))
150 return false;
151 }
152 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000153 }
154 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000155
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000156 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
157 // and DestBB may have conflicting incoming values for the block. If so, we
158 // can't merge the block.
159 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
160 if (!DestBBPN) return true; // no conflict.
Eric Christopher692bf6b2008-09-24 05:32:41 +0000161
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000162 // Collect the preds of BB.
Chris Lattnerf67f73a2007-11-06 22:07:40 +0000163 SmallPtrSet<const BasicBlock*, 16> BBPreds;
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000164 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
165 // It is faster to get preds from a PHI than with pred_iterator.
166 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
167 BBPreds.insert(BBPN->getIncomingBlock(i));
168 } else {
169 BBPreds.insert(pred_begin(BB), pred_end(BB));
170 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000171
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000172 // Walk the preds of DestBB.
173 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
174 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
175 if (BBPreds.count(Pred)) { // Common predecessor?
176 BBI = DestBB->begin();
177 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
178 const Value *V1 = PN->getIncomingValueForBlock(Pred);
179 const Value *V2 = PN->getIncomingValueForBlock(BB);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000180
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000181 // If V2 is a phi node in BB, look up what the mapped value will be.
182 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
183 if (V2PN->getParent() == BB)
184 V2 = V2PN->getIncomingValueForBlock(Pred);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000185
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000186 // If there is a conflict, bail out.
187 if (V1 != V2) return false;
188 }
189 }
190 }
191
192 return true;
193}
194
195
196/// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
197/// an unconditional branch in it.
198void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
199 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
200 BasicBlock *DestBB = BI->getSuccessor(0);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000201
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000202 DOUT << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000203
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000204 // If the destination block has a single pred, then this is a trivial edge,
205 // just collapse it.
206 if (DestBB->getSinglePredecessor()) {
207 // If DestBB has single-entry PHI nodes, fold them.
208 while (PHINode *PN = dyn_cast<PHINode>(DestBB->begin())) {
Chris Lattner47f57512008-11-24 19:25:36 +0000209 Value *NewVal = PN->getIncomingValue(0);
210 // Replace self referencing PHI with undef, it must be dead.
211 if (NewVal == PN) NewVal = UndefValue::get(PN->getType());
212 PN->replaceAllUsesWith(NewVal);
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000213 PN->eraseFromParent();
214 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000215
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000216 // Splice all the PHI nodes from BB over to DestBB.
217 DestBB->getInstList().splice(DestBB->begin(), BB->getInstList(),
218 BB->begin(), BI);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000219
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000220 // Anything that branched to BB now branches to DestBB.
221 BB->replaceAllUsesWith(DestBB);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000222
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000223 // Nuke BB.
224 BB->eraseFromParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000225
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000226 DOUT << "AFTER:\n" << *DestBB << "\n\n\n";
227 return;
228 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000229
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000230 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
231 // to handle the new incoming edges it is about to have.
232 PHINode *PN;
233 for (BasicBlock::iterator BBI = DestBB->begin();
234 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
235 // Remove the incoming value for BB, and remember it.
236 Value *InVal = PN->removeIncomingValue(BB, false);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000237
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000238 // Two options: either the InVal is a phi node defined in BB or it is some
239 // value that dominates BB.
240 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
241 if (InValPhi && InValPhi->getParent() == BB) {
242 // Add all of the input values of the input PHI as inputs of this phi.
243 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
244 PN->addIncoming(InValPhi->getIncomingValue(i),
245 InValPhi->getIncomingBlock(i));
246 } else {
247 // Otherwise, add one instance of the dominating value for each edge that
248 // we will be adding.
249 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
250 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
251 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
252 } else {
253 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
254 PN->addIncoming(InVal, *PI);
255 }
256 }
257 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000258
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000259 // The PHIs are now updated, change everything that refers to BB to use
260 // DestBB and remove BB.
261 BB->replaceAllUsesWith(DestBB);
262 BB->eraseFromParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000263
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000264 DOUT << "AFTER:\n" << *DestBB << "\n\n\n";
265}
266
267
Chris Lattnerebe80752007-12-24 19:32:55 +0000268/// SplitEdgeNicely - Split the critical edge from TI to its specified
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000269/// successor if it will improve codegen. We only do this if the successor has
270/// phi nodes (otherwise critical edges are ok). If there is already another
271/// predecessor of the succ that is empty (and thus has no phi nodes), use it
272/// instead of introducing a new block.
273static void SplitEdgeNicely(TerminatorInst *TI, unsigned SuccNum, Pass *P) {
274 BasicBlock *TIBB = TI->getParent();
275 BasicBlock *Dest = TI->getSuccessor(SuccNum);
276 assert(isa<PHINode>(Dest->begin()) &&
277 "This should only be called if Dest has a PHI!");
Eric Christopher692bf6b2008-09-24 05:32:41 +0000278
Chris Lattnerebe80752007-12-24 19:32:55 +0000279 // As a hack, never split backedges of loops. Even though the copy for any
280 // PHIs inserted on the backedge would be dead for exits from the loop, we
281 // assume that the cost of *splitting* the backedge would be too high.
Chris Lattnerff26ab22007-12-25 19:06:45 +0000282 if (Dest == TIBB)
Chris Lattnerebe80752007-12-24 19:32:55 +0000283 return;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000284
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000285 /// TIPHIValues - This array is lazily computed to determine the values of
286 /// PHIs in Dest that TI would provide.
Chris Lattnerebe80752007-12-24 19:32:55 +0000287 SmallVector<Value*, 32> TIPHIValues;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000288
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000289 // Check to see if Dest has any blocks that can be used as a split edge for
290 // this terminator.
291 for (pred_iterator PI = pred_begin(Dest), E = pred_end(Dest); PI != E; ++PI) {
292 BasicBlock *Pred = *PI;
293 // To be usable, the pred has to end with an uncond branch to the dest.
294 BranchInst *PredBr = dyn_cast<BranchInst>(Pred->getTerminator());
295 if (!PredBr || !PredBr->isUnconditional() ||
296 // Must be empty other than the branch.
Dale Johannesen6603a1b2007-05-08 01:01:04 +0000297 &Pred->front() != PredBr ||
298 // Cannot be the entry block; its label does not get emitted.
299 Pred == &(Dest->getParent()->getEntryBlock()))
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000300 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000301
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000302 // Finally, since we know that Dest has phi nodes in it, we have to make
303 // sure that jumping to Pred will have the same affect as going to Dest in
304 // terms of PHI values.
305 PHINode *PN;
306 unsigned PHINo = 0;
307 bool FoundMatch = true;
308 for (BasicBlock::iterator I = Dest->begin();
309 (PN = dyn_cast<PHINode>(I)); ++I, ++PHINo) {
310 if (PHINo == TIPHIValues.size())
311 TIPHIValues.push_back(PN->getIncomingValueForBlock(TIBB));
Eric Christopher692bf6b2008-09-24 05:32:41 +0000312
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000313 // If the PHI entry doesn't work, we can't use this pred.
314 if (TIPHIValues[PHINo] != PN->getIncomingValueForBlock(Pred)) {
315 FoundMatch = false;
316 break;
317 }
318 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000319
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000320 // If we found a workable predecessor, change TI to branch to Succ.
321 if (FoundMatch) {
322 Dest->removePredecessor(TIBB);
323 TI->setSuccessor(SuccNum, Pred);
324 return;
325 }
326 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000327
328 SplitCriticalEdge(TI, SuccNum, P, true);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000329}
330
Chris Lattnerdd77df32007-04-13 20:30:56 +0000331/// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
332/// copy (e.g. it's casting from one pointer type to another, int->uint, or
333/// int->sbyte on PPC), sink it into user blocks to reduce the number of virtual
Dale Johannesence0b2372007-06-12 16:50:17 +0000334/// registers that must be created and coalesced.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000335///
336/// Return true if any changes are made.
Chris Lattnerdd77df32007-04-13 20:30:56 +0000337static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
Eric Christopher692bf6b2008-09-24 05:32:41 +0000338 // If this is a noop copy,
Duncan Sands83ec4b62008-06-06 12:08:01 +0000339 MVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
340 MVT DstVT = TLI.getValueType(CI->getType());
Eric Christopher692bf6b2008-09-24 05:32:41 +0000341
Chris Lattnerdd77df32007-04-13 20:30:56 +0000342 // This is an fp<->int conversion?
Duncan Sands83ec4b62008-06-06 12:08:01 +0000343 if (SrcVT.isInteger() != DstVT.isInteger())
Chris Lattnerdd77df32007-04-13 20:30:56 +0000344 return false;
Duncan Sands8e4eb092008-06-08 20:54:56 +0000345
Chris Lattnerdd77df32007-04-13 20:30:56 +0000346 // If this is an extension, it will be a zero or sign extension, which
347 // isn't a noop.
Duncan Sands8e4eb092008-06-08 20:54:56 +0000348 if (SrcVT.bitsLT(DstVT)) return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000349
Chris Lattnerdd77df32007-04-13 20:30:56 +0000350 // If these values will be promoted, find out what they will be promoted
351 // to. This helps us consider truncates on PPC as noop copies when they
352 // are.
353 if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote)
354 SrcVT = TLI.getTypeToTransformTo(SrcVT);
355 if (TLI.getTypeAction(DstVT) == TargetLowering::Promote)
356 DstVT = TLI.getTypeToTransformTo(DstVT);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000357
Chris Lattnerdd77df32007-04-13 20:30:56 +0000358 // If, after promotion, these are the same types, this is a noop copy.
359 if (SrcVT != DstVT)
360 return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000361
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000362 BasicBlock *DefBB = CI->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000363
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000364 /// InsertedCasts - Only insert a cast in each block once.
Dale Johannesence0b2372007-06-12 16:50:17 +0000365 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000366
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000367 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000368 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000369 UI != E; ) {
370 Use &TheUse = UI.getUse();
371 Instruction *User = cast<Instruction>(*UI);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000372
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000373 // Figure out which BB this cast is used in. For PHI's this is the
374 // appropriate predecessor block.
375 BasicBlock *UserBB = User->getParent();
376 if (PHINode *PN = dyn_cast<PHINode>(User)) {
377 unsigned OpVal = UI.getOperandNo()/2;
378 UserBB = PN->getIncomingBlock(OpVal);
379 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000380
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000381 // Preincrement use iterator so we don't invalidate it.
382 ++UI;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000383
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000384 // If this user is in the same block as the cast, don't change the cast.
385 if (UserBB == DefBB) continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000386
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000387 // If we have already inserted a cast into this block, use it.
388 CastInst *&InsertedCast = InsertedCasts[UserBB];
389
390 if (!InsertedCast) {
Dan Gohman02dea8b2008-05-23 21:05:58 +0000391 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000392
393 InsertedCast =
394 CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000395 InsertPt);
396 MadeChange = true;
397 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000398
Dale Johannesence0b2372007-06-12 16:50:17 +0000399 // Replace a use of the cast with a use of the new cast.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000400 TheUse = InsertedCast;
401 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000402
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000403 // If we removed all uses, nuke the cast.
Duncan Sandse0038132008-01-20 16:51:46 +0000404 if (CI->use_empty()) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000405 CI->eraseFromParent();
Duncan Sandse0038132008-01-20 16:51:46 +0000406 MadeChange = true;
407 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000408
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000409 return MadeChange;
410}
411
Eric Christopher692bf6b2008-09-24 05:32:41 +0000412/// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
Dale Johannesence0b2372007-06-12 16:50:17 +0000413/// the number of virtual registers that must be created and coalesced. This is
Chris Lattner684b22d2007-08-02 16:53:43 +0000414/// a clear win except on targets with multiple condition code registers
415/// (PowerPC), where it might lose; some adjustment may be wanted there.
Dale Johannesence0b2372007-06-12 16:50:17 +0000416///
417/// Return true if any changes are made.
418static bool OptimizeCmpExpression(CmpInst *CI){
419
420 BasicBlock *DefBB = CI->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000421
Dale Johannesence0b2372007-06-12 16:50:17 +0000422 /// InsertedCmp - Only insert a cmp in each block once.
423 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000424
Dale Johannesence0b2372007-06-12 16:50:17 +0000425 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000426 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
Dale Johannesence0b2372007-06-12 16:50:17 +0000427 UI != E; ) {
428 Use &TheUse = UI.getUse();
429 Instruction *User = cast<Instruction>(*UI);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000430
Dale Johannesence0b2372007-06-12 16:50:17 +0000431 // Preincrement use iterator so we don't invalidate it.
432 ++UI;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000433
Dale Johannesence0b2372007-06-12 16:50:17 +0000434 // Don't bother for PHI nodes.
435 if (isa<PHINode>(User))
436 continue;
437
438 // Figure out which BB this cmp is used in.
439 BasicBlock *UserBB = User->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000440
Dale Johannesence0b2372007-06-12 16:50:17 +0000441 // If this user is in the same block as the cmp, don't change the cmp.
442 if (UserBB == DefBB) continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000443
Dale Johannesence0b2372007-06-12 16:50:17 +0000444 // If we have already inserted a cmp into this block, use it.
445 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
446
447 if (!InsertedCmp) {
Dan Gohman02dea8b2008-05-23 21:05:58 +0000448 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000449
450 InsertedCmp =
451 CmpInst::Create(CI->getOpcode(), CI->getPredicate(), CI->getOperand(0),
Dale Johannesence0b2372007-06-12 16:50:17 +0000452 CI->getOperand(1), "", InsertPt);
453 MadeChange = true;
454 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000455
Dale Johannesence0b2372007-06-12 16:50:17 +0000456 // Replace a use of the cmp with a use of the new cmp.
457 TheUse = InsertedCmp;
458 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000459
Dale Johannesence0b2372007-06-12 16:50:17 +0000460 // If we removed all uses, nuke the cmp.
461 if (CI->use_empty())
462 CI->eraseFromParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000463
Dale Johannesence0b2372007-06-12 16:50:17 +0000464 return MadeChange;
465}
466
Chris Lattnerdd77df32007-04-13 20:30:56 +0000467/// EraseDeadInstructions - Erase any dead instructions
468static void EraseDeadInstructions(Value *V) {
469 Instruction *I = dyn_cast<Instruction>(V);
470 if (!I || !I->use_empty()) return;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000471
Chris Lattnerdd77df32007-04-13 20:30:56 +0000472 SmallPtrSet<Instruction*, 16> Insts;
473 Insts.insert(I);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000474
Chris Lattnerdd77df32007-04-13 20:30:56 +0000475 while (!Insts.empty()) {
476 I = *Insts.begin();
477 Insts.erase(I);
478 if (isInstructionTriviallyDead(I)) {
479 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
480 if (Instruction *U = dyn_cast<Instruction>(I->getOperand(i)))
481 Insts.insert(U);
482 I->eraseFromParent();
483 }
484 }
485}
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000486
Dan Gohman844731a2008-05-13 00:00:25 +0000487namespace {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000488
Chris Lattnerdd77df32007-04-13 20:30:56 +0000489/// ExtAddrMode - This is an extended version of TargetLowering::AddrMode which
490/// holds actual Value*'s for register values.
491struct ExtAddrMode : public TargetLowering::AddrMode {
492 Value *BaseReg;
493 Value *ScaledReg;
494 ExtAddrMode() : BaseReg(0), ScaledReg(0) {}
495 void dump() const;
496};
497
498static std::ostream &operator<<(std::ostream &OS, const ExtAddrMode &AM) {
499 bool NeedPlus = false;
500 OS << "[";
501 if (AM.BaseGV)
502 OS << (NeedPlus ? " + " : "")
503 << "GV:%" << AM.BaseGV->getName(), NeedPlus = true;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000504
Chris Lattnerdd77df32007-04-13 20:30:56 +0000505 if (AM.BaseOffs)
506 OS << (NeedPlus ? " + " : "") << AM.BaseOffs, NeedPlus = true;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000507
Chris Lattnerdd77df32007-04-13 20:30:56 +0000508 if (AM.BaseReg)
509 OS << (NeedPlus ? " + " : "")
510 << "Base:%" << AM.BaseReg->getName(), NeedPlus = true;
511 if (AM.Scale)
512 OS << (NeedPlus ? " + " : "")
513 << AM.Scale << "*%" << AM.ScaledReg->getName(), NeedPlus = true;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000514
Chris Lattnerdd77df32007-04-13 20:30:56 +0000515 return OS << "]";
516}
517
518void ExtAddrMode::dump() const {
519 cerr << *this << "\n";
520}
521
Dan Gohman844731a2008-05-13 00:00:25 +0000522}
523
Chris Lattnerdd77df32007-04-13 20:30:56 +0000524static bool TryMatchingScaledValue(Value *ScaleReg, int64_t Scale,
525 const Type *AccessTy, ExtAddrMode &AddrMode,
526 SmallVector<Instruction*, 16> &AddrModeInsts,
527 const TargetLowering &TLI, unsigned Depth);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000528
Chris Lattnerdd77df32007-04-13 20:30:56 +0000529/// FindMaximalLegalAddressingMode - If we can, try to merge the computation of
530/// Addr into the specified addressing mode. If Addr can't be added to AddrMode
531/// this returns false. This assumes that Addr is either a pointer type or
532/// intptr_t for the target.
533static bool FindMaximalLegalAddressingMode(Value *Addr, const Type *AccessTy,
534 ExtAddrMode &AddrMode,
535 SmallVector<Instruction*, 16> &AddrModeInsts,
536 const TargetLowering &TLI,
537 unsigned Depth) {
Eric Christopher692bf6b2008-09-24 05:32:41 +0000538
Chris Lattnerdd77df32007-04-13 20:30:56 +0000539 // If this is a global variable, fold it into the addressing mode if possible.
540 if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
541 if (AddrMode.BaseGV == 0) {
542 AddrMode.BaseGV = GV;
543 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
544 return true;
545 AddrMode.BaseGV = 0;
546 }
547 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
548 AddrMode.BaseOffs += CI->getSExtValue();
549 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
550 return true;
551 AddrMode.BaseOffs -= CI->getSExtValue();
552 } else if (isa<ConstantPointerNull>(Addr)) {
553 return true;
554 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000555
Chris Lattnerdd77df32007-04-13 20:30:56 +0000556 // Look through constant exprs and instructions.
557 unsigned Opcode = ~0U;
558 User *AddrInst = 0;
559 if (Instruction *I = dyn_cast<Instruction>(Addr)) {
560 Opcode = I->getOpcode();
561 AddrInst = I;
562 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
563 Opcode = CE->getOpcode();
564 AddrInst = CE;
565 }
566
567 // Limit recursion to avoid exponential behavior.
568 if (Depth == 5) { AddrInst = 0; Opcode = ~0U; }
569
570 // If this is really an instruction, add it to our list of related
571 // instructions.
572 if (Instruction *I = dyn_cast_or_null<Instruction>(AddrInst))
573 AddrModeInsts.push_back(I);
574
Chris Lattner47f57512008-11-24 19:25:36 +0000575 if (AddrInst && !AddrInst->hasOneUse())
576 ;
577 else
Chris Lattnerdd77df32007-04-13 20:30:56 +0000578 switch (Opcode) {
579 case Instruction::PtrToInt:
580 // PtrToInt is always a noop, as we know that the int type is pointer sized.
581 if (FindMaximalLegalAddressingMode(AddrInst->getOperand(0), AccessTy,
582 AddrMode, AddrModeInsts, TLI, Depth))
583 return true;
584 break;
585 case Instruction::IntToPtr:
586 // This inttoptr is a no-op if the integer type is pointer sized.
587 if (TLI.getValueType(AddrInst->getOperand(0)->getType()) ==
588 TLI.getPointerTy()) {
589 if (FindMaximalLegalAddressingMode(AddrInst->getOperand(0), AccessTy,
590 AddrMode, AddrModeInsts, TLI, Depth))
591 return true;
592 }
593 break;
594 case Instruction::Add: {
595 // Check to see if we can merge in the RHS then the LHS. If so, we win.
596 ExtAddrMode BackupAddrMode = AddrMode;
597 unsigned OldSize = AddrModeInsts.size();
598 if (FindMaximalLegalAddressingMode(AddrInst->getOperand(1), AccessTy,
599 AddrMode, AddrModeInsts, TLI, Depth+1) &&
600 FindMaximalLegalAddressingMode(AddrInst->getOperand(0), AccessTy,
601 AddrMode, AddrModeInsts, TLI, Depth+1))
602 return true;
603
604 // Restore the old addr mode info.
605 AddrMode = BackupAddrMode;
606 AddrModeInsts.resize(OldSize);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000607
Chris Lattnerdd77df32007-04-13 20:30:56 +0000608 // Otherwise this was over-aggressive. Try merging in the LHS then the RHS.
609 if (FindMaximalLegalAddressingMode(AddrInst->getOperand(0), AccessTy,
610 AddrMode, AddrModeInsts, TLI, Depth+1) &&
611 FindMaximalLegalAddressingMode(AddrInst->getOperand(1), AccessTy,
612 AddrMode, AddrModeInsts, TLI, Depth+1))
613 return true;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000614
Chris Lattnerdd77df32007-04-13 20:30:56 +0000615 // Otherwise we definitely can't merge the ADD in.
616 AddrMode = BackupAddrMode;
617 AddrModeInsts.resize(OldSize);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000618 break;
Chris Lattnerdd77df32007-04-13 20:30:56 +0000619 }
620 case Instruction::Or: {
621 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
622 if (!RHS) break;
623 // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
624 break;
625 }
626 case Instruction::Mul:
627 case Instruction::Shl: {
628 // Can only handle X*C and X << C, and can only handle this when the scale
629 // field is available.
630 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
631 if (!RHS) break;
632 int64_t Scale = RHS->getSExtValue();
633 if (Opcode == Instruction::Shl)
634 Scale = 1 << Scale;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000635
Chris Lattnerdd77df32007-04-13 20:30:56 +0000636 if (TryMatchingScaledValue(AddrInst->getOperand(0), Scale, AccessTy,
637 AddrMode, AddrModeInsts, TLI, Depth))
638 return true;
639 break;
640 }
641 case Instruction::GetElementPtr: {
642 // Scan the GEP. We check it if it contains constant offsets and at most
643 // one variable offset.
644 int VariableOperand = -1;
645 unsigned VariableScale = 0;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000646
Chris Lattnerdd77df32007-04-13 20:30:56 +0000647 int64_t ConstantOffset = 0;
648 const TargetData *TD = TLI.getTargetData();
649 gep_type_iterator GTI = gep_type_begin(AddrInst);
650 for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
651 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
652 const StructLayout *SL = TD->getStructLayout(STy);
653 unsigned Idx =
654 cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
655 ConstantOffset += SL->getElementOffset(Idx);
656 } else {
Duncan Sands514ab342007-11-01 20:53:16 +0000657 uint64_t TypeSize = TD->getABITypeSize(GTI.getIndexedType());
Chris Lattnerdd77df32007-04-13 20:30:56 +0000658 if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
659 ConstantOffset += CI->getSExtValue()*TypeSize;
660 } else if (TypeSize) { // Scales of zero don't do anything.
661 // We only allow one variable index at the moment.
662 if (VariableOperand != -1) {
663 VariableOperand = -2;
664 break;
665 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000666
Chris Lattnerdd77df32007-04-13 20:30:56 +0000667 // Remember the variable index.
668 VariableOperand = i;
669 VariableScale = TypeSize;
670 }
671 }
672 }
673
674 // If the GEP had multiple variable indices, punt.
675 if (VariableOperand == -2)
676 break;
677
678 // A common case is for the GEP to only do a constant offset. In this case,
679 // just add it to the disp field and check validity.
680 if (VariableOperand == -1) {
681 AddrMode.BaseOffs += ConstantOffset;
682 if (ConstantOffset == 0 || TLI.isLegalAddressingMode(AddrMode, AccessTy)){
683 // Check to see if we can fold the base pointer in too.
684 if (FindMaximalLegalAddressingMode(AddrInst->getOperand(0), AccessTy,
685 AddrMode, AddrModeInsts, TLI,
686 Depth+1))
687 return true;
688 }
689 AddrMode.BaseOffs -= ConstantOffset;
690 } else {
691 // Check that this has no base reg yet. If so, we won't have a place to
692 // put the base of the GEP (assuming it is not a null ptr).
693 bool SetBaseReg = false;
694 if (AddrMode.HasBaseReg) {
695 if (!isa<ConstantPointerNull>(AddrInst->getOperand(0)))
696 break;
697 } else {
698 AddrMode.HasBaseReg = true;
699 AddrMode.BaseReg = AddrInst->getOperand(0);
700 SetBaseReg = true;
701 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000702
Chris Lattnerdd77df32007-04-13 20:30:56 +0000703 // See if the scale amount is valid for this target.
704 AddrMode.BaseOffs += ConstantOffset;
705 if (TryMatchingScaledValue(AddrInst->getOperand(VariableOperand),
Eric Christopher692bf6b2008-09-24 05:32:41 +0000706 VariableScale, AccessTy, AddrMode,
Chris Lattnerdd77df32007-04-13 20:30:56 +0000707 AddrModeInsts, TLI, Depth)) {
708 if (!SetBaseReg) return true;
709
710 // If this match succeeded, we know that we can form an address with the
711 // GepBase as the basereg. See if we can match *more*.
712 AddrMode.HasBaseReg = false;
713 AddrMode.BaseReg = 0;
714 if (FindMaximalLegalAddressingMode(AddrInst->getOperand(0), AccessTy,
715 AddrMode, AddrModeInsts, TLI,
716 Depth+1))
717 return true;
718 // Strange, shouldn't happen. Restore the base reg and succeed the easy
Eric Christopher692bf6b2008-09-24 05:32:41 +0000719 // way.
Chris Lattnerdd77df32007-04-13 20:30:56 +0000720 AddrMode.HasBaseReg = true;
721 AddrMode.BaseReg = AddrInst->getOperand(0);
722 return true;
723 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000724
Chris Lattnerdd77df32007-04-13 20:30:56 +0000725 AddrMode.BaseOffs -= ConstantOffset;
726 if (SetBaseReg) {
727 AddrMode.HasBaseReg = false;
728 AddrMode.BaseReg = 0;
729 }
730 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000731 break;
Chris Lattnerdd77df32007-04-13 20:30:56 +0000732 }
733 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000734
Chris Lattnerdd77df32007-04-13 20:30:56 +0000735 if (Instruction *I = dyn_cast_or_null<Instruction>(AddrInst)) {
Chris Lattner0c80c752008-04-06 21:44:08 +0000736 assert(AddrModeInsts.back() == I && "Stack imbalance"); I = I;
Chris Lattnerdd77df32007-04-13 20:30:56 +0000737 AddrModeInsts.pop_back();
738 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000739
Chris Lattnerdd77df32007-04-13 20:30:56 +0000740 // Worse case, the target should support [reg] addressing modes. :)
741 if (!AddrMode.HasBaseReg) {
742 AddrMode.HasBaseReg = true;
743 // Still check for legality in case the target supports [imm] but not [i+r].
744 if (TLI.isLegalAddressingMode(AddrMode, AccessTy)) {
745 AddrMode.BaseReg = Addr;
746 return true;
747 }
748 AddrMode.HasBaseReg = false;
749 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000750
Chris Lattnerdd77df32007-04-13 20:30:56 +0000751 // If the base register is already taken, see if we can do [r+r].
752 if (AddrMode.Scale == 0) {
753 AddrMode.Scale = 1;
754 if (TLI.isLegalAddressingMode(AddrMode, AccessTy)) {
755 AddrMode.ScaledReg = Addr;
756 return true;
757 }
758 AddrMode.Scale = 0;
759 }
760 // Couldn't match.
761 return false;
762}
763
764/// TryMatchingScaledValue - Try adding ScaleReg*Scale to the specified
765/// addressing mode. Return true if this addr mode is legal for the target,
766/// false if not.
767static bool TryMatchingScaledValue(Value *ScaleReg, int64_t Scale,
768 const Type *AccessTy, ExtAddrMode &AddrMode,
769 SmallVector<Instruction*, 16> &AddrModeInsts,
770 const TargetLowering &TLI, unsigned Depth) {
771 // If we already have a scale of this value, we can add to it, otherwise, we
772 // need an available scale field.
773 if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
774 return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000775
Chris Lattnerdd77df32007-04-13 20:30:56 +0000776 ExtAddrMode InputAddrMode = AddrMode;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000777
Chris Lattnerdd77df32007-04-13 20:30:56 +0000778 // Add scale to turn X*4+X*3 -> X*7. This could also do things like
779 // [A+B + A*7] -> [B+A*8].
780 AddrMode.Scale += Scale;
781 AddrMode.ScaledReg = ScaleReg;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000782
Chris Lattnerdd77df32007-04-13 20:30:56 +0000783 if (TLI.isLegalAddressingMode(AddrMode, AccessTy)) {
784 // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
785 // to see if ScaleReg is actually X+C. If so, we can turn this into adding
786 // X*Scale + C*Scale to addr mode.
787 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(ScaleReg);
788 if (BinOp && BinOp->getOpcode() == Instruction::Add &&
789 isa<ConstantInt>(BinOp->getOperand(1)) && InputAddrMode.ScaledReg ==0) {
Eric Christopher692bf6b2008-09-24 05:32:41 +0000790
Chris Lattnerdd77df32007-04-13 20:30:56 +0000791 InputAddrMode.Scale = Scale;
792 InputAddrMode.ScaledReg = BinOp->getOperand(0);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000793 InputAddrMode.BaseOffs +=
Chris Lattnerdd77df32007-04-13 20:30:56 +0000794 cast<ConstantInt>(BinOp->getOperand(1))->getSExtValue()*Scale;
795 if (TLI.isLegalAddressingMode(InputAddrMode, AccessTy)) {
796 AddrModeInsts.push_back(BinOp);
797 AddrMode = InputAddrMode;
798 return true;
799 }
800 }
801
802 // Otherwise, not (x+c)*scale, just return what we have.
803 return true;
804 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000805
Chris Lattnerdd77df32007-04-13 20:30:56 +0000806 // Otherwise, back this attempt out.
807 AddrMode.Scale -= Scale;
808 if (AddrMode.Scale == 0) AddrMode.ScaledReg = 0;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000809
Chris Lattnerdd77df32007-04-13 20:30:56 +0000810 return false;
811}
812
813
814/// IsNonLocalValue - Return true if the specified values are defined in a
815/// different basic block than BB.
816static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
817 if (Instruction *I = dyn_cast<Instruction>(V))
818 return I->getParent() != BB;
819 return false;
820}
821
822/// OptimizeLoadStoreInst - Load and Store Instructions have often have
823/// addressing modes that can do significant amounts of computation. As such,
824/// instruction selection will try to get the load or store to do as much
825/// computation as possible for the program. The problem is that isel can only
826/// see within a single block. As such, we sink as much legal addressing mode
827/// stuff into the block as possible.
828bool CodeGenPrepare::OptimizeLoadStoreInst(Instruction *LdStInst, Value *Addr,
829 const Type *AccessTy,
830 DenseMap<Value*,Value*> &SunkAddrs) {
831 // Figure out what addressing mode will be built up for this operation.
832 SmallVector<Instruction*, 16> AddrModeInsts;
833 ExtAddrMode AddrMode;
834 bool Success = FindMaximalLegalAddressingMode(Addr, AccessTy, AddrMode,
835 AddrModeInsts, *TLI, 0);
836 Success = Success; assert(Success && "Couldn't select *anything*?");
Eric Christopher692bf6b2008-09-24 05:32:41 +0000837
Chris Lattnerdd77df32007-04-13 20:30:56 +0000838 // Check to see if any of the instructions supersumed by this addr mode are
839 // non-local to I's BB.
840 bool AnyNonLocal = false;
841 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
842 if (IsNonLocalValue(AddrModeInsts[i], LdStInst->getParent())) {
843 AnyNonLocal = true;
844 break;
845 }
846 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000847
Chris Lattnerdd77df32007-04-13 20:30:56 +0000848 // If all the instructions matched are already in this BB, don't do anything.
849 if (!AnyNonLocal) {
850 DEBUG(cerr << "CGP: Found local addrmode: " << AddrMode << "\n");
851 return false;
852 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000853
Chris Lattnerdd77df32007-04-13 20:30:56 +0000854 // Insert this computation right after this user. Since our caller is
855 // scanning from the top of the BB to the bottom, reuse of the expr are
856 // guaranteed to happen later.
857 BasicBlock::iterator InsertPt = LdStInst;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000858
Chris Lattnerdd77df32007-04-13 20:30:56 +0000859 // Now that we determined the addressing expression we want to use and know
860 // that we have to sink it into this block. Check to see if we have already
861 // done this for some other load/store instr in this block. If so, reuse the
862 // computation.
863 Value *&SunkAddr = SunkAddrs[Addr];
864 if (SunkAddr) {
865 DEBUG(cerr << "CGP: Reusing nonlocal addrmode: " << AddrMode << "\n");
866 if (SunkAddr->getType() != Addr->getType())
867 SunkAddr = new BitCastInst(SunkAddr, Addr->getType(), "tmp", InsertPt);
868 } else {
869 DEBUG(cerr << "CGP: SINKING nonlocal addrmode: " << AddrMode << "\n");
870 const Type *IntPtrTy = TLI->getTargetData()->getIntPtrType();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000871
Chris Lattnerdd77df32007-04-13 20:30:56 +0000872 Value *Result = 0;
873 // Start with the scale value.
874 if (AddrMode.Scale) {
875 Value *V = AddrMode.ScaledReg;
876 if (V->getType() == IntPtrTy) {
877 // done.
878 } else if (isa<PointerType>(V->getType())) {
879 V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
880 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
881 cast<IntegerType>(V->getType())->getBitWidth()) {
882 V = new TruncInst(V, IntPtrTy, "sunkaddr", InsertPt);
883 } else {
884 V = new SExtInst(V, IntPtrTy, "sunkaddr", InsertPt);
885 }
886 if (AddrMode.Scale != 1)
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000887 V = BinaryOperator::CreateMul(V, ConstantInt::get(IntPtrTy,
Chris Lattnerdd77df32007-04-13 20:30:56 +0000888 AddrMode.Scale),
889 "sunkaddr", InsertPt);
890 Result = V;
891 }
892
893 // Add in the base register.
894 if (AddrMode.BaseReg) {
895 Value *V = AddrMode.BaseReg;
896 if (V->getType() != IntPtrTy)
897 V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
898 if (Result)
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000899 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000900 else
901 Result = V;
902 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000903
Chris Lattnerdd77df32007-04-13 20:30:56 +0000904 // Add in the BaseGV if present.
905 if (AddrMode.BaseGV) {
906 Value *V = new PtrToIntInst(AddrMode.BaseGV, IntPtrTy, "sunkaddr",
907 InsertPt);
908 if (Result)
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000909 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000910 else
911 Result = V;
912 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000913
Chris Lattnerdd77df32007-04-13 20:30:56 +0000914 // Add in the Base Offset if present.
915 if (AddrMode.BaseOffs) {
916 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
917 if (Result)
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000918 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000919 else
920 Result = V;
921 }
922
923 if (Result == 0)
924 SunkAddr = Constant::getNullValue(Addr->getType());
925 else
926 SunkAddr = new IntToPtrInst(Result, Addr->getType(), "sunkaddr",InsertPt);
927 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000928
Chris Lattnerdd77df32007-04-13 20:30:56 +0000929 LdStInst->replaceUsesOfWith(Addr, SunkAddr);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000930
Chris Lattnerdd77df32007-04-13 20:30:56 +0000931 if (Addr->use_empty())
932 EraseDeadInstructions(Addr);
933 return true;
934}
935
Evan Cheng9bf12b52008-02-26 02:42:37 +0000936/// OptimizeInlineAsmInst - If there are any memory operands, use
937/// OptimizeLoadStoreInt to sink their address computing into the block when
938/// possible / profitable.
939bool CodeGenPrepare::OptimizeInlineAsmInst(Instruction *I, CallSite CS,
940 DenseMap<Value*,Value*> &SunkAddrs) {
941 bool MadeChange = false;
942 InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
943
944 // Do a prepass over the constraints, canonicalizing them, and building up the
945 // ConstraintOperands list.
946 std::vector<InlineAsm::ConstraintInfo>
947 ConstraintInfos = IA->ParseConstraints();
948
949 /// ConstraintOperands - Information about all of the constraints.
950 std::vector<TargetLowering::AsmOperandInfo> ConstraintOperands;
951 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
952 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
953 ConstraintOperands.
954 push_back(TargetLowering::AsmOperandInfo(ConstraintInfos[i]));
955 TargetLowering::AsmOperandInfo &OpInfo = ConstraintOperands.back();
956
957 // Compute the value type for each operand.
958 switch (OpInfo.Type) {
959 case InlineAsm::isOutput:
960 if (OpInfo.isIndirect)
961 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
962 break;
963 case InlineAsm::isInput:
964 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
965 break;
966 case InlineAsm::isClobber:
967 // Nothing to do.
968 break;
969 }
970
971 // Compute the constraint code and ConstraintType to use.
Evan Chenga7e61462008-09-24 06:48:55 +0000972 TLI->ComputeConstraintToUse(OpInfo, SDValue(),
973 OpInfo.ConstraintType == TargetLowering::C_Memory);
Evan Cheng9bf12b52008-02-26 02:42:37 +0000974
Eli Friedman9ec80952008-02-26 18:37:49 +0000975 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
976 OpInfo.isIndirect) {
Evan Cheng9bf12b52008-02-26 02:42:37 +0000977 Value *OpVal = OpInfo.CallOperandVal;
978 MadeChange |= OptimizeLoadStoreInst(I, OpVal, OpVal->getType(),
979 SunkAddrs);
980 }
981 }
982
983 return MadeChange;
984}
985
Evan Chengbdcb7262007-12-05 23:58:20 +0000986bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
987 BasicBlock *DefBB = I->getParent();
988
989 // If both result of the {s|z}xt and its source are live out, rewrite all
990 // other uses of the source with result of extension.
991 Value *Src = I->getOperand(0);
992 if (Src->hasOneUse())
993 return false;
994
Evan Cheng696e5c02007-12-13 07:50:36 +0000995 // Only do this xform if truncating is free.
Gabor Greif53bdbd72008-02-26 19:13:21 +0000996 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
Evan Chengf9785f92007-12-13 03:32:53 +0000997 return false;
998
Evan Cheng772de512007-12-12 00:51:06 +0000999 // Only safe to perform the optimization if the source is also defined in
Evan Cheng765dff22007-12-12 02:53:41 +00001000 // this block.
1001 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
Evan Cheng772de512007-12-12 00:51:06 +00001002 return false;
1003
Evan Chengbdcb7262007-12-05 23:58:20 +00001004 bool DefIsLiveOut = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001005 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
Evan Chengbdcb7262007-12-05 23:58:20 +00001006 UI != E; ++UI) {
1007 Instruction *User = cast<Instruction>(*UI);
1008
1009 // Figure out which BB this ext is used in.
1010 BasicBlock *UserBB = User->getParent();
1011 if (UserBB == DefBB) continue;
1012 DefIsLiveOut = true;
1013 break;
1014 }
1015 if (!DefIsLiveOut)
1016 return false;
1017
Evan Cheng765dff22007-12-12 02:53:41 +00001018 // Make sure non of the uses are PHI nodes.
Eric Christopher692bf6b2008-09-24 05:32:41 +00001019 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
Evan Cheng765dff22007-12-12 02:53:41 +00001020 UI != E; ++UI) {
1021 Instruction *User = cast<Instruction>(*UI);
Evan Chengf9785f92007-12-13 03:32:53 +00001022 BasicBlock *UserBB = User->getParent();
1023 if (UserBB == DefBB) continue;
1024 // Be conservative. We don't want this xform to end up introducing
1025 // reloads just before load / store instructions.
1026 if (isa<PHINode>(User) || isa<LoadInst>(User) || isa<StoreInst>(User))
Evan Cheng765dff22007-12-12 02:53:41 +00001027 return false;
1028 }
1029
Evan Chengbdcb7262007-12-05 23:58:20 +00001030 // InsertedTruncs - Only insert one trunc in each block once.
1031 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
1032
1033 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001034 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
Evan Chengbdcb7262007-12-05 23:58:20 +00001035 UI != E; ++UI) {
1036 Use &TheUse = UI.getUse();
1037 Instruction *User = cast<Instruction>(*UI);
1038
1039 // Figure out which BB this ext is used in.
1040 BasicBlock *UserBB = User->getParent();
1041 if (UserBB == DefBB) continue;
1042
1043 // Both src and def are live in this block. Rewrite the use.
1044 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
1045
1046 if (!InsertedTrunc) {
Dan Gohman02dea8b2008-05-23 21:05:58 +00001047 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
Eric Christopher692bf6b2008-09-24 05:32:41 +00001048
Evan Chengbdcb7262007-12-05 23:58:20 +00001049 InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
1050 }
1051
1052 // Replace a use of the {s|z}ext source with a use of the result.
1053 TheUse = InsertedTrunc;
1054
1055 MadeChange = true;
1056 }
1057
1058 return MadeChange;
1059}
1060
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001061// In this pass we look for GEP and cast instructions that are used
1062// across basic blocks and rewrite them to improve basic-block-at-a-time
1063// selection.
1064bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
1065 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001066
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001067 // Split all critical edges where the dest block has a PHI and where the phi
1068 // has shared immediate operands.
1069 TerminatorInst *BBTI = BB.getTerminator();
1070 if (BBTI->getNumSuccessors() > 1) {
1071 for (unsigned i = 0, e = BBTI->getNumSuccessors(); i != e; ++i)
1072 if (isa<PHINode>(BBTI->getSuccessor(i)->begin()) &&
1073 isCriticalEdge(BBTI, i, true))
1074 SplitEdgeNicely(BBTI, i, this);
1075 }
Eric Christopher692bf6b2008-09-24 05:32:41 +00001076
1077
Chris Lattnerdd77df32007-04-13 20:30:56 +00001078 // Keep track of non-local addresses that have been sunk into this block.
1079 // This allows us to avoid inserting duplicate code for blocks with multiple
1080 // load/stores of the same address.
1081 DenseMap<Value*, Value*> SunkAddrs;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001082
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001083 for (BasicBlock::iterator BBI = BB.begin(), E = BB.end(); BBI != E; ) {
1084 Instruction *I = BBI++;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001085
Chris Lattnerdd77df32007-04-13 20:30:56 +00001086 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001087 // If the source of the cast is a constant, then this should have
1088 // already been constant folded. The only reason NOT to constant fold
1089 // it is if something (e.g. LSR) was careful to place the constant
1090 // evaluation in a block other than then one that uses it (e.g. to hoist
1091 // the address of globals out of a loop). If this is the case, we don't
1092 // want to forward-subst the cast.
1093 if (isa<Constant>(CI->getOperand(0)))
1094 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001095
Evan Chengbdcb7262007-12-05 23:58:20 +00001096 bool Change = false;
1097 if (TLI) {
1098 Change = OptimizeNoopCopyExpression(CI, *TLI);
1099 MadeChange |= Change;
1100 }
1101
Evan Cheng55e641b2008-03-19 22:02:26 +00001102 if (!Change && (isa<ZExtInst>(I) || isa<SExtInst>(I)))
Evan Chengbdcb7262007-12-05 23:58:20 +00001103 MadeChange |= OptimizeExtUses(I);
Dale Johannesence0b2372007-06-12 16:50:17 +00001104 } else if (CmpInst *CI = dyn_cast<CmpInst>(I)) {
1105 MadeChange |= OptimizeCmpExpression(CI);
Chris Lattnerdd77df32007-04-13 20:30:56 +00001106 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
1107 if (TLI)
1108 MadeChange |= OptimizeLoadStoreInst(I, I->getOperand(0), LI->getType(),
1109 SunkAddrs);
1110 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
1111 if (TLI)
1112 MadeChange |= OptimizeLoadStoreInst(I, SI->getOperand(1),
1113 SI->getOperand(0)->getType(),
1114 SunkAddrs);
1115 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Chris Lattnerf25646b2007-04-14 00:17:39 +00001116 if (GEPI->hasAllZeroIndices()) {
Chris Lattnerdd77df32007-04-13 20:30:56 +00001117 /// The GEP operand must be a pointer, so must its result -> BitCast
Eric Christopher692bf6b2008-09-24 05:32:41 +00001118 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
Chris Lattnerdd77df32007-04-13 20:30:56 +00001119 GEPI->getName(), GEPI);
1120 GEPI->replaceAllUsesWith(NC);
1121 GEPI->eraseFromParent();
1122 MadeChange = true;
1123 BBI = NC;
1124 }
1125 } else if (CallInst *CI = dyn_cast<CallInst>(I)) {
1126 // If we found an inline asm expession, and if the target knows how to
1127 // lower it to normal LLVM code, do so now.
1128 if (TLI && isa<InlineAsm>(CI->getCalledValue()))
Eric Christopher692bf6b2008-09-24 05:32:41 +00001129 if (const TargetAsmInfo *TAI =
Chris Lattnerdd77df32007-04-13 20:30:56 +00001130 TLI->getTargetMachine().getTargetAsmInfo()) {
1131 if (TAI->ExpandInlineAsm(CI))
1132 BBI = BB.begin();
Evan Cheng9bf12b52008-02-26 02:42:37 +00001133 else
1134 // Sink address computing for memory operands into the block.
1135 MadeChange |= OptimizeInlineAsmInst(I, &(*CI), SunkAddrs);
Chris Lattnerdd77df32007-04-13 20:30:56 +00001136 }
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001137 }
1138 }
Eric Christopher692bf6b2008-09-24 05:32:41 +00001139
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001140 return MadeChange;
1141}