blob: caf60c8c7af04ef5c18071484b241d09607c6471 [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()) {
Chris Lattner3c4f8b92008-11-27 07:54:12 +0000208 MergeBasicBlockIntoOnlyPred(DestBB);
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000209 DOUT << "AFTER:\n" << *DestBB << "\n\n\n";
210 return;
211 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000212
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000213 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
214 // to handle the new incoming edges it is about to have.
215 PHINode *PN;
216 for (BasicBlock::iterator BBI = DestBB->begin();
217 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
218 // Remove the incoming value for BB, and remember it.
219 Value *InVal = PN->removeIncomingValue(BB, false);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000220
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000221 // Two options: either the InVal is a phi node defined in BB or it is some
222 // value that dominates BB.
223 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
224 if (InValPhi && InValPhi->getParent() == BB) {
225 // Add all of the input values of the input PHI as inputs of this phi.
226 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
227 PN->addIncoming(InValPhi->getIncomingValue(i),
228 InValPhi->getIncomingBlock(i));
229 } else {
230 // Otherwise, add one instance of the dominating value for each edge that
231 // we will be adding.
232 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
233 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
234 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
235 } else {
236 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
237 PN->addIncoming(InVal, *PI);
238 }
239 }
240 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000241
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000242 // The PHIs are now updated, change everything that refers to BB to use
243 // DestBB and remove BB.
244 BB->replaceAllUsesWith(DestBB);
245 BB->eraseFromParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000246
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000247 DOUT << "AFTER:\n" << *DestBB << "\n\n\n";
248}
249
250
Chris Lattnerebe80752007-12-24 19:32:55 +0000251/// SplitEdgeNicely - Split the critical edge from TI to its specified
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000252/// successor if it will improve codegen. We only do this if the successor has
253/// phi nodes (otherwise critical edges are ok). If there is already another
254/// predecessor of the succ that is empty (and thus has no phi nodes), use it
255/// instead of introducing a new block.
256static void SplitEdgeNicely(TerminatorInst *TI, unsigned SuccNum, Pass *P) {
257 BasicBlock *TIBB = TI->getParent();
258 BasicBlock *Dest = TI->getSuccessor(SuccNum);
259 assert(isa<PHINode>(Dest->begin()) &&
260 "This should only be called if Dest has a PHI!");
Eric Christopher692bf6b2008-09-24 05:32:41 +0000261
Chris Lattnerebe80752007-12-24 19:32:55 +0000262 // As a hack, never split backedges of loops. Even though the copy for any
263 // PHIs inserted on the backedge would be dead for exits from the loop, we
264 // assume that the cost of *splitting* the backedge would be too high.
Chris Lattnerff26ab22007-12-25 19:06:45 +0000265 if (Dest == TIBB)
Chris Lattnerebe80752007-12-24 19:32:55 +0000266 return;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000267
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000268 /// TIPHIValues - This array is lazily computed to determine the values of
269 /// PHIs in Dest that TI would provide.
Chris Lattnerebe80752007-12-24 19:32:55 +0000270 SmallVector<Value*, 32> TIPHIValues;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000271
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000272 // Check to see if Dest has any blocks that can be used as a split edge for
273 // this terminator.
274 for (pred_iterator PI = pred_begin(Dest), E = pred_end(Dest); PI != E; ++PI) {
275 BasicBlock *Pred = *PI;
276 // To be usable, the pred has to end with an uncond branch to the dest.
277 BranchInst *PredBr = dyn_cast<BranchInst>(Pred->getTerminator());
278 if (!PredBr || !PredBr->isUnconditional() ||
279 // Must be empty other than the branch.
Dale Johannesen6603a1b2007-05-08 01:01:04 +0000280 &Pred->front() != PredBr ||
281 // Cannot be the entry block; its label does not get emitted.
282 Pred == &(Dest->getParent()->getEntryBlock()))
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000283 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000284
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000285 // Finally, since we know that Dest has phi nodes in it, we have to make
286 // sure that jumping to Pred will have the same affect as going to Dest in
287 // terms of PHI values.
288 PHINode *PN;
289 unsigned PHINo = 0;
290 bool FoundMatch = true;
291 for (BasicBlock::iterator I = Dest->begin();
292 (PN = dyn_cast<PHINode>(I)); ++I, ++PHINo) {
293 if (PHINo == TIPHIValues.size())
294 TIPHIValues.push_back(PN->getIncomingValueForBlock(TIBB));
Eric Christopher692bf6b2008-09-24 05:32:41 +0000295
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000296 // If the PHI entry doesn't work, we can't use this pred.
297 if (TIPHIValues[PHINo] != PN->getIncomingValueForBlock(Pred)) {
298 FoundMatch = false;
299 break;
300 }
301 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000302
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000303 // If we found a workable predecessor, change TI to branch to Succ.
304 if (FoundMatch) {
305 Dest->removePredecessor(TIBB);
306 TI->setSuccessor(SuccNum, Pred);
307 return;
308 }
309 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000310
311 SplitCriticalEdge(TI, SuccNum, P, true);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000312}
313
Chris Lattnerdd77df32007-04-13 20:30:56 +0000314/// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
315/// copy (e.g. it's casting from one pointer type to another, int->uint, or
316/// int->sbyte on PPC), sink it into user blocks to reduce the number of virtual
Dale Johannesence0b2372007-06-12 16:50:17 +0000317/// registers that must be created and coalesced.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000318///
319/// Return true if any changes are made.
Chris Lattner85fa13c2008-11-24 22:44:16 +0000320///
Chris Lattnerdd77df32007-04-13 20:30:56 +0000321static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
Eric Christopher692bf6b2008-09-24 05:32:41 +0000322 // If this is a noop copy,
Duncan Sands83ec4b62008-06-06 12:08:01 +0000323 MVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
324 MVT DstVT = TLI.getValueType(CI->getType());
Eric Christopher692bf6b2008-09-24 05:32:41 +0000325
Chris Lattnerdd77df32007-04-13 20:30:56 +0000326 // This is an fp<->int conversion?
Duncan Sands83ec4b62008-06-06 12:08:01 +0000327 if (SrcVT.isInteger() != DstVT.isInteger())
Chris Lattnerdd77df32007-04-13 20:30:56 +0000328 return false;
Duncan Sands8e4eb092008-06-08 20:54:56 +0000329
Chris Lattnerdd77df32007-04-13 20:30:56 +0000330 // If this is an extension, it will be a zero or sign extension, which
331 // isn't a noop.
Duncan Sands8e4eb092008-06-08 20:54:56 +0000332 if (SrcVT.bitsLT(DstVT)) return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000333
Chris Lattnerdd77df32007-04-13 20:30:56 +0000334 // If these values will be promoted, find out what they will be promoted
335 // to. This helps us consider truncates on PPC as noop copies when they
336 // are.
337 if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote)
338 SrcVT = TLI.getTypeToTransformTo(SrcVT);
339 if (TLI.getTypeAction(DstVT) == TargetLowering::Promote)
340 DstVT = TLI.getTypeToTransformTo(DstVT);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000341
Chris Lattnerdd77df32007-04-13 20:30:56 +0000342 // If, after promotion, these are the same types, this is a noop copy.
343 if (SrcVT != DstVT)
344 return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000345
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000346 BasicBlock *DefBB = CI->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000347
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000348 /// InsertedCasts - Only insert a cast in each block once.
Dale Johannesence0b2372007-06-12 16:50:17 +0000349 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000350
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000351 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000352 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000353 UI != E; ) {
354 Use &TheUse = UI.getUse();
355 Instruction *User = cast<Instruction>(*UI);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000356
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000357 // Figure out which BB this cast is used in. For PHI's this is the
358 // appropriate predecessor block.
359 BasicBlock *UserBB = User->getParent();
360 if (PHINode *PN = dyn_cast<PHINode>(User)) {
361 unsigned OpVal = UI.getOperandNo()/2;
362 UserBB = PN->getIncomingBlock(OpVal);
363 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000364
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000365 // Preincrement use iterator so we don't invalidate it.
366 ++UI;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000367
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000368 // If this user is in the same block as the cast, don't change the cast.
369 if (UserBB == DefBB) continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000370
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000371 // If we have already inserted a cast into this block, use it.
372 CastInst *&InsertedCast = InsertedCasts[UserBB];
373
374 if (!InsertedCast) {
Dan Gohman02dea8b2008-05-23 21:05:58 +0000375 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000376
377 InsertedCast =
378 CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000379 InsertPt);
380 MadeChange = true;
381 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000382
Dale Johannesence0b2372007-06-12 16:50:17 +0000383 // Replace a use of the cast with a use of the new cast.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000384 TheUse = InsertedCast;
385 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000386
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000387 // If we removed all uses, nuke the cast.
Duncan Sandse0038132008-01-20 16:51:46 +0000388 if (CI->use_empty()) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000389 CI->eraseFromParent();
Duncan Sandse0038132008-01-20 16:51:46 +0000390 MadeChange = true;
391 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000392
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000393 return MadeChange;
394}
395
Eric Christopher692bf6b2008-09-24 05:32:41 +0000396/// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
Dale Johannesence0b2372007-06-12 16:50:17 +0000397/// the number of virtual registers that must be created and coalesced. This is
Chris Lattner684b22d2007-08-02 16:53:43 +0000398/// a clear win except on targets with multiple condition code registers
399/// (PowerPC), where it might lose; some adjustment may be wanted there.
Dale Johannesence0b2372007-06-12 16:50:17 +0000400///
401/// Return true if any changes are made.
Chris Lattner85fa13c2008-11-24 22:44:16 +0000402static bool OptimizeCmpExpression(CmpInst *CI) {
Dale Johannesence0b2372007-06-12 16:50:17 +0000403 BasicBlock *DefBB = CI->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000404
Dale Johannesence0b2372007-06-12 16:50:17 +0000405 /// InsertedCmp - Only insert a cmp in each block once.
406 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000407
Dale Johannesence0b2372007-06-12 16:50:17 +0000408 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000409 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
Dale Johannesence0b2372007-06-12 16:50:17 +0000410 UI != E; ) {
411 Use &TheUse = UI.getUse();
412 Instruction *User = cast<Instruction>(*UI);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000413
Dale Johannesence0b2372007-06-12 16:50:17 +0000414 // Preincrement use iterator so we don't invalidate it.
415 ++UI;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000416
Dale Johannesence0b2372007-06-12 16:50:17 +0000417 // Don't bother for PHI nodes.
418 if (isa<PHINode>(User))
419 continue;
420
421 // Figure out which BB this cmp is used in.
422 BasicBlock *UserBB = User->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000423
Dale Johannesence0b2372007-06-12 16:50:17 +0000424 // If this user is in the same block as the cmp, don't change the cmp.
425 if (UserBB == DefBB) continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000426
Dale Johannesence0b2372007-06-12 16:50:17 +0000427 // If we have already inserted a cmp into this block, use it.
428 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
429
430 if (!InsertedCmp) {
Dan Gohman02dea8b2008-05-23 21:05:58 +0000431 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000432
433 InsertedCmp =
434 CmpInst::Create(CI->getOpcode(), CI->getPredicate(), CI->getOperand(0),
Dale Johannesence0b2372007-06-12 16:50:17 +0000435 CI->getOperand(1), "", InsertPt);
436 MadeChange = true;
437 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000438
Dale Johannesence0b2372007-06-12 16:50:17 +0000439 // Replace a use of the cmp with a use of the new cmp.
440 TheUse = InsertedCmp;
441 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000442
Dale Johannesence0b2372007-06-12 16:50:17 +0000443 // If we removed all uses, nuke the cmp.
444 if (CI->use_empty())
445 CI->eraseFromParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000446
Dale Johannesence0b2372007-06-12 16:50:17 +0000447 return MadeChange;
448}
449
Chris Lattner85fa13c2008-11-24 22:44:16 +0000450/// EraseDeadInstructions - Erase any dead instructions, recursively.
Chris Lattnerdd77df32007-04-13 20:30:56 +0000451static void EraseDeadInstructions(Value *V) {
452 Instruction *I = dyn_cast<Instruction>(V);
453 if (!I || !I->use_empty()) return;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000454
Chris Lattnerdd77df32007-04-13 20:30:56 +0000455 SmallPtrSet<Instruction*, 16> Insts;
456 Insts.insert(I);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000457
Chris Lattnerdd77df32007-04-13 20:30:56 +0000458 while (!Insts.empty()) {
459 I = *Insts.begin();
460 Insts.erase(I);
461 if (isInstructionTriviallyDead(I)) {
462 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
463 if (Instruction *U = dyn_cast<Instruction>(I->getOperand(i)))
464 Insts.insert(U);
465 I->eraseFromParent();
466 }
467 }
468}
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000469
Chris Lattner88a5c832008-11-25 07:09:13 +0000470//===----------------------------------------------------------------------===//
471// Addressing Mode Analysis and Optimization
472//===----------------------------------------------------------------------===//
473
Dan Gohman844731a2008-05-13 00:00:25 +0000474namespace {
Chris Lattner4744d852008-11-24 22:40:05 +0000475 /// ExtAddrMode - This is an extended version of TargetLowering::AddrMode
476 /// which holds actual Value*'s for register values.
477 struct ExtAddrMode : public TargetLowering::AddrMode {
478 Value *BaseReg;
479 Value *ScaledReg;
480 ExtAddrMode() : BaseReg(0), ScaledReg(0) {}
481 void print(OStream &OS) const;
482 void dump() const {
483 print(cerr);
484 cerr << '\n';
485 }
486 };
487} // end anonymous namespace
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000488
Chris Lattner5eecb7f2008-11-26 02:00:14 +0000489static inline OStream &operator<<(OStream &OS, const ExtAddrMode &AM) {
Chris Lattner4744d852008-11-24 22:40:05 +0000490 AM.print(OS);
491 return OS;
492}
Chris Lattnerdd77df32007-04-13 20:30:56 +0000493
Chris Lattner4744d852008-11-24 22:40:05 +0000494void ExtAddrMode::print(OStream &OS) const {
Chris Lattnerdd77df32007-04-13 20:30:56 +0000495 bool NeedPlus = false;
496 OS << "[";
Chris Lattner4744d852008-11-24 22:40:05 +0000497 if (BaseGV)
Chris Lattnerdd77df32007-04-13 20:30:56 +0000498 OS << (NeedPlus ? " + " : "")
Chris Lattner4744d852008-11-24 22:40:05 +0000499 << "GV:%" << BaseGV->getName(), NeedPlus = true;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000500
Chris Lattner4744d852008-11-24 22:40:05 +0000501 if (BaseOffs)
502 OS << (NeedPlus ? " + " : "") << BaseOffs, NeedPlus = true;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000503
Chris Lattner4744d852008-11-24 22:40:05 +0000504 if (BaseReg)
Chris Lattnerdd77df32007-04-13 20:30:56 +0000505 OS << (NeedPlus ? " + " : "")
Chris Lattner4744d852008-11-24 22:40:05 +0000506 << "Base:%" << BaseReg->getName(), NeedPlus = true;
507 if (Scale)
Chris Lattnerdd77df32007-04-13 20:30:56 +0000508 OS << (NeedPlus ? " + " : "")
Chris Lattner4744d852008-11-24 22:40:05 +0000509 << Scale << "*%" << ScaledReg->getName(), NeedPlus = true;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000510
Chris Lattner4744d852008-11-24 22:40:05 +0000511 OS << ']';
Dan Gohman844731a2008-05-13 00:00:25 +0000512}
513
Chris Lattner88a5c832008-11-25 07:09:13 +0000514namespace {
515/// AddressingModeMatcher - This class exposes a single public method, which is
516/// used to construct a "maximal munch" of the addressing mode for the target
517/// specified by TLI for an access to "V" with an access type of AccessTy. This
518/// returns the addressing mode that is actually matched by value, but also
519/// returns the list of instructions involved in that addressing computation in
520/// AddrModeInsts.
521class AddressingModeMatcher {
522 SmallVectorImpl<Instruction*> &AddrModeInsts;
523 const TargetLowering &TLI;
Chris Lattner896617b2008-11-26 03:20:37 +0000524
525 /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
526 /// the memory instruction that we're computing this address for.
Chris Lattner88a5c832008-11-25 07:09:13 +0000527 const Type *AccessTy;
Chris Lattner896617b2008-11-26 03:20:37 +0000528 Instruction *MemoryInst;
529
530 /// AddrMode - This is the addressing mode that we're building up. This is
531 /// part of the return value of this addressing mode matching stuff.
Chris Lattner88a5c832008-11-25 07:09:13 +0000532 ExtAddrMode &AddrMode;
Chris Lattner5eecb7f2008-11-26 02:00:14 +0000533
534 /// IgnoreProfitability - This is set to true when we should not do
535 /// profitability checks. When true, IsProfitableToFoldIntoAddressingMode
536 /// always returns true.
537 bool IgnoreProfitability;
538
Chris Lattner88a5c832008-11-25 07:09:13 +0000539 AddressingModeMatcher(SmallVectorImpl<Instruction*> &AMI,
Chris Lattner896617b2008-11-26 03:20:37 +0000540 const TargetLowering &T, const Type *AT,
541 Instruction *MI, ExtAddrMode &AM)
542 : AddrModeInsts(AMI), TLI(T), AccessTy(AT), MemoryInst(MI), AddrMode(AM) {
Chris Lattner5eecb7f2008-11-26 02:00:14 +0000543 IgnoreProfitability = false;
544 }
Chris Lattner88a5c832008-11-25 07:09:13 +0000545public:
546
Chris Lattner5eecb7f2008-11-26 02:00:14 +0000547 /// Match - Find the maximal addressing mode that a load/store of V can fold,
548 /// give an access type of AccessTy. This returns a list of involved
549 /// instructions in AddrModeInsts.
Chris Lattner896617b2008-11-26 03:20:37 +0000550 static ExtAddrMode Match(Value *V, const Type *AccessTy,
551 Instruction *MemoryInst,
Chris Lattner88a5c832008-11-25 07:09:13 +0000552 SmallVectorImpl<Instruction*> &AddrModeInsts,
553 const TargetLowering &TLI) {
554 ExtAddrMode Result;
555
556 bool Success =
Chris Lattner896617b2008-11-26 03:20:37 +0000557 AddressingModeMatcher(AddrModeInsts, TLI, AccessTy,
558 MemoryInst, Result).MatchAddr(V, 0);
Chris Lattner88a5c832008-11-25 07:09:13 +0000559 Success = Success; assert(Success && "Couldn't select *anything*?");
560 return Result;
561 }
562private:
Chris Lattner3b485012008-11-25 07:25:26 +0000563 bool MatchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
Chris Lattner88a5c832008-11-25 07:09:13 +0000564 bool MatchAddr(Value *V, unsigned Depth);
565 bool MatchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth);
Chris Lattner84d1b402008-11-26 03:02:41 +0000566 bool IsProfitableToFoldIntoAddressingMode(Instruction *I,
567 ExtAddrMode &AMBefore,
568 ExtAddrMode &AMAfter);
569 bool ValueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
Chris Lattner88a5c832008-11-25 07:09:13 +0000570};
571} // end anonymous namespace
572
573/// MatchScaledValue - Try adding ScaleReg*Scale to the current addressing mode.
574/// Return true and update AddrMode if this addr mode is legal for the target,
Chris Lattner85fa13c2008-11-24 22:44:16 +0000575/// false if not.
Chris Lattner3b485012008-11-25 07:25:26 +0000576bool AddressingModeMatcher::MatchScaledValue(Value *ScaleReg, int64_t Scale,
577 unsigned Depth) {
578 // If Scale is 1, then this is the same as adding ScaleReg to the addressing
579 // mode. Just process that directly.
580 if (Scale == 1)
581 return MatchAddr(ScaleReg, Depth);
582
583 // If the scale is 0, it takes nothing to add this.
584 if (Scale == 0)
585 return true;
586
Chris Lattner85fa13c2008-11-24 22:44:16 +0000587 // If we already have a scale of this value, we can add to it, otherwise, we
588 // need an available scale field.
589 if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
590 return false;
591
Chris Lattner088a1e82008-11-25 04:42:10 +0000592 ExtAddrMode TestAddrMode = AddrMode;
Chris Lattner85fa13c2008-11-24 22:44:16 +0000593
594 // Add scale to turn X*4+X*3 -> X*7. This could also do things like
595 // [A+B + A*7] -> [B+A*8].
Chris Lattner088a1e82008-11-25 04:42:10 +0000596 TestAddrMode.Scale += Scale;
597 TestAddrMode.ScaledReg = ScaleReg;
Chris Lattner85fa13c2008-11-24 22:44:16 +0000598
Chris Lattner088a1e82008-11-25 04:42:10 +0000599 // If the new address isn't legal, bail out.
600 if (!TLI.isLegalAddressingMode(TestAddrMode, AccessTy))
601 return false;
Chris Lattner85fa13c2008-11-24 22:44:16 +0000602
Chris Lattner088a1e82008-11-25 04:42:10 +0000603 // It was legal, so commit it.
604 AddrMode = TestAddrMode;
605
606 // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
607 // to see if ScaleReg is actually X+C. If so, we can turn this into adding
608 // X*Scale + C*Scale to addr mode.
609 ConstantInt *CI; Value *AddLHS;
610 if (match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
611 TestAddrMode.ScaledReg = AddLHS;
612 TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
613
614 // If this addressing mode is legal, commit it and remember that we folded
615 // this instruction.
616 if (TLI.isLegalAddressingMode(TestAddrMode, AccessTy)) {
617 AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
618 AddrMode = TestAddrMode;
Chris Lattner88a5c832008-11-25 07:09:13 +0000619 return true;
Chris Lattner85fa13c2008-11-24 22:44:16 +0000620 }
Chris Lattner85fa13c2008-11-24 22:44:16 +0000621 }
622
Chris Lattner088a1e82008-11-25 04:42:10 +0000623 // Otherwise, not (x+c)*scale, just return what we have.
624 return true;
Chris Lattner85fa13c2008-11-24 22:44:16 +0000625}
626
Chris Lattner5eecb7f2008-11-26 02:00:14 +0000627/// MightBeFoldableInst - This is a little filter, which returns true if an
628/// addressing computation involving I might be folded into a load/store
629/// accessing it. This doesn't need to be perfect, but needs to accept at least
630/// the set of instructions that MatchOperationAddr can.
631static bool MightBeFoldableInst(Instruction *I) {
632 switch (I->getOpcode()) {
633 case Instruction::BitCast:
634 // Don't touch identity bitcasts.
635 if (I->getType() == I->getOperand(0)->getType())
636 return false;
637 return isa<PointerType>(I->getType()) || isa<IntegerType>(I->getType());
638 case Instruction::PtrToInt:
639 // PtrToInt is always a noop, as we know that the int type is pointer sized.
640 return true;
641 case Instruction::IntToPtr:
642 // We know the input is intptr_t, so this is foldable.
643 return true;
644 case Instruction::Add:
645 return true;
646 case Instruction::Mul:
647 case Instruction::Shl:
648 // Can only handle X*C and X << C.
649 return isa<ConstantInt>(I->getOperand(1));
650 case Instruction::GetElementPtr:
651 return true;
652 default:
653 return false;
654 }
655}
656
Chris Lattnerbb3204a2008-11-25 05:15:49 +0000657
Chris Lattner88a5c832008-11-25 07:09:13 +0000658/// MatchOperationAddr - Given an instruction or constant expr, see if we can
659/// fold the operation into the addressing mode. If so, update the addressing
660/// mode and return true, otherwise return false without modifying AddrMode.
661bool AddressingModeMatcher::MatchOperationAddr(User *AddrInst, unsigned Opcode,
662 unsigned Depth) {
663 // Avoid exponential behavior on extremely deep expression trees.
664 if (Depth >= 5) return false;
665
Chris Lattnerdd77df32007-04-13 20:30:56 +0000666 switch (Opcode) {
667 case Instruction::PtrToInt:
668 // PtrToInt is always a noop, as we know that the int type is pointer sized.
Chris Lattner88a5c832008-11-25 07:09:13 +0000669 return MatchAddr(AddrInst->getOperand(0), Depth);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000670 case Instruction::IntToPtr:
671 // This inttoptr is a no-op if the integer type is pointer sized.
672 if (TLI.getValueType(AddrInst->getOperand(0)->getType()) ==
Chris Lattner88a5c832008-11-25 07:09:13 +0000673 TLI.getPointerTy())
674 return MatchAddr(AddrInst->getOperand(0), Depth);
675 return false;
Chris Lattner2efbbb32008-11-26 00:26:16 +0000676 case Instruction::BitCast:
677 // BitCast is always a noop, and we can handle it as long as it is
678 // int->int or pointer->pointer (we don't want int<->fp or something).
679 if ((isa<PointerType>(AddrInst->getOperand(0)->getType()) ||
680 isa<IntegerType>(AddrInst->getOperand(0)->getType())) &&
681 // Don't touch identity bitcasts. These were probably put here by LSR,
682 // and we don't want to mess around with them. Assume it knows what it
683 // is doing.
684 AddrInst->getOperand(0)->getType() != AddrInst->getType())
685 return MatchAddr(AddrInst->getOperand(0), Depth);
686 return false;
Chris Lattnerdd77df32007-04-13 20:30:56 +0000687 case Instruction::Add: {
688 // Check to see if we can merge in the RHS then the LHS. If so, we win.
689 ExtAddrMode BackupAddrMode = AddrMode;
690 unsigned OldSize = AddrModeInsts.size();
Chris Lattner88a5c832008-11-25 07:09:13 +0000691 if (MatchAddr(AddrInst->getOperand(1), Depth+1) &&
692 MatchAddr(AddrInst->getOperand(0), Depth+1))
Chris Lattnerdd77df32007-04-13 20:30:56 +0000693 return true;
Chris Lattnerbb3204a2008-11-25 05:15:49 +0000694
Chris Lattnerdd77df32007-04-13 20:30:56 +0000695 // Restore the old addr mode info.
696 AddrMode = BackupAddrMode;
697 AddrModeInsts.resize(OldSize);
Chris Lattnerbb3204a2008-11-25 05:15:49 +0000698
Chris Lattnerdd77df32007-04-13 20:30:56 +0000699 // Otherwise this was over-aggressive. Try merging in the LHS then the RHS.
Chris Lattner88a5c832008-11-25 07:09:13 +0000700 if (MatchAddr(AddrInst->getOperand(0), Depth+1) &&
701 MatchAddr(AddrInst->getOperand(1), Depth+1))
Chris Lattnerdd77df32007-04-13 20:30:56 +0000702 return true;
Chris Lattnerbb3204a2008-11-25 05:15:49 +0000703
Chris Lattnerdd77df32007-04-13 20:30:56 +0000704 // Otherwise we definitely can't merge the ADD in.
705 AddrMode = BackupAddrMode;
706 AddrModeInsts.resize(OldSize);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000707 break;
Chris Lattnerdd77df32007-04-13 20:30:56 +0000708 }
Chris Lattner5eecb7f2008-11-26 02:00:14 +0000709 //case Instruction::Or:
710 // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
711 //break;
Chris Lattnerdd77df32007-04-13 20:30:56 +0000712 case Instruction::Mul:
713 case Instruction::Shl: {
Chris Lattner7ad1c732008-11-25 04:47:41 +0000714 // Can only handle X*C and X << C.
Chris Lattnerdd77df32007-04-13 20:30:56 +0000715 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
Chris Lattner88a5c832008-11-25 07:09:13 +0000716 if (!RHS) return false;
Chris Lattnerdd77df32007-04-13 20:30:56 +0000717 int64_t Scale = RHS->getSExtValue();
718 if (Opcode == Instruction::Shl)
719 Scale = 1 << Scale;
Chris Lattnerbb3204a2008-11-25 05:15:49 +0000720
Chris Lattner3b485012008-11-25 07:25:26 +0000721 return MatchScaledValue(AddrInst->getOperand(0), Scale, Depth);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000722 }
723 case Instruction::GetElementPtr: {
724 // Scan the GEP. We check it if it contains constant offsets and at most
725 // one variable offset.
726 int VariableOperand = -1;
727 unsigned VariableScale = 0;
Chris Lattnerbb3204a2008-11-25 05:15:49 +0000728
Chris Lattnerdd77df32007-04-13 20:30:56 +0000729 int64_t ConstantOffset = 0;
730 const TargetData *TD = TLI.getTargetData();
731 gep_type_iterator GTI = gep_type_begin(AddrInst);
732 for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
733 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
734 const StructLayout *SL = TD->getStructLayout(STy);
735 unsigned Idx =
Chris Lattner88a5c832008-11-25 07:09:13 +0000736 cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
Chris Lattnerdd77df32007-04-13 20:30:56 +0000737 ConstantOffset += SL->getElementOffset(Idx);
738 } else {
Duncan Sands514ab342007-11-01 20:53:16 +0000739 uint64_t TypeSize = TD->getABITypeSize(GTI.getIndexedType());
Chris Lattnerdd77df32007-04-13 20:30:56 +0000740 if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
741 ConstantOffset += CI->getSExtValue()*TypeSize;
742 } else if (TypeSize) { // Scales of zero don't do anything.
743 // We only allow one variable index at the moment.
Chris Lattner88a5c832008-11-25 07:09:13 +0000744 if (VariableOperand != -1)
745 return false;
Chris Lattnerbb3204a2008-11-25 05:15:49 +0000746
Chris Lattnerdd77df32007-04-13 20:30:56 +0000747 // Remember the variable index.
748 VariableOperand = i;
749 VariableScale = TypeSize;
750 }
751 }
752 }
Chris Lattnerbb3204a2008-11-25 05:15:49 +0000753
Chris Lattnerdd77df32007-04-13 20:30:56 +0000754 // A common case is for the GEP to only do a constant offset. In this case,
755 // just add it to the disp field and check validity.
756 if (VariableOperand == -1) {
757 AddrMode.BaseOffs += ConstantOffset;
758 if (ConstantOffset == 0 || TLI.isLegalAddressingMode(AddrMode, AccessTy)){
759 // Check to see if we can fold the base pointer in too.
Chris Lattner88a5c832008-11-25 07:09:13 +0000760 if (MatchAddr(AddrInst->getOperand(0), Depth+1))
Chris Lattnerdd77df32007-04-13 20:30:56 +0000761 return true;
762 }
763 AddrMode.BaseOffs -= ConstantOffset;
Chris Lattner88a5c832008-11-25 07:09:13 +0000764 return false;
Chris Lattnerdd77df32007-04-13 20:30:56 +0000765 }
Chris Lattner88a5c832008-11-25 07:09:13 +0000766
767 // Save the valid addressing mode in case we can't match.
768 ExtAddrMode BackupAddrMode = AddrMode;
769
770 // Check that this has no base reg yet. If so, we won't have a place to
771 // put the base of the GEP (assuming it is not a null ptr).
772 bool SetBaseReg = true;
773 if (isa<ConstantPointerNull>(AddrInst->getOperand(0)))
774 SetBaseReg = false; // null pointer base doesn't need representation.
775 else if (AddrMode.HasBaseReg)
776 return false; // Base register already specified, can't match GEP.
777 else {
778 // Otherwise, we'll use the GEP base as the BaseReg.
779 AddrMode.HasBaseReg = true;
780 AddrMode.BaseReg = AddrInst->getOperand(0);
781 }
782
783 // See if the scale and offset amount is valid for this target.
784 AddrMode.BaseOffs += ConstantOffset;
785
Chris Lattner3b485012008-11-25 07:25:26 +0000786 if (!MatchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
787 Depth)) {
Chris Lattner88a5c832008-11-25 07:09:13 +0000788 AddrMode = BackupAddrMode;
789 return false;
790 }
791
792 // If we have a null as the base of the GEP, folding in the constant offset
793 // plus variable scale is all we can do.
794 if (!SetBaseReg) return true;
795
796 // If this match succeeded, we know that we can form an address with the
797 // GepBase as the basereg. Match the base pointer of the GEP more
798 // aggressively by zeroing out BaseReg and rematching. If the base is
799 // (for example) another GEP, this allows merging in that other GEP into
800 // the addressing mode we're forming.
801 AddrMode.HasBaseReg = false;
802 AddrMode.BaseReg = 0;
803 bool Success = MatchAddr(AddrInst->getOperand(0), Depth+1);
804 assert(Success && "MatchAddr should be able to fill in BaseReg!");
805 Success=Success;
806 return true;
Chris Lattnerdd77df32007-04-13 20:30:56 +0000807 }
808 }
Chris Lattnerbb3204a2008-11-25 05:15:49 +0000809 return false;
810}
Eric Christopher692bf6b2008-09-24 05:32:41 +0000811
Chris Lattner88a5c832008-11-25 07:09:13 +0000812/// MatchAddr - If we can, try to add the value of 'Addr' into the current
813/// addressing mode. If Addr can't be added to AddrMode this returns false and
814/// leaves AddrMode unmodified. This assumes that Addr is either a pointer type
815/// or intptr_t for the target.
Chris Lattnerbb3204a2008-11-25 05:15:49 +0000816///
Chris Lattner88a5c832008-11-25 07:09:13 +0000817bool AddressingModeMatcher::MatchAddr(Value *Addr, unsigned Depth) {
Chris Lattnerbb3204a2008-11-25 05:15:49 +0000818 if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
819 // Fold in immediates if legal for the target.
820 AddrMode.BaseOffs += CI->getSExtValue();
821 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
822 return true;
823 AddrMode.BaseOffs -= CI->getSExtValue();
824 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
Chris Lattner88a5c832008-11-25 07:09:13 +0000825 // If this is a global variable, try to fold it into the addressing mode.
Chris Lattnerbb3204a2008-11-25 05:15:49 +0000826 if (AddrMode.BaseGV == 0) {
827 AddrMode.BaseGV = GV;
828 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
829 return true;
830 AddrMode.BaseGV = 0;
831 }
832 } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
Chris Lattner5eecb7f2008-11-26 02:00:14 +0000833 ExtAddrMode BackupAddrMode = AddrMode;
834 unsigned OldSize = AddrModeInsts.size();
835
836 // Check to see if it is possible to fold this operation.
Chris Lattner88a5c832008-11-25 07:09:13 +0000837 if (MatchOperationAddr(I, I->getOpcode(), Depth)) {
Chris Lattner5eecb7f2008-11-26 02:00:14 +0000838 // Okay, it's possible to fold this. Check to see if it is actually
839 // *profitable* to do so. We use a simple cost model to avoid increasing
840 // register pressure too much.
Chris Lattner84d1b402008-11-26 03:02:41 +0000841 if (I->hasOneUse() ||
842 IsProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
Chris Lattner5eecb7f2008-11-26 02:00:14 +0000843 AddrModeInsts.push_back(I);
844 return true;
845 }
846
847 // It isn't profitable to do this, roll back.
848 //cerr << "NOT FOLDING: " << *I;
849 AddrMode = BackupAddrMode;
850 AddrModeInsts.resize(OldSize);
Chris Lattnerbb3204a2008-11-25 05:15:49 +0000851 }
852 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
Chris Lattner88a5c832008-11-25 07:09:13 +0000853 if (MatchOperationAddr(CE, CE->getOpcode(), Depth))
Chris Lattnerbb3204a2008-11-25 05:15:49 +0000854 return true;
855 } else if (isa<ConstantPointerNull>(Addr)) {
Chris Lattner88a5c832008-11-25 07:09:13 +0000856 // Null pointer gets folded without affecting the addressing mode.
Chris Lattnerbb3204a2008-11-25 05:15:49 +0000857 return true;
Chris Lattnerdd77df32007-04-13 20:30:56 +0000858 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000859
Chris Lattnerdd77df32007-04-13 20:30:56 +0000860 // Worse case, the target should support [reg] addressing modes. :)
861 if (!AddrMode.HasBaseReg) {
862 AddrMode.HasBaseReg = true;
Chris Lattner653b2582008-11-26 02:11:11 +0000863 AddrMode.BaseReg = Addr;
Chris Lattnerdd77df32007-04-13 20:30:56 +0000864 // Still check for legality in case the target supports [imm] but not [i+r].
Chris Lattner653b2582008-11-26 02:11:11 +0000865 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
Chris Lattnerdd77df32007-04-13 20:30:56 +0000866 return true;
Chris Lattnerdd77df32007-04-13 20:30:56 +0000867 AddrMode.HasBaseReg = false;
Chris Lattner653b2582008-11-26 02:11:11 +0000868 AddrMode.BaseReg = 0;
Chris Lattnerdd77df32007-04-13 20:30:56 +0000869 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000870
Chris Lattnerdd77df32007-04-13 20:30:56 +0000871 // If the base register is already taken, see if we can do [r+r].
872 if (AddrMode.Scale == 0) {
873 AddrMode.Scale = 1;
Chris Lattner653b2582008-11-26 02:11:11 +0000874 AddrMode.ScaledReg = Addr;
875 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
Chris Lattnerdd77df32007-04-13 20:30:56 +0000876 return true;
Chris Lattnerdd77df32007-04-13 20:30:56 +0000877 AddrMode.Scale = 0;
Chris Lattner653b2582008-11-26 02:11:11 +0000878 AddrMode.ScaledReg = 0;
Chris Lattnerdd77df32007-04-13 20:30:56 +0000879 }
880 // Couldn't match.
881 return false;
882}
883
Chris Lattner695d8ec2008-11-26 04:59:11 +0000884
885/// IsOperandAMemoryOperand - Check to see if all uses of OpVal by the specified
886/// inline asm call are due to memory operands. If so, return true, otherwise
887/// return false.
888static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
889 const TargetLowering &TLI) {
890 std::vector<InlineAsm::ConstraintInfo>
891 Constraints = IA->ParseConstraints();
892
893 unsigned ArgNo = 1; // ArgNo - The operand of the CallInst.
894 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
895 TargetLowering::AsmOperandInfo OpInfo(Constraints[i]);
896
897 // Compute the value type for each operand.
898 switch (OpInfo.Type) {
899 case InlineAsm::isOutput:
900 if (OpInfo.isIndirect)
901 OpInfo.CallOperandVal = CI->getOperand(ArgNo++);
902 break;
903 case InlineAsm::isInput:
904 OpInfo.CallOperandVal = CI->getOperand(ArgNo++);
905 break;
906 case InlineAsm::isClobber:
907 // Nothing to do.
908 break;
909 }
910
911 // Compute the constraint code and ConstraintType to use.
912 TLI.ComputeConstraintToUse(OpInfo, SDValue(),
913 OpInfo.ConstraintType == TargetLowering::C_Memory);
914
915 // If this asm operand is our Value*, and if it isn't an indirect memory
916 // operand, we can't fold it!
917 if (OpInfo.CallOperandVal == OpVal &&
918 (OpInfo.ConstraintType != TargetLowering::C_Memory ||
919 !OpInfo.isIndirect))
920 return false;
921 }
922
923 return true;
924}
925
926
Chris Lattner5eecb7f2008-11-26 02:00:14 +0000927/// FindAllMemoryUses - Recursively walk all the uses of I until we find a
928/// memory use. If we find an obviously non-foldable instruction, return true.
929/// Add the ultimately found memory instructions to MemoryUses.
930static bool FindAllMemoryUses(Instruction *I,
931 SmallVectorImpl<std::pair<Instruction*,unsigned> > &MemoryUses,
Chris Lattner695d8ec2008-11-26 04:59:11 +0000932 SmallPtrSet<Instruction*, 16> &ConsideredInsts,
933 const TargetLowering &TLI) {
Chris Lattner5eecb7f2008-11-26 02:00:14 +0000934 // If we already considered this instruction, we're done.
935 if (!ConsideredInsts.insert(I))
936 return false;
937
938 // If this is an obviously unfoldable instruction, bail out.
939 if (!MightBeFoldableInst(I))
940 return true;
941
942 // Loop over all the uses, recursively processing them.
943 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
944 UI != E; ++UI) {
945 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
946 MemoryUses.push_back(std::make_pair(LI, UI.getOperandNo()));
947 continue;
948 }
949
950 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
951 if (UI.getOperandNo() == 0) return true; // Storing addr, not into addr.
952 MemoryUses.push_back(std::make_pair(SI, UI.getOperandNo()));
953 continue;
954 }
955
956 if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
957 InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
958 if (IA == 0) return true;
Chris Lattner5eecb7f2008-11-26 02:00:14 +0000959
Chris Lattner695d8ec2008-11-26 04:59:11 +0000960 // If this is a memory operand, we're cool, otherwise bail out.
961 if (!IsOperandAMemoryOperand(CI, IA, I, TLI))
962 return true;
963 continue;
Chris Lattner5eecb7f2008-11-26 02:00:14 +0000964 }
965
Chris Lattner695d8ec2008-11-26 04:59:11 +0000966 if (FindAllMemoryUses(cast<Instruction>(*UI), MemoryUses, ConsideredInsts,
967 TLI))
Chris Lattner5eecb7f2008-11-26 02:00:14 +0000968 return true;
969 }
970
971 return false;
972}
Chris Lattner84d1b402008-11-26 03:02:41 +0000973
974
975/// ValueAlreadyLiveAtInst - Retrn true if Val is already known to be live at
976/// the use site that we're folding it into. If so, there is no cost to
977/// include it in the addressing mode. KnownLive1 and KnownLive2 are two values
978/// that we know are live at the instruction already.
979bool AddressingModeMatcher::ValueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
980 Value *KnownLive2) {
981 // If Val is either of the known-live values, we know it is live!
982 if (Val == 0 || Val == KnownLive1 || Val == KnownLive2)
983 return true;
Chris Lattner5eecb7f2008-11-26 02:00:14 +0000984
Chris Lattner896617b2008-11-26 03:20:37 +0000985 // All values other than instructions and arguments (e.g. constants) are live.
Chris Lattner84d1b402008-11-26 03:02:41 +0000986 if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
987
988 // If Val is a constant sized alloca in the entry block, it is live, this is
989 // true because it is just a reference to the stack/frame pointer, which is
990 // live for the whole function.
991 if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
992 if (AI->isStaticAlloca())
993 return true;
994
Chris Lattner896617b2008-11-26 03:20:37 +0000995 // Check to see if this value is already used in the memory instruction's
996 // block. If so, it's already live into the block at the very least, so we
997 // can reasonably fold it.
998 BasicBlock *MemBB = MemoryInst->getParent();
999 for (Value::use_iterator UI = Val->use_begin(), E = Val->use_end();
1000 UI != E; ++UI)
1001 // We know that uses of arguments and instructions have to be instructions.
1002 if (cast<Instruction>(*UI)->getParent() == MemBB)
1003 return true;
1004
Chris Lattner84d1b402008-11-26 03:02:41 +00001005 return false;
1006}
1007
1008
1009
Chris Lattner5eecb7f2008-11-26 02:00:14 +00001010/// IsProfitableToFoldIntoAddressingMode - It is possible for the addressing
1011/// mode of the machine to fold the specified instruction into a load or store
1012/// that ultimately uses it. However, the specified instruction has multiple
1013/// uses. Given this, it may actually increase register pressure to fold it
1014/// into the load. For example, consider this code:
1015///
1016/// X = ...
1017/// Y = X+1
1018/// use(Y) -> nonload/store
1019/// Z = Y+1
1020/// load Z
1021///
1022/// In this case, Y has multiple uses, and can be folded into the load of Z
1023/// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to
1024/// be live at the use(Y) line. If we don't fold Y into load Z, we use one
1025/// fewer register. Since Y can't be folded into "use(Y)" we don't increase the
1026/// number of computations either.
1027///
1028/// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If
1029/// X was live across 'load Z' for other reasons, we actually *would* want to
Chris Lattner653b2582008-11-26 02:11:11 +00001030/// fold the addressing mode in the Z case. This would make Y die earlier.
Chris Lattner5eecb7f2008-11-26 02:00:14 +00001031bool AddressingModeMatcher::
Chris Lattner84d1b402008-11-26 03:02:41 +00001032IsProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
1033 ExtAddrMode &AMAfter) {
Chris Lattnerab8b7942008-11-26 22:16:44 +00001034 if (IgnoreProfitability) return true;
Chris Lattner5eecb7f2008-11-26 02:00:14 +00001035
Chris Lattner84d1b402008-11-26 03:02:41 +00001036 // AMBefore is the addressing mode before this instruction was folded into it,
1037 // and AMAfter is the addressing mode after the instruction was folded. Get
1038 // the set of registers referenced by AMAfter and subtract out those
1039 // referenced by AMBefore: this is the set of values which folding in this
1040 // address extends the lifetime of.
1041 //
1042 // Note that there are only two potential values being referenced here,
1043 // BaseReg and ScaleReg (global addresses are always available, as are any
1044 // folded immediates).
1045 Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
1046
1047 // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
1048 // lifetime wasn't extended by adding this instruction.
1049 if (ValueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
1050 BaseReg = 0;
1051 if (ValueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
1052 ScaledReg = 0;
1053
1054 // If folding this instruction (and it's subexprs) didn't extend any live
1055 // ranges, we're ok with it.
1056 if (BaseReg == 0 && ScaledReg == 0)
1057 return true;
Chris Lattner5eecb7f2008-11-26 02:00:14 +00001058
1059 // If all uses of this instruction are ultimately load/store/inlineasm's,
1060 // check to see if their addressing modes will include this instruction. If
1061 // so, we can fold it into all uses, so it doesn't matter if it has multiple
1062 // uses.
1063 SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
1064 SmallPtrSet<Instruction*, 16> ConsideredInsts;
Chris Lattner695d8ec2008-11-26 04:59:11 +00001065 if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TLI))
Chris Lattner5eecb7f2008-11-26 02:00:14 +00001066 return false; // Has a non-memory, non-foldable use!
1067
1068 // Now that we know that all uses of this instruction are part of a chain of
1069 // computation involving only operations that could theoretically be folded
1070 // into a memory use, loop over each of these uses and see if they could
1071 // *actually* fold the instruction.
1072 SmallVector<Instruction*, 32> MatchedAddrModeInsts;
1073 for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
1074 Instruction *User = MemoryUses[i].first;
1075 unsigned OpNo = MemoryUses[i].second;
1076
1077 // Get the access type of this use. If the use isn't a pointer, we don't
1078 // know what it accesses.
1079 Value *Address = User->getOperand(OpNo);
1080 if (!isa<PointerType>(Address->getType()))
1081 return false;
1082 const Type *AddressAccessTy =
1083 cast<PointerType>(Address->getType())->getElementType();
1084
1085 // Do a match against the root of this address, ignoring profitability. This
1086 // will tell us if the addressing mode for the memory operation will
1087 // *actually* cover the shared instruction.
1088 ExtAddrMode Result;
1089 AddressingModeMatcher Matcher(MatchedAddrModeInsts, TLI, AddressAccessTy,
Chris Lattner896617b2008-11-26 03:20:37 +00001090 MemoryInst, Result);
Chris Lattner5eecb7f2008-11-26 02:00:14 +00001091 Matcher.IgnoreProfitability = true;
1092 bool Success = Matcher.MatchAddr(Address, 0);
1093 Success = Success; assert(Success && "Couldn't select *anything*?");
1094
1095 // If the match didn't cover I, then it won't be shared by it.
1096 if (std::find(MatchedAddrModeInsts.begin(), MatchedAddrModeInsts.end(),
1097 I) == MatchedAddrModeInsts.end())
1098 return false;
1099
1100 MatchedAddrModeInsts.clear();
1101 }
1102
1103 return true;
1104}
1105
Chris Lattnerdd77df32007-04-13 20:30:56 +00001106
Chris Lattner88a5c832008-11-25 07:09:13 +00001107//===----------------------------------------------------------------------===//
1108// Memory Optimization
1109//===----------------------------------------------------------------------===//
1110
Chris Lattnerdd77df32007-04-13 20:30:56 +00001111/// IsNonLocalValue - Return true if the specified values are defined in a
1112/// different basic block than BB.
1113static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
1114 if (Instruction *I = dyn_cast<Instruction>(V))
1115 return I->getParent() != BB;
1116 return false;
1117}
1118
Chris Lattner88a5c832008-11-25 07:09:13 +00001119/// OptimizeMemoryInst - Load and Store Instructions have often have
Chris Lattnerdd77df32007-04-13 20:30:56 +00001120/// addressing modes that can do significant amounts of computation. As such,
1121/// instruction selection will try to get the load or store to do as much
1122/// computation as possible for the program. The problem is that isel can only
1123/// see within a single block. As such, we sink as much legal addressing mode
1124/// stuff into the block as possible.
Chris Lattner88a5c832008-11-25 07:09:13 +00001125///
1126/// This method is used to optimize both load/store and inline asms with memory
1127/// operands.
Chris Lattner896617b2008-11-26 03:20:37 +00001128bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
Chris Lattner88a5c832008-11-25 07:09:13 +00001129 const Type *AccessTy,
1130 DenseMap<Value*,Value*> &SunkAddrs) {
Chris Lattnerdd77df32007-04-13 20:30:56 +00001131 // Figure out what addressing mode will be built up for this operation.
1132 SmallVector<Instruction*, 16> AddrModeInsts;
Chris Lattner896617b2008-11-26 03:20:37 +00001133 ExtAddrMode AddrMode = AddressingModeMatcher::Match(Addr, AccessTy,MemoryInst,
1134 AddrModeInsts, *TLI);
Eric Christopher692bf6b2008-09-24 05:32:41 +00001135
Chris Lattnerdd77df32007-04-13 20:30:56 +00001136 // Check to see if any of the instructions supersumed by this addr mode are
1137 // non-local to I's BB.
1138 bool AnyNonLocal = false;
1139 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
Chris Lattner896617b2008-11-26 03:20:37 +00001140 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
Chris Lattnerdd77df32007-04-13 20:30:56 +00001141 AnyNonLocal = true;
1142 break;
1143 }
1144 }
Eric Christopher692bf6b2008-09-24 05:32:41 +00001145
Chris Lattnerdd77df32007-04-13 20:30:56 +00001146 // If all the instructions matched are already in this BB, don't do anything.
1147 if (!AnyNonLocal) {
1148 DEBUG(cerr << "CGP: Found local addrmode: " << AddrMode << "\n");
1149 return false;
1150 }
Eric Christopher692bf6b2008-09-24 05:32:41 +00001151
Chris Lattnerdd77df32007-04-13 20:30:56 +00001152 // Insert this computation right after this user. Since our caller is
1153 // scanning from the top of the BB to the bottom, reuse of the expr are
1154 // guaranteed to happen later.
Chris Lattner896617b2008-11-26 03:20:37 +00001155 BasicBlock::iterator InsertPt = MemoryInst;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001156
Chris Lattnerdd77df32007-04-13 20:30:56 +00001157 // Now that we determined the addressing expression we want to use and know
1158 // that we have to sink it into this block. Check to see if we have already
1159 // done this for some other load/store instr in this block. If so, reuse the
1160 // computation.
1161 Value *&SunkAddr = SunkAddrs[Addr];
1162 if (SunkAddr) {
1163 DEBUG(cerr << "CGP: Reusing nonlocal addrmode: " << AddrMode << "\n");
1164 if (SunkAddr->getType() != Addr->getType())
1165 SunkAddr = new BitCastInst(SunkAddr, Addr->getType(), "tmp", InsertPt);
1166 } else {
1167 DEBUG(cerr << "CGP: SINKING nonlocal addrmode: " << AddrMode << "\n");
1168 const Type *IntPtrTy = TLI->getTargetData()->getIntPtrType();
Eric Christopher692bf6b2008-09-24 05:32:41 +00001169
Chris Lattnerdd77df32007-04-13 20:30:56 +00001170 Value *Result = 0;
1171 // Start with the scale value.
1172 if (AddrMode.Scale) {
1173 Value *V = AddrMode.ScaledReg;
1174 if (V->getType() == IntPtrTy) {
1175 // done.
1176 } else if (isa<PointerType>(V->getType())) {
1177 V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
1178 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
1179 cast<IntegerType>(V->getType())->getBitWidth()) {
1180 V = new TruncInst(V, IntPtrTy, "sunkaddr", InsertPt);
1181 } else {
1182 V = new SExtInst(V, IntPtrTy, "sunkaddr", InsertPt);
1183 }
1184 if (AddrMode.Scale != 1)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001185 V = BinaryOperator::CreateMul(V, ConstantInt::get(IntPtrTy,
Chris Lattnerdd77df32007-04-13 20:30:56 +00001186 AddrMode.Scale),
1187 "sunkaddr", InsertPt);
1188 Result = V;
1189 }
1190
1191 // Add in the base register.
1192 if (AddrMode.BaseReg) {
1193 Value *V = AddrMode.BaseReg;
1194 if (V->getType() != IntPtrTy)
1195 V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
1196 if (Result)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001197 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
Chris Lattnerdd77df32007-04-13 20:30:56 +00001198 else
1199 Result = V;
1200 }
Eric Christopher692bf6b2008-09-24 05:32:41 +00001201
Chris Lattnerdd77df32007-04-13 20:30:56 +00001202 // Add in the BaseGV if present.
1203 if (AddrMode.BaseGV) {
1204 Value *V = new PtrToIntInst(AddrMode.BaseGV, IntPtrTy, "sunkaddr",
1205 InsertPt);
1206 if (Result)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001207 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
Chris Lattnerdd77df32007-04-13 20:30:56 +00001208 else
1209 Result = V;
1210 }
Eric Christopher692bf6b2008-09-24 05:32:41 +00001211
Chris Lattnerdd77df32007-04-13 20:30:56 +00001212 // Add in the Base Offset if present.
1213 if (AddrMode.BaseOffs) {
1214 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
1215 if (Result)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001216 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
Chris Lattnerdd77df32007-04-13 20:30:56 +00001217 else
1218 Result = V;
1219 }
1220
1221 if (Result == 0)
1222 SunkAddr = Constant::getNullValue(Addr->getType());
1223 else
1224 SunkAddr = new IntToPtrInst(Result, Addr->getType(), "sunkaddr",InsertPt);
1225 }
Eric Christopher692bf6b2008-09-24 05:32:41 +00001226
Chris Lattner896617b2008-11-26 03:20:37 +00001227 MemoryInst->replaceUsesOfWith(Addr, SunkAddr);
Eric Christopher692bf6b2008-09-24 05:32:41 +00001228
Chris Lattnerdd77df32007-04-13 20:30:56 +00001229 if (Addr->use_empty())
1230 EraseDeadInstructions(Addr);
1231 return true;
1232}
1233
Evan Cheng9bf12b52008-02-26 02:42:37 +00001234/// OptimizeInlineAsmInst - If there are any memory operands, use
Chris Lattner88a5c832008-11-25 07:09:13 +00001235/// OptimizeMemoryInst to sink their address computing into the block when
Evan Cheng9bf12b52008-02-26 02:42:37 +00001236/// possible / profitable.
1237bool CodeGenPrepare::OptimizeInlineAsmInst(Instruction *I, CallSite CS,
1238 DenseMap<Value*,Value*> &SunkAddrs) {
1239 bool MadeChange = false;
1240 InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
1241
1242 // Do a prepass over the constraints, canonicalizing them, and building up the
1243 // ConstraintOperands list.
1244 std::vector<InlineAsm::ConstraintInfo>
1245 ConstraintInfos = IA->ParseConstraints();
1246
1247 /// ConstraintOperands - Information about all of the constraints.
1248 std::vector<TargetLowering::AsmOperandInfo> ConstraintOperands;
1249 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
1250 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
1251 ConstraintOperands.
1252 push_back(TargetLowering::AsmOperandInfo(ConstraintInfos[i]));
1253 TargetLowering::AsmOperandInfo &OpInfo = ConstraintOperands.back();
1254
1255 // Compute the value type for each operand.
1256 switch (OpInfo.Type) {
1257 case InlineAsm::isOutput:
1258 if (OpInfo.isIndirect)
1259 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
1260 break;
1261 case InlineAsm::isInput:
1262 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
1263 break;
1264 case InlineAsm::isClobber:
1265 // Nothing to do.
1266 break;
1267 }
1268
1269 // Compute the constraint code and ConstraintType to use.
Evan Chenga7e61462008-09-24 06:48:55 +00001270 TLI->ComputeConstraintToUse(OpInfo, SDValue(),
1271 OpInfo.ConstraintType == TargetLowering::C_Memory);
Evan Cheng9bf12b52008-02-26 02:42:37 +00001272
Eli Friedman9ec80952008-02-26 18:37:49 +00001273 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
1274 OpInfo.isIndirect) {
Evan Cheng9bf12b52008-02-26 02:42:37 +00001275 Value *OpVal = OpInfo.CallOperandVal;
Chris Lattner88a5c832008-11-25 07:09:13 +00001276 MadeChange |= OptimizeMemoryInst(I, OpVal, OpVal->getType(), SunkAddrs);
Evan Cheng9bf12b52008-02-26 02:42:37 +00001277 }
1278 }
1279
1280 return MadeChange;
1281}
1282
Evan Chengbdcb7262007-12-05 23:58:20 +00001283bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
1284 BasicBlock *DefBB = I->getParent();
1285
1286 // If both result of the {s|z}xt and its source are live out, rewrite all
1287 // other uses of the source with result of extension.
1288 Value *Src = I->getOperand(0);
1289 if (Src->hasOneUse())
1290 return false;
1291
Evan Cheng696e5c02007-12-13 07:50:36 +00001292 // Only do this xform if truncating is free.
Gabor Greif53bdbd72008-02-26 19:13:21 +00001293 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
Evan Chengf9785f92007-12-13 03:32:53 +00001294 return false;
1295
Evan Cheng772de512007-12-12 00:51:06 +00001296 // Only safe to perform the optimization if the source is also defined in
Evan Cheng765dff22007-12-12 02:53:41 +00001297 // this block.
1298 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
Evan Cheng772de512007-12-12 00:51:06 +00001299 return false;
1300
Evan Chengbdcb7262007-12-05 23:58:20 +00001301 bool DefIsLiveOut = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001302 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
Evan Chengbdcb7262007-12-05 23:58:20 +00001303 UI != E; ++UI) {
1304 Instruction *User = cast<Instruction>(*UI);
1305
1306 // Figure out which BB this ext is used in.
1307 BasicBlock *UserBB = User->getParent();
1308 if (UserBB == DefBB) continue;
1309 DefIsLiveOut = true;
1310 break;
1311 }
1312 if (!DefIsLiveOut)
1313 return false;
1314
Evan Cheng765dff22007-12-12 02:53:41 +00001315 // Make sure non of the uses are PHI nodes.
Eric Christopher692bf6b2008-09-24 05:32:41 +00001316 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
Evan Cheng765dff22007-12-12 02:53:41 +00001317 UI != E; ++UI) {
1318 Instruction *User = cast<Instruction>(*UI);
Evan Chengf9785f92007-12-13 03:32:53 +00001319 BasicBlock *UserBB = User->getParent();
1320 if (UserBB == DefBB) continue;
1321 // Be conservative. We don't want this xform to end up introducing
1322 // reloads just before load / store instructions.
1323 if (isa<PHINode>(User) || isa<LoadInst>(User) || isa<StoreInst>(User))
Evan Cheng765dff22007-12-12 02:53:41 +00001324 return false;
1325 }
1326
Evan Chengbdcb7262007-12-05 23:58:20 +00001327 // InsertedTruncs - Only insert one trunc in each block once.
1328 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
1329
1330 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001331 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
Evan Chengbdcb7262007-12-05 23:58:20 +00001332 UI != E; ++UI) {
1333 Use &TheUse = UI.getUse();
1334 Instruction *User = cast<Instruction>(*UI);
1335
1336 // Figure out which BB this ext is used in.
1337 BasicBlock *UserBB = User->getParent();
1338 if (UserBB == DefBB) continue;
1339
1340 // Both src and def are live in this block. Rewrite the use.
1341 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
1342
1343 if (!InsertedTrunc) {
Dan Gohman02dea8b2008-05-23 21:05:58 +00001344 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
Eric Christopher692bf6b2008-09-24 05:32:41 +00001345
Evan Chengbdcb7262007-12-05 23:58:20 +00001346 InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
1347 }
1348
1349 // Replace a use of the {s|z}ext source with a use of the result.
1350 TheUse = InsertedTrunc;
1351
1352 MadeChange = true;
1353 }
1354
1355 return MadeChange;
1356}
1357
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001358// In this pass we look for GEP and cast instructions that are used
1359// across basic blocks and rewrite them to improve basic-block-at-a-time
1360// selection.
1361bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
1362 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001363
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001364 // Split all critical edges where the dest block has a PHI and where the phi
1365 // has shared immediate operands.
1366 TerminatorInst *BBTI = BB.getTerminator();
1367 if (BBTI->getNumSuccessors() > 1) {
1368 for (unsigned i = 0, e = BBTI->getNumSuccessors(); i != e; ++i)
1369 if (isa<PHINode>(BBTI->getSuccessor(i)->begin()) &&
1370 isCriticalEdge(BBTI, i, true))
1371 SplitEdgeNicely(BBTI, i, this);
1372 }
Eric Christopher692bf6b2008-09-24 05:32:41 +00001373
1374
Chris Lattnerdd77df32007-04-13 20:30:56 +00001375 // Keep track of non-local addresses that have been sunk into this block.
1376 // This allows us to avoid inserting duplicate code for blocks with multiple
1377 // load/stores of the same address.
1378 DenseMap<Value*, Value*> SunkAddrs;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001379
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001380 for (BasicBlock::iterator BBI = BB.begin(), E = BB.end(); BBI != E; ) {
1381 Instruction *I = BBI++;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001382
Chris Lattnerdd77df32007-04-13 20:30:56 +00001383 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001384 // If the source of the cast is a constant, then this should have
1385 // already been constant folded. The only reason NOT to constant fold
1386 // it is if something (e.g. LSR) was careful to place the constant
1387 // evaluation in a block other than then one that uses it (e.g. to hoist
1388 // the address of globals out of a loop). If this is the case, we don't
1389 // want to forward-subst the cast.
1390 if (isa<Constant>(CI->getOperand(0)))
1391 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001392
Evan Chengbdcb7262007-12-05 23:58:20 +00001393 bool Change = false;
1394 if (TLI) {
1395 Change = OptimizeNoopCopyExpression(CI, *TLI);
1396 MadeChange |= Change;
1397 }
1398
Evan Cheng55e641b2008-03-19 22:02:26 +00001399 if (!Change && (isa<ZExtInst>(I) || isa<SExtInst>(I)))
Evan Chengbdcb7262007-12-05 23:58:20 +00001400 MadeChange |= OptimizeExtUses(I);
Dale Johannesence0b2372007-06-12 16:50:17 +00001401 } else if (CmpInst *CI = dyn_cast<CmpInst>(I)) {
1402 MadeChange |= OptimizeCmpExpression(CI);
Chris Lattnerdd77df32007-04-13 20:30:56 +00001403 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
1404 if (TLI)
Chris Lattner88a5c832008-11-25 07:09:13 +00001405 MadeChange |= OptimizeMemoryInst(I, I->getOperand(0), LI->getType(),
1406 SunkAddrs);
Chris Lattnerdd77df32007-04-13 20:30:56 +00001407 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
1408 if (TLI)
Chris Lattner88a5c832008-11-25 07:09:13 +00001409 MadeChange |= OptimizeMemoryInst(I, SI->getOperand(1),
1410 SI->getOperand(0)->getType(),
1411 SunkAddrs);
Chris Lattnerdd77df32007-04-13 20:30:56 +00001412 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Chris Lattnerf25646b2007-04-14 00:17:39 +00001413 if (GEPI->hasAllZeroIndices()) {
Chris Lattnerdd77df32007-04-13 20:30:56 +00001414 /// The GEP operand must be a pointer, so must its result -> BitCast
Eric Christopher692bf6b2008-09-24 05:32:41 +00001415 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
Chris Lattnerdd77df32007-04-13 20:30:56 +00001416 GEPI->getName(), GEPI);
1417 GEPI->replaceAllUsesWith(NC);
1418 GEPI->eraseFromParent();
1419 MadeChange = true;
1420 BBI = NC;
1421 }
1422 } else if (CallInst *CI = dyn_cast<CallInst>(I)) {
1423 // If we found an inline asm expession, and if the target knows how to
1424 // lower it to normal LLVM code, do so now.
1425 if (TLI && isa<InlineAsm>(CI->getCalledValue()))
Eric Christopher692bf6b2008-09-24 05:32:41 +00001426 if (const TargetAsmInfo *TAI =
Chris Lattnerdd77df32007-04-13 20:30:56 +00001427 TLI->getTargetMachine().getTargetAsmInfo()) {
1428 if (TAI->ExpandInlineAsm(CI))
1429 BBI = BB.begin();
Evan Cheng9bf12b52008-02-26 02:42:37 +00001430 else
1431 // Sink address computing for memory operands into the block.
1432 MadeChange |= OptimizeInlineAsmInst(I, &(*CI), SunkAddrs);
Chris Lattnerdd77df32007-04-13 20:30:56 +00001433 }
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001434 }
1435 }
Eric Christopher692bf6b2008-09-24 05:32:41 +00001436
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001437 return MadeChange;
1438}