blob: 1d06a24a430086743e710217d3751008d61bc0b3 [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"
Owen Andersond672ecb2009-07-03 00:17:18 +000024#include "llvm/LLVMContext.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000025#include "llvm/Pass.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000026#include "llvm/Target/TargetData.h"
27#include "llvm/Target/TargetLowering.h"
Evan Chenga1fd5b32009-02-20 18:24:38 +000028#include "llvm/Transforms/Utils/AddrModeMatcher.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000029#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattnerdd77df32007-04-13 20:30:56 +000030#include "llvm/Transforms/Utils/Local.h"
31#include "llvm/ADT/DenseMap.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000032#include "llvm/ADT/SmallSet.h"
Dan Gohman03ce0422009-02-13 17:45:12 +000033#include "llvm/Assembly/Writer.h"
Evan Cheng9bf12b52008-02-26 02:42:37 +000034#include "llvm/Support/CallSite.h"
Evan Chengab631522008-12-19 18:03:11 +000035#include "llvm/Support/CommandLine.h"
Evan Chengbdcb7262007-12-05 23:58:20 +000036#include "llvm/Support/Debug.h"
Chris Lattnerdd77df32007-04-13 20:30:56 +000037#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner088a1e82008-11-25 04:42:10 +000038#include "llvm/Support/PatternMatch.h"
Dan Gohman6c1980b2009-07-25 01:13:51 +000039#include "llvm/Support/raw_ostream.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000040using namespace llvm;
Chris Lattner088a1e82008-11-25 04:42:10 +000041using namespace llvm::PatternMatch;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000042
Evan Chengab631522008-12-19 18:03:11 +000043static cl::opt<bool> FactorCommonPreds("split-critical-paths-tweak",
44 cl::init(false), cl::Hidden);
45
Eric Christopher692bf6b2008-09-24 05:32:41 +000046namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +000047 class CodeGenPrepare : public FunctionPass {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000048 /// TLI - Keep a pointer of a TargetLowering to consult for determining
49 /// transformation profitability.
50 const TargetLowering *TLI;
Evan Chengab631522008-12-19 18:03:11 +000051
52 /// BackEdges - Keep a set of all the loop back edges.
53 ///
Mike Stumpfe095f32009-05-04 18:40:41 +000054 SmallSet<std::pair<const BasicBlock*, const BasicBlock*>, 8> BackEdges;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000055 public:
Nick Lewyckyecd94c82007-05-06 13:37:16 +000056 static char ID; // Pass identification, replacement for typeid
Dan Gohmanc2bbfc12007-08-01 15:32:29 +000057 explicit CodeGenPrepare(const TargetLowering *tli = 0)
Dan Gohmanae73dc12008-09-04 17:05:41 +000058 : FunctionPass(&ID), TLI(tli) {}
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000059 bool runOnFunction(Function &F);
Eric Christopher692bf6b2008-09-24 05:32:41 +000060
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000061 private:
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +000062 bool EliminateMostlyEmptyBlocks(Function &F);
63 bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
64 void EliminateMostlyEmptyBlock(BasicBlock *BB);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000065 bool OptimizeBlock(BasicBlock &BB);
Chris Lattner88a5c832008-11-25 07:09:13 +000066 bool OptimizeMemoryInst(Instruction *I, Value *Addr, const Type *AccessTy,
67 DenseMap<Value*,Value*> &SunkAddrs);
Evan Cheng9bf12b52008-02-26 02:42:37 +000068 bool OptimizeInlineAsmInst(Instruction *I, CallSite CS,
69 DenseMap<Value*,Value*> &SunkAddrs);
Evan Chengbdcb7262007-12-05 23:58:20 +000070 bool OptimizeExtUses(Instruction *I);
Mike Stumpfe095f32009-05-04 18:40:41 +000071 void findLoopBackEdges(const Function &F);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000072 };
73}
Devang Patel794fd752007-05-01 21:15:47 +000074
Devang Patel19974732007-05-03 01:11:54 +000075char CodeGenPrepare::ID = 0;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000076static RegisterPass<CodeGenPrepare> X("codegenprepare",
77 "Optimize for code generation");
78
79FunctionPass *llvm::createCodeGenPreparePass(const TargetLowering *TLI) {
80 return new CodeGenPrepare(TLI);
81}
82
Evan Chengab631522008-12-19 18:03:11 +000083/// findLoopBackEdges - Do a DFS walk to find loop back edges.
84///
Mike Stumpfe095f32009-05-04 18:40:41 +000085void CodeGenPrepare::findLoopBackEdges(const Function &F) {
86 SmallVector<std::pair<const BasicBlock*,const BasicBlock*>, 32> Edges;
87 FindFunctionBackedges(F, Edges);
88
89 BackEdges.insert(Edges.begin(), Edges.end());
Evan Chengab631522008-12-19 18:03:11 +000090}
91
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000092
93bool CodeGenPrepare::runOnFunction(Function &F) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000094 bool EverMadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +000095
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +000096 // First pass, eliminate blocks that contain only PHI nodes and an
97 // unconditional branch.
98 EverMadeChange |= EliminateMostlyEmptyBlocks(F);
Eric Christopher692bf6b2008-09-24 05:32:41 +000099
Evan Cheng7e66c0d2009-01-05 21:17:27 +0000100 // Now find loop back edges.
101 findLoopBackEdges(F);
102
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000103 bool MadeChange = true;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000104 while (MadeChange) {
105 MadeChange = false;
106 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
107 MadeChange |= OptimizeBlock(*BB);
108 EverMadeChange |= MadeChange;
109 }
110 return EverMadeChange;
111}
112
Dale Johannesen2d697242009-03-27 01:13:37 +0000113/// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes,
114/// debug info directives, and an unconditional branch. Passes before isel
115/// (e.g. LSR/loopsimplify) often split edges in ways that are non-optimal for
116/// isel. Start by eliminating these blocks so we can split them the way we
117/// want them.
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000118bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
119 bool MadeChange = false;
120 // Note that this intentionally skips the entry block.
121 for (Function::iterator I = ++F.begin(), E = F.end(); I != E; ) {
122 BasicBlock *BB = I++;
123
124 // If this block doesn't end with an uncond branch, ignore it.
125 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
126 if (!BI || !BI->isUnconditional())
127 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000128
Dale Johannesen2d697242009-03-27 01:13:37 +0000129 // If the instruction before the branch (skipping debug info) isn't a phi
130 // node, then other stuff is happening here.
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000131 BasicBlock::iterator BBI = BI;
132 if (BBI != BB->begin()) {
133 --BBI;
Dale Johannesen2d697242009-03-27 01:13:37 +0000134 while (isa<DbgInfoIntrinsic>(BBI)) {
135 if (BBI == BB->begin())
136 break;
137 --BBI;
138 }
139 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
140 continue;
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000141 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000142
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000143 // Do not break infinite loops.
144 BasicBlock *DestBB = BI->getSuccessor(0);
145 if (DestBB == BB)
146 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000147
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000148 if (!CanMergeBlocks(BB, DestBB))
149 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000150
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000151 EliminateMostlyEmptyBlock(BB);
152 MadeChange = true;
153 }
154 return MadeChange;
155}
156
157/// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
158/// single uncond branch between them, and BB contains no other non-phi
159/// instructions.
160bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
161 const BasicBlock *DestBB) const {
162 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
163 // the successor. If there are more complex condition (e.g. preheaders),
164 // don't mess around with them.
165 BasicBlock::const_iterator BBI = BB->begin();
166 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
167 for (Value::use_const_iterator UI = PN->use_begin(), E = PN->use_end();
168 UI != E; ++UI) {
169 const Instruction *User = cast<Instruction>(*UI);
170 if (User->getParent() != DestBB || !isa<PHINode>(User))
171 return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000172 // If User is inside DestBB block and it is a PHINode then check
173 // incoming value. If incoming value is not from BB then this is
Devang Patel75abc1e2007-04-25 00:37:04 +0000174 // a complex condition (e.g. preheaders) we want to avoid here.
175 if (User->getParent() == DestBB) {
176 if (const PHINode *UPN = dyn_cast<PHINode>(User))
177 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
178 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
179 if (Insn && Insn->getParent() == BB &&
180 Insn->getParent() != UPN->getIncomingBlock(I))
181 return false;
182 }
183 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000184 }
185 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000186
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000187 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
188 // and DestBB may have conflicting incoming values for the block. If so, we
189 // can't merge the block.
190 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
191 if (!DestBBPN) return true; // no conflict.
Eric Christopher692bf6b2008-09-24 05:32:41 +0000192
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000193 // Collect the preds of BB.
Chris Lattnerf67f73a2007-11-06 22:07:40 +0000194 SmallPtrSet<const BasicBlock*, 16> BBPreds;
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000195 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
196 // It is faster to get preds from a PHI than with pred_iterator.
197 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
198 BBPreds.insert(BBPN->getIncomingBlock(i));
199 } else {
200 BBPreds.insert(pred_begin(BB), pred_end(BB));
201 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000202
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000203 // Walk the preds of DestBB.
204 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
205 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
206 if (BBPreds.count(Pred)) { // Common predecessor?
207 BBI = DestBB->begin();
208 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
209 const Value *V1 = PN->getIncomingValueForBlock(Pred);
210 const Value *V2 = PN->getIncomingValueForBlock(BB);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000211
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000212 // If V2 is a phi node in BB, look up what the mapped value will be.
213 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
214 if (V2PN->getParent() == BB)
215 V2 = V2PN->getIncomingValueForBlock(Pred);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000216
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000217 // If there is a conflict, bail out.
218 if (V1 != V2) return false;
219 }
220 }
221 }
222
223 return true;
224}
225
226
227/// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
228/// an unconditional branch in it.
229void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
230 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
231 BasicBlock *DestBB = BI->getSuccessor(0);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000232
Chris Lattnerbdff5482009-08-23 04:37:46 +0000233 DEBUG(errs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000234
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000235 // If the destination block has a single pred, then this is a trivial edge,
236 // just collapse it.
Chris Lattner9918fb52008-11-27 19:29:14 +0000237 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
Chris Lattnerf5102a02008-11-28 19:54:49 +0000238 if (SinglePred != DestBB) {
239 // Remember if SinglePred was the entry block of the function. If so, we
240 // will need to move BB back to the entry position.
241 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
242 MergeBasicBlockIntoOnlyPred(DestBB);
Chris Lattner9918fb52008-11-27 19:29:14 +0000243
Chris Lattnerf5102a02008-11-28 19:54:49 +0000244 if (isEntry && BB != &BB->getParent()->getEntryBlock())
245 BB->moveBefore(&BB->getParent()->getEntryBlock());
246
Chris Lattnerbdff5482009-08-23 04:37:46 +0000247 DEBUG(errs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerf5102a02008-11-28 19:54:49 +0000248 return;
249 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000250 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000251
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000252 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
253 // to handle the new incoming edges it is about to have.
254 PHINode *PN;
255 for (BasicBlock::iterator BBI = DestBB->begin();
256 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
257 // Remove the incoming value for BB, and remember it.
258 Value *InVal = PN->removeIncomingValue(BB, false);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000259
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000260 // Two options: either the InVal is a phi node defined in BB or it is some
261 // value that dominates BB.
262 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
263 if (InValPhi && InValPhi->getParent() == BB) {
264 // Add all of the input values of the input PHI as inputs of this phi.
265 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
266 PN->addIncoming(InValPhi->getIncomingValue(i),
267 InValPhi->getIncomingBlock(i));
268 } else {
269 // Otherwise, add one instance of the dominating value for each edge that
270 // we will be adding.
271 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
272 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
273 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
274 } else {
275 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
276 PN->addIncoming(InVal, *PI);
277 }
278 }
279 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000280
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000281 // The PHIs are now updated, change everything that refers to BB to use
282 // DestBB and remove BB.
283 BB->replaceAllUsesWith(DestBB);
284 BB->eraseFromParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000285
Chris Lattnerbdff5482009-08-23 04:37:46 +0000286 DEBUG(errs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000287}
288
289
Chris Lattnerebe80752007-12-24 19:32:55 +0000290/// SplitEdgeNicely - Split the critical edge from TI to its specified
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000291/// successor if it will improve codegen. We only do this if the successor has
292/// phi nodes (otherwise critical edges are ok). If there is already another
293/// predecessor of the succ that is empty (and thus has no phi nodes), use it
294/// instead of introducing a new block.
Evan Chengab631522008-12-19 18:03:11 +0000295static void SplitEdgeNicely(TerminatorInst *TI, unsigned SuccNum,
Mike Stumpfe095f32009-05-04 18:40:41 +0000296 SmallSet<std::pair<const BasicBlock*,
297 const BasicBlock*>, 8> &BackEdges,
Evan Chengab631522008-12-19 18:03:11 +0000298 Pass *P) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000299 BasicBlock *TIBB = TI->getParent();
300 BasicBlock *Dest = TI->getSuccessor(SuccNum);
301 assert(isa<PHINode>(Dest->begin()) &&
302 "This should only be called if Dest has a PHI!");
Eric Christopher692bf6b2008-09-24 05:32:41 +0000303
Evan Chengfc0b80d2009-03-13 22:59:14 +0000304 // Do not split edges to EH landing pads.
305 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(TI)) {
306 if (Invoke->getSuccessor(1) == Dest)
307 return;
308 }
309
Chris Lattnerebe80752007-12-24 19:32:55 +0000310 // As a hack, never split backedges of loops. Even though the copy for any
311 // PHIs inserted on the backedge would be dead for exits from the loop, we
312 // assume that the cost of *splitting* the backedge would be too high.
Evan Chengab631522008-12-19 18:03:11 +0000313 if (BackEdges.count(std::make_pair(TIBB, Dest)))
Chris Lattnerebe80752007-12-24 19:32:55 +0000314 return;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000315
Evan Chengab631522008-12-19 18:03:11 +0000316 if (!FactorCommonPreds) {
317 /// TIPHIValues - This array is lazily computed to determine the values of
318 /// PHIs in Dest that TI would provide.
319 SmallVector<Value*, 32> TIPHIValues;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000320
Evan Chengab631522008-12-19 18:03:11 +0000321 // Check to see if Dest has any blocks that can be used as a split edge for
322 // this terminator.
323 for (pred_iterator PI = pred_begin(Dest), E = pred_end(Dest); PI != E; ++PI) {
324 BasicBlock *Pred = *PI;
325 // To be usable, the pred has to end with an uncond branch to the dest.
326 BranchInst *PredBr = dyn_cast<BranchInst>(Pred->getTerminator());
Dale Johannesen6aae1d62009-03-26 01:15:07 +0000327 if (!PredBr || !PredBr->isUnconditional())
328 continue;
329 // Must be empty other than the branch and debug info.
330 BasicBlock::iterator I = Pred->begin();
331 while (isa<DbgInfoIntrinsic>(I))
332 I++;
333 if (dyn_cast<Instruction>(I) != PredBr)
334 continue;
335 // Cannot be the entry block; its label does not get emitted.
336 if (Pred == &(Dest->getParent()->getEntryBlock()))
Evan Chengab631522008-12-19 18:03:11 +0000337 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000338
Evan Chengab631522008-12-19 18:03:11 +0000339 // Finally, since we know that Dest has phi nodes in it, we have to make
Dale Johannesen6aae1d62009-03-26 01:15:07 +0000340 // sure that jumping to Pred will have the same effect as going to Dest in
Evan Chengab631522008-12-19 18:03:11 +0000341 // terms of PHI values.
342 PHINode *PN;
343 unsigned PHINo = 0;
344 bool FoundMatch = true;
345 for (BasicBlock::iterator I = Dest->begin();
346 (PN = dyn_cast<PHINode>(I)); ++I, ++PHINo) {
347 if (PHINo == TIPHIValues.size())
348 TIPHIValues.push_back(PN->getIncomingValueForBlock(TIBB));
Eric Christopher692bf6b2008-09-24 05:32:41 +0000349
Evan Chengab631522008-12-19 18:03:11 +0000350 // If the PHI entry doesn't work, we can't use this pred.
351 if (TIPHIValues[PHINo] != PN->getIncomingValueForBlock(Pred)) {
352 FoundMatch = false;
353 break;
354 }
355 }
356
357 // If we found a workable predecessor, change TI to branch to Succ.
358 if (FoundMatch) {
359 Dest->removePredecessor(TIBB);
360 TI->setSuccessor(SuccNum, Pred);
361 return;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000362 }
363 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000364
Evan Chengab631522008-12-19 18:03:11 +0000365 SplitCriticalEdge(TI, SuccNum, P, true);
366 return;
367 }
368
369 PHINode *PN;
370 SmallVector<Value*, 8> TIPHIValues;
371 for (BasicBlock::iterator I = Dest->begin();
372 (PN = dyn_cast<PHINode>(I)); ++I)
373 TIPHIValues.push_back(PN->getIncomingValueForBlock(TIBB));
374
375 SmallVector<BasicBlock*, 8> IdenticalPreds;
376 for (pred_iterator PI = pred_begin(Dest), E = pred_end(Dest); PI != E; ++PI) {
377 BasicBlock *Pred = *PI;
378 if (BackEdges.count(std::make_pair(Pred, Dest)))
379 continue;
380 if (PI == TIBB)
381 IdenticalPreds.push_back(Pred);
382 else {
383 bool Identical = true;
384 unsigned PHINo = 0;
385 for (BasicBlock::iterator I = Dest->begin();
386 (PN = dyn_cast<PHINode>(I)); ++I, ++PHINo)
387 if (TIPHIValues[PHINo] != PN->getIncomingValueForBlock(Pred)) {
388 Identical = false;
389 break;
390 }
391 if (Identical)
392 IdenticalPreds.push_back(Pred);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000393 }
394 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000395
Evan Chengab631522008-12-19 18:03:11 +0000396 assert(!IdenticalPreds.empty());
397 SplitBlockPredecessors(Dest, &IdenticalPreds[0], IdenticalPreds.size(),
398 ".critedge", P);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000399}
400
Evan Chengab631522008-12-19 18:03:11 +0000401
Chris Lattnerdd77df32007-04-13 20:30:56 +0000402/// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
Dan Gohmana119de82009-06-14 23:30:43 +0000403/// copy (e.g. it's casting from one pointer type to another, i32->i8 on PPC),
404/// sink it into user blocks to reduce the number of virtual
Dale Johannesence0b2372007-06-12 16:50:17 +0000405/// registers that must be created and coalesced.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000406///
407/// Return true if any changes are made.
Chris Lattner85fa13c2008-11-24 22:44:16 +0000408///
Chris Lattnerdd77df32007-04-13 20:30:56 +0000409static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
Eric Christopher692bf6b2008-09-24 05:32:41 +0000410 // If this is a noop copy,
Owen Andersone50ed302009-08-10 22:56:29 +0000411 EVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
412 EVT DstVT = TLI.getValueType(CI->getType());
Eric Christopher692bf6b2008-09-24 05:32:41 +0000413
Chris Lattnerdd77df32007-04-13 20:30:56 +0000414 // This is an fp<->int conversion?
Duncan Sands83ec4b62008-06-06 12:08:01 +0000415 if (SrcVT.isInteger() != DstVT.isInteger())
Chris Lattnerdd77df32007-04-13 20:30:56 +0000416 return false;
Duncan Sands8e4eb092008-06-08 20:54:56 +0000417
Chris Lattnerdd77df32007-04-13 20:30:56 +0000418 // If this is an extension, it will be a zero or sign extension, which
419 // isn't a noop.
Duncan Sands8e4eb092008-06-08 20:54:56 +0000420 if (SrcVT.bitsLT(DstVT)) return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000421
Chris Lattnerdd77df32007-04-13 20:30:56 +0000422 // If these values will be promoted, find out what they will be promoted
423 // to. This helps us consider truncates on PPC as noop copies when they
424 // are.
Owen Anderson23b9b192009-08-12 00:36:31 +0000425 if (TLI.getTypeAction(CI->getContext(), SrcVT) == TargetLowering::Promote)
426 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
427 if (TLI.getTypeAction(CI->getContext(), DstVT) == TargetLowering::Promote)
428 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000429
Chris Lattnerdd77df32007-04-13 20:30:56 +0000430 // If, after promotion, these are the same types, this is a noop copy.
431 if (SrcVT != DstVT)
432 return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000433
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000434 BasicBlock *DefBB = CI->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000435
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000436 /// InsertedCasts - Only insert a cast in each block once.
Dale Johannesence0b2372007-06-12 16:50:17 +0000437 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000438
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000439 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000440 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000441 UI != E; ) {
442 Use &TheUse = UI.getUse();
443 Instruction *User = cast<Instruction>(*UI);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000444
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000445 // Figure out which BB this cast is used in. For PHI's this is the
446 // appropriate predecessor block.
447 BasicBlock *UserBB = User->getParent();
448 if (PHINode *PN = dyn_cast<PHINode>(User)) {
Gabor Greifa36791d2009-01-23 19:40:15 +0000449 UserBB = PN->getIncomingBlock(UI);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000450 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000451
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000452 // Preincrement use iterator so we don't invalidate it.
453 ++UI;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000454
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000455 // If this user is in the same block as the cast, don't change the cast.
456 if (UserBB == DefBB) continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000457
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000458 // If we have already inserted a cast into this block, use it.
459 CastInst *&InsertedCast = InsertedCasts[UserBB];
460
461 if (!InsertedCast) {
Dan Gohman02dea8b2008-05-23 21:05:58 +0000462 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000463
464 InsertedCast =
465 CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000466 InsertPt);
467 MadeChange = true;
468 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000469
Dale Johannesence0b2372007-06-12 16:50:17 +0000470 // Replace a use of the cast with a use of the new cast.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000471 TheUse = InsertedCast;
472 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000473
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000474 // If we removed all uses, nuke the cast.
Duncan Sandse0038132008-01-20 16:51:46 +0000475 if (CI->use_empty()) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000476 CI->eraseFromParent();
Duncan Sandse0038132008-01-20 16:51:46 +0000477 MadeChange = true;
478 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000479
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000480 return MadeChange;
481}
482
Eric Christopher692bf6b2008-09-24 05:32:41 +0000483/// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
Dale Johannesence0b2372007-06-12 16:50:17 +0000484/// the number of virtual registers that must be created and coalesced. This is
Chris Lattner684b22d2007-08-02 16:53:43 +0000485/// a clear win except on targets with multiple condition code registers
486/// (PowerPC), where it might lose; some adjustment may be wanted there.
Dale Johannesence0b2372007-06-12 16:50:17 +0000487///
488/// Return true if any changes are made.
Chris Lattner85fa13c2008-11-24 22:44:16 +0000489static bool OptimizeCmpExpression(CmpInst *CI) {
Dale Johannesence0b2372007-06-12 16:50:17 +0000490 BasicBlock *DefBB = CI->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000491
Dale Johannesence0b2372007-06-12 16:50:17 +0000492 /// InsertedCmp - Only insert a cmp in each block once.
493 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000494
Dale Johannesence0b2372007-06-12 16:50:17 +0000495 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000496 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
Dale Johannesence0b2372007-06-12 16:50:17 +0000497 UI != E; ) {
498 Use &TheUse = UI.getUse();
499 Instruction *User = cast<Instruction>(*UI);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000500
Dale Johannesence0b2372007-06-12 16:50:17 +0000501 // Preincrement use iterator so we don't invalidate it.
502 ++UI;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000503
Dale Johannesence0b2372007-06-12 16:50:17 +0000504 // Don't bother for PHI nodes.
505 if (isa<PHINode>(User))
506 continue;
507
508 // Figure out which BB this cmp is used in.
509 BasicBlock *UserBB = User->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000510
Dale Johannesence0b2372007-06-12 16:50:17 +0000511 // If this user is in the same block as the cmp, don't change the cmp.
512 if (UserBB == DefBB) continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000513
Dale Johannesence0b2372007-06-12 16:50:17 +0000514 // If we have already inserted a cmp into this block, use it.
515 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
516
517 if (!InsertedCmp) {
Dan Gohman02dea8b2008-05-23 21:05:58 +0000518 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000519
520 InsertedCmp =
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000521 CmpInst::Create(CI->getOpcode(),
Owen Anderson333c4002009-07-09 23:48:35 +0000522 CI->getPredicate(), CI->getOperand(0),
Dale Johannesence0b2372007-06-12 16:50:17 +0000523 CI->getOperand(1), "", InsertPt);
524 MadeChange = true;
525 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000526
Dale Johannesence0b2372007-06-12 16:50:17 +0000527 // Replace a use of the cmp with a use of the new cmp.
528 TheUse = InsertedCmp;
529 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000530
Dale Johannesence0b2372007-06-12 16:50:17 +0000531 // If we removed all uses, nuke the cmp.
532 if (CI->use_empty())
533 CI->eraseFromParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000534
Dale Johannesence0b2372007-06-12 16:50:17 +0000535 return MadeChange;
536}
537
Chris Lattner88a5c832008-11-25 07:09:13 +0000538//===----------------------------------------------------------------------===//
Chris Lattner88a5c832008-11-25 07:09:13 +0000539// Memory Optimization
540//===----------------------------------------------------------------------===//
541
Chris Lattnerdd77df32007-04-13 20:30:56 +0000542/// IsNonLocalValue - Return true if the specified values are defined in a
543/// different basic block than BB.
544static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
545 if (Instruction *I = dyn_cast<Instruction>(V))
546 return I->getParent() != BB;
547 return false;
548}
549
Chris Lattner88a5c832008-11-25 07:09:13 +0000550/// OptimizeMemoryInst - Load and Store Instructions have often have
Chris Lattnerdd77df32007-04-13 20:30:56 +0000551/// addressing modes that can do significant amounts of computation. As such,
552/// instruction selection will try to get the load or store to do as much
553/// computation as possible for the program. The problem is that isel can only
554/// see within a single block. As such, we sink as much legal addressing mode
555/// stuff into the block as possible.
Chris Lattner88a5c832008-11-25 07:09:13 +0000556///
557/// This method is used to optimize both load/store and inline asms with memory
558/// operands.
Chris Lattner896617b2008-11-26 03:20:37 +0000559bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
Chris Lattner88a5c832008-11-25 07:09:13 +0000560 const Type *AccessTy,
561 DenseMap<Value*,Value*> &SunkAddrs) {
Chris Lattnerdd77df32007-04-13 20:30:56 +0000562 // Figure out what addressing mode will be built up for this operation.
563 SmallVector<Instruction*, 16> AddrModeInsts;
Chris Lattner896617b2008-11-26 03:20:37 +0000564 ExtAddrMode AddrMode = AddressingModeMatcher::Match(Addr, AccessTy,MemoryInst,
565 AddrModeInsts, *TLI);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000566
Chris Lattnerdd77df32007-04-13 20:30:56 +0000567 // Check to see if any of the instructions supersumed by this addr mode are
568 // non-local to I's BB.
569 bool AnyNonLocal = false;
570 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
Chris Lattner896617b2008-11-26 03:20:37 +0000571 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
Chris Lattnerdd77df32007-04-13 20:30:56 +0000572 AnyNonLocal = true;
573 break;
574 }
575 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000576
Chris Lattnerdd77df32007-04-13 20:30:56 +0000577 // If all the instructions matched are already in this BB, don't do anything.
578 if (!AnyNonLocal) {
Dan Gohman6c1980b2009-07-25 01:13:51 +0000579 DEBUG(errs() << "CGP: Found local addrmode: " << AddrMode << "\n");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000580 return false;
581 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000582
Chris Lattnerdd77df32007-04-13 20:30:56 +0000583 // Insert this computation right after this user. Since our caller is
584 // scanning from the top of the BB to the bottom, reuse of the expr are
585 // guaranteed to happen later.
Chris Lattner896617b2008-11-26 03:20:37 +0000586 BasicBlock::iterator InsertPt = MemoryInst;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000587
Chris Lattnerdd77df32007-04-13 20:30:56 +0000588 // Now that we determined the addressing expression we want to use and know
589 // that we have to sink it into this block. Check to see if we have already
590 // done this for some other load/store instr in this block. If so, reuse the
591 // computation.
592 Value *&SunkAddr = SunkAddrs[Addr];
593 if (SunkAddr) {
Dan Gohman6c1980b2009-07-25 01:13:51 +0000594 DEBUG(errs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
595 << *MemoryInst);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000596 if (SunkAddr->getType() != Addr->getType())
597 SunkAddr = new BitCastInst(SunkAddr, Addr->getType(), "tmp", InsertPt);
598 } else {
Dan Gohman6c1980b2009-07-25 01:13:51 +0000599 DEBUG(errs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
600 << *MemoryInst);
Owen Anderson1d0be152009-08-13 21:58:54 +0000601 const Type *IntPtrTy =
602 TLI->getTargetData()->getIntPtrType(AccessTy->getContext());
Eric Christopher692bf6b2008-09-24 05:32:41 +0000603
Chris Lattnerdd77df32007-04-13 20:30:56 +0000604 Value *Result = 0;
605 // Start with the scale value.
606 if (AddrMode.Scale) {
607 Value *V = AddrMode.ScaledReg;
608 if (V->getType() == IntPtrTy) {
609 // done.
610 } else if (isa<PointerType>(V->getType())) {
611 V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
612 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
613 cast<IntegerType>(V->getType())->getBitWidth()) {
614 V = new TruncInst(V, IntPtrTy, "sunkaddr", InsertPt);
615 } else {
616 V = new SExtInst(V, IntPtrTy, "sunkaddr", InsertPt);
617 }
618 if (AddrMode.Scale != 1)
Owen Andersoneed707b2009-07-24 23:12:02 +0000619 V = BinaryOperator::CreateMul(V, ConstantInt::get(IntPtrTy,
Owen Andersond672ecb2009-07-03 00:17:18 +0000620 AddrMode.Scale),
Chris Lattnerdd77df32007-04-13 20:30:56 +0000621 "sunkaddr", InsertPt);
622 Result = V;
623 }
624
625 // Add in the base register.
626 if (AddrMode.BaseReg) {
627 Value *V = AddrMode.BaseReg;
Dan Gohman8b0d4f62009-06-02 21:29:13 +0000628 if (isa<PointerType>(V->getType()))
Chris Lattnerdd77df32007-04-13 20:30:56 +0000629 V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
Dan Gohman8b0d4f62009-06-02 21:29:13 +0000630 if (V->getType() != IntPtrTy)
631 V = CastInst::CreateIntegerCast(V, IntPtrTy, /*isSigned=*/true,
632 "sunkaddr", InsertPt);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000633 if (Result)
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000634 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000635 else
636 Result = V;
637 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000638
Chris Lattnerdd77df32007-04-13 20:30:56 +0000639 // Add in the BaseGV if present.
640 if (AddrMode.BaseGV) {
641 Value *V = new PtrToIntInst(AddrMode.BaseGV, IntPtrTy, "sunkaddr",
642 InsertPt);
643 if (Result)
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000644 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000645 else
646 Result = V;
647 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000648
Chris Lattnerdd77df32007-04-13 20:30:56 +0000649 // Add in the Base Offset if present.
650 if (AddrMode.BaseOffs) {
Owen Andersoneed707b2009-07-24 23:12:02 +0000651 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000652 if (Result)
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000653 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000654 else
655 Result = V;
656 }
657
658 if (Result == 0)
Owen Andersona7235ea2009-07-31 20:28:14 +0000659 SunkAddr = Constant::getNullValue(Addr->getType());
Chris Lattnerdd77df32007-04-13 20:30:56 +0000660 else
661 SunkAddr = new IntToPtrInst(Result, Addr->getType(), "sunkaddr",InsertPt);
662 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000663
Chris Lattner896617b2008-11-26 03:20:37 +0000664 MemoryInst->replaceUsesOfWith(Addr, SunkAddr);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000665
Chris Lattnerdd77df32007-04-13 20:30:56 +0000666 if (Addr->use_empty())
Chris Lattner3481f242008-11-27 22:57:53 +0000667 RecursivelyDeleteTriviallyDeadInstructions(Addr);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000668 return true;
669}
670
Evan Cheng9bf12b52008-02-26 02:42:37 +0000671/// OptimizeInlineAsmInst - If there are any memory operands, use
Chris Lattner88a5c832008-11-25 07:09:13 +0000672/// OptimizeMemoryInst to sink their address computing into the block when
Evan Cheng9bf12b52008-02-26 02:42:37 +0000673/// possible / profitable.
674bool CodeGenPrepare::OptimizeInlineAsmInst(Instruction *I, CallSite CS,
675 DenseMap<Value*,Value*> &SunkAddrs) {
676 bool MadeChange = false;
677 InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
678
679 // Do a prepass over the constraints, canonicalizing them, and building up the
680 // ConstraintOperands list.
681 std::vector<InlineAsm::ConstraintInfo>
682 ConstraintInfos = IA->ParseConstraints();
683
684 /// ConstraintOperands - Information about all of the constraints.
685 std::vector<TargetLowering::AsmOperandInfo> ConstraintOperands;
686 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
687 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
688 ConstraintOperands.
689 push_back(TargetLowering::AsmOperandInfo(ConstraintInfos[i]));
690 TargetLowering::AsmOperandInfo &OpInfo = ConstraintOperands.back();
691
692 // Compute the value type for each operand.
693 switch (OpInfo.Type) {
694 case InlineAsm::isOutput:
695 if (OpInfo.isIndirect)
696 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
697 break;
698 case InlineAsm::isInput:
699 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
700 break;
701 case InlineAsm::isClobber:
702 // Nothing to do.
703 break;
704 }
705
706 // Compute the constraint code and ConstraintType to use.
Evan Chenga7e61462008-09-24 06:48:55 +0000707 TLI->ComputeConstraintToUse(OpInfo, SDValue(),
708 OpInfo.ConstraintType == TargetLowering::C_Memory);
Evan Cheng9bf12b52008-02-26 02:42:37 +0000709
Eli Friedman9ec80952008-02-26 18:37:49 +0000710 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
711 OpInfo.isIndirect) {
Evan Cheng9bf12b52008-02-26 02:42:37 +0000712 Value *OpVal = OpInfo.CallOperandVal;
Chris Lattner88a5c832008-11-25 07:09:13 +0000713 MadeChange |= OptimizeMemoryInst(I, OpVal, OpVal->getType(), SunkAddrs);
Evan Cheng9bf12b52008-02-26 02:42:37 +0000714 }
715 }
716
717 return MadeChange;
718}
719
Evan Chengbdcb7262007-12-05 23:58:20 +0000720bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
721 BasicBlock *DefBB = I->getParent();
722
723 // If both result of the {s|z}xt and its source are live out, rewrite all
724 // other uses of the source with result of extension.
725 Value *Src = I->getOperand(0);
726 if (Src->hasOneUse())
727 return false;
728
Evan Cheng696e5c02007-12-13 07:50:36 +0000729 // Only do this xform if truncating is free.
Gabor Greif53bdbd72008-02-26 19:13:21 +0000730 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
Evan Chengf9785f92007-12-13 03:32:53 +0000731 return false;
732
Evan Cheng772de512007-12-12 00:51:06 +0000733 // Only safe to perform the optimization if the source is also defined in
Evan Cheng765dff22007-12-12 02:53:41 +0000734 // this block.
735 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
Evan Cheng772de512007-12-12 00:51:06 +0000736 return false;
737
Evan Chengbdcb7262007-12-05 23:58:20 +0000738 bool DefIsLiveOut = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000739 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
Evan Chengbdcb7262007-12-05 23:58:20 +0000740 UI != E; ++UI) {
741 Instruction *User = cast<Instruction>(*UI);
742
743 // Figure out which BB this ext is used in.
744 BasicBlock *UserBB = User->getParent();
745 if (UserBB == DefBB) continue;
746 DefIsLiveOut = true;
747 break;
748 }
749 if (!DefIsLiveOut)
750 return false;
751
Evan Cheng765dff22007-12-12 02:53:41 +0000752 // Make sure non of the uses are PHI nodes.
Eric Christopher692bf6b2008-09-24 05:32:41 +0000753 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
Evan Cheng765dff22007-12-12 02:53:41 +0000754 UI != E; ++UI) {
755 Instruction *User = cast<Instruction>(*UI);
Evan Chengf9785f92007-12-13 03:32:53 +0000756 BasicBlock *UserBB = User->getParent();
757 if (UserBB == DefBB) continue;
758 // Be conservative. We don't want this xform to end up introducing
759 // reloads just before load / store instructions.
760 if (isa<PHINode>(User) || isa<LoadInst>(User) || isa<StoreInst>(User))
Evan Cheng765dff22007-12-12 02:53:41 +0000761 return false;
762 }
763
Evan Chengbdcb7262007-12-05 23:58:20 +0000764 // InsertedTruncs - Only insert one trunc in each block once.
765 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
766
767 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000768 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
Evan Chengbdcb7262007-12-05 23:58:20 +0000769 UI != E; ++UI) {
770 Use &TheUse = UI.getUse();
771 Instruction *User = cast<Instruction>(*UI);
772
773 // Figure out which BB this ext is used in.
774 BasicBlock *UserBB = User->getParent();
775 if (UserBB == DefBB) continue;
776
777 // Both src and def are live in this block. Rewrite the use.
778 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
779
780 if (!InsertedTrunc) {
Dan Gohman02dea8b2008-05-23 21:05:58 +0000781 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000782
Evan Chengbdcb7262007-12-05 23:58:20 +0000783 InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
784 }
785
786 // Replace a use of the {s|z}ext source with a use of the result.
787 TheUse = InsertedTrunc;
788
789 MadeChange = true;
790 }
791
792 return MadeChange;
793}
794
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000795// In this pass we look for GEP and cast instructions that are used
796// across basic blocks and rewrite them to improve basic-block-at-a-time
797// selection.
798bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
799 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000800
Evan Chengab631522008-12-19 18:03:11 +0000801 // Split all critical edges where the dest block has a PHI.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000802 TerminatorInst *BBTI = BB.getTerminator();
803 if (BBTI->getNumSuccessors() > 1) {
Evan Chengab631522008-12-19 18:03:11 +0000804 for (unsigned i = 0, e = BBTI->getNumSuccessors(); i != e; ++i) {
805 BasicBlock *SuccBB = BBTI->getSuccessor(i);
806 if (isa<PHINode>(SuccBB->begin()) && isCriticalEdge(BBTI, i, true))
807 SplitEdgeNicely(BBTI, i, BackEdges, this);
808 }
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000809 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000810
Chris Lattnerdd77df32007-04-13 20:30:56 +0000811 // Keep track of non-local addresses that have been sunk into this block.
812 // This allows us to avoid inserting duplicate code for blocks with multiple
813 // load/stores of the same address.
814 DenseMap<Value*, Value*> SunkAddrs;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000815
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000816 for (BasicBlock::iterator BBI = BB.begin(), E = BB.end(); BBI != E; ) {
817 Instruction *I = BBI++;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000818
Chris Lattnerdd77df32007-04-13 20:30:56 +0000819 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000820 // If the source of the cast is a constant, then this should have
821 // already been constant folded. The only reason NOT to constant fold
822 // it is if something (e.g. LSR) was careful to place the constant
823 // evaluation in a block other than then one that uses it (e.g. to hoist
824 // the address of globals out of a loop). If this is the case, we don't
825 // want to forward-subst the cast.
826 if (isa<Constant>(CI->getOperand(0)))
827 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000828
Evan Chengbdcb7262007-12-05 23:58:20 +0000829 bool Change = false;
830 if (TLI) {
831 Change = OptimizeNoopCopyExpression(CI, *TLI);
832 MadeChange |= Change;
833 }
834
Evan Cheng55e641b2008-03-19 22:02:26 +0000835 if (!Change && (isa<ZExtInst>(I) || isa<SExtInst>(I)))
Evan Chengbdcb7262007-12-05 23:58:20 +0000836 MadeChange |= OptimizeExtUses(I);
Dale Johannesence0b2372007-06-12 16:50:17 +0000837 } else if (CmpInst *CI = dyn_cast<CmpInst>(I)) {
838 MadeChange |= OptimizeCmpExpression(CI);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000839 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
840 if (TLI)
Chris Lattner88a5c832008-11-25 07:09:13 +0000841 MadeChange |= OptimizeMemoryInst(I, I->getOperand(0), LI->getType(),
842 SunkAddrs);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000843 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
844 if (TLI)
Chris Lattner88a5c832008-11-25 07:09:13 +0000845 MadeChange |= OptimizeMemoryInst(I, SI->getOperand(1),
846 SI->getOperand(0)->getType(),
847 SunkAddrs);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000848 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Chris Lattnerf25646b2007-04-14 00:17:39 +0000849 if (GEPI->hasAllZeroIndices()) {
Chris Lattnerdd77df32007-04-13 20:30:56 +0000850 /// The GEP operand must be a pointer, so must its result -> BitCast
Eric Christopher692bf6b2008-09-24 05:32:41 +0000851 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
Chris Lattnerdd77df32007-04-13 20:30:56 +0000852 GEPI->getName(), GEPI);
853 GEPI->replaceAllUsesWith(NC);
854 GEPI->eraseFromParent();
855 MadeChange = true;
856 BBI = NC;
857 }
858 } else if (CallInst *CI = dyn_cast<CallInst>(I)) {
859 // If we found an inline asm expession, and if the target knows how to
860 // lower it to normal LLVM code, do so now.
Chris Lattner8850b362009-07-20 17:52:52 +0000861 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
862 if (TLI->ExpandInlineAsm(CI)) {
863 BBI = BB.begin();
864 // Avoid processing instructions out of order, which could cause
865 // reuse before a value is defined.
866 SunkAddrs.clear();
867 } else
868 // Sink address computing for memory operands into the block.
869 MadeChange |= OptimizeInlineAsmInst(I, &(*CI), SunkAddrs);
870 }
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000871 }
872 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000873
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000874 return MadeChange;
875}