blob: 59c6586532c08c12c0d5320cd97e304fd21721aa [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"
Evan Chengab631522008-12-19 18:03:11 +000033#include "llvm/Support/CommandLine.h"
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +000034#include "llvm/Support/Compiler.h"
Evan Chengbdcb7262007-12-05 23:58:20 +000035#include "llvm/Support/Debug.h"
Chris Lattnerdd77df32007-04-13 20:30:56 +000036#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner088a1e82008-11-25 04:42:10 +000037#include "llvm/Support/PatternMatch.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000038using namespace llvm;
Chris Lattner088a1e82008-11-25 04:42:10 +000039using namespace llvm::PatternMatch;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000040
Evan Chengab631522008-12-19 18:03:11 +000041static cl::opt<bool> FactorCommonPreds("split-critical-paths-tweak",
42 cl::init(false), cl::Hidden);
43
Eric Christopher692bf6b2008-09-24 05:32:41 +000044namespace {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000045 class VISIBILITY_HIDDEN CodeGenPrepare : public FunctionPass {
46 /// TLI - Keep a pointer of a TargetLowering to consult for determining
47 /// transformation profitability.
48 const TargetLowering *TLI;
Evan Chengab631522008-12-19 18:03:11 +000049
50 /// BackEdges - Keep a set of all the loop back edges.
51 ///
52 SmallSet<std::pair<BasicBlock*,BasicBlock*>, 8> BackEdges;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000053 public:
Nick Lewyckyecd94c82007-05-06 13:37:16 +000054 static char ID; // Pass identification, replacement for typeid
Dan Gohmanc2bbfc12007-08-01 15:32:29 +000055 explicit CodeGenPrepare(const TargetLowering *tli = 0)
Dan Gohmanae73dc12008-09-04 17:05:41 +000056 : FunctionPass(&ID), TLI(tli) {}
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000057 bool runOnFunction(Function &F);
Eric Christopher692bf6b2008-09-24 05:32:41 +000058
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000059 private:
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +000060 bool EliminateMostlyEmptyBlocks(Function &F);
61 bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
62 void EliminateMostlyEmptyBlock(BasicBlock *BB);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000063 bool OptimizeBlock(BasicBlock &BB);
Chris Lattner88a5c832008-11-25 07:09:13 +000064 bool OptimizeMemoryInst(Instruction *I, Value *Addr, const Type *AccessTy,
65 DenseMap<Value*,Value*> &SunkAddrs);
Evan Cheng9bf12b52008-02-26 02:42:37 +000066 bool OptimizeInlineAsmInst(Instruction *I, CallSite CS,
67 DenseMap<Value*,Value*> &SunkAddrs);
Evan Chengbdcb7262007-12-05 23:58:20 +000068 bool OptimizeExtUses(Instruction *I);
Evan Chengab631522008-12-19 18:03:11 +000069 void findLoopBackEdges(Function &F);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000070 };
71}
Devang Patel794fd752007-05-01 21:15:47 +000072
Devang Patel19974732007-05-03 01:11:54 +000073char CodeGenPrepare::ID = 0;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000074static RegisterPass<CodeGenPrepare> X("codegenprepare",
75 "Optimize for code generation");
76
77FunctionPass *llvm::createCodeGenPreparePass(const TargetLowering *TLI) {
78 return new CodeGenPrepare(TLI);
79}
80
Evan Chengab631522008-12-19 18:03:11 +000081/// findLoopBackEdges - Do a DFS walk to find loop back edges.
82///
83void CodeGenPrepare::findLoopBackEdges(Function &F) {
84 SmallPtrSet<BasicBlock*, 8> Visited;
85 SmallVector<std::pair<BasicBlock*, succ_iterator>, 8> VisitStack;
86 SmallPtrSet<BasicBlock*, 8> InStack;
87
88 BasicBlock *BB = &F.getEntryBlock();
89 if (succ_begin(BB) == succ_end(BB))
90 return;
91 Visited.insert(BB);
92 VisitStack.push_back(std::make_pair(BB, succ_begin(BB)));
93 InStack.insert(BB);
94 do {
95 std::pair<BasicBlock*, succ_iterator> &Top = VisitStack.back();
96 BasicBlock *ParentBB = Top.first;
97 succ_iterator &I = Top.second;
98
99 bool FoundNew = false;
100 while (I != succ_end(ParentBB)) {
101 BB = *I++;
102 if (Visited.insert(BB)) {
103 FoundNew = true;
104 break;
105 }
106 // Successor is in VisitStack, it's a back edge.
107 if (InStack.count(BB))
108 BackEdges.insert(std::make_pair(ParentBB, BB));
109 }
110
111 if (FoundNew) {
112 // Go down one level if there is a unvisited successor.
113 InStack.insert(BB);
114 VisitStack.push_back(std::make_pair(BB, succ_begin(BB)));
115 } else {
116 // Go up one level.
117 std::pair<BasicBlock*, succ_iterator> &Pop = VisitStack.back();
118 InStack.erase(Pop.first);
119 VisitStack.pop_back();
120 }
121 } while (!VisitStack.empty());
122}
123
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000124
125bool CodeGenPrepare::runOnFunction(Function &F) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000126 bool EverMadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000127
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000128 // First pass, eliminate blocks that contain only PHI nodes and an
129 // unconditional branch.
130 EverMadeChange |= EliminateMostlyEmptyBlocks(F);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000131
Evan Cheng7e66c0d2009-01-05 21:17:27 +0000132 // Now find loop back edges.
133 findLoopBackEdges(F);
134
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000135 bool MadeChange = true;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000136 while (MadeChange) {
137 MadeChange = false;
138 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
139 MadeChange |= OptimizeBlock(*BB);
140 EverMadeChange |= MadeChange;
141 }
142 return EverMadeChange;
143}
144
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000145/// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes
Eric Christopher692bf6b2008-09-24 05:32:41 +0000146/// and an unconditional branch. Passes before isel (e.g. LSR/loopsimplify)
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000147/// often split edges in ways that are non-optimal for isel. Start by
148/// eliminating these blocks so we can split them the way we want them.
149bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
150 bool MadeChange = false;
151 // Note that this intentionally skips the entry block.
152 for (Function::iterator I = ++F.begin(), E = F.end(); I != E; ) {
153 BasicBlock *BB = I++;
154
155 // If this block doesn't end with an uncond branch, ignore it.
156 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
157 if (!BI || !BI->isUnconditional())
158 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000159
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000160 // If the instruction before the branch isn't a phi node, then other stuff
161 // is happening here.
162 BasicBlock::iterator BBI = BI;
163 if (BBI != BB->begin()) {
164 --BBI;
165 if (!isa<PHINode>(BBI)) continue;
166 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000167
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000168 // Do not break infinite loops.
169 BasicBlock *DestBB = BI->getSuccessor(0);
170 if (DestBB == BB)
171 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000172
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000173 if (!CanMergeBlocks(BB, DestBB))
174 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000175
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000176 EliminateMostlyEmptyBlock(BB);
177 MadeChange = true;
178 }
179 return MadeChange;
180}
181
182/// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
183/// single uncond branch between them, and BB contains no other non-phi
184/// instructions.
185bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
186 const BasicBlock *DestBB) const {
187 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
188 // the successor. If there are more complex condition (e.g. preheaders),
189 // don't mess around with them.
190 BasicBlock::const_iterator BBI = BB->begin();
191 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
192 for (Value::use_const_iterator UI = PN->use_begin(), E = PN->use_end();
193 UI != E; ++UI) {
194 const Instruction *User = cast<Instruction>(*UI);
195 if (User->getParent() != DestBB || !isa<PHINode>(User))
196 return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000197 // If User is inside DestBB block and it is a PHINode then check
198 // incoming value. If incoming value is not from BB then this is
Devang Patel75abc1e2007-04-25 00:37:04 +0000199 // a complex condition (e.g. preheaders) we want to avoid here.
200 if (User->getParent() == DestBB) {
201 if (const PHINode *UPN = dyn_cast<PHINode>(User))
202 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
203 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
204 if (Insn && Insn->getParent() == BB &&
205 Insn->getParent() != UPN->getIncomingBlock(I))
206 return false;
207 }
208 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000209 }
210 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000211
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000212 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
213 // and DestBB may have conflicting incoming values for the block. If so, we
214 // can't merge the block.
215 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
216 if (!DestBBPN) return true; // no conflict.
Eric Christopher692bf6b2008-09-24 05:32:41 +0000217
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000218 // Collect the preds of BB.
Chris Lattnerf67f73a2007-11-06 22:07:40 +0000219 SmallPtrSet<const BasicBlock*, 16> BBPreds;
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000220 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
221 // It is faster to get preds from a PHI than with pred_iterator.
222 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
223 BBPreds.insert(BBPN->getIncomingBlock(i));
224 } else {
225 BBPreds.insert(pred_begin(BB), pred_end(BB));
226 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000227
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000228 // Walk the preds of DestBB.
229 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
230 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
231 if (BBPreds.count(Pred)) { // Common predecessor?
232 BBI = DestBB->begin();
233 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
234 const Value *V1 = PN->getIncomingValueForBlock(Pred);
235 const Value *V2 = PN->getIncomingValueForBlock(BB);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000236
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000237 // If V2 is a phi node in BB, look up what the mapped value will be.
238 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
239 if (V2PN->getParent() == BB)
240 V2 = V2PN->getIncomingValueForBlock(Pred);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000241
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000242 // If there is a conflict, bail out.
243 if (V1 != V2) return false;
244 }
245 }
246 }
247
248 return true;
249}
250
251
252/// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
253/// an unconditional branch in it.
254void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
255 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
256 BasicBlock *DestBB = BI->getSuccessor(0);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000257
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000258 DOUT << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000259
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000260 // If the destination block has a single pred, then this is a trivial edge,
261 // just collapse it.
Chris Lattner9918fb52008-11-27 19:29:14 +0000262 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
Chris Lattnerf5102a02008-11-28 19:54:49 +0000263 if (SinglePred != DestBB) {
264 // Remember if SinglePred was the entry block of the function. If so, we
265 // will need to move BB back to the entry position.
266 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
267 MergeBasicBlockIntoOnlyPred(DestBB);
Chris Lattner9918fb52008-11-27 19:29:14 +0000268
Chris Lattnerf5102a02008-11-28 19:54:49 +0000269 if (isEntry && BB != &BB->getParent()->getEntryBlock())
270 BB->moveBefore(&BB->getParent()->getEntryBlock());
271
272 DOUT << "AFTER:\n" << *DestBB << "\n\n\n";
273 return;
274 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000275 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000276
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000277 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
278 // to handle the new incoming edges it is about to have.
279 PHINode *PN;
280 for (BasicBlock::iterator BBI = DestBB->begin();
281 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
282 // Remove the incoming value for BB, and remember it.
283 Value *InVal = PN->removeIncomingValue(BB, false);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000284
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000285 // Two options: either the InVal is a phi node defined in BB or it is some
286 // value that dominates BB.
287 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
288 if (InValPhi && InValPhi->getParent() == BB) {
289 // Add all of the input values of the input PHI as inputs of this phi.
290 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
291 PN->addIncoming(InValPhi->getIncomingValue(i),
292 InValPhi->getIncomingBlock(i));
293 } else {
294 // Otherwise, add one instance of the dominating value for each edge that
295 // we will be adding.
296 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
297 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
298 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
299 } else {
300 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
301 PN->addIncoming(InVal, *PI);
302 }
303 }
304 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000305
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000306 // The PHIs are now updated, change everything that refers to BB to use
307 // DestBB and remove BB.
308 BB->replaceAllUsesWith(DestBB);
309 BB->eraseFromParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000310
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000311 DOUT << "AFTER:\n" << *DestBB << "\n\n\n";
312}
313
314
Chris Lattnerebe80752007-12-24 19:32:55 +0000315/// SplitEdgeNicely - Split the critical edge from TI to its specified
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000316/// successor if it will improve codegen. We only do this if the successor has
317/// phi nodes (otherwise critical edges are ok). If there is already another
318/// predecessor of the succ that is empty (and thus has no phi nodes), use it
319/// instead of introducing a new block.
Evan Chengab631522008-12-19 18:03:11 +0000320static void SplitEdgeNicely(TerminatorInst *TI, unsigned SuccNum,
321 SmallSet<std::pair<BasicBlock*,BasicBlock*>, 8> &BackEdges,
322 Pass *P) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000323 BasicBlock *TIBB = TI->getParent();
324 BasicBlock *Dest = TI->getSuccessor(SuccNum);
325 assert(isa<PHINode>(Dest->begin()) &&
326 "This should only be called if Dest has a PHI!");
Eric Christopher692bf6b2008-09-24 05:32:41 +0000327
Chris Lattnerebe80752007-12-24 19:32:55 +0000328 // As a hack, never split backedges of loops. Even though the copy for any
329 // PHIs inserted on the backedge would be dead for exits from the loop, we
330 // assume that the cost of *splitting* the backedge would be too high.
Evan Chengab631522008-12-19 18:03:11 +0000331 if (BackEdges.count(std::make_pair(TIBB, Dest)))
Chris Lattnerebe80752007-12-24 19:32:55 +0000332 return;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000333
Evan Chengab631522008-12-19 18:03:11 +0000334 if (!FactorCommonPreds) {
335 /// TIPHIValues - This array is lazily computed to determine the values of
336 /// PHIs in Dest that TI would provide.
337 SmallVector<Value*, 32> TIPHIValues;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000338
Evan Chengab631522008-12-19 18:03:11 +0000339 // Check to see if Dest has any blocks that can be used as a split edge for
340 // this terminator.
341 for (pred_iterator PI = pred_begin(Dest), E = pred_end(Dest); PI != E; ++PI) {
342 BasicBlock *Pred = *PI;
343 // To be usable, the pred has to end with an uncond branch to the dest.
344 BranchInst *PredBr = dyn_cast<BranchInst>(Pred->getTerminator());
345 if (!PredBr || !PredBr->isUnconditional() ||
346 // Must be empty other than the branch.
347 &Pred->front() != PredBr ||
348 // Cannot be the entry block; its label does not get emitted.
349 Pred == &(Dest->getParent()->getEntryBlock()))
350 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000351
Evan Chengab631522008-12-19 18:03:11 +0000352 // Finally, since we know that Dest has phi nodes in it, we have to make
353 // sure that jumping to Pred will have the same affect as going to Dest in
354 // terms of PHI values.
355 PHINode *PN;
356 unsigned PHINo = 0;
357 bool FoundMatch = true;
358 for (BasicBlock::iterator I = Dest->begin();
359 (PN = dyn_cast<PHINode>(I)); ++I, ++PHINo) {
360 if (PHINo == TIPHIValues.size())
361 TIPHIValues.push_back(PN->getIncomingValueForBlock(TIBB));
Eric Christopher692bf6b2008-09-24 05:32:41 +0000362
Evan Chengab631522008-12-19 18:03:11 +0000363 // If the PHI entry doesn't work, we can't use this pred.
364 if (TIPHIValues[PHINo] != PN->getIncomingValueForBlock(Pred)) {
365 FoundMatch = false;
366 break;
367 }
368 }
369
370 // If we found a workable predecessor, change TI to branch to Succ.
371 if (FoundMatch) {
372 Dest->removePredecessor(TIBB);
373 TI->setSuccessor(SuccNum, Pred);
374 return;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000375 }
376 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000377
Evan Chengab631522008-12-19 18:03:11 +0000378 SplitCriticalEdge(TI, SuccNum, P, true);
379 return;
380 }
381
382 PHINode *PN;
383 SmallVector<Value*, 8> TIPHIValues;
384 for (BasicBlock::iterator I = Dest->begin();
385 (PN = dyn_cast<PHINode>(I)); ++I)
386 TIPHIValues.push_back(PN->getIncomingValueForBlock(TIBB));
387
388 SmallVector<BasicBlock*, 8> IdenticalPreds;
389 for (pred_iterator PI = pred_begin(Dest), E = pred_end(Dest); PI != E; ++PI) {
390 BasicBlock *Pred = *PI;
391 if (BackEdges.count(std::make_pair(Pred, Dest)))
392 continue;
393 if (PI == TIBB)
394 IdenticalPreds.push_back(Pred);
395 else {
396 bool Identical = true;
397 unsigned PHINo = 0;
398 for (BasicBlock::iterator I = Dest->begin();
399 (PN = dyn_cast<PHINode>(I)); ++I, ++PHINo)
400 if (TIPHIValues[PHINo] != PN->getIncomingValueForBlock(Pred)) {
401 Identical = false;
402 break;
403 }
404 if (Identical)
405 IdenticalPreds.push_back(Pred);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000406 }
407 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000408
Evan Chengab631522008-12-19 18:03:11 +0000409 assert(!IdenticalPreds.empty());
410 SplitBlockPredecessors(Dest, &IdenticalPreds[0], IdenticalPreds.size(),
411 ".critedge", P);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000412}
413
Evan Chengab631522008-12-19 18:03:11 +0000414
Chris Lattnerdd77df32007-04-13 20:30:56 +0000415/// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
416/// copy (e.g. it's casting from one pointer type to another, int->uint, or
417/// int->sbyte on PPC), sink it into user blocks to reduce the number of virtual
Dale Johannesence0b2372007-06-12 16:50:17 +0000418/// registers that must be created and coalesced.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000419///
420/// Return true if any changes are made.
Chris Lattner85fa13c2008-11-24 22:44:16 +0000421///
Chris Lattnerdd77df32007-04-13 20:30:56 +0000422static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
Eric Christopher692bf6b2008-09-24 05:32:41 +0000423 // If this is a noop copy,
Duncan Sands83ec4b62008-06-06 12:08:01 +0000424 MVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
425 MVT DstVT = TLI.getValueType(CI->getType());
Eric Christopher692bf6b2008-09-24 05:32:41 +0000426
Chris Lattnerdd77df32007-04-13 20:30:56 +0000427 // This is an fp<->int conversion?
Duncan Sands83ec4b62008-06-06 12:08:01 +0000428 if (SrcVT.isInteger() != DstVT.isInteger())
Chris Lattnerdd77df32007-04-13 20:30:56 +0000429 return false;
Duncan Sands8e4eb092008-06-08 20:54:56 +0000430
Chris Lattnerdd77df32007-04-13 20:30:56 +0000431 // If this is an extension, it will be a zero or sign extension, which
432 // isn't a noop.
Duncan Sands8e4eb092008-06-08 20:54:56 +0000433 if (SrcVT.bitsLT(DstVT)) return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000434
Chris Lattnerdd77df32007-04-13 20:30:56 +0000435 // If these values will be promoted, find out what they will be promoted
436 // to. This helps us consider truncates on PPC as noop copies when they
437 // are.
438 if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote)
439 SrcVT = TLI.getTypeToTransformTo(SrcVT);
440 if (TLI.getTypeAction(DstVT) == TargetLowering::Promote)
441 DstVT = TLI.getTypeToTransformTo(DstVT);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000442
Chris Lattnerdd77df32007-04-13 20:30:56 +0000443 // If, after promotion, these are the same types, this is a noop copy.
444 if (SrcVT != DstVT)
445 return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000446
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000447 BasicBlock *DefBB = CI->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000448
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000449 /// InsertedCasts - Only insert a cast in each block once.
Dale Johannesence0b2372007-06-12 16:50:17 +0000450 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000451
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000452 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000453 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000454 UI != E; ) {
455 Use &TheUse = UI.getUse();
456 Instruction *User = cast<Instruction>(*UI);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000457
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000458 // Figure out which BB this cast is used in. For PHI's this is the
459 // appropriate predecessor block.
460 BasicBlock *UserBB = User->getParent();
461 if (PHINode *PN = dyn_cast<PHINode>(User)) {
462 unsigned OpVal = UI.getOperandNo()/2;
463 UserBB = PN->getIncomingBlock(OpVal);
464 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000465
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000466 // Preincrement use iterator so we don't invalidate it.
467 ++UI;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000468
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000469 // If this user is in the same block as the cast, don't change the cast.
470 if (UserBB == DefBB) continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000471
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000472 // If we have already inserted a cast into this block, use it.
473 CastInst *&InsertedCast = InsertedCasts[UserBB];
474
475 if (!InsertedCast) {
Dan Gohman02dea8b2008-05-23 21:05:58 +0000476 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000477
478 InsertedCast =
479 CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000480 InsertPt);
481 MadeChange = true;
482 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000483
Dale Johannesence0b2372007-06-12 16:50:17 +0000484 // Replace a use of the cast with a use of the new cast.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000485 TheUse = InsertedCast;
486 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000487
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000488 // If we removed all uses, nuke the cast.
Duncan Sandse0038132008-01-20 16:51:46 +0000489 if (CI->use_empty()) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000490 CI->eraseFromParent();
Duncan Sandse0038132008-01-20 16:51:46 +0000491 MadeChange = true;
492 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000493
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000494 return MadeChange;
495}
496
Eric Christopher692bf6b2008-09-24 05:32:41 +0000497/// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
Dale Johannesence0b2372007-06-12 16:50:17 +0000498/// the number of virtual registers that must be created and coalesced. This is
Chris Lattner684b22d2007-08-02 16:53:43 +0000499/// a clear win except on targets with multiple condition code registers
500/// (PowerPC), where it might lose; some adjustment may be wanted there.
Dale Johannesence0b2372007-06-12 16:50:17 +0000501///
502/// Return true if any changes are made.
Chris Lattner85fa13c2008-11-24 22:44:16 +0000503static bool OptimizeCmpExpression(CmpInst *CI) {
Dale Johannesence0b2372007-06-12 16:50:17 +0000504 BasicBlock *DefBB = CI->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000505
Dale Johannesence0b2372007-06-12 16:50:17 +0000506 /// InsertedCmp - Only insert a cmp in each block once.
507 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000508
Dale Johannesence0b2372007-06-12 16:50:17 +0000509 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000510 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
Dale Johannesence0b2372007-06-12 16:50:17 +0000511 UI != E; ) {
512 Use &TheUse = UI.getUse();
513 Instruction *User = cast<Instruction>(*UI);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000514
Dale Johannesence0b2372007-06-12 16:50:17 +0000515 // Preincrement use iterator so we don't invalidate it.
516 ++UI;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000517
Dale Johannesence0b2372007-06-12 16:50:17 +0000518 // Don't bother for PHI nodes.
519 if (isa<PHINode>(User))
520 continue;
521
522 // Figure out which BB this cmp is used in.
523 BasicBlock *UserBB = User->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000524
Dale Johannesence0b2372007-06-12 16:50:17 +0000525 // If this user is in the same block as the cmp, don't change the cmp.
526 if (UserBB == DefBB) continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000527
Dale Johannesence0b2372007-06-12 16:50:17 +0000528 // If we have already inserted a cmp into this block, use it.
529 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
530
531 if (!InsertedCmp) {
Dan Gohman02dea8b2008-05-23 21:05:58 +0000532 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000533
534 InsertedCmp =
535 CmpInst::Create(CI->getOpcode(), CI->getPredicate(), CI->getOperand(0),
Dale Johannesence0b2372007-06-12 16:50:17 +0000536 CI->getOperand(1), "", InsertPt);
537 MadeChange = true;
538 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000539
Dale Johannesence0b2372007-06-12 16:50:17 +0000540 // Replace a use of the cmp with a use of the new cmp.
541 TheUse = InsertedCmp;
542 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000543
Dale Johannesence0b2372007-06-12 16:50:17 +0000544 // If we removed all uses, nuke the cmp.
545 if (CI->use_empty())
546 CI->eraseFromParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000547
Dale Johannesence0b2372007-06-12 16:50:17 +0000548 return MadeChange;
549}
550
Chris Lattner88a5c832008-11-25 07:09:13 +0000551//===----------------------------------------------------------------------===//
552// Addressing Mode Analysis and Optimization
553//===----------------------------------------------------------------------===//
554
Dan Gohman844731a2008-05-13 00:00:25 +0000555namespace {
Chris Lattner4744d852008-11-24 22:40:05 +0000556 /// ExtAddrMode - This is an extended version of TargetLowering::AddrMode
557 /// which holds actual Value*'s for register values.
558 struct ExtAddrMode : public TargetLowering::AddrMode {
559 Value *BaseReg;
560 Value *ScaledReg;
561 ExtAddrMode() : BaseReg(0), ScaledReg(0) {}
562 void print(OStream &OS) const;
563 void dump() const {
564 print(cerr);
565 cerr << '\n';
566 }
567 };
568} // end anonymous namespace
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000569
Chris Lattner5eecb7f2008-11-26 02:00:14 +0000570static inline OStream &operator<<(OStream &OS, const ExtAddrMode &AM) {
Chris Lattner4744d852008-11-24 22:40:05 +0000571 AM.print(OS);
572 return OS;
573}
Chris Lattnerdd77df32007-04-13 20:30:56 +0000574
Chris Lattner4744d852008-11-24 22:40:05 +0000575void ExtAddrMode::print(OStream &OS) const {
Chris Lattnerdd77df32007-04-13 20:30:56 +0000576 bool NeedPlus = false;
577 OS << "[";
Chris Lattner4744d852008-11-24 22:40:05 +0000578 if (BaseGV)
Chris Lattnerdd77df32007-04-13 20:30:56 +0000579 OS << (NeedPlus ? " + " : "")
Chris Lattner4744d852008-11-24 22:40:05 +0000580 << "GV:%" << BaseGV->getName(), NeedPlus = true;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000581
Chris Lattner4744d852008-11-24 22:40:05 +0000582 if (BaseOffs)
583 OS << (NeedPlus ? " + " : "") << BaseOffs, NeedPlus = true;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000584
Chris Lattner4744d852008-11-24 22:40:05 +0000585 if (BaseReg)
Chris Lattnerdd77df32007-04-13 20:30:56 +0000586 OS << (NeedPlus ? " + " : "")
Chris Lattner4744d852008-11-24 22:40:05 +0000587 << "Base:%" << BaseReg->getName(), NeedPlus = true;
588 if (Scale)
Chris Lattnerdd77df32007-04-13 20:30:56 +0000589 OS << (NeedPlus ? " + " : "")
Chris Lattner4744d852008-11-24 22:40:05 +0000590 << Scale << "*%" << ScaledReg->getName(), NeedPlus = true;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000591
Chris Lattner4744d852008-11-24 22:40:05 +0000592 OS << ']';
Dan Gohman844731a2008-05-13 00:00:25 +0000593}
594
Chris Lattner88a5c832008-11-25 07:09:13 +0000595namespace {
596/// AddressingModeMatcher - This class exposes a single public method, which is
597/// used to construct a "maximal munch" of the addressing mode for the target
598/// specified by TLI for an access to "V" with an access type of AccessTy. This
599/// returns the addressing mode that is actually matched by value, but also
600/// returns the list of instructions involved in that addressing computation in
601/// AddrModeInsts.
602class AddressingModeMatcher {
603 SmallVectorImpl<Instruction*> &AddrModeInsts;
604 const TargetLowering &TLI;
Chris Lattner896617b2008-11-26 03:20:37 +0000605
606 /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
607 /// the memory instruction that we're computing this address for.
Chris Lattner88a5c832008-11-25 07:09:13 +0000608 const Type *AccessTy;
Chris Lattner896617b2008-11-26 03:20:37 +0000609 Instruction *MemoryInst;
610
611 /// AddrMode - This is the addressing mode that we're building up. This is
612 /// part of the return value of this addressing mode matching stuff.
Chris Lattner88a5c832008-11-25 07:09:13 +0000613 ExtAddrMode &AddrMode;
Chris Lattner5eecb7f2008-11-26 02:00:14 +0000614
615 /// IgnoreProfitability - This is set to true when we should not do
616 /// profitability checks. When true, IsProfitableToFoldIntoAddressingMode
617 /// always returns true.
618 bool IgnoreProfitability;
619
Chris Lattner88a5c832008-11-25 07:09:13 +0000620 AddressingModeMatcher(SmallVectorImpl<Instruction*> &AMI,
Chris Lattner896617b2008-11-26 03:20:37 +0000621 const TargetLowering &T, const Type *AT,
622 Instruction *MI, ExtAddrMode &AM)
623 : AddrModeInsts(AMI), TLI(T), AccessTy(AT), MemoryInst(MI), AddrMode(AM) {
Chris Lattner5eecb7f2008-11-26 02:00:14 +0000624 IgnoreProfitability = false;
625 }
Chris Lattner88a5c832008-11-25 07:09:13 +0000626public:
627
Chris Lattner5eecb7f2008-11-26 02:00:14 +0000628 /// Match - Find the maximal addressing mode that a load/store of V can fold,
629 /// give an access type of AccessTy. This returns a list of involved
630 /// instructions in AddrModeInsts.
Chris Lattner896617b2008-11-26 03:20:37 +0000631 static ExtAddrMode Match(Value *V, const Type *AccessTy,
632 Instruction *MemoryInst,
Chris Lattner88a5c832008-11-25 07:09:13 +0000633 SmallVectorImpl<Instruction*> &AddrModeInsts,
634 const TargetLowering &TLI) {
635 ExtAddrMode Result;
636
637 bool Success =
Chris Lattner896617b2008-11-26 03:20:37 +0000638 AddressingModeMatcher(AddrModeInsts, TLI, AccessTy,
639 MemoryInst, Result).MatchAddr(V, 0);
Chris Lattner88a5c832008-11-25 07:09:13 +0000640 Success = Success; assert(Success && "Couldn't select *anything*?");
641 return Result;
642 }
643private:
Chris Lattner3b485012008-11-25 07:25:26 +0000644 bool MatchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
Chris Lattner88a5c832008-11-25 07:09:13 +0000645 bool MatchAddr(Value *V, unsigned Depth);
646 bool MatchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth);
Chris Lattner84d1b402008-11-26 03:02:41 +0000647 bool IsProfitableToFoldIntoAddressingMode(Instruction *I,
648 ExtAddrMode &AMBefore,
649 ExtAddrMode &AMAfter);
650 bool ValueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
Chris Lattner88a5c832008-11-25 07:09:13 +0000651};
652} // end anonymous namespace
653
654/// MatchScaledValue - Try adding ScaleReg*Scale to the current addressing mode.
655/// Return true and update AddrMode if this addr mode is legal for the target,
Chris Lattner85fa13c2008-11-24 22:44:16 +0000656/// false if not.
Chris Lattner3b485012008-11-25 07:25:26 +0000657bool AddressingModeMatcher::MatchScaledValue(Value *ScaleReg, int64_t Scale,
658 unsigned Depth) {
659 // If Scale is 1, then this is the same as adding ScaleReg to the addressing
660 // mode. Just process that directly.
661 if (Scale == 1)
662 return MatchAddr(ScaleReg, Depth);
663
664 // If the scale is 0, it takes nothing to add this.
665 if (Scale == 0)
666 return true;
667
Chris Lattner85fa13c2008-11-24 22:44:16 +0000668 // If we already have a scale of this value, we can add to it, otherwise, we
669 // need an available scale field.
670 if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
671 return false;
672
Chris Lattner088a1e82008-11-25 04:42:10 +0000673 ExtAddrMode TestAddrMode = AddrMode;
Chris Lattner85fa13c2008-11-24 22:44:16 +0000674
675 // Add scale to turn X*4+X*3 -> X*7. This could also do things like
676 // [A+B + A*7] -> [B+A*8].
Chris Lattner088a1e82008-11-25 04:42:10 +0000677 TestAddrMode.Scale += Scale;
678 TestAddrMode.ScaledReg = ScaleReg;
Chris Lattner85fa13c2008-11-24 22:44:16 +0000679
Chris Lattner088a1e82008-11-25 04:42:10 +0000680 // If the new address isn't legal, bail out.
681 if (!TLI.isLegalAddressingMode(TestAddrMode, AccessTy))
682 return false;
Chris Lattner85fa13c2008-11-24 22:44:16 +0000683
Chris Lattner088a1e82008-11-25 04:42:10 +0000684 // It was legal, so commit it.
685 AddrMode = TestAddrMode;
686
687 // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
688 // to see if ScaleReg is actually X+C. If so, we can turn this into adding
689 // X*Scale + C*Scale to addr mode.
690 ConstantInt *CI; Value *AddLHS;
Chris Lattnerd62284a2009-01-18 20:35:00 +0000691 if (isa<Instruction>(ScaleReg) && // not a constant expr.
692 match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
Chris Lattner088a1e82008-11-25 04:42:10 +0000693 TestAddrMode.ScaledReg = AddLHS;
694 TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
695
696 // If this addressing mode is legal, commit it and remember that we folded
697 // this instruction.
698 if (TLI.isLegalAddressingMode(TestAddrMode, AccessTy)) {
699 AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
700 AddrMode = TestAddrMode;
Chris Lattner88a5c832008-11-25 07:09:13 +0000701 return true;
Chris Lattner85fa13c2008-11-24 22:44:16 +0000702 }
Chris Lattner85fa13c2008-11-24 22:44:16 +0000703 }
704
Chris Lattner088a1e82008-11-25 04:42:10 +0000705 // Otherwise, not (x+c)*scale, just return what we have.
706 return true;
Chris Lattner85fa13c2008-11-24 22:44:16 +0000707}
708
Chris Lattner5eecb7f2008-11-26 02:00:14 +0000709/// MightBeFoldableInst - This is a little filter, which returns true if an
710/// addressing computation involving I might be folded into a load/store
711/// accessing it. This doesn't need to be perfect, but needs to accept at least
712/// the set of instructions that MatchOperationAddr can.
713static bool MightBeFoldableInst(Instruction *I) {
714 switch (I->getOpcode()) {
715 case Instruction::BitCast:
716 // Don't touch identity bitcasts.
717 if (I->getType() == I->getOperand(0)->getType())
718 return false;
719 return isa<PointerType>(I->getType()) || isa<IntegerType>(I->getType());
720 case Instruction::PtrToInt:
721 // PtrToInt is always a noop, as we know that the int type is pointer sized.
722 return true;
723 case Instruction::IntToPtr:
724 // We know the input is intptr_t, so this is foldable.
725 return true;
726 case Instruction::Add:
727 return true;
728 case Instruction::Mul:
729 case Instruction::Shl:
730 // Can only handle X*C and X << C.
731 return isa<ConstantInt>(I->getOperand(1));
732 case Instruction::GetElementPtr:
733 return true;
734 default:
735 return false;
736 }
737}
738
Chris Lattnerbb3204a2008-11-25 05:15:49 +0000739
Chris Lattner88a5c832008-11-25 07:09:13 +0000740/// MatchOperationAddr - Given an instruction or constant expr, see if we can
741/// fold the operation into the addressing mode. If so, update the addressing
742/// mode and return true, otherwise return false without modifying AddrMode.
743bool AddressingModeMatcher::MatchOperationAddr(User *AddrInst, unsigned Opcode,
744 unsigned Depth) {
745 // Avoid exponential behavior on extremely deep expression trees.
746 if (Depth >= 5) return false;
747
Chris Lattnerdd77df32007-04-13 20:30:56 +0000748 switch (Opcode) {
749 case Instruction::PtrToInt:
750 // PtrToInt is always a noop, as we know that the int type is pointer sized.
Chris Lattner88a5c832008-11-25 07:09:13 +0000751 return MatchAddr(AddrInst->getOperand(0), Depth);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000752 case Instruction::IntToPtr:
753 // This inttoptr is a no-op if the integer type is pointer sized.
754 if (TLI.getValueType(AddrInst->getOperand(0)->getType()) ==
Chris Lattner88a5c832008-11-25 07:09:13 +0000755 TLI.getPointerTy())
756 return MatchAddr(AddrInst->getOperand(0), Depth);
757 return false;
Chris Lattner2efbbb32008-11-26 00:26:16 +0000758 case Instruction::BitCast:
759 // BitCast is always a noop, and we can handle it as long as it is
760 // int->int or pointer->pointer (we don't want int<->fp or something).
761 if ((isa<PointerType>(AddrInst->getOperand(0)->getType()) ||
762 isa<IntegerType>(AddrInst->getOperand(0)->getType())) &&
763 // Don't touch identity bitcasts. These were probably put here by LSR,
764 // and we don't want to mess around with them. Assume it knows what it
765 // is doing.
766 AddrInst->getOperand(0)->getType() != AddrInst->getType())
767 return MatchAddr(AddrInst->getOperand(0), Depth);
768 return false;
Chris Lattnerdd77df32007-04-13 20:30:56 +0000769 case Instruction::Add: {
770 // Check to see if we can merge in the RHS then the LHS. If so, we win.
771 ExtAddrMode BackupAddrMode = AddrMode;
772 unsigned OldSize = AddrModeInsts.size();
Chris Lattner88a5c832008-11-25 07:09:13 +0000773 if (MatchAddr(AddrInst->getOperand(1), Depth+1) &&
774 MatchAddr(AddrInst->getOperand(0), Depth+1))
Chris Lattnerdd77df32007-04-13 20:30:56 +0000775 return true;
Chris Lattnerbb3204a2008-11-25 05:15:49 +0000776
Chris Lattnerdd77df32007-04-13 20:30:56 +0000777 // Restore the old addr mode info.
778 AddrMode = BackupAddrMode;
779 AddrModeInsts.resize(OldSize);
Chris Lattnerbb3204a2008-11-25 05:15:49 +0000780
Chris Lattnerdd77df32007-04-13 20:30:56 +0000781 // Otherwise this was over-aggressive. Try merging in the LHS then the RHS.
Chris Lattner88a5c832008-11-25 07:09:13 +0000782 if (MatchAddr(AddrInst->getOperand(0), Depth+1) &&
783 MatchAddr(AddrInst->getOperand(1), Depth+1))
Chris Lattnerdd77df32007-04-13 20:30:56 +0000784 return true;
Chris Lattnerbb3204a2008-11-25 05:15:49 +0000785
Chris Lattnerdd77df32007-04-13 20:30:56 +0000786 // Otherwise we definitely can't merge the ADD in.
787 AddrMode = BackupAddrMode;
788 AddrModeInsts.resize(OldSize);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000789 break;
Chris Lattnerdd77df32007-04-13 20:30:56 +0000790 }
Chris Lattner5eecb7f2008-11-26 02:00:14 +0000791 //case Instruction::Or:
792 // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
793 //break;
Chris Lattnerdd77df32007-04-13 20:30:56 +0000794 case Instruction::Mul:
795 case Instruction::Shl: {
Chris Lattner7ad1c732008-11-25 04:47:41 +0000796 // Can only handle X*C and X << C.
Chris Lattnerdd77df32007-04-13 20:30:56 +0000797 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
Chris Lattner88a5c832008-11-25 07:09:13 +0000798 if (!RHS) return false;
Chris Lattnerdd77df32007-04-13 20:30:56 +0000799 int64_t Scale = RHS->getSExtValue();
800 if (Opcode == Instruction::Shl)
801 Scale = 1 << Scale;
Chris Lattnerbb3204a2008-11-25 05:15:49 +0000802
Chris Lattner3b485012008-11-25 07:25:26 +0000803 return MatchScaledValue(AddrInst->getOperand(0), Scale, Depth);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000804 }
805 case Instruction::GetElementPtr: {
806 // Scan the GEP. We check it if it contains constant offsets and at most
807 // one variable offset.
808 int VariableOperand = -1;
809 unsigned VariableScale = 0;
Chris Lattnerbb3204a2008-11-25 05:15:49 +0000810
Chris Lattnerdd77df32007-04-13 20:30:56 +0000811 int64_t ConstantOffset = 0;
812 const TargetData *TD = TLI.getTargetData();
813 gep_type_iterator GTI = gep_type_begin(AddrInst);
814 for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
815 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
816 const StructLayout *SL = TD->getStructLayout(STy);
817 unsigned Idx =
Chris Lattner88a5c832008-11-25 07:09:13 +0000818 cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
Chris Lattnerdd77df32007-04-13 20:30:56 +0000819 ConstantOffset += SL->getElementOffset(Idx);
820 } else {
Duncan Sandsceb4d1a2009-01-12 20:38:59 +0000821 uint64_t TypeSize = TD->getTypePaddedSize(GTI.getIndexedType());
Chris Lattnerdd77df32007-04-13 20:30:56 +0000822 if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
823 ConstantOffset += CI->getSExtValue()*TypeSize;
824 } else if (TypeSize) { // Scales of zero don't do anything.
825 // We only allow one variable index at the moment.
Chris Lattner88a5c832008-11-25 07:09:13 +0000826 if (VariableOperand != -1)
827 return false;
Chris Lattnerbb3204a2008-11-25 05:15:49 +0000828
Chris Lattnerdd77df32007-04-13 20:30:56 +0000829 // Remember the variable index.
830 VariableOperand = i;
831 VariableScale = TypeSize;
832 }
833 }
834 }
Chris Lattnerbb3204a2008-11-25 05:15:49 +0000835
Chris Lattnerdd77df32007-04-13 20:30:56 +0000836 // A common case is for the GEP to only do a constant offset. In this case,
837 // just add it to the disp field and check validity.
838 if (VariableOperand == -1) {
839 AddrMode.BaseOffs += ConstantOffset;
840 if (ConstantOffset == 0 || TLI.isLegalAddressingMode(AddrMode, AccessTy)){
841 // Check to see if we can fold the base pointer in too.
Chris Lattner88a5c832008-11-25 07:09:13 +0000842 if (MatchAddr(AddrInst->getOperand(0), Depth+1))
Chris Lattnerdd77df32007-04-13 20:30:56 +0000843 return true;
844 }
845 AddrMode.BaseOffs -= ConstantOffset;
Chris Lattner88a5c832008-11-25 07:09:13 +0000846 return false;
Chris Lattnerdd77df32007-04-13 20:30:56 +0000847 }
Chris Lattner88a5c832008-11-25 07:09:13 +0000848
849 // Save the valid addressing mode in case we can't match.
850 ExtAddrMode BackupAddrMode = AddrMode;
851
852 // Check that this has no base reg yet. If so, we won't have a place to
853 // put the base of the GEP (assuming it is not a null ptr).
854 bool SetBaseReg = true;
855 if (isa<ConstantPointerNull>(AddrInst->getOperand(0)))
856 SetBaseReg = false; // null pointer base doesn't need representation.
857 else if (AddrMode.HasBaseReg)
858 return false; // Base register already specified, can't match GEP.
859 else {
860 // Otherwise, we'll use the GEP base as the BaseReg.
861 AddrMode.HasBaseReg = true;
862 AddrMode.BaseReg = AddrInst->getOperand(0);
863 }
864
865 // See if the scale and offset amount is valid for this target.
866 AddrMode.BaseOffs += ConstantOffset;
867
Chris Lattner3b485012008-11-25 07:25:26 +0000868 if (!MatchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
869 Depth)) {
Chris Lattner88a5c832008-11-25 07:09:13 +0000870 AddrMode = BackupAddrMode;
871 return false;
872 }
873
874 // If we have a null as the base of the GEP, folding in the constant offset
875 // plus variable scale is all we can do.
876 if (!SetBaseReg) return true;
877
878 // If this match succeeded, we know that we can form an address with the
879 // GepBase as the basereg. Match the base pointer of the GEP more
880 // aggressively by zeroing out BaseReg and rematching. If the base is
881 // (for example) another GEP, this allows merging in that other GEP into
882 // the addressing mode we're forming.
883 AddrMode.HasBaseReg = false;
884 AddrMode.BaseReg = 0;
885 bool Success = MatchAddr(AddrInst->getOperand(0), Depth+1);
886 assert(Success && "MatchAddr should be able to fill in BaseReg!");
887 Success=Success;
888 return true;
Chris Lattnerdd77df32007-04-13 20:30:56 +0000889 }
890 }
Chris Lattnerbb3204a2008-11-25 05:15:49 +0000891 return false;
892}
Eric Christopher692bf6b2008-09-24 05:32:41 +0000893
Chris Lattner88a5c832008-11-25 07:09:13 +0000894/// MatchAddr - If we can, try to add the value of 'Addr' into the current
895/// addressing mode. If Addr can't be added to AddrMode this returns false and
896/// leaves AddrMode unmodified. This assumes that Addr is either a pointer type
897/// or intptr_t for the target.
Chris Lattnerbb3204a2008-11-25 05:15:49 +0000898///
Chris Lattner88a5c832008-11-25 07:09:13 +0000899bool AddressingModeMatcher::MatchAddr(Value *Addr, unsigned Depth) {
Chris Lattnerbb3204a2008-11-25 05:15:49 +0000900 if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
901 // Fold in immediates if legal for the target.
902 AddrMode.BaseOffs += CI->getSExtValue();
903 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
904 return true;
905 AddrMode.BaseOffs -= CI->getSExtValue();
906 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
Chris Lattner88a5c832008-11-25 07:09:13 +0000907 // If this is a global variable, try to fold it into the addressing mode.
Chris Lattnerbb3204a2008-11-25 05:15:49 +0000908 if (AddrMode.BaseGV == 0) {
909 AddrMode.BaseGV = GV;
910 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
911 return true;
912 AddrMode.BaseGV = 0;
913 }
914 } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
Chris Lattner5eecb7f2008-11-26 02:00:14 +0000915 ExtAddrMode BackupAddrMode = AddrMode;
916 unsigned OldSize = AddrModeInsts.size();
917
918 // Check to see if it is possible to fold this operation.
Chris Lattner88a5c832008-11-25 07:09:13 +0000919 if (MatchOperationAddr(I, I->getOpcode(), Depth)) {
Chris Lattner5eecb7f2008-11-26 02:00:14 +0000920 // Okay, it's possible to fold this. Check to see if it is actually
921 // *profitable* to do so. We use a simple cost model to avoid increasing
922 // register pressure too much.
Chris Lattner84d1b402008-11-26 03:02:41 +0000923 if (I->hasOneUse() ||
924 IsProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
Chris Lattner5eecb7f2008-11-26 02:00:14 +0000925 AddrModeInsts.push_back(I);
926 return true;
927 }
928
929 // It isn't profitable to do this, roll back.
930 //cerr << "NOT FOLDING: " << *I;
931 AddrMode = BackupAddrMode;
932 AddrModeInsts.resize(OldSize);
Chris Lattnerbb3204a2008-11-25 05:15:49 +0000933 }
934 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
Chris Lattner88a5c832008-11-25 07:09:13 +0000935 if (MatchOperationAddr(CE, CE->getOpcode(), Depth))
Chris Lattnerbb3204a2008-11-25 05:15:49 +0000936 return true;
937 } else if (isa<ConstantPointerNull>(Addr)) {
Chris Lattner88a5c832008-11-25 07:09:13 +0000938 // Null pointer gets folded without affecting the addressing mode.
Chris Lattnerbb3204a2008-11-25 05:15:49 +0000939 return true;
Chris Lattnerdd77df32007-04-13 20:30:56 +0000940 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000941
Chris Lattnerdd77df32007-04-13 20:30:56 +0000942 // Worse case, the target should support [reg] addressing modes. :)
943 if (!AddrMode.HasBaseReg) {
944 AddrMode.HasBaseReg = true;
Chris Lattner653b2582008-11-26 02:11:11 +0000945 AddrMode.BaseReg = Addr;
Chris Lattnerdd77df32007-04-13 20:30:56 +0000946 // Still check for legality in case the target supports [imm] but not [i+r].
Chris Lattner653b2582008-11-26 02:11:11 +0000947 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
Chris Lattnerdd77df32007-04-13 20:30:56 +0000948 return true;
Chris Lattnerdd77df32007-04-13 20:30:56 +0000949 AddrMode.HasBaseReg = false;
Chris Lattner653b2582008-11-26 02:11:11 +0000950 AddrMode.BaseReg = 0;
Chris Lattnerdd77df32007-04-13 20:30:56 +0000951 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000952
Chris Lattnerdd77df32007-04-13 20:30:56 +0000953 // If the base register is already taken, see if we can do [r+r].
954 if (AddrMode.Scale == 0) {
955 AddrMode.Scale = 1;
Chris Lattner653b2582008-11-26 02:11:11 +0000956 AddrMode.ScaledReg = Addr;
957 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
Chris Lattnerdd77df32007-04-13 20:30:56 +0000958 return true;
Chris Lattnerdd77df32007-04-13 20:30:56 +0000959 AddrMode.Scale = 0;
Chris Lattner653b2582008-11-26 02:11:11 +0000960 AddrMode.ScaledReg = 0;
Chris Lattnerdd77df32007-04-13 20:30:56 +0000961 }
962 // Couldn't match.
963 return false;
964}
965
Chris Lattner695d8ec2008-11-26 04:59:11 +0000966
967/// IsOperandAMemoryOperand - Check to see if all uses of OpVal by the specified
968/// inline asm call are due to memory operands. If so, return true, otherwise
969/// return false.
970static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
971 const TargetLowering &TLI) {
972 std::vector<InlineAsm::ConstraintInfo>
973 Constraints = IA->ParseConstraints();
974
975 unsigned ArgNo = 1; // ArgNo - The operand of the CallInst.
976 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
977 TargetLowering::AsmOperandInfo OpInfo(Constraints[i]);
978
979 // Compute the value type for each operand.
980 switch (OpInfo.Type) {
981 case InlineAsm::isOutput:
982 if (OpInfo.isIndirect)
983 OpInfo.CallOperandVal = CI->getOperand(ArgNo++);
984 break;
985 case InlineAsm::isInput:
986 OpInfo.CallOperandVal = CI->getOperand(ArgNo++);
987 break;
988 case InlineAsm::isClobber:
989 // Nothing to do.
990 break;
991 }
992
993 // Compute the constraint code and ConstraintType to use.
994 TLI.ComputeConstraintToUse(OpInfo, SDValue(),
995 OpInfo.ConstraintType == TargetLowering::C_Memory);
996
997 // If this asm operand is our Value*, and if it isn't an indirect memory
998 // operand, we can't fold it!
999 if (OpInfo.CallOperandVal == OpVal &&
1000 (OpInfo.ConstraintType != TargetLowering::C_Memory ||
1001 !OpInfo.isIndirect))
1002 return false;
1003 }
1004
1005 return true;
1006}
1007
1008
Chris Lattner5eecb7f2008-11-26 02:00:14 +00001009/// FindAllMemoryUses - Recursively walk all the uses of I until we find a
1010/// memory use. If we find an obviously non-foldable instruction, return true.
1011/// Add the ultimately found memory instructions to MemoryUses.
1012static bool FindAllMemoryUses(Instruction *I,
1013 SmallVectorImpl<std::pair<Instruction*,unsigned> > &MemoryUses,
Chris Lattner695d8ec2008-11-26 04:59:11 +00001014 SmallPtrSet<Instruction*, 16> &ConsideredInsts,
1015 const TargetLowering &TLI) {
Chris Lattner5eecb7f2008-11-26 02:00:14 +00001016 // If we already considered this instruction, we're done.
1017 if (!ConsideredInsts.insert(I))
1018 return false;
1019
1020 // If this is an obviously unfoldable instruction, bail out.
1021 if (!MightBeFoldableInst(I))
1022 return true;
1023
1024 // Loop over all the uses, recursively processing them.
1025 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1026 UI != E; ++UI) {
1027 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
1028 MemoryUses.push_back(std::make_pair(LI, UI.getOperandNo()));
1029 continue;
1030 }
1031
1032 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
1033 if (UI.getOperandNo() == 0) return true; // Storing addr, not into addr.
1034 MemoryUses.push_back(std::make_pair(SI, UI.getOperandNo()));
1035 continue;
1036 }
1037
1038 if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
1039 InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
1040 if (IA == 0) return true;
Chris Lattner5eecb7f2008-11-26 02:00:14 +00001041
Chris Lattner695d8ec2008-11-26 04:59:11 +00001042 // If this is a memory operand, we're cool, otherwise bail out.
1043 if (!IsOperandAMemoryOperand(CI, IA, I, TLI))
1044 return true;
1045 continue;
Chris Lattner5eecb7f2008-11-26 02:00:14 +00001046 }
1047
Chris Lattner695d8ec2008-11-26 04:59:11 +00001048 if (FindAllMemoryUses(cast<Instruction>(*UI), MemoryUses, ConsideredInsts,
1049 TLI))
Chris Lattner5eecb7f2008-11-26 02:00:14 +00001050 return true;
1051 }
1052
1053 return false;
1054}
Chris Lattner84d1b402008-11-26 03:02:41 +00001055
1056
1057/// ValueAlreadyLiveAtInst - Retrn true if Val is already known to be live at
1058/// the use site that we're folding it into. If so, there is no cost to
1059/// include it in the addressing mode. KnownLive1 and KnownLive2 are two values
1060/// that we know are live at the instruction already.
1061bool AddressingModeMatcher::ValueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
1062 Value *KnownLive2) {
1063 // If Val is either of the known-live values, we know it is live!
1064 if (Val == 0 || Val == KnownLive1 || Val == KnownLive2)
1065 return true;
Chris Lattner5eecb7f2008-11-26 02:00:14 +00001066
Chris Lattner896617b2008-11-26 03:20:37 +00001067 // All values other than instructions and arguments (e.g. constants) are live.
Chris Lattner84d1b402008-11-26 03:02:41 +00001068 if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
1069
1070 // If Val is a constant sized alloca in the entry block, it is live, this is
1071 // true because it is just a reference to the stack/frame pointer, which is
1072 // live for the whole function.
1073 if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
1074 if (AI->isStaticAlloca())
1075 return true;
1076
Chris Lattner896617b2008-11-26 03:20:37 +00001077 // Check to see if this value is already used in the memory instruction's
1078 // block. If so, it's already live into the block at the very least, so we
1079 // can reasonably fold it.
1080 BasicBlock *MemBB = MemoryInst->getParent();
1081 for (Value::use_iterator UI = Val->use_begin(), E = Val->use_end();
1082 UI != E; ++UI)
1083 // We know that uses of arguments and instructions have to be instructions.
1084 if (cast<Instruction>(*UI)->getParent() == MemBB)
1085 return true;
1086
Chris Lattner84d1b402008-11-26 03:02:41 +00001087 return false;
1088}
1089
1090
1091
Chris Lattner5eecb7f2008-11-26 02:00:14 +00001092/// IsProfitableToFoldIntoAddressingMode - It is possible for the addressing
1093/// mode of the machine to fold the specified instruction into a load or store
1094/// that ultimately uses it. However, the specified instruction has multiple
1095/// uses. Given this, it may actually increase register pressure to fold it
1096/// into the load. For example, consider this code:
1097///
1098/// X = ...
1099/// Y = X+1
1100/// use(Y) -> nonload/store
1101/// Z = Y+1
1102/// load Z
1103///
1104/// In this case, Y has multiple uses, and can be folded into the load of Z
1105/// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to
1106/// be live at the use(Y) line. If we don't fold Y into load Z, we use one
1107/// fewer register. Since Y can't be folded into "use(Y)" we don't increase the
1108/// number of computations either.
1109///
1110/// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If
1111/// X was live across 'load Z' for other reasons, we actually *would* want to
Chris Lattner653b2582008-11-26 02:11:11 +00001112/// fold the addressing mode in the Z case. This would make Y die earlier.
Chris Lattner5eecb7f2008-11-26 02:00:14 +00001113bool AddressingModeMatcher::
Chris Lattner84d1b402008-11-26 03:02:41 +00001114IsProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
1115 ExtAddrMode &AMAfter) {
Chris Lattnerab8b7942008-11-26 22:16:44 +00001116 if (IgnoreProfitability) return true;
Chris Lattner5eecb7f2008-11-26 02:00:14 +00001117
Chris Lattner84d1b402008-11-26 03:02:41 +00001118 // AMBefore is the addressing mode before this instruction was folded into it,
1119 // and AMAfter is the addressing mode after the instruction was folded. Get
1120 // the set of registers referenced by AMAfter and subtract out those
1121 // referenced by AMBefore: this is the set of values which folding in this
1122 // address extends the lifetime of.
1123 //
1124 // Note that there are only two potential values being referenced here,
1125 // BaseReg and ScaleReg (global addresses are always available, as are any
1126 // folded immediates).
1127 Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
1128
1129 // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
1130 // lifetime wasn't extended by adding this instruction.
1131 if (ValueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
1132 BaseReg = 0;
1133 if (ValueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
1134 ScaledReg = 0;
1135
1136 // If folding this instruction (and it's subexprs) didn't extend any live
1137 // ranges, we're ok with it.
1138 if (BaseReg == 0 && ScaledReg == 0)
1139 return true;
Chris Lattner5eecb7f2008-11-26 02:00:14 +00001140
1141 // If all uses of this instruction are ultimately load/store/inlineasm's,
1142 // check to see if their addressing modes will include this instruction. If
1143 // so, we can fold it into all uses, so it doesn't matter if it has multiple
1144 // uses.
1145 SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
1146 SmallPtrSet<Instruction*, 16> ConsideredInsts;
Chris Lattner695d8ec2008-11-26 04:59:11 +00001147 if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TLI))
Chris Lattner5eecb7f2008-11-26 02:00:14 +00001148 return false; // Has a non-memory, non-foldable use!
1149
1150 // Now that we know that all uses of this instruction are part of a chain of
1151 // computation involving only operations that could theoretically be folded
1152 // into a memory use, loop over each of these uses and see if they could
1153 // *actually* fold the instruction.
1154 SmallVector<Instruction*, 32> MatchedAddrModeInsts;
1155 for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
1156 Instruction *User = MemoryUses[i].first;
1157 unsigned OpNo = MemoryUses[i].second;
1158
1159 // Get the access type of this use. If the use isn't a pointer, we don't
1160 // know what it accesses.
1161 Value *Address = User->getOperand(OpNo);
1162 if (!isa<PointerType>(Address->getType()))
1163 return false;
1164 const Type *AddressAccessTy =
1165 cast<PointerType>(Address->getType())->getElementType();
1166
1167 // Do a match against the root of this address, ignoring profitability. This
1168 // will tell us if the addressing mode for the memory operation will
1169 // *actually* cover the shared instruction.
1170 ExtAddrMode Result;
1171 AddressingModeMatcher Matcher(MatchedAddrModeInsts, TLI, AddressAccessTy,
Chris Lattner896617b2008-11-26 03:20:37 +00001172 MemoryInst, Result);
Chris Lattner5eecb7f2008-11-26 02:00:14 +00001173 Matcher.IgnoreProfitability = true;
1174 bool Success = Matcher.MatchAddr(Address, 0);
1175 Success = Success; assert(Success && "Couldn't select *anything*?");
1176
1177 // If the match didn't cover I, then it won't be shared by it.
1178 if (std::find(MatchedAddrModeInsts.begin(), MatchedAddrModeInsts.end(),
1179 I) == MatchedAddrModeInsts.end())
1180 return false;
1181
1182 MatchedAddrModeInsts.clear();
1183 }
1184
1185 return true;
1186}
1187
Chris Lattnerdd77df32007-04-13 20:30:56 +00001188
Chris Lattner88a5c832008-11-25 07:09:13 +00001189//===----------------------------------------------------------------------===//
1190// Memory Optimization
1191//===----------------------------------------------------------------------===//
1192
Chris Lattnerdd77df32007-04-13 20:30:56 +00001193/// IsNonLocalValue - Return true if the specified values are defined in a
1194/// different basic block than BB.
1195static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
1196 if (Instruction *I = dyn_cast<Instruction>(V))
1197 return I->getParent() != BB;
1198 return false;
1199}
1200
Chris Lattner88a5c832008-11-25 07:09:13 +00001201/// OptimizeMemoryInst - Load and Store Instructions have often have
Chris Lattnerdd77df32007-04-13 20:30:56 +00001202/// addressing modes that can do significant amounts of computation. As such,
1203/// instruction selection will try to get the load or store to do as much
1204/// computation as possible for the program. The problem is that isel can only
1205/// see within a single block. As such, we sink as much legal addressing mode
1206/// stuff into the block as possible.
Chris Lattner88a5c832008-11-25 07:09:13 +00001207///
1208/// This method is used to optimize both load/store and inline asms with memory
1209/// operands.
Chris Lattner896617b2008-11-26 03:20:37 +00001210bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
Chris Lattner88a5c832008-11-25 07:09:13 +00001211 const Type *AccessTy,
1212 DenseMap<Value*,Value*> &SunkAddrs) {
Chris Lattnerdd77df32007-04-13 20:30:56 +00001213 // Figure out what addressing mode will be built up for this operation.
1214 SmallVector<Instruction*, 16> AddrModeInsts;
Chris Lattner896617b2008-11-26 03:20:37 +00001215 ExtAddrMode AddrMode = AddressingModeMatcher::Match(Addr, AccessTy,MemoryInst,
1216 AddrModeInsts, *TLI);
Eric Christopher692bf6b2008-09-24 05:32:41 +00001217
Chris Lattnerdd77df32007-04-13 20:30:56 +00001218 // Check to see if any of the instructions supersumed by this addr mode are
1219 // non-local to I's BB.
1220 bool AnyNonLocal = false;
1221 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
Chris Lattner896617b2008-11-26 03:20:37 +00001222 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
Chris Lattnerdd77df32007-04-13 20:30:56 +00001223 AnyNonLocal = true;
1224 break;
1225 }
1226 }
Eric Christopher692bf6b2008-09-24 05:32:41 +00001227
Chris Lattnerdd77df32007-04-13 20:30:56 +00001228 // If all the instructions matched are already in this BB, don't do anything.
1229 if (!AnyNonLocal) {
1230 DEBUG(cerr << "CGP: Found local addrmode: " << AddrMode << "\n");
1231 return false;
1232 }
Eric Christopher692bf6b2008-09-24 05:32:41 +00001233
Chris Lattnerdd77df32007-04-13 20:30:56 +00001234 // Insert this computation right after this user. Since our caller is
1235 // scanning from the top of the BB to the bottom, reuse of the expr are
1236 // guaranteed to happen later.
Chris Lattner896617b2008-11-26 03:20:37 +00001237 BasicBlock::iterator InsertPt = MemoryInst;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001238
Chris Lattnerdd77df32007-04-13 20:30:56 +00001239 // Now that we determined the addressing expression we want to use and know
1240 // that we have to sink it into this block. Check to see if we have already
1241 // done this for some other load/store instr in this block. If so, reuse the
1242 // computation.
1243 Value *&SunkAddr = SunkAddrs[Addr];
1244 if (SunkAddr) {
1245 DEBUG(cerr << "CGP: Reusing nonlocal addrmode: " << AddrMode << "\n");
1246 if (SunkAddr->getType() != Addr->getType())
1247 SunkAddr = new BitCastInst(SunkAddr, Addr->getType(), "tmp", InsertPt);
1248 } else {
1249 DEBUG(cerr << "CGP: SINKING nonlocal addrmode: " << AddrMode << "\n");
1250 const Type *IntPtrTy = TLI->getTargetData()->getIntPtrType();
Eric Christopher692bf6b2008-09-24 05:32:41 +00001251
Chris Lattnerdd77df32007-04-13 20:30:56 +00001252 Value *Result = 0;
1253 // Start with the scale value.
1254 if (AddrMode.Scale) {
1255 Value *V = AddrMode.ScaledReg;
1256 if (V->getType() == IntPtrTy) {
1257 // done.
1258 } else if (isa<PointerType>(V->getType())) {
1259 V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
1260 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
1261 cast<IntegerType>(V->getType())->getBitWidth()) {
1262 V = new TruncInst(V, IntPtrTy, "sunkaddr", InsertPt);
1263 } else {
1264 V = new SExtInst(V, IntPtrTy, "sunkaddr", InsertPt);
1265 }
1266 if (AddrMode.Scale != 1)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001267 V = BinaryOperator::CreateMul(V, ConstantInt::get(IntPtrTy,
Chris Lattnerdd77df32007-04-13 20:30:56 +00001268 AddrMode.Scale),
1269 "sunkaddr", InsertPt);
1270 Result = V;
1271 }
1272
1273 // Add in the base register.
1274 if (AddrMode.BaseReg) {
1275 Value *V = AddrMode.BaseReg;
1276 if (V->getType() != IntPtrTy)
1277 V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
1278 if (Result)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001279 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
Chris Lattnerdd77df32007-04-13 20:30:56 +00001280 else
1281 Result = V;
1282 }
Eric Christopher692bf6b2008-09-24 05:32:41 +00001283
Chris Lattnerdd77df32007-04-13 20:30:56 +00001284 // Add in the BaseGV if present.
1285 if (AddrMode.BaseGV) {
1286 Value *V = new PtrToIntInst(AddrMode.BaseGV, IntPtrTy, "sunkaddr",
1287 InsertPt);
1288 if (Result)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001289 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
Chris Lattnerdd77df32007-04-13 20:30:56 +00001290 else
1291 Result = V;
1292 }
Eric Christopher692bf6b2008-09-24 05:32:41 +00001293
Chris Lattnerdd77df32007-04-13 20:30:56 +00001294 // Add in the Base Offset if present.
1295 if (AddrMode.BaseOffs) {
1296 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
1297 if (Result)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001298 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
Chris Lattnerdd77df32007-04-13 20:30:56 +00001299 else
1300 Result = V;
1301 }
1302
1303 if (Result == 0)
1304 SunkAddr = Constant::getNullValue(Addr->getType());
1305 else
1306 SunkAddr = new IntToPtrInst(Result, Addr->getType(), "sunkaddr",InsertPt);
1307 }
Eric Christopher692bf6b2008-09-24 05:32:41 +00001308
Chris Lattner896617b2008-11-26 03:20:37 +00001309 MemoryInst->replaceUsesOfWith(Addr, SunkAddr);
Eric Christopher692bf6b2008-09-24 05:32:41 +00001310
Chris Lattnerdd77df32007-04-13 20:30:56 +00001311 if (Addr->use_empty())
Chris Lattner3481f242008-11-27 22:57:53 +00001312 RecursivelyDeleteTriviallyDeadInstructions(Addr);
Chris Lattnerdd77df32007-04-13 20:30:56 +00001313 return true;
1314}
1315
Evan Cheng9bf12b52008-02-26 02:42:37 +00001316/// OptimizeInlineAsmInst - If there are any memory operands, use
Chris Lattner88a5c832008-11-25 07:09:13 +00001317/// OptimizeMemoryInst to sink their address computing into the block when
Evan Cheng9bf12b52008-02-26 02:42:37 +00001318/// possible / profitable.
1319bool CodeGenPrepare::OptimizeInlineAsmInst(Instruction *I, CallSite CS,
1320 DenseMap<Value*,Value*> &SunkAddrs) {
1321 bool MadeChange = false;
1322 InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
1323
1324 // Do a prepass over the constraints, canonicalizing them, and building up the
1325 // ConstraintOperands list.
1326 std::vector<InlineAsm::ConstraintInfo>
1327 ConstraintInfos = IA->ParseConstraints();
1328
1329 /// ConstraintOperands - Information about all of the constraints.
1330 std::vector<TargetLowering::AsmOperandInfo> ConstraintOperands;
1331 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
1332 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
1333 ConstraintOperands.
1334 push_back(TargetLowering::AsmOperandInfo(ConstraintInfos[i]));
1335 TargetLowering::AsmOperandInfo &OpInfo = ConstraintOperands.back();
1336
1337 // Compute the value type for each operand.
1338 switch (OpInfo.Type) {
1339 case InlineAsm::isOutput:
1340 if (OpInfo.isIndirect)
1341 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
1342 break;
1343 case InlineAsm::isInput:
1344 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
1345 break;
1346 case InlineAsm::isClobber:
1347 // Nothing to do.
1348 break;
1349 }
1350
1351 // Compute the constraint code and ConstraintType to use.
Evan Chenga7e61462008-09-24 06:48:55 +00001352 TLI->ComputeConstraintToUse(OpInfo, SDValue(),
1353 OpInfo.ConstraintType == TargetLowering::C_Memory);
Evan Cheng9bf12b52008-02-26 02:42:37 +00001354
Eli Friedman9ec80952008-02-26 18:37:49 +00001355 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
1356 OpInfo.isIndirect) {
Evan Cheng9bf12b52008-02-26 02:42:37 +00001357 Value *OpVal = OpInfo.CallOperandVal;
Chris Lattner88a5c832008-11-25 07:09:13 +00001358 MadeChange |= OptimizeMemoryInst(I, OpVal, OpVal->getType(), SunkAddrs);
Evan Cheng9bf12b52008-02-26 02:42:37 +00001359 }
1360 }
1361
1362 return MadeChange;
1363}
1364
Evan Chengbdcb7262007-12-05 23:58:20 +00001365bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
1366 BasicBlock *DefBB = I->getParent();
1367
1368 // If both result of the {s|z}xt and its source are live out, rewrite all
1369 // other uses of the source with result of extension.
1370 Value *Src = I->getOperand(0);
1371 if (Src->hasOneUse())
1372 return false;
1373
Evan Cheng696e5c02007-12-13 07:50:36 +00001374 // Only do this xform if truncating is free.
Gabor Greif53bdbd72008-02-26 19:13:21 +00001375 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
Evan Chengf9785f92007-12-13 03:32:53 +00001376 return false;
1377
Evan Cheng772de512007-12-12 00:51:06 +00001378 // Only safe to perform the optimization if the source is also defined in
Evan Cheng765dff22007-12-12 02:53:41 +00001379 // this block.
1380 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
Evan Cheng772de512007-12-12 00:51:06 +00001381 return false;
1382
Evan Chengbdcb7262007-12-05 23:58:20 +00001383 bool DefIsLiveOut = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001384 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
Evan Chengbdcb7262007-12-05 23:58:20 +00001385 UI != E; ++UI) {
1386 Instruction *User = cast<Instruction>(*UI);
1387
1388 // Figure out which BB this ext is used in.
1389 BasicBlock *UserBB = User->getParent();
1390 if (UserBB == DefBB) continue;
1391 DefIsLiveOut = true;
1392 break;
1393 }
1394 if (!DefIsLiveOut)
1395 return false;
1396
Evan Cheng765dff22007-12-12 02:53:41 +00001397 // Make sure non of the uses are PHI nodes.
Eric Christopher692bf6b2008-09-24 05:32:41 +00001398 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
Evan Cheng765dff22007-12-12 02:53:41 +00001399 UI != E; ++UI) {
1400 Instruction *User = cast<Instruction>(*UI);
Evan Chengf9785f92007-12-13 03:32:53 +00001401 BasicBlock *UserBB = User->getParent();
1402 if (UserBB == DefBB) continue;
1403 // Be conservative. We don't want this xform to end up introducing
1404 // reloads just before load / store instructions.
1405 if (isa<PHINode>(User) || isa<LoadInst>(User) || isa<StoreInst>(User))
Evan Cheng765dff22007-12-12 02:53:41 +00001406 return false;
1407 }
1408
Evan Chengbdcb7262007-12-05 23:58:20 +00001409 // InsertedTruncs - Only insert one trunc in each block once.
1410 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
1411
1412 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001413 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
Evan Chengbdcb7262007-12-05 23:58:20 +00001414 UI != E; ++UI) {
1415 Use &TheUse = UI.getUse();
1416 Instruction *User = cast<Instruction>(*UI);
1417
1418 // Figure out which BB this ext is used in.
1419 BasicBlock *UserBB = User->getParent();
1420 if (UserBB == DefBB) continue;
1421
1422 // Both src and def are live in this block. Rewrite the use.
1423 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
1424
1425 if (!InsertedTrunc) {
Dan Gohman02dea8b2008-05-23 21:05:58 +00001426 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
Eric Christopher692bf6b2008-09-24 05:32:41 +00001427
Evan Chengbdcb7262007-12-05 23:58:20 +00001428 InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
1429 }
1430
1431 // Replace a use of the {s|z}ext source with a use of the result.
1432 TheUse = InsertedTrunc;
1433
1434 MadeChange = true;
1435 }
1436
1437 return MadeChange;
1438}
1439
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001440// In this pass we look for GEP and cast instructions that are used
1441// across basic blocks and rewrite them to improve basic-block-at-a-time
1442// selection.
1443bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
1444 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001445
Evan Chengab631522008-12-19 18:03:11 +00001446 // Split all critical edges where the dest block has a PHI.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001447 TerminatorInst *BBTI = BB.getTerminator();
1448 if (BBTI->getNumSuccessors() > 1) {
Evan Chengab631522008-12-19 18:03:11 +00001449 for (unsigned i = 0, e = BBTI->getNumSuccessors(); i != e; ++i) {
1450 BasicBlock *SuccBB = BBTI->getSuccessor(i);
1451 if (isa<PHINode>(SuccBB->begin()) && isCriticalEdge(BBTI, i, true))
1452 SplitEdgeNicely(BBTI, i, BackEdges, this);
1453 }
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001454 }
Eric Christopher692bf6b2008-09-24 05:32:41 +00001455
Chris Lattnerdd77df32007-04-13 20:30:56 +00001456 // Keep track of non-local addresses that have been sunk into this block.
1457 // This allows us to avoid inserting duplicate code for blocks with multiple
1458 // load/stores of the same address.
1459 DenseMap<Value*, Value*> SunkAddrs;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001460
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001461 for (BasicBlock::iterator BBI = BB.begin(), E = BB.end(); BBI != E; ) {
1462 Instruction *I = BBI++;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001463
Chris Lattnerdd77df32007-04-13 20:30:56 +00001464 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001465 // If the source of the cast is a constant, then this should have
1466 // already been constant folded. The only reason NOT to constant fold
1467 // it is if something (e.g. LSR) was careful to place the constant
1468 // evaluation in a block other than then one that uses it (e.g. to hoist
1469 // the address of globals out of a loop). If this is the case, we don't
1470 // want to forward-subst the cast.
1471 if (isa<Constant>(CI->getOperand(0)))
1472 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001473
Evan Chengbdcb7262007-12-05 23:58:20 +00001474 bool Change = false;
1475 if (TLI) {
1476 Change = OptimizeNoopCopyExpression(CI, *TLI);
1477 MadeChange |= Change;
1478 }
1479
Evan Cheng55e641b2008-03-19 22:02:26 +00001480 if (!Change && (isa<ZExtInst>(I) || isa<SExtInst>(I)))
Evan Chengbdcb7262007-12-05 23:58:20 +00001481 MadeChange |= OptimizeExtUses(I);
Dale Johannesence0b2372007-06-12 16:50:17 +00001482 } else if (CmpInst *CI = dyn_cast<CmpInst>(I)) {
1483 MadeChange |= OptimizeCmpExpression(CI);
Chris Lattnerdd77df32007-04-13 20:30:56 +00001484 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
1485 if (TLI)
Chris Lattner88a5c832008-11-25 07:09:13 +00001486 MadeChange |= OptimizeMemoryInst(I, I->getOperand(0), LI->getType(),
1487 SunkAddrs);
Chris Lattnerdd77df32007-04-13 20:30:56 +00001488 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
1489 if (TLI)
Chris Lattner88a5c832008-11-25 07:09:13 +00001490 MadeChange |= OptimizeMemoryInst(I, SI->getOperand(1),
1491 SI->getOperand(0)->getType(),
1492 SunkAddrs);
Chris Lattnerdd77df32007-04-13 20:30:56 +00001493 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Chris Lattnerf25646b2007-04-14 00:17:39 +00001494 if (GEPI->hasAllZeroIndices()) {
Chris Lattnerdd77df32007-04-13 20:30:56 +00001495 /// The GEP operand must be a pointer, so must its result -> BitCast
Eric Christopher692bf6b2008-09-24 05:32:41 +00001496 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
Chris Lattnerdd77df32007-04-13 20:30:56 +00001497 GEPI->getName(), GEPI);
1498 GEPI->replaceAllUsesWith(NC);
1499 GEPI->eraseFromParent();
1500 MadeChange = true;
1501 BBI = NC;
1502 }
1503 } else if (CallInst *CI = dyn_cast<CallInst>(I)) {
1504 // If we found an inline asm expession, and if the target knows how to
1505 // lower it to normal LLVM code, do so now.
1506 if (TLI && isa<InlineAsm>(CI->getCalledValue()))
Eric Christopher692bf6b2008-09-24 05:32:41 +00001507 if (const TargetAsmInfo *TAI =
Chris Lattnerdd77df32007-04-13 20:30:56 +00001508 TLI->getTargetMachine().getTargetAsmInfo()) {
1509 if (TAI->ExpandInlineAsm(CI))
1510 BBI = BB.begin();
Evan Cheng9bf12b52008-02-26 02:42:37 +00001511 else
1512 // Sink address computing for memory operands into the block.
1513 MadeChange |= OptimizeInlineAsmInst(I, &(*CI), SunkAddrs);
Chris Lattnerdd77df32007-04-13 20:30:56 +00001514 }
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001515 }
1516 }
Eric Christopher692bf6b2008-09-24 05:32:41 +00001517
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001518 return MadeChange;
1519}