blob: 0a464a788370cc5091449bfc34d5feda0f10eb04 [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 Lattner088a1e82008-11-25 04:42:10 +000036#include "llvm/Support/PatternMatch.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000037using namespace llvm;
Chris Lattner088a1e82008-11-25 04:42:10 +000038using namespace llvm::PatternMatch;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000039
Eric Christopher692bf6b2008-09-24 05:32:41 +000040namespace {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000041 class VISIBILITY_HIDDEN CodeGenPrepare : public FunctionPass {
42 /// TLI - Keep a pointer of a TargetLowering to consult for determining
43 /// transformation profitability.
44 const TargetLowering *TLI;
45 public:
Nick Lewyckyecd94c82007-05-06 13:37:16 +000046 static char ID; // Pass identification, replacement for typeid
Dan Gohmanc2bbfc12007-08-01 15:32:29 +000047 explicit CodeGenPrepare(const TargetLowering *tli = 0)
Dan Gohmanae73dc12008-09-04 17:05:41 +000048 : FunctionPass(&ID), TLI(tli) {}
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000049 bool runOnFunction(Function &F);
Eric Christopher692bf6b2008-09-24 05:32:41 +000050
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000051 private:
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +000052 bool EliminateMostlyEmptyBlocks(Function &F);
53 bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
54 void EliminateMostlyEmptyBlock(BasicBlock *BB);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000055 bool OptimizeBlock(BasicBlock &BB);
Chris Lattnerdd77df32007-04-13 20:30:56 +000056 bool OptimizeLoadStoreInst(Instruction *I, Value *Addr,
57 const Type *AccessTy,
58 DenseMap<Value*,Value*> &SunkAddrs);
Evan Cheng9bf12b52008-02-26 02:42:37 +000059 bool OptimizeInlineAsmInst(Instruction *I, CallSite CS,
60 DenseMap<Value*,Value*> &SunkAddrs);
Evan Chengbdcb7262007-12-05 23:58:20 +000061 bool OptimizeExtUses(Instruction *I);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000062 };
63}
Devang Patel794fd752007-05-01 21:15:47 +000064
Devang Patel19974732007-05-03 01:11:54 +000065char CodeGenPrepare::ID = 0;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000066static RegisterPass<CodeGenPrepare> X("codegenprepare",
67 "Optimize for code generation");
68
69FunctionPass *llvm::createCodeGenPreparePass(const TargetLowering *TLI) {
70 return new CodeGenPrepare(TLI);
71}
72
73
74bool CodeGenPrepare::runOnFunction(Function &F) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000075 bool EverMadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +000076
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +000077 // First pass, eliminate blocks that contain only PHI nodes and an
78 // unconditional branch.
79 EverMadeChange |= EliminateMostlyEmptyBlocks(F);
Eric Christopher692bf6b2008-09-24 05:32:41 +000080
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +000081 bool MadeChange = true;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000082 while (MadeChange) {
83 MadeChange = false;
84 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
85 MadeChange |= OptimizeBlock(*BB);
86 EverMadeChange |= MadeChange;
87 }
88 return EverMadeChange;
89}
90
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +000091/// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes
Eric Christopher692bf6b2008-09-24 05:32:41 +000092/// and an unconditional branch. Passes before isel (e.g. LSR/loopsimplify)
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +000093/// often split edges in ways that are non-optimal for isel. Start by
94/// eliminating these blocks so we can split them the way we want them.
95bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
96 bool MadeChange = false;
97 // Note that this intentionally skips the entry block.
98 for (Function::iterator I = ++F.begin(), E = F.end(); I != E; ) {
99 BasicBlock *BB = I++;
100
101 // If this block doesn't end with an uncond branch, ignore it.
102 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
103 if (!BI || !BI->isUnconditional())
104 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000105
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000106 // If the instruction before the branch isn't a phi node, then other stuff
107 // is happening here.
108 BasicBlock::iterator BBI = BI;
109 if (BBI != BB->begin()) {
110 --BBI;
111 if (!isa<PHINode>(BBI)) continue;
112 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000113
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000114 // Do not break infinite loops.
115 BasicBlock *DestBB = BI->getSuccessor(0);
116 if (DestBB == BB)
117 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000118
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000119 if (!CanMergeBlocks(BB, DestBB))
120 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000121
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000122 EliminateMostlyEmptyBlock(BB);
123 MadeChange = true;
124 }
125 return MadeChange;
126}
127
128/// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
129/// single uncond branch between them, and BB contains no other non-phi
130/// instructions.
131bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
132 const BasicBlock *DestBB) const {
133 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
134 // the successor. If there are more complex condition (e.g. preheaders),
135 // don't mess around with them.
136 BasicBlock::const_iterator BBI = BB->begin();
137 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
138 for (Value::use_const_iterator UI = PN->use_begin(), E = PN->use_end();
139 UI != E; ++UI) {
140 const Instruction *User = cast<Instruction>(*UI);
141 if (User->getParent() != DestBB || !isa<PHINode>(User))
142 return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000143 // If User is inside DestBB block and it is a PHINode then check
144 // incoming value. If incoming value is not from BB then this is
Devang Patel75abc1e2007-04-25 00:37:04 +0000145 // a complex condition (e.g. preheaders) we want to avoid here.
146 if (User->getParent() == DestBB) {
147 if (const PHINode *UPN = dyn_cast<PHINode>(User))
148 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
149 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
150 if (Insn && Insn->getParent() == BB &&
151 Insn->getParent() != UPN->getIncomingBlock(I))
152 return false;
153 }
154 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000155 }
156 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000157
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000158 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
159 // and DestBB may have conflicting incoming values for the block. If so, we
160 // can't merge the block.
161 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
162 if (!DestBBPN) return true; // no conflict.
Eric Christopher692bf6b2008-09-24 05:32:41 +0000163
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000164 // Collect the preds of BB.
Chris Lattnerf67f73a2007-11-06 22:07:40 +0000165 SmallPtrSet<const BasicBlock*, 16> BBPreds;
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000166 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
167 // It is faster to get preds from a PHI than with pred_iterator.
168 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
169 BBPreds.insert(BBPN->getIncomingBlock(i));
170 } else {
171 BBPreds.insert(pred_begin(BB), pred_end(BB));
172 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000173
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000174 // Walk the preds of DestBB.
175 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
176 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
177 if (BBPreds.count(Pred)) { // Common predecessor?
178 BBI = DestBB->begin();
179 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
180 const Value *V1 = PN->getIncomingValueForBlock(Pred);
181 const Value *V2 = PN->getIncomingValueForBlock(BB);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000182
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000183 // If V2 is a phi node in BB, look up what the mapped value will be.
184 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
185 if (V2PN->getParent() == BB)
186 V2 = V2PN->getIncomingValueForBlock(Pred);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000187
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000188 // If there is a conflict, bail out.
189 if (V1 != V2) return false;
190 }
191 }
192 }
193
194 return true;
195}
196
197
198/// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
199/// an unconditional branch in it.
200void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
201 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
202 BasicBlock *DestBB = BI->getSuccessor(0);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000203
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000204 DOUT << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000205
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000206 // If the destination block has a single pred, then this is a trivial edge,
207 // just collapse it.
208 if (DestBB->getSinglePredecessor()) {
209 // If DestBB has single-entry PHI nodes, fold them.
210 while (PHINode *PN = dyn_cast<PHINode>(DestBB->begin())) {
Chris Lattner47f57512008-11-24 19:25:36 +0000211 Value *NewVal = PN->getIncomingValue(0);
212 // Replace self referencing PHI with undef, it must be dead.
Chris Lattnerae297f82008-11-24 21:26:21 +0000213 if (NewVal == PN) NewVal = UndefValue::get(PN->getType());
Chris Lattner47f57512008-11-24 19:25:36 +0000214 PN->replaceAllUsesWith(NewVal);
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000215 PN->eraseFromParent();
216 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000217
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000218 // Splice all the PHI nodes from BB over to DestBB.
219 DestBB->getInstList().splice(DestBB->begin(), BB->getInstList(),
220 BB->begin(), BI);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000221
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000222 // Anything that branched to BB now branches to DestBB.
223 BB->replaceAllUsesWith(DestBB);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000224
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000225 // Nuke BB.
226 BB->eraseFromParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000227
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000228 DOUT << "AFTER:\n" << *DestBB << "\n\n\n";
229 return;
230 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000231
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000232 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
233 // to handle the new incoming edges it is about to have.
234 PHINode *PN;
235 for (BasicBlock::iterator BBI = DestBB->begin();
236 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
237 // Remove the incoming value for BB, and remember it.
238 Value *InVal = PN->removeIncomingValue(BB, false);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000239
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000240 // Two options: either the InVal is a phi node defined in BB or it is some
241 // value that dominates BB.
242 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
243 if (InValPhi && InValPhi->getParent() == BB) {
244 // Add all of the input values of the input PHI as inputs of this phi.
245 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
246 PN->addIncoming(InValPhi->getIncomingValue(i),
247 InValPhi->getIncomingBlock(i));
248 } else {
249 // Otherwise, add one instance of the dominating value for each edge that
250 // we will be adding.
251 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
252 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
253 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
254 } else {
255 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
256 PN->addIncoming(InVal, *PI);
257 }
258 }
259 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000260
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000261 // The PHIs are now updated, change everything that refers to BB to use
262 // DestBB and remove BB.
263 BB->replaceAllUsesWith(DestBB);
264 BB->eraseFromParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000265
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000266 DOUT << "AFTER:\n" << *DestBB << "\n\n\n";
267}
268
269
Chris Lattnerebe80752007-12-24 19:32:55 +0000270/// SplitEdgeNicely - Split the critical edge from TI to its specified
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000271/// successor if it will improve codegen. We only do this if the successor has
272/// phi nodes (otherwise critical edges are ok). If there is already another
273/// predecessor of the succ that is empty (and thus has no phi nodes), use it
274/// instead of introducing a new block.
275static void SplitEdgeNicely(TerminatorInst *TI, unsigned SuccNum, Pass *P) {
276 BasicBlock *TIBB = TI->getParent();
277 BasicBlock *Dest = TI->getSuccessor(SuccNum);
278 assert(isa<PHINode>(Dest->begin()) &&
279 "This should only be called if Dest has a PHI!");
Eric Christopher692bf6b2008-09-24 05:32:41 +0000280
Chris Lattnerebe80752007-12-24 19:32:55 +0000281 // As a hack, never split backedges of loops. Even though the copy for any
282 // PHIs inserted on the backedge would be dead for exits from the loop, we
283 // assume that the cost of *splitting* the backedge would be too high.
Chris Lattnerff26ab22007-12-25 19:06:45 +0000284 if (Dest == TIBB)
Chris Lattnerebe80752007-12-24 19:32:55 +0000285 return;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000286
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000287 /// TIPHIValues - This array is lazily computed to determine the values of
288 /// PHIs in Dest that TI would provide.
Chris Lattnerebe80752007-12-24 19:32:55 +0000289 SmallVector<Value*, 32> TIPHIValues;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000290
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000291 // Check to see if Dest has any blocks that can be used as a split edge for
292 // this terminator.
293 for (pred_iterator PI = pred_begin(Dest), E = pred_end(Dest); PI != E; ++PI) {
294 BasicBlock *Pred = *PI;
295 // To be usable, the pred has to end with an uncond branch to the dest.
296 BranchInst *PredBr = dyn_cast<BranchInst>(Pred->getTerminator());
297 if (!PredBr || !PredBr->isUnconditional() ||
298 // Must be empty other than the branch.
Dale Johannesen6603a1b2007-05-08 01:01:04 +0000299 &Pred->front() != PredBr ||
300 // Cannot be the entry block; its label does not get emitted.
301 Pred == &(Dest->getParent()->getEntryBlock()))
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000302 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000303
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000304 // Finally, since we know that Dest has phi nodes in it, we have to make
305 // sure that jumping to Pred will have the same affect as going to Dest in
306 // terms of PHI values.
307 PHINode *PN;
308 unsigned PHINo = 0;
309 bool FoundMatch = true;
310 for (BasicBlock::iterator I = Dest->begin();
311 (PN = dyn_cast<PHINode>(I)); ++I, ++PHINo) {
312 if (PHINo == TIPHIValues.size())
313 TIPHIValues.push_back(PN->getIncomingValueForBlock(TIBB));
Eric Christopher692bf6b2008-09-24 05:32:41 +0000314
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000315 // If the PHI entry doesn't work, we can't use this pred.
316 if (TIPHIValues[PHINo] != PN->getIncomingValueForBlock(Pred)) {
317 FoundMatch = false;
318 break;
319 }
320 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000321
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000322 // If we found a workable predecessor, change TI to branch to Succ.
323 if (FoundMatch) {
324 Dest->removePredecessor(TIBB);
325 TI->setSuccessor(SuccNum, Pred);
326 return;
327 }
328 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000329
330 SplitCriticalEdge(TI, SuccNum, P, true);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000331}
332
Chris Lattnerdd77df32007-04-13 20:30:56 +0000333/// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
334/// copy (e.g. it's casting from one pointer type to another, int->uint, or
335/// int->sbyte on PPC), sink it into user blocks to reduce the number of virtual
Dale Johannesence0b2372007-06-12 16:50:17 +0000336/// registers that must be created and coalesced.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000337///
338/// Return true if any changes are made.
Chris Lattner85fa13c2008-11-24 22:44:16 +0000339///
Chris Lattnerdd77df32007-04-13 20:30:56 +0000340static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
Eric Christopher692bf6b2008-09-24 05:32:41 +0000341 // If this is a noop copy,
Duncan Sands83ec4b62008-06-06 12:08:01 +0000342 MVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
343 MVT DstVT = TLI.getValueType(CI->getType());
Eric Christopher692bf6b2008-09-24 05:32:41 +0000344
Chris Lattnerdd77df32007-04-13 20:30:56 +0000345 // This is an fp<->int conversion?
Duncan Sands83ec4b62008-06-06 12:08:01 +0000346 if (SrcVT.isInteger() != DstVT.isInteger())
Chris Lattnerdd77df32007-04-13 20:30:56 +0000347 return false;
Duncan Sands8e4eb092008-06-08 20:54:56 +0000348
Chris Lattnerdd77df32007-04-13 20:30:56 +0000349 // If this is an extension, it will be a zero or sign extension, which
350 // isn't a noop.
Duncan Sands8e4eb092008-06-08 20:54:56 +0000351 if (SrcVT.bitsLT(DstVT)) return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000352
Chris Lattnerdd77df32007-04-13 20:30:56 +0000353 // If these values will be promoted, find out what they will be promoted
354 // to. This helps us consider truncates on PPC as noop copies when they
355 // are.
356 if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote)
357 SrcVT = TLI.getTypeToTransformTo(SrcVT);
358 if (TLI.getTypeAction(DstVT) == TargetLowering::Promote)
359 DstVT = TLI.getTypeToTransformTo(DstVT);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000360
Chris Lattnerdd77df32007-04-13 20:30:56 +0000361 // If, after promotion, these are the same types, this is a noop copy.
362 if (SrcVT != DstVT)
363 return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000364
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000365 BasicBlock *DefBB = CI->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000366
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000367 /// InsertedCasts - Only insert a cast in each block once.
Dale Johannesence0b2372007-06-12 16:50:17 +0000368 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000369
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000370 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000371 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000372 UI != E; ) {
373 Use &TheUse = UI.getUse();
374 Instruction *User = cast<Instruction>(*UI);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000375
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000376 // Figure out which BB this cast is used in. For PHI's this is the
377 // appropriate predecessor block.
378 BasicBlock *UserBB = User->getParent();
379 if (PHINode *PN = dyn_cast<PHINode>(User)) {
380 unsigned OpVal = UI.getOperandNo()/2;
381 UserBB = PN->getIncomingBlock(OpVal);
382 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000383
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000384 // Preincrement use iterator so we don't invalidate it.
385 ++UI;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000386
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000387 // If this user is in the same block as the cast, don't change the cast.
388 if (UserBB == DefBB) continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000389
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000390 // If we have already inserted a cast into this block, use it.
391 CastInst *&InsertedCast = InsertedCasts[UserBB];
392
393 if (!InsertedCast) {
Dan Gohman02dea8b2008-05-23 21:05:58 +0000394 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000395
396 InsertedCast =
397 CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000398 InsertPt);
399 MadeChange = true;
400 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000401
Dale Johannesence0b2372007-06-12 16:50:17 +0000402 // Replace a use of the cast with a use of the new cast.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000403 TheUse = InsertedCast;
404 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000405
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000406 // If we removed all uses, nuke the cast.
Duncan Sandse0038132008-01-20 16:51:46 +0000407 if (CI->use_empty()) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000408 CI->eraseFromParent();
Duncan Sandse0038132008-01-20 16:51:46 +0000409 MadeChange = true;
410 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000411
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000412 return MadeChange;
413}
414
Eric Christopher692bf6b2008-09-24 05:32:41 +0000415/// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
Dale Johannesence0b2372007-06-12 16:50:17 +0000416/// the number of virtual registers that must be created and coalesced. This is
Chris Lattner684b22d2007-08-02 16:53:43 +0000417/// a clear win except on targets with multiple condition code registers
418/// (PowerPC), where it might lose; some adjustment may be wanted there.
Dale Johannesence0b2372007-06-12 16:50:17 +0000419///
420/// Return true if any changes are made.
Chris Lattner85fa13c2008-11-24 22:44:16 +0000421static bool OptimizeCmpExpression(CmpInst *CI) {
Dale Johannesence0b2372007-06-12 16:50:17 +0000422 BasicBlock *DefBB = CI->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000423
Dale Johannesence0b2372007-06-12 16:50:17 +0000424 /// InsertedCmp - Only insert a cmp in each block once.
425 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000426
Dale Johannesence0b2372007-06-12 16:50:17 +0000427 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000428 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
Dale Johannesence0b2372007-06-12 16:50:17 +0000429 UI != E; ) {
430 Use &TheUse = UI.getUse();
431 Instruction *User = cast<Instruction>(*UI);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000432
Dale Johannesence0b2372007-06-12 16:50:17 +0000433 // Preincrement use iterator so we don't invalidate it.
434 ++UI;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000435
Dale Johannesence0b2372007-06-12 16:50:17 +0000436 // Don't bother for PHI nodes.
437 if (isa<PHINode>(User))
438 continue;
439
440 // Figure out which BB this cmp is used in.
441 BasicBlock *UserBB = User->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000442
Dale Johannesence0b2372007-06-12 16:50:17 +0000443 // If this user is in the same block as the cmp, don't change the cmp.
444 if (UserBB == DefBB) continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000445
Dale Johannesence0b2372007-06-12 16:50:17 +0000446 // If we have already inserted a cmp into this block, use it.
447 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
448
449 if (!InsertedCmp) {
Dan Gohman02dea8b2008-05-23 21:05:58 +0000450 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000451
452 InsertedCmp =
453 CmpInst::Create(CI->getOpcode(), CI->getPredicate(), CI->getOperand(0),
Dale Johannesence0b2372007-06-12 16:50:17 +0000454 CI->getOperand(1), "", InsertPt);
455 MadeChange = true;
456 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000457
Dale Johannesence0b2372007-06-12 16:50:17 +0000458 // Replace a use of the cmp with a use of the new cmp.
459 TheUse = InsertedCmp;
460 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000461
Dale Johannesence0b2372007-06-12 16:50:17 +0000462 // If we removed all uses, nuke the cmp.
463 if (CI->use_empty())
464 CI->eraseFromParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000465
Dale Johannesence0b2372007-06-12 16:50:17 +0000466 return MadeChange;
467}
468
Chris Lattner85fa13c2008-11-24 22:44:16 +0000469/// EraseDeadInstructions - Erase any dead instructions, recursively.
Chris Lattnerdd77df32007-04-13 20:30:56 +0000470static void EraseDeadInstructions(Value *V) {
471 Instruction *I = dyn_cast<Instruction>(V);
472 if (!I || !I->use_empty()) return;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000473
Chris Lattnerdd77df32007-04-13 20:30:56 +0000474 SmallPtrSet<Instruction*, 16> Insts;
475 Insts.insert(I);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000476
Chris Lattnerdd77df32007-04-13 20:30:56 +0000477 while (!Insts.empty()) {
478 I = *Insts.begin();
479 Insts.erase(I);
480 if (isInstructionTriviallyDead(I)) {
481 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
482 if (Instruction *U = dyn_cast<Instruction>(I->getOperand(i)))
483 Insts.insert(U);
484 I->eraseFromParent();
485 }
486 }
487}
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000488
Dan Gohman844731a2008-05-13 00:00:25 +0000489namespace {
Chris Lattner4744d852008-11-24 22:40:05 +0000490 /// ExtAddrMode - This is an extended version of TargetLowering::AddrMode
491 /// which holds actual Value*'s for register values.
492 struct ExtAddrMode : public TargetLowering::AddrMode {
493 Value *BaseReg;
494 Value *ScaledReg;
495 ExtAddrMode() : BaseReg(0), ScaledReg(0) {}
496 void print(OStream &OS) const;
497 void dump() const {
498 print(cerr);
499 cerr << '\n';
500 }
501 };
502} // end anonymous namespace
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000503
Chris Lattner4744d852008-11-24 22:40:05 +0000504static OStream &operator<<(OStream &OS, const ExtAddrMode &AM) {
505 AM.print(OS);
506 return OS;
507}
Chris Lattnerdd77df32007-04-13 20:30:56 +0000508
Chris Lattner4744d852008-11-24 22:40:05 +0000509
510void ExtAddrMode::print(OStream &OS) const {
Chris Lattnerdd77df32007-04-13 20:30:56 +0000511 bool NeedPlus = false;
512 OS << "[";
Chris Lattner4744d852008-11-24 22:40:05 +0000513 if (BaseGV)
Chris Lattnerdd77df32007-04-13 20:30:56 +0000514 OS << (NeedPlus ? " + " : "")
Chris Lattner4744d852008-11-24 22:40:05 +0000515 << "GV:%" << BaseGV->getName(), NeedPlus = true;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000516
Chris Lattner4744d852008-11-24 22:40:05 +0000517 if (BaseOffs)
518 OS << (NeedPlus ? " + " : "") << BaseOffs, NeedPlus = true;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000519
Chris Lattner4744d852008-11-24 22:40:05 +0000520 if (BaseReg)
Chris Lattnerdd77df32007-04-13 20:30:56 +0000521 OS << (NeedPlus ? " + " : "")
Chris Lattner4744d852008-11-24 22:40:05 +0000522 << "Base:%" << BaseReg->getName(), NeedPlus = true;
523 if (Scale)
Chris Lattnerdd77df32007-04-13 20:30:56 +0000524 OS << (NeedPlus ? " + " : "")
Chris Lattner4744d852008-11-24 22:40:05 +0000525 << Scale << "*%" << ScaledReg->getName(), NeedPlus = true;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000526
Chris Lattner4744d852008-11-24 22:40:05 +0000527 OS << ']';
Dan Gohman844731a2008-05-13 00:00:25 +0000528}
529
Chris Lattner85fa13c2008-11-24 22:44:16 +0000530/// TryMatchingScaledValue - Try adding ScaleReg*Scale to the specified
531/// addressing mode. Return true if this addr mode is legal for the target,
532/// false if not.
Chris Lattnerdd77df32007-04-13 20:30:56 +0000533static bool TryMatchingScaledValue(Value *ScaleReg, int64_t Scale,
534 const Type *AccessTy, ExtAddrMode &AddrMode,
535 SmallVector<Instruction*, 16> &AddrModeInsts,
Chris Lattner85fa13c2008-11-24 22:44:16 +0000536 const TargetLowering &TLI, unsigned Depth) {
537 // If we already have a scale of this value, we can add to it, otherwise, we
538 // need an available scale field.
539 if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
540 return false;
541
Chris Lattner088a1e82008-11-25 04:42:10 +0000542 ExtAddrMode TestAddrMode = AddrMode;
Chris Lattner85fa13c2008-11-24 22:44:16 +0000543
544 // Add scale to turn X*4+X*3 -> X*7. This could also do things like
545 // [A+B + A*7] -> [B+A*8].
Chris Lattner088a1e82008-11-25 04:42:10 +0000546 TestAddrMode.Scale += Scale;
547 TestAddrMode.ScaledReg = ScaleReg;
Chris Lattner85fa13c2008-11-24 22:44:16 +0000548
Chris Lattner088a1e82008-11-25 04:42:10 +0000549 // If the new address isn't legal, bail out.
550 if (!TLI.isLegalAddressingMode(TestAddrMode, AccessTy))
551 return false;
Chris Lattner85fa13c2008-11-24 22:44:16 +0000552
Chris Lattner088a1e82008-11-25 04:42:10 +0000553 // It was legal, so commit it.
554 AddrMode = TestAddrMode;
555
556 // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
557 // to see if ScaleReg is actually X+C. If so, we can turn this into adding
558 // X*Scale + C*Scale to addr mode.
559 ConstantInt *CI; Value *AddLHS;
560 if (match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
561 TestAddrMode.ScaledReg = AddLHS;
562 TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
563
564 // If this addressing mode is legal, commit it and remember that we folded
565 // this instruction.
566 if (TLI.isLegalAddressingMode(TestAddrMode, AccessTy)) {
567 AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
568 AddrMode = TestAddrMode;
Chris Lattner85fa13c2008-11-24 22:44:16 +0000569 }
Chris Lattner85fa13c2008-11-24 22:44:16 +0000570 }
571
Chris Lattner088a1e82008-11-25 04:42:10 +0000572 // Otherwise, not (x+c)*scale, just return what we have.
573 return true;
Chris Lattner85fa13c2008-11-24 22:44:16 +0000574}
575
Eric Christopher692bf6b2008-09-24 05:32:41 +0000576
Chris Lattnerdd77df32007-04-13 20:30:56 +0000577/// FindMaximalLegalAddressingMode - If we can, try to merge the computation of
578/// Addr into the specified addressing mode. If Addr can't be added to AddrMode
579/// this returns false. This assumes that Addr is either a pointer type or
580/// intptr_t for the target.
Chris Lattner85fa13c2008-11-24 22:44:16 +0000581///
582/// This method is used to optimize both load/store and inline asms with memory
583/// operands.
Chris Lattnerdd77df32007-04-13 20:30:56 +0000584static bool FindMaximalLegalAddressingMode(Value *Addr, const Type *AccessTy,
585 ExtAddrMode &AddrMode,
Chris Lattner088a1e82008-11-25 04:42:10 +0000586 SmallVectorImpl<Instruction*> &AddrModeInsts,
Chris Lattnerdd77df32007-04-13 20:30:56 +0000587 const TargetLowering &TLI,
588 unsigned Depth) {
Eric Christopher692bf6b2008-09-24 05:32:41 +0000589
Chris Lattnerdd77df32007-04-13 20:30:56 +0000590 // If this is a global variable, fold it into the addressing mode if possible.
591 if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
592 if (AddrMode.BaseGV == 0) {
593 AddrMode.BaseGV = GV;
594 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
595 return true;
596 AddrMode.BaseGV = 0;
597 }
598 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
599 AddrMode.BaseOffs += CI->getSExtValue();
600 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
601 return true;
602 AddrMode.BaseOffs -= CI->getSExtValue();
603 } else if (isa<ConstantPointerNull>(Addr)) {
604 return true;
605 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000606
Chris Lattnerdd77df32007-04-13 20:30:56 +0000607 // Look through constant exprs and instructions.
608 unsigned Opcode = ~0U;
609 User *AddrInst = 0;
610 if (Instruction *I = dyn_cast<Instruction>(Addr)) {
611 Opcode = I->getOpcode();
612 AddrInst = I;
613 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
614 Opcode = CE->getOpcode();
615 AddrInst = CE;
616 }
617
618 // Limit recursion to avoid exponential behavior.
619 if (Depth == 5) { AddrInst = 0; Opcode = ~0U; }
620
621 // If this is really an instruction, add it to our list of related
622 // instructions.
623 if (Instruction *I = dyn_cast_or_null<Instruction>(AddrInst))
624 AddrModeInsts.push_back(I);
625
Chris Lattner4744d852008-11-24 22:40:05 +0000626#if 0
627 if (AddrInst && !AddrInst->hasOneUse())
628 ;
629 else
630#endif
Chris Lattnerdd77df32007-04-13 20:30:56 +0000631 switch (Opcode) {
632 case Instruction::PtrToInt:
633 // PtrToInt is always a noop, as we know that the int type is pointer sized.
634 if (FindMaximalLegalAddressingMode(AddrInst->getOperand(0), AccessTy,
635 AddrMode, AddrModeInsts, TLI, Depth))
636 return true;
637 break;
638 case Instruction::IntToPtr:
639 // This inttoptr is a no-op if the integer type is pointer sized.
640 if (TLI.getValueType(AddrInst->getOperand(0)->getType()) ==
641 TLI.getPointerTy()) {
642 if (FindMaximalLegalAddressingMode(AddrInst->getOperand(0), AccessTy,
643 AddrMode, AddrModeInsts, TLI, Depth))
644 return true;
645 }
646 break;
647 case Instruction::Add: {
648 // Check to see if we can merge in the RHS then the LHS. If so, we win.
649 ExtAddrMode BackupAddrMode = AddrMode;
650 unsigned OldSize = AddrModeInsts.size();
651 if (FindMaximalLegalAddressingMode(AddrInst->getOperand(1), AccessTy,
652 AddrMode, AddrModeInsts, TLI, Depth+1) &&
653 FindMaximalLegalAddressingMode(AddrInst->getOperand(0), AccessTy,
654 AddrMode, AddrModeInsts, TLI, Depth+1))
655 return true;
656
657 // Restore the old addr mode info.
658 AddrMode = BackupAddrMode;
659 AddrModeInsts.resize(OldSize);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000660
Chris Lattnerdd77df32007-04-13 20:30:56 +0000661 // Otherwise this was over-aggressive. Try merging in the LHS then the RHS.
662 if (FindMaximalLegalAddressingMode(AddrInst->getOperand(0), AccessTy,
663 AddrMode, AddrModeInsts, TLI, Depth+1) &&
664 FindMaximalLegalAddressingMode(AddrInst->getOperand(1), AccessTy,
665 AddrMode, AddrModeInsts, TLI, Depth+1))
666 return true;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000667
Chris Lattnerdd77df32007-04-13 20:30:56 +0000668 // Otherwise we definitely can't merge the ADD in.
669 AddrMode = BackupAddrMode;
670 AddrModeInsts.resize(OldSize);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000671 break;
Chris Lattnerdd77df32007-04-13 20:30:56 +0000672 }
673 case Instruction::Or: {
Chris Lattner088a1e82008-11-25 04:42:10 +0000674 //ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
675 //if (!RHS) break;
Chris Lattnerdd77df32007-04-13 20:30:56 +0000676 // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
677 break;
678 }
679 case Instruction::Mul:
680 case Instruction::Shl: {
681 // Can only handle X*C and X << C, and can only handle this when the scale
682 // field is available.
683 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
684 if (!RHS) break;
685 int64_t Scale = RHS->getSExtValue();
686 if (Opcode == Instruction::Shl)
687 Scale = 1 << Scale;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000688
Chris Lattnerdd77df32007-04-13 20:30:56 +0000689 if (TryMatchingScaledValue(AddrInst->getOperand(0), Scale, AccessTy,
690 AddrMode, AddrModeInsts, TLI, Depth))
691 return true;
692 break;
693 }
694 case Instruction::GetElementPtr: {
695 // Scan the GEP. We check it if it contains constant offsets and at most
696 // one variable offset.
697 int VariableOperand = -1;
698 unsigned VariableScale = 0;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000699
Chris Lattnerdd77df32007-04-13 20:30:56 +0000700 int64_t ConstantOffset = 0;
701 const TargetData *TD = TLI.getTargetData();
702 gep_type_iterator GTI = gep_type_begin(AddrInst);
703 for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
704 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
705 const StructLayout *SL = TD->getStructLayout(STy);
706 unsigned Idx =
707 cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
708 ConstantOffset += SL->getElementOffset(Idx);
709 } else {
Duncan Sands514ab342007-11-01 20:53:16 +0000710 uint64_t TypeSize = TD->getABITypeSize(GTI.getIndexedType());
Chris Lattnerdd77df32007-04-13 20:30:56 +0000711 if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
712 ConstantOffset += CI->getSExtValue()*TypeSize;
713 } else if (TypeSize) { // Scales of zero don't do anything.
714 // We only allow one variable index at the moment.
715 if (VariableOperand != -1) {
716 VariableOperand = -2;
717 break;
718 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000719
Chris Lattnerdd77df32007-04-13 20:30:56 +0000720 // Remember the variable index.
721 VariableOperand = i;
722 VariableScale = TypeSize;
723 }
724 }
725 }
726
727 // If the GEP had multiple variable indices, punt.
728 if (VariableOperand == -2)
729 break;
730
731 // A common case is for the GEP to only do a constant offset. In this case,
732 // just add it to the disp field and check validity.
733 if (VariableOperand == -1) {
734 AddrMode.BaseOffs += ConstantOffset;
735 if (ConstantOffset == 0 || TLI.isLegalAddressingMode(AddrMode, AccessTy)){
736 // Check to see if we can fold the base pointer in too.
737 if (FindMaximalLegalAddressingMode(AddrInst->getOperand(0), AccessTy,
738 AddrMode, AddrModeInsts, TLI,
739 Depth+1))
740 return true;
741 }
742 AddrMode.BaseOffs -= ConstantOffset;
743 } else {
744 // Check that this has no base reg yet. If so, we won't have a place to
745 // put the base of the GEP (assuming it is not a null ptr).
746 bool SetBaseReg = false;
747 if (AddrMode.HasBaseReg) {
748 if (!isa<ConstantPointerNull>(AddrInst->getOperand(0)))
749 break;
750 } else {
751 AddrMode.HasBaseReg = true;
752 AddrMode.BaseReg = AddrInst->getOperand(0);
753 SetBaseReg = true;
754 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000755
Chris Lattnerdd77df32007-04-13 20:30:56 +0000756 // See if the scale amount is valid for this target.
757 AddrMode.BaseOffs += ConstantOffset;
758 if (TryMatchingScaledValue(AddrInst->getOperand(VariableOperand),
Eric Christopher692bf6b2008-09-24 05:32:41 +0000759 VariableScale, AccessTy, AddrMode,
Chris Lattnerdd77df32007-04-13 20:30:56 +0000760 AddrModeInsts, TLI, Depth)) {
761 if (!SetBaseReg) return true;
762
763 // If this match succeeded, we know that we can form an address with the
764 // GepBase as the basereg. See if we can match *more*.
765 AddrMode.HasBaseReg = false;
766 AddrMode.BaseReg = 0;
767 if (FindMaximalLegalAddressingMode(AddrInst->getOperand(0), AccessTy,
768 AddrMode, AddrModeInsts, TLI,
769 Depth+1))
770 return true;
771 // Strange, shouldn't happen. Restore the base reg and succeed the easy
Eric Christopher692bf6b2008-09-24 05:32:41 +0000772 // way.
Chris Lattnerdd77df32007-04-13 20:30:56 +0000773 AddrMode.HasBaseReg = true;
774 AddrMode.BaseReg = AddrInst->getOperand(0);
775 return true;
776 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000777
Chris Lattnerdd77df32007-04-13 20:30:56 +0000778 AddrMode.BaseOffs -= ConstantOffset;
779 if (SetBaseReg) {
780 AddrMode.HasBaseReg = false;
781 AddrMode.BaseReg = 0;
782 }
783 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000784 break;
Chris Lattnerdd77df32007-04-13 20:30:56 +0000785 }
786 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000787
Chris Lattnerdd77df32007-04-13 20:30:56 +0000788 if (Instruction *I = dyn_cast_or_null<Instruction>(AddrInst)) {
Chris Lattner0c80c752008-04-06 21:44:08 +0000789 assert(AddrModeInsts.back() == I && "Stack imbalance"); I = I;
Chris Lattnerdd77df32007-04-13 20:30:56 +0000790 AddrModeInsts.pop_back();
791 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000792
Chris Lattnerdd77df32007-04-13 20:30:56 +0000793 // Worse case, the target should support [reg] addressing modes. :)
794 if (!AddrMode.HasBaseReg) {
795 AddrMode.HasBaseReg = true;
796 // Still check for legality in case the target supports [imm] but not [i+r].
797 if (TLI.isLegalAddressingMode(AddrMode, AccessTy)) {
798 AddrMode.BaseReg = Addr;
799 return true;
800 }
801 AddrMode.HasBaseReg = false;
802 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000803
Chris Lattnerdd77df32007-04-13 20:30:56 +0000804 // If the base register is already taken, see if we can do [r+r].
805 if (AddrMode.Scale == 0) {
806 AddrMode.Scale = 1;
807 if (TLI.isLegalAddressingMode(AddrMode, AccessTy)) {
808 AddrMode.ScaledReg = Addr;
809 return true;
810 }
811 AddrMode.Scale = 0;
812 }
813 // Couldn't match.
814 return false;
815}
816
Chris Lattnerdd77df32007-04-13 20:30:56 +0000817
818/// IsNonLocalValue - Return true if the specified values are defined in a
819/// different basic block than BB.
820static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
821 if (Instruction *I = dyn_cast<Instruction>(V))
822 return I->getParent() != BB;
823 return false;
824}
825
826/// OptimizeLoadStoreInst - Load and Store Instructions have often have
827/// addressing modes that can do significant amounts of computation. As such,
828/// instruction selection will try to get the load or store to do as much
829/// computation as possible for the program. The problem is that isel can only
830/// see within a single block. As such, we sink as much legal addressing mode
831/// stuff into the block as possible.
832bool CodeGenPrepare::OptimizeLoadStoreInst(Instruction *LdStInst, Value *Addr,
833 const Type *AccessTy,
834 DenseMap<Value*,Value*> &SunkAddrs) {
835 // Figure out what addressing mode will be built up for this operation.
836 SmallVector<Instruction*, 16> AddrModeInsts;
837 ExtAddrMode AddrMode;
838 bool Success = FindMaximalLegalAddressingMode(Addr, AccessTy, AddrMode,
839 AddrModeInsts, *TLI, 0);
840 Success = Success; assert(Success && "Couldn't select *anything*?");
Eric Christopher692bf6b2008-09-24 05:32:41 +0000841
Chris Lattnerdd77df32007-04-13 20:30:56 +0000842 // Check to see if any of the instructions supersumed by this addr mode are
843 // non-local to I's BB.
844 bool AnyNonLocal = false;
845 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
846 if (IsNonLocalValue(AddrModeInsts[i], LdStInst->getParent())) {
847 AnyNonLocal = true;
848 break;
849 }
850 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000851
Chris Lattnerdd77df32007-04-13 20:30:56 +0000852 // If all the instructions matched are already in this BB, don't do anything.
853 if (!AnyNonLocal) {
854 DEBUG(cerr << "CGP: Found local addrmode: " << AddrMode << "\n");
855 return false;
856 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000857
Chris Lattnerdd77df32007-04-13 20:30:56 +0000858 // Insert this computation right after this user. Since our caller is
859 // scanning from the top of the BB to the bottom, reuse of the expr are
860 // guaranteed to happen later.
861 BasicBlock::iterator InsertPt = LdStInst;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000862
Chris Lattnerdd77df32007-04-13 20:30:56 +0000863 // Now that we determined the addressing expression we want to use and know
864 // that we have to sink it into this block. Check to see if we have already
865 // done this for some other load/store instr in this block. If so, reuse the
866 // computation.
867 Value *&SunkAddr = SunkAddrs[Addr];
868 if (SunkAddr) {
869 DEBUG(cerr << "CGP: Reusing nonlocal addrmode: " << AddrMode << "\n");
870 if (SunkAddr->getType() != Addr->getType())
871 SunkAddr = new BitCastInst(SunkAddr, Addr->getType(), "tmp", InsertPt);
872 } else {
873 DEBUG(cerr << "CGP: SINKING nonlocal addrmode: " << AddrMode << "\n");
874 const Type *IntPtrTy = TLI->getTargetData()->getIntPtrType();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000875
Chris Lattnerdd77df32007-04-13 20:30:56 +0000876 Value *Result = 0;
877 // Start with the scale value.
878 if (AddrMode.Scale) {
879 Value *V = AddrMode.ScaledReg;
880 if (V->getType() == IntPtrTy) {
881 // done.
882 } else if (isa<PointerType>(V->getType())) {
883 V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
884 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
885 cast<IntegerType>(V->getType())->getBitWidth()) {
886 V = new TruncInst(V, IntPtrTy, "sunkaddr", InsertPt);
887 } else {
888 V = new SExtInst(V, IntPtrTy, "sunkaddr", InsertPt);
889 }
890 if (AddrMode.Scale != 1)
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000891 V = BinaryOperator::CreateMul(V, ConstantInt::get(IntPtrTy,
Chris Lattnerdd77df32007-04-13 20:30:56 +0000892 AddrMode.Scale),
893 "sunkaddr", InsertPt);
894 Result = V;
895 }
896
897 // Add in the base register.
898 if (AddrMode.BaseReg) {
899 Value *V = AddrMode.BaseReg;
900 if (V->getType() != IntPtrTy)
901 V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
902 if (Result)
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000903 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000904 else
905 Result = V;
906 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000907
Chris Lattnerdd77df32007-04-13 20:30:56 +0000908 // Add in the BaseGV if present.
909 if (AddrMode.BaseGV) {
910 Value *V = new PtrToIntInst(AddrMode.BaseGV, IntPtrTy, "sunkaddr",
911 InsertPt);
912 if (Result)
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000913 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000914 else
915 Result = V;
916 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000917
Chris Lattnerdd77df32007-04-13 20:30:56 +0000918 // Add in the Base Offset if present.
919 if (AddrMode.BaseOffs) {
920 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
921 if (Result)
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000922 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000923 else
924 Result = V;
925 }
926
927 if (Result == 0)
928 SunkAddr = Constant::getNullValue(Addr->getType());
929 else
930 SunkAddr = new IntToPtrInst(Result, Addr->getType(), "sunkaddr",InsertPt);
931 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000932
Chris Lattnerdd77df32007-04-13 20:30:56 +0000933 LdStInst->replaceUsesOfWith(Addr, SunkAddr);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000934
Chris Lattnerdd77df32007-04-13 20:30:56 +0000935 if (Addr->use_empty())
936 EraseDeadInstructions(Addr);
937 return true;
938}
939
Evan Cheng9bf12b52008-02-26 02:42:37 +0000940/// OptimizeInlineAsmInst - If there are any memory operands, use
941/// OptimizeLoadStoreInt to sink their address computing into the block when
942/// possible / profitable.
943bool CodeGenPrepare::OptimizeInlineAsmInst(Instruction *I, CallSite CS,
944 DenseMap<Value*,Value*> &SunkAddrs) {
945 bool MadeChange = false;
946 InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
947
948 // Do a prepass over the constraints, canonicalizing them, and building up the
949 // ConstraintOperands list.
950 std::vector<InlineAsm::ConstraintInfo>
951 ConstraintInfos = IA->ParseConstraints();
952
953 /// ConstraintOperands - Information about all of the constraints.
954 std::vector<TargetLowering::AsmOperandInfo> ConstraintOperands;
955 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
956 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
957 ConstraintOperands.
958 push_back(TargetLowering::AsmOperandInfo(ConstraintInfos[i]));
959 TargetLowering::AsmOperandInfo &OpInfo = ConstraintOperands.back();
960
961 // Compute the value type for each operand.
962 switch (OpInfo.Type) {
963 case InlineAsm::isOutput:
964 if (OpInfo.isIndirect)
965 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
966 break;
967 case InlineAsm::isInput:
968 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
969 break;
970 case InlineAsm::isClobber:
971 // Nothing to do.
972 break;
973 }
974
975 // Compute the constraint code and ConstraintType to use.
Evan Chenga7e61462008-09-24 06:48:55 +0000976 TLI->ComputeConstraintToUse(OpInfo, SDValue(),
977 OpInfo.ConstraintType == TargetLowering::C_Memory);
Evan Cheng9bf12b52008-02-26 02:42:37 +0000978
Eli Friedman9ec80952008-02-26 18:37:49 +0000979 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
980 OpInfo.isIndirect) {
Evan Cheng9bf12b52008-02-26 02:42:37 +0000981 Value *OpVal = OpInfo.CallOperandVal;
982 MadeChange |= OptimizeLoadStoreInst(I, OpVal, OpVal->getType(),
983 SunkAddrs);
984 }
985 }
986
987 return MadeChange;
988}
989
Evan Chengbdcb7262007-12-05 23:58:20 +0000990bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
991 BasicBlock *DefBB = I->getParent();
992
993 // If both result of the {s|z}xt and its source are live out, rewrite all
994 // other uses of the source with result of extension.
995 Value *Src = I->getOperand(0);
996 if (Src->hasOneUse())
997 return false;
998
Evan Cheng696e5c02007-12-13 07:50:36 +0000999 // Only do this xform if truncating is free.
Gabor Greif53bdbd72008-02-26 19:13:21 +00001000 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
Evan Chengf9785f92007-12-13 03:32:53 +00001001 return false;
1002
Evan Cheng772de512007-12-12 00:51:06 +00001003 // Only safe to perform the optimization if the source is also defined in
Evan Cheng765dff22007-12-12 02:53:41 +00001004 // this block.
1005 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
Evan Cheng772de512007-12-12 00:51:06 +00001006 return false;
1007
Evan Chengbdcb7262007-12-05 23:58:20 +00001008 bool DefIsLiveOut = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001009 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
Evan Chengbdcb7262007-12-05 23:58:20 +00001010 UI != E; ++UI) {
1011 Instruction *User = cast<Instruction>(*UI);
1012
1013 // Figure out which BB this ext is used in.
1014 BasicBlock *UserBB = User->getParent();
1015 if (UserBB == DefBB) continue;
1016 DefIsLiveOut = true;
1017 break;
1018 }
1019 if (!DefIsLiveOut)
1020 return false;
1021
Evan Cheng765dff22007-12-12 02:53:41 +00001022 // Make sure non of the uses are PHI nodes.
Eric Christopher692bf6b2008-09-24 05:32:41 +00001023 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
Evan Cheng765dff22007-12-12 02:53:41 +00001024 UI != E; ++UI) {
1025 Instruction *User = cast<Instruction>(*UI);
Evan Chengf9785f92007-12-13 03:32:53 +00001026 BasicBlock *UserBB = User->getParent();
1027 if (UserBB == DefBB) continue;
1028 // Be conservative. We don't want this xform to end up introducing
1029 // reloads just before load / store instructions.
1030 if (isa<PHINode>(User) || isa<LoadInst>(User) || isa<StoreInst>(User))
Evan Cheng765dff22007-12-12 02:53:41 +00001031 return false;
1032 }
1033
Evan Chengbdcb7262007-12-05 23:58:20 +00001034 // InsertedTruncs - Only insert one trunc in each block once.
1035 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
1036
1037 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001038 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
Evan Chengbdcb7262007-12-05 23:58:20 +00001039 UI != E; ++UI) {
1040 Use &TheUse = UI.getUse();
1041 Instruction *User = cast<Instruction>(*UI);
1042
1043 // Figure out which BB this ext is used in.
1044 BasicBlock *UserBB = User->getParent();
1045 if (UserBB == DefBB) continue;
1046
1047 // Both src and def are live in this block. Rewrite the use.
1048 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
1049
1050 if (!InsertedTrunc) {
Dan Gohman02dea8b2008-05-23 21:05:58 +00001051 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
Eric Christopher692bf6b2008-09-24 05:32:41 +00001052
Evan Chengbdcb7262007-12-05 23:58:20 +00001053 InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
1054 }
1055
1056 // Replace a use of the {s|z}ext source with a use of the result.
1057 TheUse = InsertedTrunc;
1058
1059 MadeChange = true;
1060 }
1061
1062 return MadeChange;
1063}
1064
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001065// In this pass we look for GEP and cast instructions that are used
1066// across basic blocks and rewrite them to improve basic-block-at-a-time
1067// selection.
1068bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
1069 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001070
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001071 // Split all critical edges where the dest block has a PHI and where the phi
1072 // has shared immediate operands.
1073 TerminatorInst *BBTI = BB.getTerminator();
1074 if (BBTI->getNumSuccessors() > 1) {
1075 for (unsigned i = 0, e = BBTI->getNumSuccessors(); i != e; ++i)
1076 if (isa<PHINode>(BBTI->getSuccessor(i)->begin()) &&
1077 isCriticalEdge(BBTI, i, true))
1078 SplitEdgeNicely(BBTI, i, this);
1079 }
Eric Christopher692bf6b2008-09-24 05:32:41 +00001080
1081
Chris Lattnerdd77df32007-04-13 20:30:56 +00001082 // Keep track of non-local addresses that have been sunk into this block.
1083 // This allows us to avoid inserting duplicate code for blocks with multiple
1084 // load/stores of the same address.
1085 DenseMap<Value*, Value*> SunkAddrs;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001086
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001087 for (BasicBlock::iterator BBI = BB.begin(), E = BB.end(); BBI != E; ) {
1088 Instruction *I = BBI++;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001089
Chris Lattnerdd77df32007-04-13 20:30:56 +00001090 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001091 // If the source of the cast is a constant, then this should have
1092 // already been constant folded. The only reason NOT to constant fold
1093 // it is if something (e.g. LSR) was careful to place the constant
1094 // evaluation in a block other than then one that uses it (e.g. to hoist
1095 // the address of globals out of a loop). If this is the case, we don't
1096 // want to forward-subst the cast.
1097 if (isa<Constant>(CI->getOperand(0)))
1098 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001099
Evan Chengbdcb7262007-12-05 23:58:20 +00001100 bool Change = false;
1101 if (TLI) {
1102 Change = OptimizeNoopCopyExpression(CI, *TLI);
1103 MadeChange |= Change;
1104 }
1105
Evan Cheng55e641b2008-03-19 22:02:26 +00001106 if (!Change && (isa<ZExtInst>(I) || isa<SExtInst>(I)))
Evan Chengbdcb7262007-12-05 23:58:20 +00001107 MadeChange |= OptimizeExtUses(I);
Dale Johannesence0b2372007-06-12 16:50:17 +00001108 } else if (CmpInst *CI = dyn_cast<CmpInst>(I)) {
1109 MadeChange |= OptimizeCmpExpression(CI);
Chris Lattnerdd77df32007-04-13 20:30:56 +00001110 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
1111 if (TLI)
1112 MadeChange |= OptimizeLoadStoreInst(I, I->getOperand(0), LI->getType(),
1113 SunkAddrs);
1114 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
1115 if (TLI)
1116 MadeChange |= OptimizeLoadStoreInst(I, SI->getOperand(1),
1117 SI->getOperand(0)->getType(),
1118 SunkAddrs);
1119 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Chris Lattnerf25646b2007-04-14 00:17:39 +00001120 if (GEPI->hasAllZeroIndices()) {
Chris Lattnerdd77df32007-04-13 20:30:56 +00001121 /// The GEP operand must be a pointer, so must its result -> BitCast
Eric Christopher692bf6b2008-09-24 05:32:41 +00001122 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
Chris Lattnerdd77df32007-04-13 20:30:56 +00001123 GEPI->getName(), GEPI);
1124 GEPI->replaceAllUsesWith(NC);
1125 GEPI->eraseFromParent();
1126 MadeChange = true;
1127 BBI = NC;
1128 }
1129 } else if (CallInst *CI = dyn_cast<CallInst>(I)) {
1130 // If we found an inline asm expession, and if the target knows how to
1131 // lower it to normal LLVM code, do so now.
1132 if (TLI && isa<InlineAsm>(CI->getCalledValue()))
Eric Christopher692bf6b2008-09-24 05:32:41 +00001133 if (const TargetAsmInfo *TAI =
Chris Lattnerdd77df32007-04-13 20:30:56 +00001134 TLI->getTargetMachine().getTargetAsmInfo()) {
1135 if (TAI->ExpandInlineAsm(CI))
1136 BBI = BB.begin();
Evan Cheng9bf12b52008-02-26 02:42:37 +00001137 else
1138 // Sink address computing for memory operands into the block.
1139 MadeChange |= OptimizeInlineAsmInst(I, &(*CI), SunkAddrs);
Chris Lattnerdd77df32007-04-13 20:30:56 +00001140 }
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001141 }
1142 }
Eric Christopher692bf6b2008-09-24 05:32:41 +00001143
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001144 return MadeChange;
1145}