blob: 4eb49e9a95cd4f772166b54c547838f5c14b8a6c [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
Dale Johannesen2d697242009-03-27 01:13:37 +0000148/// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes,
149/// debug info directives, and an unconditional branch. Passes before isel
150/// (e.g. LSR/loopsimplify) often split edges in ways that are non-optimal for
151/// isel. Start by eliminating these blocks so we can split them the way we
152/// want them.
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000153bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
154 bool MadeChange = false;
155 // Note that this intentionally skips the entry block.
156 for (Function::iterator I = ++F.begin(), E = F.end(); I != E; ) {
157 BasicBlock *BB = I++;
158
159 // If this block doesn't end with an uncond branch, ignore it.
160 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
161 if (!BI || !BI->isUnconditional())
162 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000163
Dale Johannesen2d697242009-03-27 01:13:37 +0000164 // If the instruction before the branch (skipping debug info) isn't a phi
165 // node, then other stuff is happening here.
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000166 BasicBlock::iterator BBI = BI;
167 if (BBI != BB->begin()) {
168 --BBI;
Dale Johannesen2d697242009-03-27 01:13:37 +0000169 while (isa<DbgInfoIntrinsic>(BBI)) {
170 if (BBI == BB->begin())
171 break;
172 --BBI;
173 }
174 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
175 continue;
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000176 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000177
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000178 // Do not break infinite loops.
179 BasicBlock *DestBB = BI->getSuccessor(0);
180 if (DestBB == BB)
181 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000182
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000183 if (!CanMergeBlocks(BB, DestBB))
184 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000185
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000186 EliminateMostlyEmptyBlock(BB);
187 MadeChange = true;
188 }
189 return MadeChange;
190}
191
192/// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
193/// single uncond branch between them, and BB contains no other non-phi
194/// instructions.
195bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
196 const BasicBlock *DestBB) const {
197 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
198 // the successor. If there are more complex condition (e.g. preheaders),
199 // don't mess around with them.
200 BasicBlock::const_iterator BBI = BB->begin();
201 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
202 for (Value::use_const_iterator UI = PN->use_begin(), E = PN->use_end();
203 UI != E; ++UI) {
204 const Instruction *User = cast<Instruction>(*UI);
205 if (User->getParent() != DestBB || !isa<PHINode>(User))
206 return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000207 // If User is inside DestBB block and it is a PHINode then check
208 // incoming value. If incoming value is not from BB then this is
Devang Patel75abc1e2007-04-25 00:37:04 +0000209 // a complex condition (e.g. preheaders) we want to avoid here.
210 if (User->getParent() == DestBB) {
211 if (const PHINode *UPN = dyn_cast<PHINode>(User))
212 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
213 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
214 if (Insn && Insn->getParent() == BB &&
215 Insn->getParent() != UPN->getIncomingBlock(I))
216 return false;
217 }
218 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000219 }
220 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000221
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000222 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
223 // and DestBB may have conflicting incoming values for the block. If so, we
224 // can't merge the block.
225 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
226 if (!DestBBPN) return true; // no conflict.
Eric Christopher692bf6b2008-09-24 05:32:41 +0000227
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000228 // Collect the preds of BB.
Chris Lattnerf67f73a2007-11-06 22:07:40 +0000229 SmallPtrSet<const BasicBlock*, 16> BBPreds;
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000230 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
231 // It is faster to get preds from a PHI than with pred_iterator.
232 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
233 BBPreds.insert(BBPN->getIncomingBlock(i));
234 } else {
235 BBPreds.insert(pred_begin(BB), pred_end(BB));
236 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000237
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000238 // Walk the preds of DestBB.
239 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
240 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
241 if (BBPreds.count(Pred)) { // Common predecessor?
242 BBI = DestBB->begin();
243 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
244 const Value *V1 = PN->getIncomingValueForBlock(Pred);
245 const Value *V2 = PN->getIncomingValueForBlock(BB);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000246
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000247 // If V2 is a phi node in BB, look up what the mapped value will be.
248 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
249 if (V2PN->getParent() == BB)
250 V2 = V2PN->getIncomingValueForBlock(Pred);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000251
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000252 // If there is a conflict, bail out.
253 if (V1 != V2) return false;
254 }
255 }
256 }
257
258 return true;
259}
260
261
262/// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
263/// an unconditional branch in it.
264void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
265 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
266 BasicBlock *DestBB = BI->getSuccessor(0);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000267
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000268 DOUT << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000269
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000270 // If the destination block has a single pred, then this is a trivial edge,
271 // just collapse it.
Chris Lattner9918fb52008-11-27 19:29:14 +0000272 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
Chris Lattnerf5102a02008-11-28 19:54:49 +0000273 if (SinglePred != DestBB) {
274 // Remember if SinglePred was the entry block of the function. If so, we
275 // will need to move BB back to the entry position.
276 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
277 MergeBasicBlockIntoOnlyPred(DestBB);
Chris Lattner9918fb52008-11-27 19:29:14 +0000278
Chris Lattnerf5102a02008-11-28 19:54:49 +0000279 if (isEntry && BB != &BB->getParent()->getEntryBlock())
280 BB->moveBefore(&BB->getParent()->getEntryBlock());
281
282 DOUT << "AFTER:\n" << *DestBB << "\n\n\n";
283 return;
284 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000285 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000286
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000287 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
288 // to handle the new incoming edges it is about to have.
289 PHINode *PN;
290 for (BasicBlock::iterator BBI = DestBB->begin();
291 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
292 // Remove the incoming value for BB, and remember it.
293 Value *InVal = PN->removeIncomingValue(BB, false);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000294
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000295 // Two options: either the InVal is a phi node defined in BB or it is some
296 // value that dominates BB.
297 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
298 if (InValPhi && InValPhi->getParent() == BB) {
299 // Add all of the input values of the input PHI as inputs of this phi.
300 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
301 PN->addIncoming(InValPhi->getIncomingValue(i),
302 InValPhi->getIncomingBlock(i));
303 } else {
304 // Otherwise, add one instance of the dominating value for each edge that
305 // we will be adding.
306 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
307 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
308 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
309 } else {
310 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
311 PN->addIncoming(InVal, *PI);
312 }
313 }
314 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000315
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000316 // The PHIs are now updated, change everything that refers to BB to use
317 // DestBB and remove BB.
318 BB->replaceAllUsesWith(DestBB);
319 BB->eraseFromParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000320
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000321 DOUT << "AFTER:\n" << *DestBB << "\n\n\n";
322}
323
324
Chris Lattnerebe80752007-12-24 19:32:55 +0000325/// SplitEdgeNicely - Split the critical edge from TI to its specified
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000326/// successor if it will improve codegen. We only do this if the successor has
327/// phi nodes (otherwise critical edges are ok). If there is already another
328/// predecessor of the succ that is empty (and thus has no phi nodes), use it
329/// instead of introducing a new block.
Evan Chengab631522008-12-19 18:03:11 +0000330static void SplitEdgeNicely(TerminatorInst *TI, unsigned SuccNum,
331 SmallSet<std::pair<BasicBlock*,BasicBlock*>, 8> &BackEdges,
332 Pass *P) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000333 BasicBlock *TIBB = TI->getParent();
334 BasicBlock *Dest = TI->getSuccessor(SuccNum);
335 assert(isa<PHINode>(Dest->begin()) &&
336 "This should only be called if Dest has a PHI!");
Eric Christopher692bf6b2008-09-24 05:32:41 +0000337
Evan Chengfc0b80d2009-03-13 22:59:14 +0000338 // Do not split edges to EH landing pads.
339 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(TI)) {
340 if (Invoke->getSuccessor(1) == Dest)
341 return;
342 }
343
Chris Lattnerebe80752007-12-24 19:32:55 +0000344 // As a hack, never split backedges of loops. Even though the copy for any
345 // PHIs inserted on the backedge would be dead for exits from the loop, we
346 // assume that the cost of *splitting* the backedge would be too high.
Evan Chengab631522008-12-19 18:03:11 +0000347 if (BackEdges.count(std::make_pair(TIBB, Dest)))
Chris Lattnerebe80752007-12-24 19:32:55 +0000348 return;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000349
Evan Chengab631522008-12-19 18:03:11 +0000350 if (!FactorCommonPreds) {
351 /// TIPHIValues - This array is lazily computed to determine the values of
352 /// PHIs in Dest that TI would provide.
353 SmallVector<Value*, 32> TIPHIValues;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000354
Evan Chengab631522008-12-19 18:03:11 +0000355 // Check to see if Dest has any blocks that can be used as a split edge for
356 // this terminator.
357 for (pred_iterator PI = pred_begin(Dest), E = pred_end(Dest); PI != E; ++PI) {
358 BasicBlock *Pred = *PI;
359 // To be usable, the pred has to end with an uncond branch to the dest.
360 BranchInst *PredBr = dyn_cast<BranchInst>(Pred->getTerminator());
Dale Johannesen6aae1d62009-03-26 01:15:07 +0000361 if (!PredBr || !PredBr->isUnconditional())
362 continue;
363 // Must be empty other than the branch and debug info.
364 BasicBlock::iterator I = Pred->begin();
365 while (isa<DbgInfoIntrinsic>(I))
366 I++;
367 if (dyn_cast<Instruction>(I) != PredBr)
368 continue;
369 // Cannot be the entry block; its label does not get emitted.
370 if (Pred == &(Dest->getParent()->getEntryBlock()))
Evan Chengab631522008-12-19 18:03:11 +0000371 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000372
Evan Chengab631522008-12-19 18:03:11 +0000373 // Finally, since we know that Dest has phi nodes in it, we have to make
Dale Johannesen6aae1d62009-03-26 01:15:07 +0000374 // sure that jumping to Pred will have the same effect as going to Dest in
Evan Chengab631522008-12-19 18:03:11 +0000375 // terms of PHI values.
376 PHINode *PN;
377 unsigned PHINo = 0;
378 bool FoundMatch = true;
379 for (BasicBlock::iterator I = Dest->begin();
380 (PN = dyn_cast<PHINode>(I)); ++I, ++PHINo) {
381 if (PHINo == TIPHIValues.size())
382 TIPHIValues.push_back(PN->getIncomingValueForBlock(TIBB));
Eric Christopher692bf6b2008-09-24 05:32:41 +0000383
Evan Chengab631522008-12-19 18:03:11 +0000384 // If the PHI entry doesn't work, we can't use this pred.
385 if (TIPHIValues[PHINo] != PN->getIncomingValueForBlock(Pred)) {
386 FoundMatch = false;
387 break;
388 }
389 }
390
391 // If we found a workable predecessor, change TI to branch to Succ.
392 if (FoundMatch) {
393 Dest->removePredecessor(TIBB);
394 TI->setSuccessor(SuccNum, Pred);
395 return;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000396 }
397 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000398
Evan Chengab631522008-12-19 18:03:11 +0000399 SplitCriticalEdge(TI, SuccNum, P, true);
400 return;
401 }
402
403 PHINode *PN;
404 SmallVector<Value*, 8> TIPHIValues;
405 for (BasicBlock::iterator I = Dest->begin();
406 (PN = dyn_cast<PHINode>(I)); ++I)
407 TIPHIValues.push_back(PN->getIncomingValueForBlock(TIBB));
408
409 SmallVector<BasicBlock*, 8> IdenticalPreds;
410 for (pred_iterator PI = pred_begin(Dest), E = pred_end(Dest); PI != E; ++PI) {
411 BasicBlock *Pred = *PI;
412 if (BackEdges.count(std::make_pair(Pred, Dest)))
413 continue;
414 if (PI == TIBB)
415 IdenticalPreds.push_back(Pred);
416 else {
417 bool Identical = true;
418 unsigned PHINo = 0;
419 for (BasicBlock::iterator I = Dest->begin();
420 (PN = dyn_cast<PHINode>(I)); ++I, ++PHINo)
421 if (TIPHIValues[PHINo] != PN->getIncomingValueForBlock(Pred)) {
422 Identical = false;
423 break;
424 }
425 if (Identical)
426 IdenticalPreds.push_back(Pred);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000427 }
428 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000429
Evan Chengab631522008-12-19 18:03:11 +0000430 assert(!IdenticalPreds.empty());
431 SplitBlockPredecessors(Dest, &IdenticalPreds[0], IdenticalPreds.size(),
432 ".critedge", P);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000433}
434
Evan Chengab631522008-12-19 18:03:11 +0000435
Chris Lattnerdd77df32007-04-13 20:30:56 +0000436/// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
437/// copy (e.g. it's casting from one pointer type to another, int->uint, or
438/// int->sbyte on PPC), sink it into user blocks to reduce the number of virtual
Dale Johannesence0b2372007-06-12 16:50:17 +0000439/// registers that must be created and coalesced.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000440///
441/// Return true if any changes are made.
Chris Lattner85fa13c2008-11-24 22:44:16 +0000442///
Chris Lattnerdd77df32007-04-13 20:30:56 +0000443static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
Eric Christopher692bf6b2008-09-24 05:32:41 +0000444 // If this is a noop copy,
Duncan Sands83ec4b62008-06-06 12:08:01 +0000445 MVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
446 MVT DstVT = TLI.getValueType(CI->getType());
Eric Christopher692bf6b2008-09-24 05:32:41 +0000447
Chris Lattnerdd77df32007-04-13 20:30:56 +0000448 // This is an fp<->int conversion?
Duncan Sands83ec4b62008-06-06 12:08:01 +0000449 if (SrcVT.isInteger() != DstVT.isInteger())
Chris Lattnerdd77df32007-04-13 20:30:56 +0000450 return false;
Duncan Sands8e4eb092008-06-08 20:54:56 +0000451
Chris Lattnerdd77df32007-04-13 20:30:56 +0000452 // If this is an extension, it will be a zero or sign extension, which
453 // isn't a noop.
Duncan Sands8e4eb092008-06-08 20:54:56 +0000454 if (SrcVT.bitsLT(DstVT)) return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000455
Chris Lattnerdd77df32007-04-13 20:30:56 +0000456 // If these values will be promoted, find out what they will be promoted
457 // to. This helps us consider truncates on PPC as noop copies when they
458 // are.
459 if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote)
460 SrcVT = TLI.getTypeToTransformTo(SrcVT);
461 if (TLI.getTypeAction(DstVT) == TargetLowering::Promote)
462 DstVT = TLI.getTypeToTransformTo(DstVT);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000463
Chris Lattnerdd77df32007-04-13 20:30:56 +0000464 // If, after promotion, these are the same types, this is a noop copy.
465 if (SrcVT != DstVT)
466 return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000467
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000468 BasicBlock *DefBB = CI->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000469
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000470 /// InsertedCasts - Only insert a cast in each block once.
Dale Johannesence0b2372007-06-12 16:50:17 +0000471 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000472
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000473 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000474 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000475 UI != E; ) {
476 Use &TheUse = UI.getUse();
477 Instruction *User = cast<Instruction>(*UI);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000478
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000479 // Figure out which BB this cast is used in. For PHI's this is the
480 // appropriate predecessor block.
481 BasicBlock *UserBB = User->getParent();
482 if (PHINode *PN = dyn_cast<PHINode>(User)) {
Gabor Greifa36791d2009-01-23 19:40:15 +0000483 UserBB = PN->getIncomingBlock(UI);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000484 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000485
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000486 // Preincrement use iterator so we don't invalidate it.
487 ++UI;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000488
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000489 // If this user is in the same block as the cast, don't change the cast.
490 if (UserBB == DefBB) continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000491
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000492 // If we have already inserted a cast into this block, use it.
493 CastInst *&InsertedCast = InsertedCasts[UserBB];
494
495 if (!InsertedCast) {
Dan Gohman02dea8b2008-05-23 21:05:58 +0000496 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000497
498 InsertedCast =
499 CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000500 InsertPt);
501 MadeChange = true;
502 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000503
Dale Johannesence0b2372007-06-12 16:50:17 +0000504 // Replace a use of the cast with a use of the new cast.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000505 TheUse = InsertedCast;
506 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000507
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000508 // If we removed all uses, nuke the cast.
Duncan Sandse0038132008-01-20 16:51:46 +0000509 if (CI->use_empty()) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000510 CI->eraseFromParent();
Duncan Sandse0038132008-01-20 16:51:46 +0000511 MadeChange = true;
512 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000513
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000514 return MadeChange;
515}
516
Eric Christopher692bf6b2008-09-24 05:32:41 +0000517/// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
Dale Johannesence0b2372007-06-12 16:50:17 +0000518/// the number of virtual registers that must be created and coalesced. This is
Chris Lattner684b22d2007-08-02 16:53:43 +0000519/// a clear win except on targets with multiple condition code registers
520/// (PowerPC), where it might lose; some adjustment may be wanted there.
Dale Johannesence0b2372007-06-12 16:50:17 +0000521///
522/// Return true if any changes are made.
Chris Lattner85fa13c2008-11-24 22:44:16 +0000523static bool OptimizeCmpExpression(CmpInst *CI) {
Dale Johannesence0b2372007-06-12 16:50:17 +0000524 BasicBlock *DefBB = CI->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000525
Dale Johannesence0b2372007-06-12 16:50:17 +0000526 /// InsertedCmp - Only insert a cmp in each block once.
527 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000528
Dale Johannesence0b2372007-06-12 16:50:17 +0000529 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000530 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
Dale Johannesence0b2372007-06-12 16:50:17 +0000531 UI != E; ) {
532 Use &TheUse = UI.getUse();
533 Instruction *User = cast<Instruction>(*UI);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000534
Dale Johannesence0b2372007-06-12 16:50:17 +0000535 // Preincrement use iterator so we don't invalidate it.
536 ++UI;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000537
Dale Johannesence0b2372007-06-12 16:50:17 +0000538 // Don't bother for PHI nodes.
539 if (isa<PHINode>(User))
540 continue;
541
542 // Figure out which BB this cmp is used in.
543 BasicBlock *UserBB = User->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000544
Dale Johannesence0b2372007-06-12 16:50:17 +0000545 // If this user is in the same block as the cmp, don't change the cmp.
546 if (UserBB == DefBB) continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000547
Dale Johannesence0b2372007-06-12 16:50:17 +0000548 // If we have already inserted a cmp into this block, use it.
549 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
550
551 if (!InsertedCmp) {
Dan Gohman02dea8b2008-05-23 21:05:58 +0000552 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000553
554 InsertedCmp =
555 CmpInst::Create(CI->getOpcode(), CI->getPredicate(), CI->getOperand(0),
Dale Johannesence0b2372007-06-12 16:50:17 +0000556 CI->getOperand(1), "", InsertPt);
557 MadeChange = true;
558 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000559
Dale Johannesence0b2372007-06-12 16:50:17 +0000560 // Replace a use of the cmp with a use of the new cmp.
561 TheUse = InsertedCmp;
562 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000563
Dale Johannesence0b2372007-06-12 16:50:17 +0000564 // If we removed all uses, nuke the cmp.
565 if (CI->use_empty())
566 CI->eraseFromParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000567
Dale Johannesence0b2372007-06-12 16:50:17 +0000568 return MadeChange;
569}
570
Chris Lattner88a5c832008-11-25 07:09:13 +0000571//===----------------------------------------------------------------------===//
572// Addressing Mode Analysis and Optimization
573//===----------------------------------------------------------------------===//
574
Chris Lattner88a5c832008-11-25 07:09:13 +0000575//===----------------------------------------------------------------------===//
576// Memory Optimization
577//===----------------------------------------------------------------------===//
578
Chris Lattnerdd77df32007-04-13 20:30:56 +0000579/// IsNonLocalValue - Return true if the specified values are defined in a
580/// different basic block than BB.
581static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
582 if (Instruction *I = dyn_cast<Instruction>(V))
583 return I->getParent() != BB;
584 return false;
585}
586
Chris Lattner88a5c832008-11-25 07:09:13 +0000587/// OptimizeMemoryInst - Load and Store Instructions have often have
Chris Lattnerdd77df32007-04-13 20:30:56 +0000588/// addressing modes that can do significant amounts of computation. As such,
589/// instruction selection will try to get the load or store to do as much
590/// computation as possible for the program. The problem is that isel can only
591/// see within a single block. As such, we sink as much legal addressing mode
592/// stuff into the block as possible.
Chris Lattner88a5c832008-11-25 07:09:13 +0000593///
594/// This method is used to optimize both load/store and inline asms with memory
595/// operands.
Chris Lattner896617b2008-11-26 03:20:37 +0000596bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
Chris Lattner88a5c832008-11-25 07:09:13 +0000597 const Type *AccessTy,
598 DenseMap<Value*,Value*> &SunkAddrs) {
Chris Lattnerdd77df32007-04-13 20:30:56 +0000599 // Figure out what addressing mode will be built up for this operation.
600 SmallVector<Instruction*, 16> AddrModeInsts;
Chris Lattner896617b2008-11-26 03:20:37 +0000601 ExtAddrMode AddrMode = AddressingModeMatcher::Match(Addr, AccessTy,MemoryInst,
602 AddrModeInsts, *TLI);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000603
Chris Lattnerdd77df32007-04-13 20:30:56 +0000604 // Check to see if any of the instructions supersumed by this addr mode are
605 // non-local to I's BB.
606 bool AnyNonLocal = false;
607 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
Chris Lattner896617b2008-11-26 03:20:37 +0000608 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
Chris Lattnerdd77df32007-04-13 20:30:56 +0000609 AnyNonLocal = true;
610 break;
611 }
612 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000613
Chris Lattnerdd77df32007-04-13 20:30:56 +0000614 // If all the instructions matched are already in this BB, don't do anything.
615 if (!AnyNonLocal) {
616 DEBUG(cerr << "CGP: Found local addrmode: " << AddrMode << "\n");
617 return false;
618 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000619
Chris Lattnerdd77df32007-04-13 20:30:56 +0000620 // Insert this computation right after this user. Since our caller is
621 // scanning from the top of the BB to the bottom, reuse of the expr are
622 // guaranteed to happen later.
Chris Lattner896617b2008-11-26 03:20:37 +0000623 BasicBlock::iterator InsertPt = MemoryInst;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000624
Chris Lattnerdd77df32007-04-13 20:30:56 +0000625 // Now that we determined the addressing expression we want to use and know
626 // that we have to sink it into this block. Check to see if we have already
627 // done this for some other load/store instr in this block. If so, reuse the
628 // computation.
629 Value *&SunkAddr = SunkAddrs[Addr];
630 if (SunkAddr) {
Chris Lattner65c02fb2009-02-12 06:56:08 +0000631 DEBUG(cerr << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
632 << *MemoryInst);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000633 if (SunkAddr->getType() != Addr->getType())
634 SunkAddr = new BitCastInst(SunkAddr, Addr->getType(), "tmp", InsertPt);
635 } else {
Chris Lattner65c02fb2009-02-12 06:56:08 +0000636 DEBUG(cerr << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
637 << *MemoryInst);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000638 const Type *IntPtrTy = TLI->getTargetData()->getIntPtrType();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000639
Chris Lattnerdd77df32007-04-13 20:30:56 +0000640 Value *Result = 0;
641 // Start with the scale value.
642 if (AddrMode.Scale) {
643 Value *V = AddrMode.ScaledReg;
644 if (V->getType() == IntPtrTy) {
645 // done.
646 } else if (isa<PointerType>(V->getType())) {
647 V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
648 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
649 cast<IntegerType>(V->getType())->getBitWidth()) {
650 V = new TruncInst(V, IntPtrTy, "sunkaddr", InsertPt);
651 } else {
652 V = new SExtInst(V, IntPtrTy, "sunkaddr", InsertPt);
653 }
654 if (AddrMode.Scale != 1)
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000655 V = BinaryOperator::CreateMul(V, ConstantInt::get(IntPtrTy,
Chris Lattnerdd77df32007-04-13 20:30:56 +0000656 AddrMode.Scale),
657 "sunkaddr", InsertPt);
658 Result = V;
659 }
660
661 // Add in the base register.
662 if (AddrMode.BaseReg) {
663 Value *V = AddrMode.BaseReg;
664 if (V->getType() != IntPtrTy)
665 V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
666 if (Result)
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000667 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000668 else
669 Result = V;
670 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000671
Chris Lattnerdd77df32007-04-13 20:30:56 +0000672 // Add in the BaseGV if present.
673 if (AddrMode.BaseGV) {
674 Value *V = new PtrToIntInst(AddrMode.BaseGV, IntPtrTy, "sunkaddr",
675 InsertPt);
676 if (Result)
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000677 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000678 else
679 Result = V;
680 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000681
Chris Lattnerdd77df32007-04-13 20:30:56 +0000682 // Add in the Base Offset if present.
683 if (AddrMode.BaseOffs) {
684 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
685 if (Result)
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000686 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000687 else
688 Result = V;
689 }
690
691 if (Result == 0)
692 SunkAddr = Constant::getNullValue(Addr->getType());
693 else
694 SunkAddr = new IntToPtrInst(Result, Addr->getType(), "sunkaddr",InsertPt);
695 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000696
Chris Lattner896617b2008-11-26 03:20:37 +0000697 MemoryInst->replaceUsesOfWith(Addr, SunkAddr);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000698
Chris Lattnerdd77df32007-04-13 20:30:56 +0000699 if (Addr->use_empty())
Chris Lattner3481f242008-11-27 22:57:53 +0000700 RecursivelyDeleteTriviallyDeadInstructions(Addr);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000701 return true;
702}
703
Evan Cheng9bf12b52008-02-26 02:42:37 +0000704/// OptimizeInlineAsmInst - If there are any memory operands, use
Chris Lattner88a5c832008-11-25 07:09:13 +0000705/// OptimizeMemoryInst to sink their address computing into the block when
Evan Cheng9bf12b52008-02-26 02:42:37 +0000706/// possible / profitable.
707bool CodeGenPrepare::OptimizeInlineAsmInst(Instruction *I, CallSite CS,
708 DenseMap<Value*,Value*> &SunkAddrs) {
709 bool MadeChange = false;
710 InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
711
712 // Do a prepass over the constraints, canonicalizing them, and building up the
713 // ConstraintOperands list.
714 std::vector<InlineAsm::ConstraintInfo>
715 ConstraintInfos = IA->ParseConstraints();
716
717 /// ConstraintOperands - Information about all of the constraints.
718 std::vector<TargetLowering::AsmOperandInfo> ConstraintOperands;
719 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
720 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
721 ConstraintOperands.
722 push_back(TargetLowering::AsmOperandInfo(ConstraintInfos[i]));
723 TargetLowering::AsmOperandInfo &OpInfo = ConstraintOperands.back();
724
725 // Compute the value type for each operand.
726 switch (OpInfo.Type) {
727 case InlineAsm::isOutput:
728 if (OpInfo.isIndirect)
729 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
730 break;
731 case InlineAsm::isInput:
732 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
733 break;
734 case InlineAsm::isClobber:
735 // Nothing to do.
736 break;
737 }
738
739 // Compute the constraint code and ConstraintType to use.
Evan Chenga7e61462008-09-24 06:48:55 +0000740 TLI->ComputeConstraintToUse(OpInfo, SDValue(),
741 OpInfo.ConstraintType == TargetLowering::C_Memory);
Evan Cheng9bf12b52008-02-26 02:42:37 +0000742
Eli Friedman9ec80952008-02-26 18:37:49 +0000743 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
744 OpInfo.isIndirect) {
Evan Cheng9bf12b52008-02-26 02:42:37 +0000745 Value *OpVal = OpInfo.CallOperandVal;
Chris Lattner88a5c832008-11-25 07:09:13 +0000746 MadeChange |= OptimizeMemoryInst(I, OpVal, OpVal->getType(), SunkAddrs);
Evan Cheng9bf12b52008-02-26 02:42:37 +0000747 }
748 }
749
750 return MadeChange;
751}
752
Evan Chengbdcb7262007-12-05 23:58:20 +0000753bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
754 BasicBlock *DefBB = I->getParent();
755
756 // If both result of the {s|z}xt and its source are live out, rewrite all
757 // other uses of the source with result of extension.
758 Value *Src = I->getOperand(0);
759 if (Src->hasOneUse())
760 return false;
761
Evan Cheng696e5c02007-12-13 07:50:36 +0000762 // Only do this xform if truncating is free.
Gabor Greif53bdbd72008-02-26 19:13:21 +0000763 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
Evan Chengf9785f92007-12-13 03:32:53 +0000764 return false;
765
Evan Cheng772de512007-12-12 00:51:06 +0000766 // Only safe to perform the optimization if the source is also defined in
Evan Cheng765dff22007-12-12 02:53:41 +0000767 // this block.
768 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
Evan Cheng772de512007-12-12 00:51:06 +0000769 return false;
770
Evan Chengbdcb7262007-12-05 23:58:20 +0000771 bool DefIsLiveOut = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000772 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
Evan Chengbdcb7262007-12-05 23:58:20 +0000773 UI != E; ++UI) {
774 Instruction *User = cast<Instruction>(*UI);
775
776 // Figure out which BB this ext is used in.
777 BasicBlock *UserBB = User->getParent();
778 if (UserBB == DefBB) continue;
779 DefIsLiveOut = true;
780 break;
781 }
782 if (!DefIsLiveOut)
783 return false;
784
Evan Cheng765dff22007-12-12 02:53:41 +0000785 // Make sure non of the uses are PHI nodes.
Eric Christopher692bf6b2008-09-24 05:32:41 +0000786 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
Evan Cheng765dff22007-12-12 02:53:41 +0000787 UI != E; ++UI) {
788 Instruction *User = cast<Instruction>(*UI);
Evan Chengf9785f92007-12-13 03:32:53 +0000789 BasicBlock *UserBB = User->getParent();
790 if (UserBB == DefBB) continue;
791 // Be conservative. We don't want this xform to end up introducing
792 // reloads just before load / store instructions.
793 if (isa<PHINode>(User) || isa<LoadInst>(User) || isa<StoreInst>(User))
Evan Cheng765dff22007-12-12 02:53:41 +0000794 return false;
795 }
796
Evan Chengbdcb7262007-12-05 23:58:20 +0000797 // InsertedTruncs - Only insert one trunc in each block once.
798 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
799
800 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000801 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
Evan Chengbdcb7262007-12-05 23:58:20 +0000802 UI != E; ++UI) {
803 Use &TheUse = UI.getUse();
804 Instruction *User = cast<Instruction>(*UI);
805
806 // Figure out which BB this ext is used in.
807 BasicBlock *UserBB = User->getParent();
808 if (UserBB == DefBB) continue;
809
810 // Both src and def are live in this block. Rewrite the use.
811 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
812
813 if (!InsertedTrunc) {
Dan Gohman02dea8b2008-05-23 21:05:58 +0000814 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000815
Evan Chengbdcb7262007-12-05 23:58:20 +0000816 InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
817 }
818
819 // Replace a use of the {s|z}ext source with a use of the result.
820 TheUse = InsertedTrunc;
821
822 MadeChange = true;
823 }
824
825 return MadeChange;
826}
827
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000828// In this pass we look for GEP and cast instructions that are used
829// across basic blocks and rewrite them to improve basic-block-at-a-time
830// selection.
831bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
832 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000833
Evan Chengab631522008-12-19 18:03:11 +0000834 // Split all critical edges where the dest block has a PHI.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000835 TerminatorInst *BBTI = BB.getTerminator();
836 if (BBTI->getNumSuccessors() > 1) {
Evan Chengab631522008-12-19 18:03:11 +0000837 for (unsigned i = 0, e = BBTI->getNumSuccessors(); i != e; ++i) {
838 BasicBlock *SuccBB = BBTI->getSuccessor(i);
839 if (isa<PHINode>(SuccBB->begin()) && isCriticalEdge(BBTI, i, true))
840 SplitEdgeNicely(BBTI, i, BackEdges, this);
841 }
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000842 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000843
Chris Lattnerdd77df32007-04-13 20:30:56 +0000844 // Keep track of non-local addresses that have been sunk into this block.
845 // This allows us to avoid inserting duplicate code for blocks with multiple
846 // load/stores of the same address.
847 DenseMap<Value*, Value*> SunkAddrs;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000848
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000849 for (BasicBlock::iterator BBI = BB.begin(), E = BB.end(); BBI != E; ) {
850 Instruction *I = BBI++;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000851
Chris Lattnerdd77df32007-04-13 20:30:56 +0000852 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000853 // If the source of the cast is a constant, then this should have
854 // already been constant folded. The only reason NOT to constant fold
855 // it is if something (e.g. LSR) was careful to place the constant
856 // evaluation in a block other than then one that uses it (e.g. to hoist
857 // the address of globals out of a loop). If this is the case, we don't
858 // want to forward-subst the cast.
859 if (isa<Constant>(CI->getOperand(0)))
860 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000861
Evan Chengbdcb7262007-12-05 23:58:20 +0000862 bool Change = false;
863 if (TLI) {
864 Change = OptimizeNoopCopyExpression(CI, *TLI);
865 MadeChange |= Change;
866 }
867
Evan Cheng55e641b2008-03-19 22:02:26 +0000868 if (!Change && (isa<ZExtInst>(I) || isa<SExtInst>(I)))
Evan Chengbdcb7262007-12-05 23:58:20 +0000869 MadeChange |= OptimizeExtUses(I);
Dale Johannesence0b2372007-06-12 16:50:17 +0000870 } else if (CmpInst *CI = dyn_cast<CmpInst>(I)) {
871 MadeChange |= OptimizeCmpExpression(CI);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000872 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
873 if (TLI)
Chris Lattner88a5c832008-11-25 07:09:13 +0000874 MadeChange |= OptimizeMemoryInst(I, I->getOperand(0), LI->getType(),
875 SunkAddrs);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000876 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
877 if (TLI)
Chris Lattner88a5c832008-11-25 07:09:13 +0000878 MadeChange |= OptimizeMemoryInst(I, SI->getOperand(1),
879 SI->getOperand(0)->getType(),
880 SunkAddrs);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000881 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Chris Lattnerf25646b2007-04-14 00:17:39 +0000882 if (GEPI->hasAllZeroIndices()) {
Chris Lattnerdd77df32007-04-13 20:30:56 +0000883 /// The GEP operand must be a pointer, so must its result -> BitCast
Eric Christopher692bf6b2008-09-24 05:32:41 +0000884 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
Chris Lattnerdd77df32007-04-13 20:30:56 +0000885 GEPI->getName(), GEPI);
886 GEPI->replaceAllUsesWith(NC);
887 GEPI->eraseFromParent();
888 MadeChange = true;
889 BBI = NC;
890 }
891 } else if (CallInst *CI = dyn_cast<CallInst>(I)) {
892 // If we found an inline asm expession, and if the target knows how to
893 // lower it to normal LLVM code, do so now.
894 if (TLI && isa<InlineAsm>(CI->getCalledValue()))
Eric Christopher692bf6b2008-09-24 05:32:41 +0000895 if (const TargetAsmInfo *TAI =
Chris Lattnerdd77df32007-04-13 20:30:56 +0000896 TLI->getTargetMachine().getTargetAsmInfo()) {
Chris Lattner65c02fb2009-02-12 06:56:08 +0000897 if (TAI->ExpandInlineAsm(CI)) {
Chris Lattnerdd77df32007-04-13 20:30:56 +0000898 BBI = BB.begin();
Chris Lattner65c02fb2009-02-12 06:56:08 +0000899 // Avoid processing instructions out of order, which could cause
900 // reuse before a value is defined.
901 SunkAddrs.clear();
902 } else
Evan Cheng9bf12b52008-02-26 02:42:37 +0000903 // Sink address computing for memory operands into the block.
904 MadeChange |= OptimizeInlineAsmInst(I, &(*CI), SunkAddrs);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000905 }
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000906 }
907 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000908
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000909 return MadeChange;
910}