blob: f09a7e42262788e3f2eb15a7c2ce7f21a3aa31d0 [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 Lattner88a5c832008-11-25 07:09:13 +000056 bool OptimizeMemoryInst(Instruction *I, Value *Addr, const Type *AccessTy,
57 DenseMap<Value*,Value*> &SunkAddrs);
Evan Cheng9bf12b52008-02-26 02:42:37 +000058 bool OptimizeInlineAsmInst(Instruction *I, CallSite CS,
59 DenseMap<Value*,Value*> &SunkAddrs);
Evan Chengbdcb7262007-12-05 23:58:20 +000060 bool OptimizeExtUses(Instruction *I);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000061 };
62}
Devang Patel794fd752007-05-01 21:15:47 +000063
Devang Patel19974732007-05-03 01:11:54 +000064char CodeGenPrepare::ID = 0;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000065static RegisterPass<CodeGenPrepare> X("codegenprepare",
66 "Optimize for code generation");
67
68FunctionPass *llvm::createCodeGenPreparePass(const TargetLowering *TLI) {
69 return new CodeGenPrepare(TLI);
70}
71
72
73bool CodeGenPrepare::runOnFunction(Function &F) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000074 bool EverMadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +000075
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +000076 // First pass, eliminate blocks that contain only PHI nodes and an
77 // unconditional branch.
78 EverMadeChange |= EliminateMostlyEmptyBlocks(F);
Eric Christopher692bf6b2008-09-24 05:32:41 +000079
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +000080 bool MadeChange = true;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000081 while (MadeChange) {
82 MadeChange = false;
83 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
84 MadeChange |= OptimizeBlock(*BB);
85 EverMadeChange |= MadeChange;
86 }
87 return EverMadeChange;
88}
89
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +000090/// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes
Eric Christopher692bf6b2008-09-24 05:32:41 +000091/// and an unconditional branch. Passes before isel (e.g. LSR/loopsimplify)
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +000092/// often split edges in ways that are non-optimal for isel. Start by
93/// eliminating these blocks so we can split them the way we want them.
94bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
95 bool MadeChange = false;
96 // Note that this intentionally skips the entry block.
97 for (Function::iterator I = ++F.begin(), E = F.end(); I != E; ) {
98 BasicBlock *BB = I++;
99
100 // If this block doesn't end with an uncond branch, ignore it.
101 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
102 if (!BI || !BI->isUnconditional())
103 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000104
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000105 // If the instruction before the branch isn't a phi node, then other stuff
106 // is happening here.
107 BasicBlock::iterator BBI = BI;
108 if (BBI != BB->begin()) {
109 --BBI;
110 if (!isa<PHINode>(BBI)) continue;
111 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000112
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000113 // Do not break infinite loops.
114 BasicBlock *DestBB = BI->getSuccessor(0);
115 if (DestBB == BB)
116 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000117
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000118 if (!CanMergeBlocks(BB, DestBB))
119 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000120
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000121 EliminateMostlyEmptyBlock(BB);
122 MadeChange = true;
123 }
124 return MadeChange;
125}
126
127/// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
128/// single uncond branch between them, and BB contains no other non-phi
129/// instructions.
130bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
131 const BasicBlock *DestBB) const {
132 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
133 // the successor. If there are more complex condition (e.g. preheaders),
134 // don't mess around with them.
135 BasicBlock::const_iterator BBI = BB->begin();
136 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
137 for (Value::use_const_iterator UI = PN->use_begin(), E = PN->use_end();
138 UI != E; ++UI) {
139 const Instruction *User = cast<Instruction>(*UI);
140 if (User->getParent() != DestBB || !isa<PHINode>(User))
141 return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000142 // If User is inside DestBB block and it is a PHINode then check
143 // incoming value. If incoming value is not from BB then this is
Devang Patel75abc1e2007-04-25 00:37:04 +0000144 // a complex condition (e.g. preheaders) we want to avoid here.
145 if (User->getParent() == DestBB) {
146 if (const PHINode *UPN = dyn_cast<PHINode>(User))
147 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
148 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
149 if (Insn && Insn->getParent() == BB &&
150 Insn->getParent() != UPN->getIncomingBlock(I))
151 return false;
152 }
153 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000154 }
155 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000156
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000157 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
158 // and DestBB may have conflicting incoming values for the block. If so, we
159 // can't merge the block.
160 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
161 if (!DestBBPN) return true; // no conflict.
Eric Christopher692bf6b2008-09-24 05:32:41 +0000162
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000163 // Collect the preds of BB.
Chris Lattnerf67f73a2007-11-06 22:07:40 +0000164 SmallPtrSet<const BasicBlock*, 16> BBPreds;
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000165 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
166 // It is faster to get preds from a PHI than with pred_iterator.
167 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
168 BBPreds.insert(BBPN->getIncomingBlock(i));
169 } else {
170 BBPreds.insert(pred_begin(BB), pred_end(BB));
171 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000172
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000173 // Walk the preds of DestBB.
174 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
175 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
176 if (BBPreds.count(Pred)) { // Common predecessor?
177 BBI = DestBB->begin();
178 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
179 const Value *V1 = PN->getIncomingValueForBlock(Pred);
180 const Value *V2 = PN->getIncomingValueForBlock(BB);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000181
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000182 // If V2 is a phi node in BB, look up what the mapped value will be.
183 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
184 if (V2PN->getParent() == BB)
185 V2 = V2PN->getIncomingValueForBlock(Pred);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000186
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000187 // If there is a conflict, bail out.
188 if (V1 != V2) return false;
189 }
190 }
191 }
192
193 return true;
194}
195
196
197/// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
198/// an unconditional branch in it.
199void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
200 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
201 BasicBlock *DestBB = BI->getSuccessor(0);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000202
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000203 DOUT << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000204
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000205 // If the destination block has a single pred, then this is a trivial edge,
206 // just collapse it.
207 if (DestBB->getSinglePredecessor()) {
208 // If DestBB has single-entry PHI nodes, fold them.
209 while (PHINode *PN = dyn_cast<PHINode>(DestBB->begin())) {
Chris Lattner47f57512008-11-24 19:25:36 +0000210 Value *NewVal = PN->getIncomingValue(0);
211 // Replace self referencing PHI with undef, it must be dead.
Chris Lattnerae297f82008-11-24 21:26:21 +0000212 if (NewVal == PN) NewVal = UndefValue::get(PN->getType());
Chris Lattner47f57512008-11-24 19:25:36 +0000213 PN->replaceAllUsesWith(NewVal);
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000214 PN->eraseFromParent();
215 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000216
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000217 // Splice all the PHI nodes from BB over to DestBB.
218 DestBB->getInstList().splice(DestBB->begin(), BB->getInstList(),
219 BB->begin(), BI);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000220
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000221 // Anything that branched to BB now branches to DestBB.
222 BB->replaceAllUsesWith(DestBB);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000223
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000224 // Nuke BB.
225 BB->eraseFromParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000226
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000227 DOUT << "AFTER:\n" << *DestBB << "\n\n\n";
228 return;
229 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000230
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000231 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
232 // to handle the new incoming edges it is about to have.
233 PHINode *PN;
234 for (BasicBlock::iterator BBI = DestBB->begin();
235 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
236 // Remove the incoming value for BB, and remember it.
237 Value *InVal = PN->removeIncomingValue(BB, false);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000238
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000239 // Two options: either the InVal is a phi node defined in BB or it is some
240 // value that dominates BB.
241 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
242 if (InValPhi && InValPhi->getParent() == BB) {
243 // Add all of the input values of the input PHI as inputs of this phi.
244 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
245 PN->addIncoming(InValPhi->getIncomingValue(i),
246 InValPhi->getIncomingBlock(i));
247 } else {
248 // Otherwise, add one instance of the dominating value for each edge that
249 // we will be adding.
250 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
251 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
252 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
253 } else {
254 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
255 PN->addIncoming(InVal, *PI);
256 }
257 }
258 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000259
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000260 // The PHIs are now updated, change everything that refers to BB to use
261 // DestBB and remove BB.
262 BB->replaceAllUsesWith(DestBB);
263 BB->eraseFromParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000264
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000265 DOUT << "AFTER:\n" << *DestBB << "\n\n\n";
266}
267
268
Chris Lattnerebe80752007-12-24 19:32:55 +0000269/// SplitEdgeNicely - Split the critical edge from TI to its specified
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000270/// successor if it will improve codegen. We only do this if the successor has
271/// phi nodes (otherwise critical edges are ok). If there is already another
272/// predecessor of the succ that is empty (and thus has no phi nodes), use it
273/// instead of introducing a new block.
274static void SplitEdgeNicely(TerminatorInst *TI, unsigned SuccNum, Pass *P) {
275 BasicBlock *TIBB = TI->getParent();
276 BasicBlock *Dest = TI->getSuccessor(SuccNum);
277 assert(isa<PHINode>(Dest->begin()) &&
278 "This should only be called if Dest has a PHI!");
Eric Christopher692bf6b2008-09-24 05:32:41 +0000279
Chris Lattnerebe80752007-12-24 19:32:55 +0000280 // As a hack, never split backedges of loops. Even though the copy for any
281 // PHIs inserted on the backedge would be dead for exits from the loop, we
282 // assume that the cost of *splitting* the backedge would be too high.
Chris Lattnerff26ab22007-12-25 19:06:45 +0000283 if (Dest == TIBB)
Chris Lattnerebe80752007-12-24 19:32:55 +0000284 return;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000285
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000286 /// TIPHIValues - This array is lazily computed to determine the values of
287 /// PHIs in Dest that TI would provide.
Chris Lattnerebe80752007-12-24 19:32:55 +0000288 SmallVector<Value*, 32> TIPHIValues;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000289
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000290 // Check to see if Dest has any blocks that can be used as a split edge for
291 // this terminator.
292 for (pred_iterator PI = pred_begin(Dest), E = pred_end(Dest); PI != E; ++PI) {
293 BasicBlock *Pred = *PI;
294 // To be usable, the pred has to end with an uncond branch to the dest.
295 BranchInst *PredBr = dyn_cast<BranchInst>(Pred->getTerminator());
296 if (!PredBr || !PredBr->isUnconditional() ||
297 // Must be empty other than the branch.
Dale Johannesen6603a1b2007-05-08 01:01:04 +0000298 &Pred->front() != PredBr ||
299 // Cannot be the entry block; its label does not get emitted.
300 Pred == &(Dest->getParent()->getEntryBlock()))
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000301 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000302
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000303 // Finally, since we know that Dest has phi nodes in it, we have to make
304 // sure that jumping to Pred will have the same affect as going to Dest in
305 // terms of PHI values.
306 PHINode *PN;
307 unsigned PHINo = 0;
308 bool FoundMatch = true;
309 for (BasicBlock::iterator I = Dest->begin();
310 (PN = dyn_cast<PHINode>(I)); ++I, ++PHINo) {
311 if (PHINo == TIPHIValues.size())
312 TIPHIValues.push_back(PN->getIncomingValueForBlock(TIBB));
Eric Christopher692bf6b2008-09-24 05:32:41 +0000313
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000314 // If the PHI entry doesn't work, we can't use this pred.
315 if (TIPHIValues[PHINo] != PN->getIncomingValueForBlock(Pred)) {
316 FoundMatch = false;
317 break;
318 }
319 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000320
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000321 // If we found a workable predecessor, change TI to branch to Succ.
322 if (FoundMatch) {
323 Dest->removePredecessor(TIBB);
324 TI->setSuccessor(SuccNum, Pred);
325 return;
326 }
327 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000328
329 SplitCriticalEdge(TI, SuccNum, P, true);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000330}
331
Chris Lattnerdd77df32007-04-13 20:30:56 +0000332/// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
333/// copy (e.g. it's casting from one pointer type to another, int->uint, or
334/// int->sbyte on PPC), sink it into user blocks to reduce the number of virtual
Dale Johannesence0b2372007-06-12 16:50:17 +0000335/// registers that must be created and coalesced.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000336///
337/// Return true if any changes are made.
Chris Lattner85fa13c2008-11-24 22:44:16 +0000338///
Chris Lattnerdd77df32007-04-13 20:30:56 +0000339static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
Eric Christopher692bf6b2008-09-24 05:32:41 +0000340 // If this is a noop copy,
Duncan Sands83ec4b62008-06-06 12:08:01 +0000341 MVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
342 MVT DstVT = TLI.getValueType(CI->getType());
Eric Christopher692bf6b2008-09-24 05:32:41 +0000343
Chris Lattnerdd77df32007-04-13 20:30:56 +0000344 // This is an fp<->int conversion?
Duncan Sands83ec4b62008-06-06 12:08:01 +0000345 if (SrcVT.isInteger() != DstVT.isInteger())
Chris Lattnerdd77df32007-04-13 20:30:56 +0000346 return false;
Duncan Sands8e4eb092008-06-08 20:54:56 +0000347
Chris Lattnerdd77df32007-04-13 20:30:56 +0000348 // If this is an extension, it will be a zero or sign extension, which
349 // isn't a noop.
Duncan Sands8e4eb092008-06-08 20:54:56 +0000350 if (SrcVT.bitsLT(DstVT)) return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000351
Chris Lattnerdd77df32007-04-13 20:30:56 +0000352 // If these values will be promoted, find out what they will be promoted
353 // to. This helps us consider truncates on PPC as noop copies when they
354 // are.
355 if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote)
356 SrcVT = TLI.getTypeToTransformTo(SrcVT);
357 if (TLI.getTypeAction(DstVT) == TargetLowering::Promote)
358 DstVT = TLI.getTypeToTransformTo(DstVT);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000359
Chris Lattnerdd77df32007-04-13 20:30:56 +0000360 // If, after promotion, these are the same types, this is a noop copy.
361 if (SrcVT != DstVT)
362 return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000363
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000364 BasicBlock *DefBB = CI->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000365
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000366 /// InsertedCasts - Only insert a cast in each block once.
Dale Johannesence0b2372007-06-12 16:50:17 +0000367 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000368
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000369 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000370 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000371 UI != E; ) {
372 Use &TheUse = UI.getUse();
373 Instruction *User = cast<Instruction>(*UI);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000374
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000375 // Figure out which BB this cast is used in. For PHI's this is the
376 // appropriate predecessor block.
377 BasicBlock *UserBB = User->getParent();
378 if (PHINode *PN = dyn_cast<PHINode>(User)) {
379 unsigned OpVal = UI.getOperandNo()/2;
380 UserBB = PN->getIncomingBlock(OpVal);
381 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000382
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000383 // Preincrement use iterator so we don't invalidate it.
384 ++UI;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000385
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000386 // If this user is in the same block as the cast, don't change the cast.
387 if (UserBB == DefBB) continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000388
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000389 // If we have already inserted a cast into this block, use it.
390 CastInst *&InsertedCast = InsertedCasts[UserBB];
391
392 if (!InsertedCast) {
Dan Gohman02dea8b2008-05-23 21:05:58 +0000393 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000394
395 InsertedCast =
396 CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000397 InsertPt);
398 MadeChange = true;
399 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000400
Dale Johannesence0b2372007-06-12 16:50:17 +0000401 // Replace a use of the cast with a use of the new cast.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000402 TheUse = InsertedCast;
403 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000404
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000405 // If we removed all uses, nuke the cast.
Duncan Sandse0038132008-01-20 16:51:46 +0000406 if (CI->use_empty()) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000407 CI->eraseFromParent();
Duncan Sandse0038132008-01-20 16:51:46 +0000408 MadeChange = true;
409 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000410
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000411 return MadeChange;
412}
413
Eric Christopher692bf6b2008-09-24 05:32:41 +0000414/// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
Dale Johannesence0b2372007-06-12 16:50:17 +0000415/// the number of virtual registers that must be created and coalesced. This is
Chris Lattner684b22d2007-08-02 16:53:43 +0000416/// a clear win except on targets with multiple condition code registers
417/// (PowerPC), where it might lose; some adjustment may be wanted there.
Dale Johannesence0b2372007-06-12 16:50:17 +0000418///
419/// Return true if any changes are made.
Chris Lattner85fa13c2008-11-24 22:44:16 +0000420static bool OptimizeCmpExpression(CmpInst *CI) {
Dale Johannesence0b2372007-06-12 16:50:17 +0000421 BasicBlock *DefBB = CI->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000422
Dale Johannesence0b2372007-06-12 16:50:17 +0000423 /// InsertedCmp - Only insert a cmp in each block once.
424 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000425
Dale Johannesence0b2372007-06-12 16:50:17 +0000426 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000427 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
Dale Johannesence0b2372007-06-12 16:50:17 +0000428 UI != E; ) {
429 Use &TheUse = UI.getUse();
430 Instruction *User = cast<Instruction>(*UI);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000431
Dale Johannesence0b2372007-06-12 16:50:17 +0000432 // Preincrement use iterator so we don't invalidate it.
433 ++UI;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000434
Dale Johannesence0b2372007-06-12 16:50:17 +0000435 // Don't bother for PHI nodes.
436 if (isa<PHINode>(User))
437 continue;
438
439 // Figure out which BB this cmp is used in.
440 BasicBlock *UserBB = User->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000441
Dale Johannesence0b2372007-06-12 16:50:17 +0000442 // If this user is in the same block as the cmp, don't change the cmp.
443 if (UserBB == DefBB) continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000444
Dale Johannesence0b2372007-06-12 16:50:17 +0000445 // If we have already inserted a cmp into this block, use it.
446 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
447
448 if (!InsertedCmp) {
Dan Gohman02dea8b2008-05-23 21:05:58 +0000449 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000450
451 InsertedCmp =
452 CmpInst::Create(CI->getOpcode(), CI->getPredicate(), CI->getOperand(0),
Dale Johannesence0b2372007-06-12 16:50:17 +0000453 CI->getOperand(1), "", InsertPt);
454 MadeChange = true;
455 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000456
Dale Johannesence0b2372007-06-12 16:50:17 +0000457 // Replace a use of the cmp with a use of the new cmp.
458 TheUse = InsertedCmp;
459 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000460
Dale Johannesence0b2372007-06-12 16:50:17 +0000461 // If we removed all uses, nuke the cmp.
462 if (CI->use_empty())
463 CI->eraseFromParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000464
Dale Johannesence0b2372007-06-12 16:50:17 +0000465 return MadeChange;
466}
467
Chris Lattner85fa13c2008-11-24 22:44:16 +0000468/// EraseDeadInstructions - Erase any dead instructions, recursively.
Chris Lattnerdd77df32007-04-13 20:30:56 +0000469static void EraseDeadInstructions(Value *V) {
470 Instruction *I = dyn_cast<Instruction>(V);
471 if (!I || !I->use_empty()) return;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000472
Chris Lattnerdd77df32007-04-13 20:30:56 +0000473 SmallPtrSet<Instruction*, 16> Insts;
474 Insts.insert(I);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000475
Chris Lattnerdd77df32007-04-13 20:30:56 +0000476 while (!Insts.empty()) {
477 I = *Insts.begin();
478 Insts.erase(I);
479 if (isInstructionTriviallyDead(I)) {
480 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
481 if (Instruction *U = dyn_cast<Instruction>(I->getOperand(i)))
482 Insts.insert(U);
483 I->eraseFromParent();
484 }
485 }
486}
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000487
Chris Lattner88a5c832008-11-25 07:09:13 +0000488//===----------------------------------------------------------------------===//
489// Addressing Mode Analysis and Optimization
490//===----------------------------------------------------------------------===//
491
Dan Gohman844731a2008-05-13 00:00:25 +0000492namespace {
Chris Lattner4744d852008-11-24 22:40:05 +0000493 /// ExtAddrMode - This is an extended version of TargetLowering::AddrMode
494 /// which holds actual Value*'s for register values.
495 struct ExtAddrMode : public TargetLowering::AddrMode {
496 Value *BaseReg;
497 Value *ScaledReg;
498 ExtAddrMode() : BaseReg(0), ScaledReg(0) {}
499 void print(OStream &OS) const;
500 void dump() const {
501 print(cerr);
502 cerr << '\n';
503 }
504 };
505} // end anonymous namespace
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000506
Chris Lattner5eecb7f2008-11-26 02:00:14 +0000507static inline OStream &operator<<(OStream &OS, const ExtAddrMode &AM) {
Chris Lattner4744d852008-11-24 22:40:05 +0000508 AM.print(OS);
509 return OS;
510}
Chris Lattnerdd77df32007-04-13 20:30:56 +0000511
Chris Lattner4744d852008-11-24 22:40:05 +0000512void ExtAddrMode::print(OStream &OS) const {
Chris Lattnerdd77df32007-04-13 20:30:56 +0000513 bool NeedPlus = false;
514 OS << "[";
Chris Lattner4744d852008-11-24 22:40:05 +0000515 if (BaseGV)
Chris Lattnerdd77df32007-04-13 20:30:56 +0000516 OS << (NeedPlus ? " + " : "")
Chris Lattner4744d852008-11-24 22:40:05 +0000517 << "GV:%" << BaseGV->getName(), NeedPlus = true;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000518
Chris Lattner4744d852008-11-24 22:40:05 +0000519 if (BaseOffs)
520 OS << (NeedPlus ? " + " : "") << BaseOffs, NeedPlus = true;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000521
Chris Lattner4744d852008-11-24 22:40:05 +0000522 if (BaseReg)
Chris Lattnerdd77df32007-04-13 20:30:56 +0000523 OS << (NeedPlus ? " + " : "")
Chris Lattner4744d852008-11-24 22:40:05 +0000524 << "Base:%" << BaseReg->getName(), NeedPlus = true;
525 if (Scale)
Chris Lattnerdd77df32007-04-13 20:30:56 +0000526 OS << (NeedPlus ? " + " : "")
Chris Lattner4744d852008-11-24 22:40:05 +0000527 << Scale << "*%" << ScaledReg->getName(), NeedPlus = true;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000528
Chris Lattner4744d852008-11-24 22:40:05 +0000529 OS << ']';
Dan Gohman844731a2008-05-13 00:00:25 +0000530}
531
Chris Lattner88a5c832008-11-25 07:09:13 +0000532namespace {
533/// AddressingModeMatcher - This class exposes a single public method, which is
534/// used to construct a "maximal munch" of the addressing mode for the target
535/// specified by TLI for an access to "V" with an access type of AccessTy. This
536/// returns the addressing mode that is actually matched by value, but also
537/// returns the list of instructions involved in that addressing computation in
538/// AddrModeInsts.
539class AddressingModeMatcher {
540 SmallVectorImpl<Instruction*> &AddrModeInsts;
541 const TargetLowering &TLI;
Chris Lattner896617b2008-11-26 03:20:37 +0000542
543 /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
544 /// the memory instruction that we're computing this address for.
Chris Lattner88a5c832008-11-25 07:09:13 +0000545 const Type *AccessTy;
Chris Lattner896617b2008-11-26 03:20:37 +0000546 Instruction *MemoryInst;
547
548 /// AddrMode - This is the addressing mode that we're building up. This is
549 /// part of the return value of this addressing mode matching stuff.
Chris Lattner88a5c832008-11-25 07:09:13 +0000550 ExtAddrMode &AddrMode;
Chris Lattner5eecb7f2008-11-26 02:00:14 +0000551
552 /// IgnoreProfitability - This is set to true when we should not do
553 /// profitability checks. When true, IsProfitableToFoldIntoAddressingMode
554 /// always returns true.
555 bool IgnoreProfitability;
556
Chris Lattner88a5c832008-11-25 07:09:13 +0000557 AddressingModeMatcher(SmallVectorImpl<Instruction*> &AMI,
Chris Lattner896617b2008-11-26 03:20:37 +0000558 const TargetLowering &T, const Type *AT,
559 Instruction *MI, ExtAddrMode &AM)
560 : AddrModeInsts(AMI), TLI(T), AccessTy(AT), MemoryInst(MI), AddrMode(AM) {
Chris Lattner5eecb7f2008-11-26 02:00:14 +0000561 IgnoreProfitability = false;
562 }
Chris Lattner88a5c832008-11-25 07:09:13 +0000563public:
564
Chris Lattner5eecb7f2008-11-26 02:00:14 +0000565 /// Match - Find the maximal addressing mode that a load/store of V can fold,
566 /// give an access type of AccessTy. This returns a list of involved
567 /// instructions in AddrModeInsts.
Chris Lattner896617b2008-11-26 03:20:37 +0000568 static ExtAddrMode Match(Value *V, const Type *AccessTy,
569 Instruction *MemoryInst,
Chris Lattner88a5c832008-11-25 07:09:13 +0000570 SmallVectorImpl<Instruction*> &AddrModeInsts,
571 const TargetLowering &TLI) {
572 ExtAddrMode Result;
573
574 bool Success =
Chris Lattner896617b2008-11-26 03:20:37 +0000575 AddressingModeMatcher(AddrModeInsts, TLI, AccessTy,
576 MemoryInst, Result).MatchAddr(V, 0);
Chris Lattner88a5c832008-11-25 07:09:13 +0000577 Success = Success; assert(Success && "Couldn't select *anything*?");
578 return Result;
579 }
580private:
Chris Lattner3b485012008-11-25 07:25:26 +0000581 bool MatchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
Chris Lattner88a5c832008-11-25 07:09:13 +0000582 bool MatchAddr(Value *V, unsigned Depth);
583 bool MatchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth);
Chris Lattner84d1b402008-11-26 03:02:41 +0000584 bool IsProfitableToFoldIntoAddressingMode(Instruction *I,
585 ExtAddrMode &AMBefore,
586 ExtAddrMode &AMAfter);
587 bool ValueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
Chris Lattner88a5c832008-11-25 07:09:13 +0000588};
589} // end anonymous namespace
590
591/// MatchScaledValue - Try adding ScaleReg*Scale to the current addressing mode.
592/// Return true and update AddrMode if this addr mode is legal for the target,
Chris Lattner85fa13c2008-11-24 22:44:16 +0000593/// false if not.
Chris Lattner3b485012008-11-25 07:25:26 +0000594bool AddressingModeMatcher::MatchScaledValue(Value *ScaleReg, int64_t Scale,
595 unsigned Depth) {
596 // If Scale is 1, then this is the same as adding ScaleReg to the addressing
597 // mode. Just process that directly.
598 if (Scale == 1)
599 return MatchAddr(ScaleReg, Depth);
600
601 // If the scale is 0, it takes nothing to add this.
602 if (Scale == 0)
603 return true;
604
Chris Lattner85fa13c2008-11-24 22:44:16 +0000605 // If we already have a scale of this value, we can add to it, otherwise, we
606 // need an available scale field.
607 if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
608 return false;
609
Chris Lattner088a1e82008-11-25 04:42:10 +0000610 ExtAddrMode TestAddrMode = AddrMode;
Chris Lattner85fa13c2008-11-24 22:44:16 +0000611
612 // Add scale to turn X*4+X*3 -> X*7. This could also do things like
613 // [A+B + A*7] -> [B+A*8].
Chris Lattner088a1e82008-11-25 04:42:10 +0000614 TestAddrMode.Scale += Scale;
615 TestAddrMode.ScaledReg = ScaleReg;
Chris Lattner85fa13c2008-11-24 22:44:16 +0000616
Chris Lattner088a1e82008-11-25 04:42:10 +0000617 // If the new address isn't legal, bail out.
618 if (!TLI.isLegalAddressingMode(TestAddrMode, AccessTy))
619 return false;
Chris Lattner85fa13c2008-11-24 22:44:16 +0000620
Chris Lattner088a1e82008-11-25 04:42:10 +0000621 // It was legal, so commit it.
622 AddrMode = TestAddrMode;
623
624 // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
625 // to see if ScaleReg is actually X+C. If so, we can turn this into adding
626 // X*Scale + C*Scale to addr mode.
627 ConstantInt *CI; Value *AddLHS;
628 if (match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
629 TestAddrMode.ScaledReg = AddLHS;
630 TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
631
632 // If this addressing mode is legal, commit it and remember that we folded
633 // this instruction.
634 if (TLI.isLegalAddressingMode(TestAddrMode, AccessTy)) {
635 AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
636 AddrMode = TestAddrMode;
Chris Lattner88a5c832008-11-25 07:09:13 +0000637 return true;
Chris Lattner85fa13c2008-11-24 22:44:16 +0000638 }
Chris Lattner85fa13c2008-11-24 22:44:16 +0000639 }
640
Chris Lattner088a1e82008-11-25 04:42:10 +0000641 // Otherwise, not (x+c)*scale, just return what we have.
642 return true;
Chris Lattner85fa13c2008-11-24 22:44:16 +0000643}
644
Chris Lattner5eecb7f2008-11-26 02:00:14 +0000645/// MightBeFoldableInst - This is a little filter, which returns true if an
646/// addressing computation involving I might be folded into a load/store
647/// accessing it. This doesn't need to be perfect, but needs to accept at least
648/// the set of instructions that MatchOperationAddr can.
649static bool MightBeFoldableInst(Instruction *I) {
650 switch (I->getOpcode()) {
651 case Instruction::BitCast:
652 // Don't touch identity bitcasts.
653 if (I->getType() == I->getOperand(0)->getType())
654 return false;
655 return isa<PointerType>(I->getType()) || isa<IntegerType>(I->getType());
656 case Instruction::PtrToInt:
657 // PtrToInt is always a noop, as we know that the int type is pointer sized.
658 return true;
659 case Instruction::IntToPtr:
660 // We know the input is intptr_t, so this is foldable.
661 return true;
662 case Instruction::Add:
663 return true;
664 case Instruction::Mul:
665 case Instruction::Shl:
666 // Can only handle X*C and X << C.
667 return isa<ConstantInt>(I->getOperand(1));
668 case Instruction::GetElementPtr:
669 return true;
670 default:
671 return false;
672 }
673}
674
Chris Lattnerbb3204a2008-11-25 05:15:49 +0000675
Chris Lattner88a5c832008-11-25 07:09:13 +0000676/// MatchOperationAddr - Given an instruction or constant expr, see if we can
677/// fold the operation into the addressing mode. If so, update the addressing
678/// mode and return true, otherwise return false without modifying AddrMode.
679bool AddressingModeMatcher::MatchOperationAddr(User *AddrInst, unsigned Opcode,
680 unsigned Depth) {
681 // Avoid exponential behavior on extremely deep expression trees.
682 if (Depth >= 5) return false;
683
Chris Lattnerdd77df32007-04-13 20:30:56 +0000684 switch (Opcode) {
685 case Instruction::PtrToInt:
686 // PtrToInt is always a noop, as we know that the int type is pointer sized.
Chris Lattner88a5c832008-11-25 07:09:13 +0000687 return MatchAddr(AddrInst->getOperand(0), Depth);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000688 case Instruction::IntToPtr:
689 // This inttoptr is a no-op if the integer type is pointer sized.
690 if (TLI.getValueType(AddrInst->getOperand(0)->getType()) ==
Chris Lattner88a5c832008-11-25 07:09:13 +0000691 TLI.getPointerTy())
692 return MatchAddr(AddrInst->getOperand(0), Depth);
693 return false;
Chris Lattner2efbbb32008-11-26 00:26:16 +0000694 case Instruction::BitCast:
695 // BitCast is always a noop, and we can handle it as long as it is
696 // int->int or pointer->pointer (we don't want int<->fp or something).
697 if ((isa<PointerType>(AddrInst->getOperand(0)->getType()) ||
698 isa<IntegerType>(AddrInst->getOperand(0)->getType())) &&
699 // Don't touch identity bitcasts. These were probably put here by LSR,
700 // and we don't want to mess around with them. Assume it knows what it
701 // is doing.
702 AddrInst->getOperand(0)->getType() != AddrInst->getType())
703 return MatchAddr(AddrInst->getOperand(0), Depth);
704 return false;
Chris Lattnerdd77df32007-04-13 20:30:56 +0000705 case Instruction::Add: {
706 // Check to see if we can merge in the RHS then the LHS. If so, we win.
707 ExtAddrMode BackupAddrMode = AddrMode;
708 unsigned OldSize = AddrModeInsts.size();
Chris Lattner88a5c832008-11-25 07:09:13 +0000709 if (MatchAddr(AddrInst->getOperand(1), Depth+1) &&
710 MatchAddr(AddrInst->getOperand(0), Depth+1))
Chris Lattnerdd77df32007-04-13 20:30:56 +0000711 return true;
Chris Lattnerbb3204a2008-11-25 05:15:49 +0000712
Chris Lattnerdd77df32007-04-13 20:30:56 +0000713 // Restore the old addr mode info.
714 AddrMode = BackupAddrMode;
715 AddrModeInsts.resize(OldSize);
Chris Lattnerbb3204a2008-11-25 05:15:49 +0000716
Chris Lattnerdd77df32007-04-13 20:30:56 +0000717 // Otherwise this was over-aggressive. Try merging in the LHS then the RHS.
Chris Lattner88a5c832008-11-25 07:09:13 +0000718 if (MatchAddr(AddrInst->getOperand(0), Depth+1) &&
719 MatchAddr(AddrInst->getOperand(1), Depth+1))
Chris Lattnerdd77df32007-04-13 20:30:56 +0000720 return true;
Chris Lattnerbb3204a2008-11-25 05:15:49 +0000721
Chris Lattnerdd77df32007-04-13 20:30:56 +0000722 // Otherwise we definitely can't merge the ADD in.
723 AddrMode = BackupAddrMode;
724 AddrModeInsts.resize(OldSize);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000725 break;
Chris Lattnerdd77df32007-04-13 20:30:56 +0000726 }
Chris Lattner5eecb7f2008-11-26 02:00:14 +0000727 //case Instruction::Or:
728 // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
729 //break;
Chris Lattnerdd77df32007-04-13 20:30:56 +0000730 case Instruction::Mul:
731 case Instruction::Shl: {
Chris Lattner7ad1c732008-11-25 04:47:41 +0000732 // Can only handle X*C and X << C.
Chris Lattnerdd77df32007-04-13 20:30:56 +0000733 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
Chris Lattner88a5c832008-11-25 07:09:13 +0000734 if (!RHS) return false;
Chris Lattnerdd77df32007-04-13 20:30:56 +0000735 int64_t Scale = RHS->getSExtValue();
736 if (Opcode == Instruction::Shl)
737 Scale = 1 << Scale;
Chris Lattnerbb3204a2008-11-25 05:15:49 +0000738
Chris Lattner3b485012008-11-25 07:25:26 +0000739 return MatchScaledValue(AddrInst->getOperand(0), Scale, Depth);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000740 }
741 case Instruction::GetElementPtr: {
742 // Scan the GEP. We check it if it contains constant offsets and at most
743 // one variable offset.
744 int VariableOperand = -1;
745 unsigned VariableScale = 0;
Chris Lattnerbb3204a2008-11-25 05:15:49 +0000746
Chris Lattnerdd77df32007-04-13 20:30:56 +0000747 int64_t ConstantOffset = 0;
748 const TargetData *TD = TLI.getTargetData();
749 gep_type_iterator GTI = gep_type_begin(AddrInst);
750 for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
751 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
752 const StructLayout *SL = TD->getStructLayout(STy);
753 unsigned Idx =
Chris Lattner88a5c832008-11-25 07:09:13 +0000754 cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
Chris Lattnerdd77df32007-04-13 20:30:56 +0000755 ConstantOffset += SL->getElementOffset(Idx);
756 } else {
Duncan Sands514ab342007-11-01 20:53:16 +0000757 uint64_t TypeSize = TD->getABITypeSize(GTI.getIndexedType());
Chris Lattnerdd77df32007-04-13 20:30:56 +0000758 if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
759 ConstantOffset += CI->getSExtValue()*TypeSize;
760 } else if (TypeSize) { // Scales of zero don't do anything.
761 // We only allow one variable index at the moment.
Chris Lattner88a5c832008-11-25 07:09:13 +0000762 if (VariableOperand != -1)
763 return false;
Chris Lattnerbb3204a2008-11-25 05:15:49 +0000764
Chris Lattnerdd77df32007-04-13 20:30:56 +0000765 // Remember the variable index.
766 VariableOperand = i;
767 VariableScale = TypeSize;
768 }
769 }
770 }
Chris Lattnerbb3204a2008-11-25 05:15:49 +0000771
Chris Lattnerdd77df32007-04-13 20:30:56 +0000772 // A common case is for the GEP to only do a constant offset. In this case,
773 // just add it to the disp field and check validity.
774 if (VariableOperand == -1) {
775 AddrMode.BaseOffs += ConstantOffset;
776 if (ConstantOffset == 0 || TLI.isLegalAddressingMode(AddrMode, AccessTy)){
777 // Check to see if we can fold the base pointer in too.
Chris Lattner88a5c832008-11-25 07:09:13 +0000778 if (MatchAddr(AddrInst->getOperand(0), Depth+1))
Chris Lattnerdd77df32007-04-13 20:30:56 +0000779 return true;
780 }
781 AddrMode.BaseOffs -= ConstantOffset;
Chris Lattner88a5c832008-11-25 07:09:13 +0000782 return false;
Chris Lattnerdd77df32007-04-13 20:30:56 +0000783 }
Chris Lattner88a5c832008-11-25 07:09:13 +0000784
785 // Save the valid addressing mode in case we can't match.
786 ExtAddrMode BackupAddrMode = AddrMode;
787
788 // Check that this has no base reg yet. If so, we won't have a place to
789 // put the base of the GEP (assuming it is not a null ptr).
790 bool SetBaseReg = true;
791 if (isa<ConstantPointerNull>(AddrInst->getOperand(0)))
792 SetBaseReg = false; // null pointer base doesn't need representation.
793 else if (AddrMode.HasBaseReg)
794 return false; // Base register already specified, can't match GEP.
795 else {
796 // Otherwise, we'll use the GEP base as the BaseReg.
797 AddrMode.HasBaseReg = true;
798 AddrMode.BaseReg = AddrInst->getOperand(0);
799 }
800
801 // See if the scale and offset amount is valid for this target.
802 AddrMode.BaseOffs += ConstantOffset;
803
Chris Lattner3b485012008-11-25 07:25:26 +0000804 if (!MatchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
805 Depth)) {
Chris Lattner88a5c832008-11-25 07:09:13 +0000806 AddrMode = BackupAddrMode;
807 return false;
808 }
809
810 // If we have a null as the base of the GEP, folding in the constant offset
811 // plus variable scale is all we can do.
812 if (!SetBaseReg) return true;
813
814 // If this match succeeded, we know that we can form an address with the
815 // GepBase as the basereg. Match the base pointer of the GEP more
816 // aggressively by zeroing out BaseReg and rematching. If the base is
817 // (for example) another GEP, this allows merging in that other GEP into
818 // the addressing mode we're forming.
819 AddrMode.HasBaseReg = false;
820 AddrMode.BaseReg = 0;
821 bool Success = MatchAddr(AddrInst->getOperand(0), Depth+1);
822 assert(Success && "MatchAddr should be able to fill in BaseReg!");
823 Success=Success;
824 return true;
Chris Lattnerdd77df32007-04-13 20:30:56 +0000825 }
826 }
Chris Lattnerbb3204a2008-11-25 05:15:49 +0000827 return false;
828}
Eric Christopher692bf6b2008-09-24 05:32:41 +0000829
Chris Lattner88a5c832008-11-25 07:09:13 +0000830/// MatchAddr - If we can, try to add the value of 'Addr' into the current
831/// addressing mode. If Addr can't be added to AddrMode this returns false and
832/// leaves AddrMode unmodified. This assumes that Addr is either a pointer type
833/// or intptr_t for the target.
Chris Lattnerbb3204a2008-11-25 05:15:49 +0000834///
Chris Lattner88a5c832008-11-25 07:09:13 +0000835bool AddressingModeMatcher::MatchAddr(Value *Addr, unsigned Depth) {
Chris Lattnerbb3204a2008-11-25 05:15:49 +0000836 if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
837 // Fold in immediates if legal for the target.
838 AddrMode.BaseOffs += CI->getSExtValue();
839 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
840 return true;
841 AddrMode.BaseOffs -= CI->getSExtValue();
842 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
Chris Lattner88a5c832008-11-25 07:09:13 +0000843 // If this is a global variable, try to fold it into the addressing mode.
Chris Lattnerbb3204a2008-11-25 05:15:49 +0000844 if (AddrMode.BaseGV == 0) {
845 AddrMode.BaseGV = GV;
846 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
847 return true;
848 AddrMode.BaseGV = 0;
849 }
850 } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
Chris Lattner5eecb7f2008-11-26 02:00:14 +0000851 ExtAddrMode BackupAddrMode = AddrMode;
852 unsigned OldSize = AddrModeInsts.size();
853
854 // Check to see if it is possible to fold this operation.
Chris Lattner88a5c832008-11-25 07:09:13 +0000855 if (MatchOperationAddr(I, I->getOpcode(), Depth)) {
Chris Lattner5eecb7f2008-11-26 02:00:14 +0000856 // Okay, it's possible to fold this. Check to see if it is actually
857 // *profitable* to do so. We use a simple cost model to avoid increasing
858 // register pressure too much.
Chris Lattner84d1b402008-11-26 03:02:41 +0000859 if (I->hasOneUse() ||
860 IsProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
Chris Lattner5eecb7f2008-11-26 02:00:14 +0000861 AddrModeInsts.push_back(I);
862 return true;
863 }
864
865 // It isn't profitable to do this, roll back.
866 //cerr << "NOT FOLDING: " << *I;
867 AddrMode = BackupAddrMode;
868 AddrModeInsts.resize(OldSize);
Chris Lattnerbb3204a2008-11-25 05:15:49 +0000869 }
870 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
Chris Lattner88a5c832008-11-25 07:09:13 +0000871 if (MatchOperationAddr(CE, CE->getOpcode(), Depth))
Chris Lattnerbb3204a2008-11-25 05:15:49 +0000872 return true;
873 } else if (isa<ConstantPointerNull>(Addr)) {
Chris Lattner88a5c832008-11-25 07:09:13 +0000874 // Null pointer gets folded without affecting the addressing mode.
Chris Lattnerbb3204a2008-11-25 05:15:49 +0000875 return true;
Chris Lattnerdd77df32007-04-13 20:30:56 +0000876 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000877
Chris Lattnerdd77df32007-04-13 20:30:56 +0000878 // Worse case, the target should support [reg] addressing modes. :)
879 if (!AddrMode.HasBaseReg) {
880 AddrMode.HasBaseReg = true;
Chris Lattner653b2582008-11-26 02:11:11 +0000881 AddrMode.BaseReg = Addr;
Chris Lattnerdd77df32007-04-13 20:30:56 +0000882 // Still check for legality in case the target supports [imm] but not [i+r].
Chris Lattner653b2582008-11-26 02:11:11 +0000883 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
Chris Lattnerdd77df32007-04-13 20:30:56 +0000884 return true;
Chris Lattnerdd77df32007-04-13 20:30:56 +0000885 AddrMode.HasBaseReg = false;
Chris Lattner653b2582008-11-26 02:11:11 +0000886 AddrMode.BaseReg = 0;
Chris Lattnerdd77df32007-04-13 20:30:56 +0000887 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000888
Chris Lattnerdd77df32007-04-13 20:30:56 +0000889 // If the base register is already taken, see if we can do [r+r].
890 if (AddrMode.Scale == 0) {
891 AddrMode.Scale = 1;
Chris Lattner653b2582008-11-26 02:11:11 +0000892 AddrMode.ScaledReg = Addr;
893 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
Chris Lattnerdd77df32007-04-13 20:30:56 +0000894 return true;
Chris Lattnerdd77df32007-04-13 20:30:56 +0000895 AddrMode.Scale = 0;
Chris Lattner653b2582008-11-26 02:11:11 +0000896 AddrMode.ScaledReg = 0;
Chris Lattnerdd77df32007-04-13 20:30:56 +0000897 }
898 // Couldn't match.
899 return false;
900}
901
Chris Lattner5eecb7f2008-11-26 02:00:14 +0000902/// FindAllMemoryUses - Recursively walk all the uses of I until we find a
903/// memory use. If we find an obviously non-foldable instruction, return true.
904/// Add the ultimately found memory instructions to MemoryUses.
905static bool FindAllMemoryUses(Instruction *I,
906 SmallVectorImpl<std::pair<Instruction*,unsigned> > &MemoryUses,
907 SmallPtrSet<Instruction*, 16> &ConsideredInsts) {
908 // If we already considered this instruction, we're done.
909 if (!ConsideredInsts.insert(I))
910 return false;
911
912 // If this is an obviously unfoldable instruction, bail out.
913 if (!MightBeFoldableInst(I))
914 return true;
915
916 // Loop over all the uses, recursively processing them.
917 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
918 UI != E; ++UI) {
919 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
920 MemoryUses.push_back(std::make_pair(LI, UI.getOperandNo()));
921 continue;
922 }
923
924 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
925 if (UI.getOperandNo() == 0) return true; // Storing addr, not into addr.
926 MemoryUses.push_back(std::make_pair(SI, UI.getOperandNo()));
927 continue;
928 }
929
930 if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
931 InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
932 if (IA == 0) return true;
933
934
935 // FIXME: HANDLE MEM OPS
936 //MemoryUses.push_back(std::make_pair(CI, UI.getOperandNo()));
937 return true;
938 }
939
940 if (FindAllMemoryUses(cast<Instruction>(*UI), MemoryUses, ConsideredInsts))
941 return true;
942 }
943
944 return false;
945}
Chris Lattner84d1b402008-11-26 03:02:41 +0000946
947
948/// ValueAlreadyLiveAtInst - Retrn true if Val is already known to be live at
949/// the use site that we're folding it into. If so, there is no cost to
950/// include it in the addressing mode. KnownLive1 and KnownLive2 are two values
951/// that we know are live at the instruction already.
952bool AddressingModeMatcher::ValueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
953 Value *KnownLive2) {
954 // If Val is either of the known-live values, we know it is live!
955 if (Val == 0 || Val == KnownLive1 || Val == KnownLive2)
956 return true;
Chris Lattner5eecb7f2008-11-26 02:00:14 +0000957
Chris Lattner896617b2008-11-26 03:20:37 +0000958 // All values other than instructions and arguments (e.g. constants) are live.
Chris Lattner84d1b402008-11-26 03:02:41 +0000959 if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
960
961 // If Val is a constant sized alloca in the entry block, it is live, this is
962 // true because it is just a reference to the stack/frame pointer, which is
963 // live for the whole function.
964 if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
965 if (AI->isStaticAlloca())
966 return true;
967
Chris Lattner896617b2008-11-26 03:20:37 +0000968 // Check to see if this value is already used in the memory instruction's
969 // block. If so, it's already live into the block at the very least, so we
970 // can reasonably fold it.
971 BasicBlock *MemBB = MemoryInst->getParent();
972 for (Value::use_iterator UI = Val->use_begin(), E = Val->use_end();
973 UI != E; ++UI)
974 // We know that uses of arguments and instructions have to be instructions.
975 if (cast<Instruction>(*UI)->getParent() == MemBB)
976 return true;
977
Chris Lattner84d1b402008-11-26 03:02:41 +0000978 return false;
979}
980
981
982
Chris Lattner5eecb7f2008-11-26 02:00:14 +0000983#include "llvm/Support/CommandLine.h"
984cl::opt<bool> ENABLECRAZYHACK("enable-smarter-addr-folding", cl::Hidden);
985
986
987/// IsProfitableToFoldIntoAddressingMode - It is possible for the addressing
988/// mode of the machine to fold the specified instruction into a load or store
989/// that ultimately uses it. However, the specified instruction has multiple
990/// uses. Given this, it may actually increase register pressure to fold it
991/// into the load. For example, consider this code:
992///
993/// X = ...
994/// Y = X+1
995/// use(Y) -> nonload/store
996/// Z = Y+1
997/// load Z
998///
999/// In this case, Y has multiple uses, and can be folded into the load of Z
1000/// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to
1001/// be live at the use(Y) line. If we don't fold Y into load Z, we use one
1002/// fewer register. Since Y can't be folded into "use(Y)" we don't increase the
1003/// number of computations either.
1004///
1005/// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If
1006/// X was live across 'load Z' for other reasons, we actually *would* want to
Chris Lattner653b2582008-11-26 02:11:11 +00001007/// fold the addressing mode in the Z case. This would make Y die earlier.
Chris Lattner5eecb7f2008-11-26 02:00:14 +00001008bool AddressingModeMatcher::
Chris Lattner84d1b402008-11-26 03:02:41 +00001009IsProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
1010 ExtAddrMode &AMAfter) {
Chris Lattner5eecb7f2008-11-26 02:00:14 +00001011 if (IgnoreProfitability || !ENABLECRAZYHACK) return true;
1012
Chris Lattner84d1b402008-11-26 03:02:41 +00001013 // AMBefore is the addressing mode before this instruction was folded into it,
1014 // and AMAfter is the addressing mode after the instruction was folded. Get
1015 // the set of registers referenced by AMAfter and subtract out those
1016 // referenced by AMBefore: this is the set of values which folding in this
1017 // address extends the lifetime of.
1018 //
1019 // Note that there are only two potential values being referenced here,
1020 // BaseReg and ScaleReg (global addresses are always available, as are any
1021 // folded immediates).
1022 Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
1023
1024 // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
1025 // lifetime wasn't extended by adding this instruction.
1026 if (ValueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
1027 BaseReg = 0;
1028 if (ValueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
1029 ScaledReg = 0;
1030
1031 // If folding this instruction (and it's subexprs) didn't extend any live
1032 // ranges, we're ok with it.
1033 if (BaseReg == 0 && ScaledReg == 0)
1034 return true;
Chris Lattner5eecb7f2008-11-26 02:00:14 +00001035
1036 // If all uses of this instruction are ultimately load/store/inlineasm's,
1037 // check to see if their addressing modes will include this instruction. If
1038 // so, we can fold it into all uses, so it doesn't matter if it has multiple
1039 // uses.
1040 SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
1041 SmallPtrSet<Instruction*, 16> ConsideredInsts;
1042 if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts))
1043 return false; // Has a non-memory, non-foldable use!
1044
1045 // Now that we know that all uses of this instruction are part of a chain of
1046 // computation involving only operations that could theoretically be folded
1047 // into a memory use, loop over each of these uses and see if they could
1048 // *actually* fold the instruction.
1049 SmallVector<Instruction*, 32> MatchedAddrModeInsts;
1050 for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
1051 Instruction *User = MemoryUses[i].first;
1052 unsigned OpNo = MemoryUses[i].second;
1053
1054 // Get the access type of this use. If the use isn't a pointer, we don't
1055 // know what it accesses.
1056 Value *Address = User->getOperand(OpNo);
1057 if (!isa<PointerType>(Address->getType()))
1058 return false;
1059 const Type *AddressAccessTy =
1060 cast<PointerType>(Address->getType())->getElementType();
1061
1062 // Do a match against the root of this address, ignoring profitability. This
1063 // will tell us if the addressing mode for the memory operation will
1064 // *actually* cover the shared instruction.
1065 ExtAddrMode Result;
1066 AddressingModeMatcher Matcher(MatchedAddrModeInsts, TLI, AddressAccessTy,
Chris Lattner896617b2008-11-26 03:20:37 +00001067 MemoryInst, Result);
Chris Lattner5eecb7f2008-11-26 02:00:14 +00001068 Matcher.IgnoreProfitability = true;
1069 bool Success = Matcher.MatchAddr(Address, 0);
1070 Success = Success; assert(Success && "Couldn't select *anything*?");
1071
1072 // If the match didn't cover I, then it won't be shared by it.
1073 if (std::find(MatchedAddrModeInsts.begin(), MatchedAddrModeInsts.end(),
1074 I) == MatchedAddrModeInsts.end())
1075 return false;
1076
1077 MatchedAddrModeInsts.clear();
1078 }
1079
1080 return true;
1081}
1082
Chris Lattnerdd77df32007-04-13 20:30:56 +00001083
Chris Lattner88a5c832008-11-25 07:09:13 +00001084//===----------------------------------------------------------------------===//
1085// Memory Optimization
1086//===----------------------------------------------------------------------===//
1087
Chris Lattnerdd77df32007-04-13 20:30:56 +00001088/// IsNonLocalValue - Return true if the specified values are defined in a
1089/// different basic block than BB.
1090static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
1091 if (Instruction *I = dyn_cast<Instruction>(V))
1092 return I->getParent() != BB;
1093 return false;
1094}
1095
Chris Lattner88a5c832008-11-25 07:09:13 +00001096/// OptimizeMemoryInst - Load and Store Instructions have often have
Chris Lattnerdd77df32007-04-13 20:30:56 +00001097/// addressing modes that can do significant amounts of computation. As such,
1098/// instruction selection will try to get the load or store to do as much
1099/// computation as possible for the program. The problem is that isel can only
1100/// see within a single block. As such, we sink as much legal addressing mode
1101/// stuff into the block as possible.
Chris Lattner88a5c832008-11-25 07:09:13 +00001102///
1103/// This method is used to optimize both load/store and inline asms with memory
1104/// operands.
Chris Lattner896617b2008-11-26 03:20:37 +00001105bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
Chris Lattner88a5c832008-11-25 07:09:13 +00001106 const Type *AccessTy,
1107 DenseMap<Value*,Value*> &SunkAddrs) {
Chris Lattnerdd77df32007-04-13 20:30:56 +00001108 // Figure out what addressing mode will be built up for this operation.
1109 SmallVector<Instruction*, 16> AddrModeInsts;
Chris Lattner896617b2008-11-26 03:20:37 +00001110 ExtAddrMode AddrMode = AddressingModeMatcher::Match(Addr, AccessTy,MemoryInst,
1111 AddrModeInsts, *TLI);
Eric Christopher692bf6b2008-09-24 05:32:41 +00001112
Chris Lattnerdd77df32007-04-13 20:30:56 +00001113 // Check to see if any of the instructions supersumed by this addr mode are
1114 // non-local to I's BB.
1115 bool AnyNonLocal = false;
1116 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
Chris Lattner896617b2008-11-26 03:20:37 +00001117 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
Chris Lattnerdd77df32007-04-13 20:30:56 +00001118 AnyNonLocal = true;
1119 break;
1120 }
1121 }
Eric Christopher692bf6b2008-09-24 05:32:41 +00001122
Chris Lattnerdd77df32007-04-13 20:30:56 +00001123 // If all the instructions matched are already in this BB, don't do anything.
1124 if (!AnyNonLocal) {
1125 DEBUG(cerr << "CGP: Found local addrmode: " << AddrMode << "\n");
1126 return false;
1127 }
Eric Christopher692bf6b2008-09-24 05:32:41 +00001128
Chris Lattnerdd77df32007-04-13 20:30:56 +00001129 // Insert this computation right after this user. Since our caller is
1130 // scanning from the top of the BB to the bottom, reuse of the expr are
1131 // guaranteed to happen later.
Chris Lattner896617b2008-11-26 03:20:37 +00001132 BasicBlock::iterator InsertPt = MemoryInst;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001133
Chris Lattnerdd77df32007-04-13 20:30:56 +00001134 // Now that we determined the addressing expression we want to use and know
1135 // that we have to sink it into this block. Check to see if we have already
1136 // done this for some other load/store instr in this block. If so, reuse the
1137 // computation.
1138 Value *&SunkAddr = SunkAddrs[Addr];
1139 if (SunkAddr) {
1140 DEBUG(cerr << "CGP: Reusing nonlocal addrmode: " << AddrMode << "\n");
1141 if (SunkAddr->getType() != Addr->getType())
1142 SunkAddr = new BitCastInst(SunkAddr, Addr->getType(), "tmp", InsertPt);
1143 } else {
1144 DEBUG(cerr << "CGP: SINKING nonlocal addrmode: " << AddrMode << "\n");
1145 const Type *IntPtrTy = TLI->getTargetData()->getIntPtrType();
Eric Christopher692bf6b2008-09-24 05:32:41 +00001146
Chris Lattnerdd77df32007-04-13 20:30:56 +00001147 Value *Result = 0;
1148 // Start with the scale value.
1149 if (AddrMode.Scale) {
1150 Value *V = AddrMode.ScaledReg;
1151 if (V->getType() == IntPtrTy) {
1152 // done.
1153 } else if (isa<PointerType>(V->getType())) {
1154 V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
1155 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
1156 cast<IntegerType>(V->getType())->getBitWidth()) {
1157 V = new TruncInst(V, IntPtrTy, "sunkaddr", InsertPt);
1158 } else {
1159 V = new SExtInst(V, IntPtrTy, "sunkaddr", InsertPt);
1160 }
1161 if (AddrMode.Scale != 1)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001162 V = BinaryOperator::CreateMul(V, ConstantInt::get(IntPtrTy,
Chris Lattnerdd77df32007-04-13 20:30:56 +00001163 AddrMode.Scale),
1164 "sunkaddr", InsertPt);
1165 Result = V;
1166 }
1167
1168 // Add in the base register.
1169 if (AddrMode.BaseReg) {
1170 Value *V = AddrMode.BaseReg;
1171 if (V->getType() != IntPtrTy)
1172 V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
1173 if (Result)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001174 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
Chris Lattnerdd77df32007-04-13 20:30:56 +00001175 else
1176 Result = V;
1177 }
Eric Christopher692bf6b2008-09-24 05:32:41 +00001178
Chris Lattnerdd77df32007-04-13 20:30:56 +00001179 // Add in the BaseGV if present.
1180 if (AddrMode.BaseGV) {
1181 Value *V = new PtrToIntInst(AddrMode.BaseGV, IntPtrTy, "sunkaddr",
1182 InsertPt);
1183 if (Result)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001184 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
Chris Lattnerdd77df32007-04-13 20:30:56 +00001185 else
1186 Result = V;
1187 }
Eric Christopher692bf6b2008-09-24 05:32:41 +00001188
Chris Lattnerdd77df32007-04-13 20:30:56 +00001189 // Add in the Base Offset if present.
1190 if (AddrMode.BaseOffs) {
1191 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
1192 if (Result)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001193 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
Chris Lattnerdd77df32007-04-13 20:30:56 +00001194 else
1195 Result = V;
1196 }
1197
1198 if (Result == 0)
1199 SunkAddr = Constant::getNullValue(Addr->getType());
1200 else
1201 SunkAddr = new IntToPtrInst(Result, Addr->getType(), "sunkaddr",InsertPt);
1202 }
Eric Christopher692bf6b2008-09-24 05:32:41 +00001203
Chris Lattner896617b2008-11-26 03:20:37 +00001204 MemoryInst->replaceUsesOfWith(Addr, SunkAddr);
Eric Christopher692bf6b2008-09-24 05:32:41 +00001205
Chris Lattnerdd77df32007-04-13 20:30:56 +00001206 if (Addr->use_empty())
1207 EraseDeadInstructions(Addr);
1208 return true;
1209}
1210
Evan Cheng9bf12b52008-02-26 02:42:37 +00001211/// OptimizeInlineAsmInst - If there are any memory operands, use
Chris Lattner88a5c832008-11-25 07:09:13 +00001212/// OptimizeMemoryInst to sink their address computing into the block when
Evan Cheng9bf12b52008-02-26 02:42:37 +00001213/// possible / profitable.
1214bool CodeGenPrepare::OptimizeInlineAsmInst(Instruction *I, CallSite CS,
1215 DenseMap<Value*,Value*> &SunkAddrs) {
1216 bool MadeChange = false;
1217 InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
1218
1219 // Do a prepass over the constraints, canonicalizing them, and building up the
1220 // ConstraintOperands list.
1221 std::vector<InlineAsm::ConstraintInfo>
1222 ConstraintInfos = IA->ParseConstraints();
1223
1224 /// ConstraintOperands - Information about all of the constraints.
1225 std::vector<TargetLowering::AsmOperandInfo> ConstraintOperands;
1226 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
1227 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
1228 ConstraintOperands.
1229 push_back(TargetLowering::AsmOperandInfo(ConstraintInfos[i]));
1230 TargetLowering::AsmOperandInfo &OpInfo = ConstraintOperands.back();
1231
1232 // Compute the value type for each operand.
1233 switch (OpInfo.Type) {
1234 case InlineAsm::isOutput:
1235 if (OpInfo.isIndirect)
1236 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
1237 break;
1238 case InlineAsm::isInput:
1239 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
1240 break;
1241 case InlineAsm::isClobber:
1242 // Nothing to do.
1243 break;
1244 }
1245
1246 // Compute the constraint code and ConstraintType to use.
Evan Chenga7e61462008-09-24 06:48:55 +00001247 TLI->ComputeConstraintToUse(OpInfo, SDValue(),
1248 OpInfo.ConstraintType == TargetLowering::C_Memory);
Evan Cheng9bf12b52008-02-26 02:42:37 +00001249
Eli Friedman9ec80952008-02-26 18:37:49 +00001250 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
1251 OpInfo.isIndirect) {
Evan Cheng9bf12b52008-02-26 02:42:37 +00001252 Value *OpVal = OpInfo.CallOperandVal;
Chris Lattner88a5c832008-11-25 07:09:13 +00001253 MadeChange |= OptimizeMemoryInst(I, OpVal, OpVal->getType(), SunkAddrs);
Evan Cheng9bf12b52008-02-26 02:42:37 +00001254 }
1255 }
1256
1257 return MadeChange;
1258}
1259
Evan Chengbdcb7262007-12-05 23:58:20 +00001260bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
1261 BasicBlock *DefBB = I->getParent();
1262
1263 // If both result of the {s|z}xt and its source are live out, rewrite all
1264 // other uses of the source with result of extension.
1265 Value *Src = I->getOperand(0);
1266 if (Src->hasOneUse())
1267 return false;
1268
Evan Cheng696e5c02007-12-13 07:50:36 +00001269 // Only do this xform if truncating is free.
Gabor Greif53bdbd72008-02-26 19:13:21 +00001270 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
Evan Chengf9785f92007-12-13 03:32:53 +00001271 return false;
1272
Evan Cheng772de512007-12-12 00:51:06 +00001273 // Only safe to perform the optimization if the source is also defined in
Evan Cheng765dff22007-12-12 02:53:41 +00001274 // this block.
1275 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
Evan Cheng772de512007-12-12 00:51:06 +00001276 return false;
1277
Evan Chengbdcb7262007-12-05 23:58:20 +00001278 bool DefIsLiveOut = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001279 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
Evan Chengbdcb7262007-12-05 23:58:20 +00001280 UI != E; ++UI) {
1281 Instruction *User = cast<Instruction>(*UI);
1282
1283 // Figure out which BB this ext is used in.
1284 BasicBlock *UserBB = User->getParent();
1285 if (UserBB == DefBB) continue;
1286 DefIsLiveOut = true;
1287 break;
1288 }
1289 if (!DefIsLiveOut)
1290 return false;
1291
Evan Cheng765dff22007-12-12 02:53:41 +00001292 // Make sure non of the uses are PHI nodes.
Eric Christopher692bf6b2008-09-24 05:32:41 +00001293 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
Evan Cheng765dff22007-12-12 02:53:41 +00001294 UI != E; ++UI) {
1295 Instruction *User = cast<Instruction>(*UI);
Evan Chengf9785f92007-12-13 03:32:53 +00001296 BasicBlock *UserBB = User->getParent();
1297 if (UserBB == DefBB) continue;
1298 // Be conservative. We don't want this xform to end up introducing
1299 // reloads just before load / store instructions.
1300 if (isa<PHINode>(User) || isa<LoadInst>(User) || isa<StoreInst>(User))
Evan Cheng765dff22007-12-12 02:53:41 +00001301 return false;
1302 }
1303
Evan Chengbdcb7262007-12-05 23:58:20 +00001304 // InsertedTruncs - Only insert one trunc in each block once.
1305 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
1306
1307 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001308 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
Evan Chengbdcb7262007-12-05 23:58:20 +00001309 UI != E; ++UI) {
1310 Use &TheUse = UI.getUse();
1311 Instruction *User = cast<Instruction>(*UI);
1312
1313 // Figure out which BB this ext is used in.
1314 BasicBlock *UserBB = User->getParent();
1315 if (UserBB == DefBB) continue;
1316
1317 // Both src and def are live in this block. Rewrite the use.
1318 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
1319
1320 if (!InsertedTrunc) {
Dan Gohman02dea8b2008-05-23 21:05:58 +00001321 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
Eric Christopher692bf6b2008-09-24 05:32:41 +00001322
Evan Chengbdcb7262007-12-05 23:58:20 +00001323 InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
1324 }
1325
1326 // Replace a use of the {s|z}ext source with a use of the result.
1327 TheUse = InsertedTrunc;
1328
1329 MadeChange = true;
1330 }
1331
1332 return MadeChange;
1333}
1334
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001335// In this pass we look for GEP and cast instructions that are used
1336// across basic blocks and rewrite them to improve basic-block-at-a-time
1337// selection.
1338bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
1339 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001340
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001341 // Split all critical edges where the dest block has a PHI and where the phi
1342 // has shared immediate operands.
1343 TerminatorInst *BBTI = BB.getTerminator();
1344 if (BBTI->getNumSuccessors() > 1) {
1345 for (unsigned i = 0, e = BBTI->getNumSuccessors(); i != e; ++i)
1346 if (isa<PHINode>(BBTI->getSuccessor(i)->begin()) &&
1347 isCriticalEdge(BBTI, i, true))
1348 SplitEdgeNicely(BBTI, i, this);
1349 }
Eric Christopher692bf6b2008-09-24 05:32:41 +00001350
1351
Chris Lattnerdd77df32007-04-13 20:30:56 +00001352 // Keep track of non-local addresses that have been sunk into this block.
1353 // This allows us to avoid inserting duplicate code for blocks with multiple
1354 // load/stores of the same address.
1355 DenseMap<Value*, Value*> SunkAddrs;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001356
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001357 for (BasicBlock::iterator BBI = BB.begin(), E = BB.end(); BBI != E; ) {
1358 Instruction *I = BBI++;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001359
Chris Lattnerdd77df32007-04-13 20:30:56 +00001360 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001361 // If the source of the cast is a constant, then this should have
1362 // already been constant folded. The only reason NOT to constant fold
1363 // it is if something (e.g. LSR) was careful to place the constant
1364 // evaluation in a block other than then one that uses it (e.g. to hoist
1365 // the address of globals out of a loop). If this is the case, we don't
1366 // want to forward-subst the cast.
1367 if (isa<Constant>(CI->getOperand(0)))
1368 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001369
Evan Chengbdcb7262007-12-05 23:58:20 +00001370 bool Change = false;
1371 if (TLI) {
1372 Change = OptimizeNoopCopyExpression(CI, *TLI);
1373 MadeChange |= Change;
1374 }
1375
Evan Cheng55e641b2008-03-19 22:02:26 +00001376 if (!Change && (isa<ZExtInst>(I) || isa<SExtInst>(I)))
Evan Chengbdcb7262007-12-05 23:58:20 +00001377 MadeChange |= OptimizeExtUses(I);
Dale Johannesence0b2372007-06-12 16:50:17 +00001378 } else if (CmpInst *CI = dyn_cast<CmpInst>(I)) {
1379 MadeChange |= OptimizeCmpExpression(CI);
Chris Lattnerdd77df32007-04-13 20:30:56 +00001380 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
1381 if (TLI)
Chris Lattner88a5c832008-11-25 07:09:13 +00001382 MadeChange |= OptimizeMemoryInst(I, I->getOperand(0), LI->getType(),
1383 SunkAddrs);
Chris Lattnerdd77df32007-04-13 20:30:56 +00001384 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
1385 if (TLI)
Chris Lattner88a5c832008-11-25 07:09:13 +00001386 MadeChange |= OptimizeMemoryInst(I, SI->getOperand(1),
1387 SI->getOperand(0)->getType(),
1388 SunkAddrs);
Chris Lattnerdd77df32007-04-13 20:30:56 +00001389 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Chris Lattnerf25646b2007-04-14 00:17:39 +00001390 if (GEPI->hasAllZeroIndices()) {
Chris Lattnerdd77df32007-04-13 20:30:56 +00001391 /// The GEP operand must be a pointer, so must its result -> BitCast
Eric Christopher692bf6b2008-09-24 05:32:41 +00001392 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
Chris Lattnerdd77df32007-04-13 20:30:56 +00001393 GEPI->getName(), GEPI);
1394 GEPI->replaceAllUsesWith(NC);
1395 GEPI->eraseFromParent();
1396 MadeChange = true;
1397 BBI = NC;
1398 }
1399 } else if (CallInst *CI = dyn_cast<CallInst>(I)) {
1400 // If we found an inline asm expession, and if the target knows how to
1401 // lower it to normal LLVM code, do so now.
1402 if (TLI && isa<InlineAsm>(CI->getCalledValue()))
Eric Christopher692bf6b2008-09-24 05:32:41 +00001403 if (const TargetAsmInfo *TAI =
Chris Lattnerdd77df32007-04-13 20:30:56 +00001404 TLI->getTargetMachine().getTargetAsmInfo()) {
1405 if (TAI->ExpandInlineAsm(CI))
1406 BBI = BB.begin();
Evan Cheng9bf12b52008-02-26 02:42:37 +00001407 else
1408 // Sink address computing for memory operands into the block.
1409 MadeChange |= OptimizeInlineAsmInst(I, &(*CI), SunkAddrs);
Chris Lattnerdd77df32007-04-13 20:30:56 +00001410 }
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001411 }
1412 }
Eric Christopher692bf6b2008-09-24 05:32:41 +00001413
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001414 return MadeChange;
1415}