blob: b0214e030daea00d65944ecae7c1541ab6ee071c [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"
Dale Johannesen6aae1d62009-03-26 01:15:07 +000023#include "llvm/IntrinsicInst.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000024#include "llvm/Pass.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000025#include "llvm/Target/TargetAsmInfo.h"
26#include "llvm/Target/TargetData.h"
27#include "llvm/Target/TargetLowering.h"
28#include "llvm/Target/TargetMachine.h"
Evan Chenga1fd5b32009-02-20 18:24:38 +000029#include "llvm/Transforms/Utils/AddrModeMatcher.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000030#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattnerdd77df32007-04-13 20:30:56 +000031#include "llvm/Transforms/Utils/Local.h"
32#include "llvm/ADT/DenseMap.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000033#include "llvm/ADT/SmallSet.h"
Dan Gohman03ce0422009-02-13 17:45:12 +000034#include "llvm/Assembly/Writer.h"
Evan Cheng9bf12b52008-02-26 02:42:37 +000035#include "llvm/Support/CallSite.h"
Evan Chengab631522008-12-19 18:03:11 +000036#include "llvm/Support/CommandLine.h"
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +000037#include "llvm/Support/Compiler.h"
Evan Chengbdcb7262007-12-05 23:58:20 +000038#include "llvm/Support/Debug.h"
Chris Lattnerdd77df32007-04-13 20:30:56 +000039#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner088a1e82008-11-25 04:42:10 +000040#include "llvm/Support/PatternMatch.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000041using namespace llvm;
Chris Lattner088a1e82008-11-25 04:42:10 +000042using namespace llvm::PatternMatch;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000043
Evan Chengab631522008-12-19 18:03:11 +000044static cl::opt<bool> FactorCommonPreds("split-critical-paths-tweak",
45 cl::init(false), cl::Hidden);
46
Eric Christopher692bf6b2008-09-24 05:32:41 +000047namespace {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000048 class VISIBILITY_HIDDEN CodeGenPrepare : public FunctionPass {
49 /// TLI - Keep a pointer of a TargetLowering to consult for determining
50 /// transformation profitability.
51 const TargetLowering *TLI;
Evan Chengab631522008-12-19 18:03:11 +000052
53 /// BackEdges - Keep a set of all the loop back edges.
54 ///
55 SmallSet<std::pair<BasicBlock*,BasicBlock*>, 8> BackEdges;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000056 public:
Nick Lewyckyecd94c82007-05-06 13:37:16 +000057 static char ID; // Pass identification, replacement for typeid
Dan Gohmanc2bbfc12007-08-01 15:32:29 +000058 explicit CodeGenPrepare(const TargetLowering *tli = 0)
Dan Gohmanae73dc12008-09-04 17:05:41 +000059 : FunctionPass(&ID), TLI(tli) {}
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000060 bool runOnFunction(Function &F);
Eric Christopher692bf6b2008-09-24 05:32:41 +000061
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000062 private:
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +000063 bool EliminateMostlyEmptyBlocks(Function &F);
64 bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
65 void EliminateMostlyEmptyBlock(BasicBlock *BB);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000066 bool OptimizeBlock(BasicBlock &BB);
Chris Lattner88a5c832008-11-25 07:09:13 +000067 bool OptimizeMemoryInst(Instruction *I, Value *Addr, const Type *AccessTy,
68 DenseMap<Value*,Value*> &SunkAddrs);
Evan Cheng9bf12b52008-02-26 02:42:37 +000069 bool OptimizeInlineAsmInst(Instruction *I, CallSite CS,
70 DenseMap<Value*,Value*> &SunkAddrs);
Evan Chengbdcb7262007-12-05 23:58:20 +000071 bool OptimizeExtUses(Instruction *I);
Evan Chengab631522008-12-19 18:03:11 +000072 void findLoopBackEdges(Function &F);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000073 };
74}
Devang Patel794fd752007-05-01 21:15:47 +000075
Devang Patel19974732007-05-03 01:11:54 +000076char CodeGenPrepare::ID = 0;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000077static RegisterPass<CodeGenPrepare> X("codegenprepare",
78 "Optimize for code generation");
79
80FunctionPass *llvm::createCodeGenPreparePass(const TargetLowering *TLI) {
81 return new CodeGenPrepare(TLI);
82}
83
Evan Chengab631522008-12-19 18:03:11 +000084/// findLoopBackEdges - Do a DFS walk to find loop back edges.
85///
86void CodeGenPrepare::findLoopBackEdges(Function &F) {
87 SmallPtrSet<BasicBlock*, 8> Visited;
88 SmallVector<std::pair<BasicBlock*, succ_iterator>, 8> VisitStack;
89 SmallPtrSet<BasicBlock*, 8> InStack;
90
91 BasicBlock *BB = &F.getEntryBlock();
92 if (succ_begin(BB) == succ_end(BB))
93 return;
94 Visited.insert(BB);
95 VisitStack.push_back(std::make_pair(BB, succ_begin(BB)));
96 InStack.insert(BB);
97 do {
98 std::pair<BasicBlock*, succ_iterator> &Top = VisitStack.back();
99 BasicBlock *ParentBB = Top.first;
100 succ_iterator &I = Top.second;
101
102 bool FoundNew = false;
103 while (I != succ_end(ParentBB)) {
104 BB = *I++;
105 if (Visited.insert(BB)) {
106 FoundNew = true;
107 break;
108 }
109 // Successor is in VisitStack, it's a back edge.
110 if (InStack.count(BB))
111 BackEdges.insert(std::make_pair(ParentBB, BB));
112 }
113
114 if (FoundNew) {
115 // Go down one level if there is a unvisited successor.
116 InStack.insert(BB);
117 VisitStack.push_back(std::make_pair(BB, succ_begin(BB)));
118 } else {
119 // Go up one level.
120 std::pair<BasicBlock*, succ_iterator> &Pop = VisitStack.back();
121 InStack.erase(Pop.first);
122 VisitStack.pop_back();
123 }
124 } while (!VisitStack.empty());
125}
126
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000127
128bool CodeGenPrepare::runOnFunction(Function &F) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000129 bool EverMadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000130
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000131 // First pass, eliminate blocks that contain only PHI nodes and an
132 // unconditional branch.
133 EverMadeChange |= EliminateMostlyEmptyBlocks(F);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000134
Evan Cheng7e66c0d2009-01-05 21:17:27 +0000135 // Now find loop back edges.
136 findLoopBackEdges(F);
137
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000138 bool MadeChange = true;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000139 while (MadeChange) {
140 MadeChange = false;
141 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
142 MadeChange |= OptimizeBlock(*BB);
143 EverMadeChange |= MadeChange;
144 }
145 return EverMadeChange;
146}
147
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000148/// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes
Eric Christopher692bf6b2008-09-24 05:32:41 +0000149/// and an unconditional branch. Passes before isel (e.g. LSR/loopsimplify)
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000150/// often split edges in ways that are non-optimal for isel. Start by
151/// eliminating these blocks so we can split them the way we want them.
152bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
153 bool MadeChange = false;
154 // Note that this intentionally skips the entry block.
155 for (Function::iterator I = ++F.begin(), E = F.end(); I != E; ) {
156 BasicBlock *BB = I++;
157
158 // If this block doesn't end with an uncond branch, ignore it.
159 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
160 if (!BI || !BI->isUnconditional())
161 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000162
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000163 // If the instruction before the branch isn't a phi node, then other stuff
164 // is happening here.
165 BasicBlock::iterator BBI = BI;
166 if (BBI != BB->begin()) {
167 --BBI;
168 if (!isa<PHINode>(BBI)) continue;
169 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000170
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000171 // Do not break infinite loops.
172 BasicBlock *DestBB = BI->getSuccessor(0);
173 if (DestBB == BB)
174 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000175
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000176 if (!CanMergeBlocks(BB, DestBB))
177 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000178
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000179 EliminateMostlyEmptyBlock(BB);
180 MadeChange = true;
181 }
182 return MadeChange;
183}
184
185/// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
186/// single uncond branch between them, and BB contains no other non-phi
187/// instructions.
188bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
189 const BasicBlock *DestBB) const {
190 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
191 // the successor. If there are more complex condition (e.g. preheaders),
192 // don't mess around with them.
193 BasicBlock::const_iterator BBI = BB->begin();
194 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
195 for (Value::use_const_iterator UI = PN->use_begin(), E = PN->use_end();
196 UI != E; ++UI) {
197 const Instruction *User = cast<Instruction>(*UI);
198 if (User->getParent() != DestBB || !isa<PHINode>(User))
199 return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000200 // If User is inside DestBB block and it is a PHINode then check
201 // incoming value. If incoming value is not from BB then this is
Devang Patel75abc1e2007-04-25 00:37:04 +0000202 // a complex condition (e.g. preheaders) we want to avoid here.
203 if (User->getParent() == DestBB) {
204 if (const PHINode *UPN = dyn_cast<PHINode>(User))
205 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
206 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
207 if (Insn && Insn->getParent() == BB &&
208 Insn->getParent() != UPN->getIncomingBlock(I))
209 return false;
210 }
211 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000212 }
213 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000214
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000215 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
216 // and DestBB may have conflicting incoming values for the block. If so, we
217 // can't merge the block.
218 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
219 if (!DestBBPN) return true; // no conflict.
Eric Christopher692bf6b2008-09-24 05:32:41 +0000220
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000221 // Collect the preds of BB.
Chris Lattnerf67f73a2007-11-06 22:07:40 +0000222 SmallPtrSet<const BasicBlock*, 16> BBPreds;
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000223 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
224 // It is faster to get preds from a PHI than with pred_iterator.
225 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
226 BBPreds.insert(BBPN->getIncomingBlock(i));
227 } else {
228 BBPreds.insert(pred_begin(BB), pred_end(BB));
229 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000230
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000231 // Walk the preds of DestBB.
232 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
233 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
234 if (BBPreds.count(Pred)) { // Common predecessor?
235 BBI = DestBB->begin();
236 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
237 const Value *V1 = PN->getIncomingValueForBlock(Pred);
238 const Value *V2 = PN->getIncomingValueForBlock(BB);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000239
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000240 // If V2 is a phi node in BB, look up what the mapped value will be.
241 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
242 if (V2PN->getParent() == BB)
243 V2 = V2PN->getIncomingValueForBlock(Pred);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000244
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000245 // If there is a conflict, bail out.
246 if (V1 != V2) return false;
247 }
248 }
249 }
250
251 return true;
252}
253
254
255/// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
256/// an unconditional branch in it.
257void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
258 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
259 BasicBlock *DestBB = BI->getSuccessor(0);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000260
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000261 DOUT << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000262
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000263 // If the destination block has a single pred, then this is a trivial edge,
264 // just collapse it.
Chris Lattner9918fb52008-11-27 19:29:14 +0000265 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
Chris Lattnerf5102a02008-11-28 19:54:49 +0000266 if (SinglePred != DestBB) {
267 // Remember if SinglePred was the entry block of the function. If so, we
268 // will need to move BB back to the entry position.
269 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
270 MergeBasicBlockIntoOnlyPred(DestBB);
Chris Lattner9918fb52008-11-27 19:29:14 +0000271
Chris Lattnerf5102a02008-11-28 19:54:49 +0000272 if (isEntry && BB != &BB->getParent()->getEntryBlock())
273 BB->moveBefore(&BB->getParent()->getEntryBlock());
274
275 DOUT << "AFTER:\n" << *DestBB << "\n\n\n";
276 return;
277 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000278 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000279
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000280 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
281 // to handle the new incoming edges it is about to have.
282 PHINode *PN;
283 for (BasicBlock::iterator BBI = DestBB->begin();
284 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
285 // Remove the incoming value for BB, and remember it.
286 Value *InVal = PN->removeIncomingValue(BB, false);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000287
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000288 // Two options: either the InVal is a phi node defined in BB or it is some
289 // value that dominates BB.
290 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
291 if (InValPhi && InValPhi->getParent() == BB) {
292 // Add all of the input values of the input PHI as inputs of this phi.
293 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
294 PN->addIncoming(InValPhi->getIncomingValue(i),
295 InValPhi->getIncomingBlock(i));
296 } else {
297 // Otherwise, add one instance of the dominating value for each edge that
298 // we will be adding.
299 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
300 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
301 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
302 } else {
303 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
304 PN->addIncoming(InVal, *PI);
305 }
306 }
307 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000308
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000309 // The PHIs are now updated, change everything that refers to BB to use
310 // DestBB and remove BB.
311 BB->replaceAllUsesWith(DestBB);
312 BB->eraseFromParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000313
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000314 DOUT << "AFTER:\n" << *DestBB << "\n\n\n";
315}
316
317
Chris Lattnerebe80752007-12-24 19:32:55 +0000318/// SplitEdgeNicely - Split the critical edge from TI to its specified
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000319/// successor if it will improve codegen. We only do this if the successor has
320/// phi nodes (otherwise critical edges are ok). If there is already another
321/// predecessor of the succ that is empty (and thus has no phi nodes), use it
322/// instead of introducing a new block.
Evan Chengab631522008-12-19 18:03:11 +0000323static void SplitEdgeNicely(TerminatorInst *TI, unsigned SuccNum,
324 SmallSet<std::pair<BasicBlock*,BasicBlock*>, 8> &BackEdges,
325 Pass *P) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000326 BasicBlock *TIBB = TI->getParent();
327 BasicBlock *Dest = TI->getSuccessor(SuccNum);
328 assert(isa<PHINode>(Dest->begin()) &&
329 "This should only be called if Dest has a PHI!");
Eric Christopher692bf6b2008-09-24 05:32:41 +0000330
Evan Chengfc0b80d2009-03-13 22:59:14 +0000331 // Do not split edges to EH landing pads.
332 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(TI)) {
333 if (Invoke->getSuccessor(1) == Dest)
334 return;
335 }
336
Chris Lattnerebe80752007-12-24 19:32:55 +0000337 // As a hack, never split backedges of loops. Even though the copy for any
338 // PHIs inserted on the backedge would be dead for exits from the loop, we
339 // assume that the cost of *splitting* the backedge would be too high.
Evan Chengab631522008-12-19 18:03:11 +0000340 if (BackEdges.count(std::make_pair(TIBB, Dest)))
Chris Lattnerebe80752007-12-24 19:32:55 +0000341 return;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000342
Evan Chengab631522008-12-19 18:03:11 +0000343 if (!FactorCommonPreds) {
344 /// TIPHIValues - This array is lazily computed to determine the values of
345 /// PHIs in Dest that TI would provide.
346 SmallVector<Value*, 32> TIPHIValues;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000347
Evan Chengab631522008-12-19 18:03:11 +0000348 // Check to see if Dest has any blocks that can be used as a split edge for
349 // this terminator.
350 for (pred_iterator PI = pred_begin(Dest), E = pred_end(Dest); PI != E; ++PI) {
351 BasicBlock *Pred = *PI;
352 // To be usable, the pred has to end with an uncond branch to the dest.
353 BranchInst *PredBr = dyn_cast<BranchInst>(Pred->getTerminator());
Dale Johannesen6aae1d62009-03-26 01:15:07 +0000354 if (!PredBr || !PredBr->isUnconditional())
355 continue;
356 // Must be empty other than the branch and debug info.
357 BasicBlock::iterator I = Pred->begin();
358 while (isa<DbgInfoIntrinsic>(I))
359 I++;
360 if (dyn_cast<Instruction>(I) != PredBr)
361 continue;
362 // Cannot be the entry block; its label does not get emitted.
363 if (Pred == &(Dest->getParent()->getEntryBlock()))
Evan Chengab631522008-12-19 18:03:11 +0000364 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000365
Evan Chengab631522008-12-19 18:03:11 +0000366 // Finally, since we know that Dest has phi nodes in it, we have to make
Dale Johannesen6aae1d62009-03-26 01:15:07 +0000367 // sure that jumping to Pred will have the same effect as going to Dest in
Evan Chengab631522008-12-19 18:03:11 +0000368 // terms of PHI values.
369 PHINode *PN;
370 unsigned PHINo = 0;
371 bool FoundMatch = true;
372 for (BasicBlock::iterator I = Dest->begin();
373 (PN = dyn_cast<PHINode>(I)); ++I, ++PHINo) {
374 if (PHINo == TIPHIValues.size())
375 TIPHIValues.push_back(PN->getIncomingValueForBlock(TIBB));
Eric Christopher692bf6b2008-09-24 05:32:41 +0000376
Evan Chengab631522008-12-19 18:03:11 +0000377 // If the PHI entry doesn't work, we can't use this pred.
378 if (TIPHIValues[PHINo] != PN->getIncomingValueForBlock(Pred)) {
379 FoundMatch = false;
380 break;
381 }
382 }
383
384 // If we found a workable predecessor, change TI to branch to Succ.
385 if (FoundMatch) {
386 Dest->removePredecessor(TIBB);
387 TI->setSuccessor(SuccNum, Pred);
388 return;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000389 }
390 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000391
Evan Chengab631522008-12-19 18:03:11 +0000392 SplitCriticalEdge(TI, SuccNum, P, true);
393 return;
394 }
395
396 PHINode *PN;
397 SmallVector<Value*, 8> TIPHIValues;
398 for (BasicBlock::iterator I = Dest->begin();
399 (PN = dyn_cast<PHINode>(I)); ++I)
400 TIPHIValues.push_back(PN->getIncomingValueForBlock(TIBB));
401
402 SmallVector<BasicBlock*, 8> IdenticalPreds;
403 for (pred_iterator PI = pred_begin(Dest), E = pred_end(Dest); PI != E; ++PI) {
404 BasicBlock *Pred = *PI;
405 if (BackEdges.count(std::make_pair(Pred, Dest)))
406 continue;
407 if (PI == TIBB)
408 IdenticalPreds.push_back(Pred);
409 else {
410 bool Identical = true;
411 unsigned PHINo = 0;
412 for (BasicBlock::iterator I = Dest->begin();
413 (PN = dyn_cast<PHINode>(I)); ++I, ++PHINo)
414 if (TIPHIValues[PHINo] != PN->getIncomingValueForBlock(Pred)) {
415 Identical = false;
416 break;
417 }
418 if (Identical)
419 IdenticalPreds.push_back(Pred);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000420 }
421 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000422
Evan Chengab631522008-12-19 18:03:11 +0000423 assert(!IdenticalPreds.empty());
424 SplitBlockPredecessors(Dest, &IdenticalPreds[0], IdenticalPreds.size(),
425 ".critedge", P);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000426}
427
Evan Chengab631522008-12-19 18:03:11 +0000428
Chris Lattnerdd77df32007-04-13 20:30:56 +0000429/// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
430/// copy (e.g. it's casting from one pointer type to another, int->uint, or
431/// int->sbyte on PPC), sink it into user blocks to reduce the number of virtual
Dale Johannesence0b2372007-06-12 16:50:17 +0000432/// registers that must be created and coalesced.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000433///
434/// Return true if any changes are made.
Chris Lattner85fa13c2008-11-24 22:44:16 +0000435///
Chris Lattnerdd77df32007-04-13 20:30:56 +0000436static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
Eric Christopher692bf6b2008-09-24 05:32:41 +0000437 // If this is a noop copy,
Duncan Sands83ec4b62008-06-06 12:08:01 +0000438 MVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
439 MVT DstVT = TLI.getValueType(CI->getType());
Eric Christopher692bf6b2008-09-24 05:32:41 +0000440
Chris Lattnerdd77df32007-04-13 20:30:56 +0000441 // This is an fp<->int conversion?
Duncan Sands83ec4b62008-06-06 12:08:01 +0000442 if (SrcVT.isInteger() != DstVT.isInteger())
Chris Lattnerdd77df32007-04-13 20:30:56 +0000443 return false;
Duncan Sands8e4eb092008-06-08 20:54:56 +0000444
Chris Lattnerdd77df32007-04-13 20:30:56 +0000445 // If this is an extension, it will be a zero or sign extension, which
446 // isn't a noop.
Duncan Sands8e4eb092008-06-08 20:54:56 +0000447 if (SrcVT.bitsLT(DstVT)) return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000448
Chris Lattnerdd77df32007-04-13 20:30:56 +0000449 // If these values will be promoted, find out what they will be promoted
450 // to. This helps us consider truncates on PPC as noop copies when they
451 // are.
452 if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote)
453 SrcVT = TLI.getTypeToTransformTo(SrcVT);
454 if (TLI.getTypeAction(DstVT) == TargetLowering::Promote)
455 DstVT = TLI.getTypeToTransformTo(DstVT);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000456
Chris Lattnerdd77df32007-04-13 20:30:56 +0000457 // If, after promotion, these are the same types, this is a noop copy.
458 if (SrcVT != DstVT)
459 return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000460
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000461 BasicBlock *DefBB = CI->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000462
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000463 /// InsertedCasts - Only insert a cast in each block once.
Dale Johannesence0b2372007-06-12 16:50:17 +0000464 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000465
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000466 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000467 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000468 UI != E; ) {
469 Use &TheUse = UI.getUse();
470 Instruction *User = cast<Instruction>(*UI);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000471
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000472 // Figure out which BB this cast is used in. For PHI's this is the
473 // appropriate predecessor block.
474 BasicBlock *UserBB = User->getParent();
475 if (PHINode *PN = dyn_cast<PHINode>(User)) {
Gabor Greifa36791d2009-01-23 19:40:15 +0000476 UserBB = PN->getIncomingBlock(UI);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000477 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000478
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000479 // Preincrement use iterator so we don't invalidate it.
480 ++UI;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000481
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000482 // If this user is in the same block as the cast, don't change the cast.
483 if (UserBB == DefBB) continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000484
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000485 // If we have already inserted a cast into this block, use it.
486 CastInst *&InsertedCast = InsertedCasts[UserBB];
487
488 if (!InsertedCast) {
Dan Gohman02dea8b2008-05-23 21:05:58 +0000489 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000490
491 InsertedCast =
492 CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000493 InsertPt);
494 MadeChange = true;
495 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000496
Dale Johannesence0b2372007-06-12 16:50:17 +0000497 // Replace a use of the cast with a use of the new cast.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000498 TheUse = InsertedCast;
499 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000500
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000501 // If we removed all uses, nuke the cast.
Duncan Sandse0038132008-01-20 16:51:46 +0000502 if (CI->use_empty()) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000503 CI->eraseFromParent();
Duncan Sandse0038132008-01-20 16:51:46 +0000504 MadeChange = true;
505 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000506
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000507 return MadeChange;
508}
509
Eric Christopher692bf6b2008-09-24 05:32:41 +0000510/// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
Dale Johannesence0b2372007-06-12 16:50:17 +0000511/// the number of virtual registers that must be created and coalesced. This is
Chris Lattner684b22d2007-08-02 16:53:43 +0000512/// a clear win except on targets with multiple condition code registers
513/// (PowerPC), where it might lose; some adjustment may be wanted there.
Dale Johannesence0b2372007-06-12 16:50:17 +0000514///
515/// Return true if any changes are made.
Chris Lattner85fa13c2008-11-24 22:44:16 +0000516static bool OptimizeCmpExpression(CmpInst *CI) {
Dale Johannesence0b2372007-06-12 16:50:17 +0000517 BasicBlock *DefBB = CI->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000518
Dale Johannesence0b2372007-06-12 16:50:17 +0000519 /// InsertedCmp - Only insert a cmp in each block once.
520 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000521
Dale Johannesence0b2372007-06-12 16:50:17 +0000522 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000523 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
Dale Johannesence0b2372007-06-12 16:50:17 +0000524 UI != E; ) {
525 Use &TheUse = UI.getUse();
526 Instruction *User = cast<Instruction>(*UI);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000527
Dale Johannesence0b2372007-06-12 16:50:17 +0000528 // Preincrement use iterator so we don't invalidate it.
529 ++UI;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000530
Dale Johannesence0b2372007-06-12 16:50:17 +0000531 // Don't bother for PHI nodes.
532 if (isa<PHINode>(User))
533 continue;
534
535 // Figure out which BB this cmp is used in.
536 BasicBlock *UserBB = User->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000537
Dale Johannesence0b2372007-06-12 16:50:17 +0000538 // If this user is in the same block as the cmp, don't change the cmp.
539 if (UserBB == DefBB) continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000540
Dale Johannesence0b2372007-06-12 16:50:17 +0000541 // If we have already inserted a cmp into this block, use it.
542 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
543
544 if (!InsertedCmp) {
Dan Gohman02dea8b2008-05-23 21:05:58 +0000545 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000546
547 InsertedCmp =
548 CmpInst::Create(CI->getOpcode(), CI->getPredicate(), CI->getOperand(0),
Dale Johannesence0b2372007-06-12 16:50:17 +0000549 CI->getOperand(1), "", InsertPt);
550 MadeChange = true;
551 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000552
Dale Johannesence0b2372007-06-12 16:50:17 +0000553 // Replace a use of the cmp with a use of the new cmp.
554 TheUse = InsertedCmp;
555 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000556
Dale Johannesence0b2372007-06-12 16:50:17 +0000557 // If we removed all uses, nuke the cmp.
558 if (CI->use_empty())
559 CI->eraseFromParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000560
Dale Johannesence0b2372007-06-12 16:50:17 +0000561 return MadeChange;
562}
563
Chris Lattner88a5c832008-11-25 07:09:13 +0000564//===----------------------------------------------------------------------===//
565// Addressing Mode Analysis and Optimization
566//===----------------------------------------------------------------------===//
567
Chris Lattner88a5c832008-11-25 07:09:13 +0000568//===----------------------------------------------------------------------===//
569// Memory Optimization
570//===----------------------------------------------------------------------===//
571
Chris Lattnerdd77df32007-04-13 20:30:56 +0000572/// IsNonLocalValue - Return true if the specified values are defined in a
573/// different basic block than BB.
574static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
575 if (Instruction *I = dyn_cast<Instruction>(V))
576 return I->getParent() != BB;
577 return false;
578}
579
Chris Lattner88a5c832008-11-25 07:09:13 +0000580/// OptimizeMemoryInst - Load and Store Instructions have often have
Chris Lattnerdd77df32007-04-13 20:30:56 +0000581/// addressing modes that can do significant amounts of computation. As such,
582/// instruction selection will try to get the load or store to do as much
583/// computation as possible for the program. The problem is that isel can only
584/// see within a single block. As such, we sink as much legal addressing mode
585/// stuff into the block as possible.
Chris Lattner88a5c832008-11-25 07:09:13 +0000586///
587/// This method is used to optimize both load/store and inline asms with memory
588/// operands.
Chris Lattner896617b2008-11-26 03:20:37 +0000589bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
Chris Lattner88a5c832008-11-25 07:09:13 +0000590 const Type *AccessTy,
591 DenseMap<Value*,Value*> &SunkAddrs) {
Chris Lattnerdd77df32007-04-13 20:30:56 +0000592 // Figure out what addressing mode will be built up for this operation.
593 SmallVector<Instruction*, 16> AddrModeInsts;
Chris Lattner896617b2008-11-26 03:20:37 +0000594 ExtAddrMode AddrMode = AddressingModeMatcher::Match(Addr, AccessTy,MemoryInst,
595 AddrModeInsts, *TLI);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000596
Chris Lattnerdd77df32007-04-13 20:30:56 +0000597 // Check to see if any of the instructions supersumed by this addr mode are
598 // non-local to I's BB.
599 bool AnyNonLocal = false;
600 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
Chris Lattner896617b2008-11-26 03:20:37 +0000601 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
Chris Lattnerdd77df32007-04-13 20:30:56 +0000602 AnyNonLocal = true;
603 break;
604 }
605 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000606
Chris Lattnerdd77df32007-04-13 20:30:56 +0000607 // If all the instructions matched are already in this BB, don't do anything.
608 if (!AnyNonLocal) {
609 DEBUG(cerr << "CGP: Found local addrmode: " << AddrMode << "\n");
610 return false;
611 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000612
Chris Lattnerdd77df32007-04-13 20:30:56 +0000613 // Insert this computation right after this user. Since our caller is
614 // scanning from the top of the BB to the bottom, reuse of the expr are
615 // guaranteed to happen later.
Chris Lattner896617b2008-11-26 03:20:37 +0000616 BasicBlock::iterator InsertPt = MemoryInst;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000617
Chris Lattnerdd77df32007-04-13 20:30:56 +0000618 // Now that we determined the addressing expression we want to use and know
619 // that we have to sink it into this block. Check to see if we have already
620 // done this for some other load/store instr in this block. If so, reuse the
621 // computation.
622 Value *&SunkAddr = SunkAddrs[Addr];
623 if (SunkAddr) {
Chris Lattner65c02fb2009-02-12 06:56:08 +0000624 DEBUG(cerr << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
625 << *MemoryInst);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000626 if (SunkAddr->getType() != Addr->getType())
627 SunkAddr = new BitCastInst(SunkAddr, Addr->getType(), "tmp", InsertPt);
628 } else {
Chris Lattner65c02fb2009-02-12 06:56:08 +0000629 DEBUG(cerr << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
630 << *MemoryInst);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000631 const Type *IntPtrTy = TLI->getTargetData()->getIntPtrType();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000632
Chris Lattnerdd77df32007-04-13 20:30:56 +0000633 Value *Result = 0;
634 // Start with the scale value.
635 if (AddrMode.Scale) {
636 Value *V = AddrMode.ScaledReg;
637 if (V->getType() == IntPtrTy) {
638 // done.
639 } else if (isa<PointerType>(V->getType())) {
640 V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
641 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
642 cast<IntegerType>(V->getType())->getBitWidth()) {
643 V = new TruncInst(V, IntPtrTy, "sunkaddr", InsertPt);
644 } else {
645 V = new SExtInst(V, IntPtrTy, "sunkaddr", InsertPt);
646 }
647 if (AddrMode.Scale != 1)
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000648 V = BinaryOperator::CreateMul(V, ConstantInt::get(IntPtrTy,
Chris Lattnerdd77df32007-04-13 20:30:56 +0000649 AddrMode.Scale),
650 "sunkaddr", InsertPt);
651 Result = V;
652 }
653
654 // Add in the base register.
655 if (AddrMode.BaseReg) {
656 Value *V = AddrMode.BaseReg;
657 if (V->getType() != IntPtrTy)
658 V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
659 if (Result)
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000660 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000661 else
662 Result = V;
663 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000664
Chris Lattnerdd77df32007-04-13 20:30:56 +0000665 // Add in the BaseGV if present.
666 if (AddrMode.BaseGV) {
667 Value *V = new PtrToIntInst(AddrMode.BaseGV, IntPtrTy, "sunkaddr",
668 InsertPt);
669 if (Result)
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000670 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000671 else
672 Result = V;
673 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000674
Chris Lattnerdd77df32007-04-13 20:30:56 +0000675 // Add in the Base Offset if present.
676 if (AddrMode.BaseOffs) {
677 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
678 if (Result)
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000679 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000680 else
681 Result = V;
682 }
683
684 if (Result == 0)
685 SunkAddr = Constant::getNullValue(Addr->getType());
686 else
687 SunkAddr = new IntToPtrInst(Result, Addr->getType(), "sunkaddr",InsertPt);
688 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000689
Chris Lattner896617b2008-11-26 03:20:37 +0000690 MemoryInst->replaceUsesOfWith(Addr, SunkAddr);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000691
Chris Lattnerdd77df32007-04-13 20:30:56 +0000692 if (Addr->use_empty())
Chris Lattner3481f242008-11-27 22:57:53 +0000693 RecursivelyDeleteTriviallyDeadInstructions(Addr);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000694 return true;
695}
696
Evan Cheng9bf12b52008-02-26 02:42:37 +0000697/// OptimizeInlineAsmInst - If there are any memory operands, use
Chris Lattner88a5c832008-11-25 07:09:13 +0000698/// OptimizeMemoryInst to sink their address computing into the block when
Evan Cheng9bf12b52008-02-26 02:42:37 +0000699/// possible / profitable.
700bool CodeGenPrepare::OptimizeInlineAsmInst(Instruction *I, CallSite CS,
701 DenseMap<Value*,Value*> &SunkAddrs) {
702 bool MadeChange = false;
703 InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
704
705 // Do a prepass over the constraints, canonicalizing them, and building up the
706 // ConstraintOperands list.
707 std::vector<InlineAsm::ConstraintInfo>
708 ConstraintInfos = IA->ParseConstraints();
709
710 /// ConstraintOperands - Information about all of the constraints.
711 std::vector<TargetLowering::AsmOperandInfo> ConstraintOperands;
712 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
713 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
714 ConstraintOperands.
715 push_back(TargetLowering::AsmOperandInfo(ConstraintInfos[i]));
716 TargetLowering::AsmOperandInfo &OpInfo = ConstraintOperands.back();
717
718 // Compute the value type for each operand.
719 switch (OpInfo.Type) {
720 case InlineAsm::isOutput:
721 if (OpInfo.isIndirect)
722 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
723 break;
724 case InlineAsm::isInput:
725 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
726 break;
727 case InlineAsm::isClobber:
728 // Nothing to do.
729 break;
730 }
731
732 // Compute the constraint code and ConstraintType to use.
Evan Chenga7e61462008-09-24 06:48:55 +0000733 TLI->ComputeConstraintToUse(OpInfo, SDValue(),
734 OpInfo.ConstraintType == TargetLowering::C_Memory);
Evan Cheng9bf12b52008-02-26 02:42:37 +0000735
Eli Friedman9ec80952008-02-26 18:37:49 +0000736 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
737 OpInfo.isIndirect) {
Evan Cheng9bf12b52008-02-26 02:42:37 +0000738 Value *OpVal = OpInfo.CallOperandVal;
Chris Lattner88a5c832008-11-25 07:09:13 +0000739 MadeChange |= OptimizeMemoryInst(I, OpVal, OpVal->getType(), SunkAddrs);
Evan Cheng9bf12b52008-02-26 02:42:37 +0000740 }
741 }
742
743 return MadeChange;
744}
745
Evan Chengbdcb7262007-12-05 23:58:20 +0000746bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
747 BasicBlock *DefBB = I->getParent();
748
749 // If both result of the {s|z}xt and its source are live out, rewrite all
750 // other uses of the source with result of extension.
751 Value *Src = I->getOperand(0);
752 if (Src->hasOneUse())
753 return false;
754
Evan Cheng696e5c02007-12-13 07:50:36 +0000755 // Only do this xform if truncating is free.
Gabor Greif53bdbd72008-02-26 19:13:21 +0000756 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
Evan Chengf9785f92007-12-13 03:32:53 +0000757 return false;
758
Evan Cheng772de512007-12-12 00:51:06 +0000759 // Only safe to perform the optimization if the source is also defined in
Evan Cheng765dff22007-12-12 02:53:41 +0000760 // this block.
761 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
Evan Cheng772de512007-12-12 00:51:06 +0000762 return false;
763
Evan Chengbdcb7262007-12-05 23:58:20 +0000764 bool DefIsLiveOut = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000765 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
Evan Chengbdcb7262007-12-05 23:58:20 +0000766 UI != E; ++UI) {
767 Instruction *User = cast<Instruction>(*UI);
768
769 // Figure out which BB this ext is used in.
770 BasicBlock *UserBB = User->getParent();
771 if (UserBB == DefBB) continue;
772 DefIsLiveOut = true;
773 break;
774 }
775 if (!DefIsLiveOut)
776 return false;
777
Evan Cheng765dff22007-12-12 02:53:41 +0000778 // Make sure non of the uses are PHI nodes.
Eric Christopher692bf6b2008-09-24 05:32:41 +0000779 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
Evan Cheng765dff22007-12-12 02:53:41 +0000780 UI != E; ++UI) {
781 Instruction *User = cast<Instruction>(*UI);
Evan Chengf9785f92007-12-13 03:32:53 +0000782 BasicBlock *UserBB = User->getParent();
783 if (UserBB == DefBB) continue;
784 // Be conservative. We don't want this xform to end up introducing
785 // reloads just before load / store instructions.
786 if (isa<PHINode>(User) || isa<LoadInst>(User) || isa<StoreInst>(User))
Evan Cheng765dff22007-12-12 02:53:41 +0000787 return false;
788 }
789
Evan Chengbdcb7262007-12-05 23:58:20 +0000790 // InsertedTruncs - Only insert one trunc in each block once.
791 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
792
793 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000794 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
Evan Chengbdcb7262007-12-05 23:58:20 +0000795 UI != E; ++UI) {
796 Use &TheUse = UI.getUse();
797 Instruction *User = cast<Instruction>(*UI);
798
799 // Figure out which BB this ext is used in.
800 BasicBlock *UserBB = User->getParent();
801 if (UserBB == DefBB) continue;
802
803 // Both src and def are live in this block. Rewrite the use.
804 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
805
806 if (!InsertedTrunc) {
Dan Gohman02dea8b2008-05-23 21:05:58 +0000807 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000808
Evan Chengbdcb7262007-12-05 23:58:20 +0000809 InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
810 }
811
812 // Replace a use of the {s|z}ext source with a use of the result.
813 TheUse = InsertedTrunc;
814
815 MadeChange = true;
816 }
817
818 return MadeChange;
819}
820
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000821// In this pass we look for GEP and cast instructions that are used
822// across basic blocks and rewrite them to improve basic-block-at-a-time
823// selection.
824bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
825 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000826
Evan Chengab631522008-12-19 18:03:11 +0000827 // Split all critical edges where the dest block has a PHI.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000828 TerminatorInst *BBTI = BB.getTerminator();
829 if (BBTI->getNumSuccessors() > 1) {
Evan Chengab631522008-12-19 18:03:11 +0000830 for (unsigned i = 0, e = BBTI->getNumSuccessors(); i != e; ++i) {
831 BasicBlock *SuccBB = BBTI->getSuccessor(i);
832 if (isa<PHINode>(SuccBB->begin()) && isCriticalEdge(BBTI, i, true))
833 SplitEdgeNicely(BBTI, i, BackEdges, this);
834 }
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000835 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000836
Chris Lattnerdd77df32007-04-13 20:30:56 +0000837 // Keep track of non-local addresses that have been sunk into this block.
838 // This allows us to avoid inserting duplicate code for blocks with multiple
839 // load/stores of the same address.
840 DenseMap<Value*, Value*> SunkAddrs;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000841
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000842 for (BasicBlock::iterator BBI = BB.begin(), E = BB.end(); BBI != E; ) {
843 Instruction *I = BBI++;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000844
Chris Lattnerdd77df32007-04-13 20:30:56 +0000845 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000846 // If the source of the cast is a constant, then this should have
847 // already been constant folded. The only reason NOT to constant fold
848 // it is if something (e.g. LSR) was careful to place the constant
849 // evaluation in a block other than then one that uses it (e.g. to hoist
850 // the address of globals out of a loop). If this is the case, we don't
851 // want to forward-subst the cast.
852 if (isa<Constant>(CI->getOperand(0)))
853 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000854
Evan Chengbdcb7262007-12-05 23:58:20 +0000855 bool Change = false;
856 if (TLI) {
857 Change = OptimizeNoopCopyExpression(CI, *TLI);
858 MadeChange |= Change;
859 }
860
Evan Cheng55e641b2008-03-19 22:02:26 +0000861 if (!Change && (isa<ZExtInst>(I) || isa<SExtInst>(I)))
Evan Chengbdcb7262007-12-05 23:58:20 +0000862 MadeChange |= OptimizeExtUses(I);
Dale Johannesence0b2372007-06-12 16:50:17 +0000863 } else if (CmpInst *CI = dyn_cast<CmpInst>(I)) {
864 MadeChange |= OptimizeCmpExpression(CI);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000865 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
866 if (TLI)
Chris Lattner88a5c832008-11-25 07:09:13 +0000867 MadeChange |= OptimizeMemoryInst(I, I->getOperand(0), LI->getType(),
868 SunkAddrs);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000869 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
870 if (TLI)
Chris Lattner88a5c832008-11-25 07:09:13 +0000871 MadeChange |= OptimizeMemoryInst(I, SI->getOperand(1),
872 SI->getOperand(0)->getType(),
873 SunkAddrs);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000874 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Chris Lattnerf25646b2007-04-14 00:17:39 +0000875 if (GEPI->hasAllZeroIndices()) {
Chris Lattnerdd77df32007-04-13 20:30:56 +0000876 /// The GEP operand must be a pointer, so must its result -> BitCast
Eric Christopher692bf6b2008-09-24 05:32:41 +0000877 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
Chris Lattnerdd77df32007-04-13 20:30:56 +0000878 GEPI->getName(), GEPI);
879 GEPI->replaceAllUsesWith(NC);
880 GEPI->eraseFromParent();
881 MadeChange = true;
882 BBI = NC;
883 }
884 } else if (CallInst *CI = dyn_cast<CallInst>(I)) {
885 // If we found an inline asm expession, and if the target knows how to
886 // lower it to normal LLVM code, do so now.
887 if (TLI && isa<InlineAsm>(CI->getCalledValue()))
Eric Christopher692bf6b2008-09-24 05:32:41 +0000888 if (const TargetAsmInfo *TAI =
Chris Lattnerdd77df32007-04-13 20:30:56 +0000889 TLI->getTargetMachine().getTargetAsmInfo()) {
Chris Lattner65c02fb2009-02-12 06:56:08 +0000890 if (TAI->ExpandInlineAsm(CI)) {
Chris Lattnerdd77df32007-04-13 20:30:56 +0000891 BBI = BB.begin();
Chris Lattner65c02fb2009-02-12 06:56:08 +0000892 // Avoid processing instructions out of order, which could cause
893 // reuse before a value is defined.
894 SunkAddrs.clear();
895 } else
Evan Cheng9bf12b52008-02-26 02:42:37 +0000896 // Sink address computing for memory operands into the block.
897 MadeChange |= OptimizeInlineAsmInst(I, &(*CI), SunkAddrs);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000898 }
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000899 }
900 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000901
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000902 return MadeChange;
903}