blob: 1f842fb4f8f6a49f479dac0446b409d191480938 [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"
Owen Andersond5f86842010-12-23 20:57:35 +000025#include "llvm/Analysis/InstructionSimplify.h"
Andreas Neustifterad809812009-09-16 09:26:52 +000026#include "llvm/Analysis/ProfileInfo.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000027#include "llvm/Target/TargetData.h"
28#include "llvm/Target/TargetLowering.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"
Eric Christopher040056f2010-03-11 02:41:03 +000032#include "llvm/Transforms/Utils/BuildLibCalls.h"
Chris Lattnerdd77df32007-04-13 20:30:56 +000033#include "llvm/ADT/DenseMap.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000034#include "llvm/ADT/SmallSet.h"
Jakob Stoklund Olesen7eb589d2010-09-30 20:51:52 +000035#include "llvm/ADT/Statistic.h"
Dan Gohman03ce0422009-02-13 17:45:12 +000036#include "llvm/Assembly/Writer.h"
Evan Cheng9bf12b52008-02-26 02:42:37 +000037#include "llvm/Support/CallSite.h"
Evan Chenge1bcb442010-08-17 01:34:49 +000038#include "llvm/Support/CommandLine.h"
Evan Chengbdcb7262007-12-05 23:58:20 +000039#include "llvm/Support/Debug.h"
Chris Lattnerdd77df32007-04-13 20:30:56 +000040#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner088a1e82008-11-25 04:42:10 +000041#include "llvm/Support/PatternMatch.h"
Dan Gohman6c1980b2009-07-25 01:13:51 +000042#include "llvm/Support/raw_ostream.h"
Eric Christopher040056f2010-03-11 02:41:03 +000043#include "llvm/Support/IRBuilder.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000044using namespace llvm;
Chris Lattner088a1e82008-11-25 04:42:10 +000045using namespace llvm::PatternMatch;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000046
Cameron Zwarich31ff1332011-01-05 17:27:27 +000047STATISTIC(NumBlocksElim, "Number of blocks eliminated");
Cameron Zwarich073057f2011-01-05 17:47:38 +000048STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated");
49STATISTIC(NumGEPsElim, "Number of GEPs converted to casts");
Cameron Zwarich31ff1332011-01-05 17:27:27 +000050STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "
51 "sunken Cmps");
52STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
53 "of sunken Casts");
54STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "
55 "computations were sunk");
56STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads");
57STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized");
Jakob Stoklund Olesen7eb589d2010-09-30 20:51:52 +000058
Evan Chenge1bcb442010-08-17 01:34:49 +000059static cl::opt<bool>
60CriticalEdgeSplit("cgp-critical-edge-splitting",
61 cl::desc("Split critical edges during codegen prepare"),
Jakob Stoklund Olesen7eb589d2010-09-30 20:51:52 +000062 cl::init(false), cl::Hidden);
Evan Chenge1bcb442010-08-17 01:34:49 +000063
Eric Christopher692bf6b2008-09-24 05:32:41 +000064namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +000065 class CodeGenPrepare : public FunctionPass {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000066 /// TLI - Keep a pointer of a TargetLowering to consult for determining
67 /// transformation profitability.
68 const TargetLowering *TLI;
Evan Cheng04149f72009-12-17 09:39:49 +000069 ProfileInfo *PFI;
Evan Chengab631522008-12-19 18:03:11 +000070
71 /// BackEdges - Keep a set of all the loop back edges.
72 ///
Mike Stumpfe095f32009-05-04 18:40:41 +000073 SmallSet<std::pair<const BasicBlock*, const BasicBlock*>, 8> BackEdges;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000074 public:
Nick Lewyckyecd94c82007-05-06 13:37:16 +000075 static char ID; // Pass identification, replacement for typeid
Dan Gohmanc2bbfc12007-08-01 15:32:29 +000076 explicit CodeGenPrepare(const TargetLowering *tli = 0)
Owen Anderson081c34b2010-10-19 17:21:58 +000077 : FunctionPass(ID), TLI(tli) {
78 initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
79 }
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000080 bool runOnFunction(Function &F);
Eric Christopher692bf6b2008-09-24 05:32:41 +000081
Andreas Neustifterad809812009-09-16 09:26:52 +000082 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
83 AU.addPreserved<ProfileInfo>();
84 }
85
Dan Gohmanaa0e5232010-02-05 19:24:11 +000086 virtual void releaseMemory() {
87 BackEdges.clear();
88 }
89
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000090 private:
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +000091 bool EliminateMostlyEmptyBlocks(Function &F);
92 bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
93 void EliminateMostlyEmptyBlock(BasicBlock *BB);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000094 bool OptimizeBlock(BasicBlock &BB);
Chris Lattner88a5c832008-11-25 07:09:13 +000095 bool OptimizeMemoryInst(Instruction *I, Value *Addr, const Type *AccessTy,
96 DenseMap<Value*,Value*> &SunkAddrs);
Evan Cheng9bf12b52008-02-26 02:42:37 +000097 bool OptimizeInlineAsmInst(Instruction *I, CallSite CS,
98 DenseMap<Value*,Value*> &SunkAddrs);
Eric Christopher040056f2010-03-11 02:41:03 +000099 bool OptimizeCallInst(CallInst *CI);
Dan Gohmanb00f2362009-10-16 20:59:35 +0000100 bool MoveExtToFormExtLoad(Instruction *I);
Evan Chengbdcb7262007-12-05 23:58:20 +0000101 bool OptimizeExtUses(Instruction *I);
Mike Stumpfe095f32009-05-04 18:40:41 +0000102 void findLoopBackEdges(const Function &F);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000103 };
104}
Devang Patel794fd752007-05-01 21:15:47 +0000105
Devang Patel19974732007-05-03 01:11:54 +0000106char CodeGenPrepare::ID = 0;
Owen Andersond13db2c2010-07-21 22:09:45 +0000107INITIALIZE_PASS(CodeGenPrepare, "codegenprepare",
Owen Andersonce665bd2010-10-07 22:25:06 +0000108 "Optimize for code generation", false, false)
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000109
110FunctionPass *llvm::createCodeGenPreparePass(const TargetLowering *TLI) {
111 return new CodeGenPrepare(TLI);
112}
113
Evan Chengab631522008-12-19 18:03:11 +0000114/// findLoopBackEdges - Do a DFS walk to find loop back edges.
115///
Mike Stumpfe095f32009-05-04 18:40:41 +0000116void CodeGenPrepare::findLoopBackEdges(const Function &F) {
117 SmallVector<std::pair<const BasicBlock*,const BasicBlock*>, 32> Edges;
118 FindFunctionBackedges(F, Edges);
119
120 BackEdges.insert(Edges.begin(), Edges.end());
Evan Chengab631522008-12-19 18:03:11 +0000121}
122
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000123
124bool CodeGenPrepare::runOnFunction(Function &F) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000125 bool EverMadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000126
Evan Cheng04149f72009-12-17 09:39:49 +0000127 PFI = getAnalysisIfAvailable<ProfileInfo>();
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000128 // First pass, eliminate blocks that contain only PHI nodes and an
129 // unconditional branch.
130 EverMadeChange |= EliminateMostlyEmptyBlocks(F);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000131
Cameron Zwarich95bb0042011-01-04 04:43:31 +0000132 // Now find loop back edges, but only if they are being used to decide which
133 // critical edges to split.
134 if (CriticalEdgeSplit)
135 findLoopBackEdges(F);
Evan Cheng7e66c0d2009-01-05 21:17:27 +0000136
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000137 bool MadeChange = true;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000138 while (MadeChange) {
139 MadeChange = false;
140 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
141 MadeChange |= OptimizeBlock(*BB);
142 EverMadeChange |= MadeChange;
143 }
144 return EverMadeChange;
145}
146
Dale Johannesen2d697242009-03-27 01:13:37 +0000147/// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes,
148/// debug info directives, and an unconditional branch. Passes before isel
149/// (e.g. LSR/loopsimplify) often split edges in ways that are non-optimal for
150/// isel. Start by eliminating these blocks so we can split them the way we
151/// want them.
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000152bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
153 bool MadeChange = false;
154 // Note that this intentionally skips the entry block.
155 for (Function::iterator I = ++F.begin(), E = F.end(); I != E; ) {
156 BasicBlock *BB = I++;
157
158 // If this block doesn't end with an uncond branch, ignore it.
159 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
160 if (!BI || !BI->isUnconditional())
161 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000162
Dale Johannesen2d697242009-03-27 01:13:37 +0000163 // If the instruction before the branch (skipping debug info) isn't a phi
164 // node, then other stuff is happening here.
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000165 BasicBlock::iterator BBI = BI;
166 if (BBI != BB->begin()) {
167 --BBI;
Dale Johannesen2d697242009-03-27 01:13:37 +0000168 while (isa<DbgInfoIntrinsic>(BBI)) {
169 if (BBI == BB->begin())
170 break;
171 --BBI;
172 }
173 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
174 continue;
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000175 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000176
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000177 // Do not break infinite loops.
178 BasicBlock *DestBB = BI->getSuccessor(0);
179 if (DestBB == BB)
180 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000181
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000182 if (!CanMergeBlocks(BB, DestBB))
183 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000184
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000185 EliminateMostlyEmptyBlock(BB);
186 MadeChange = true;
187 }
188 return MadeChange;
189}
190
191/// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
192/// single uncond branch between them, and BB contains no other non-phi
193/// instructions.
194bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
195 const BasicBlock *DestBB) const {
196 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
197 // the successor. If there are more complex condition (e.g. preheaders),
198 // don't mess around with them.
199 BasicBlock::const_iterator BBI = BB->begin();
200 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
Gabor Greif60ad7812010-03-25 23:06:16 +0000201 for (Value::const_use_iterator UI = PN->use_begin(), E = PN->use_end();
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000202 UI != E; ++UI) {
203 const Instruction *User = cast<Instruction>(*UI);
204 if (User->getParent() != DestBB || !isa<PHINode>(User))
205 return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000206 // If User is inside DestBB block and it is a PHINode then check
207 // incoming value. If incoming value is not from BB then this is
Devang Patel75abc1e2007-04-25 00:37:04 +0000208 // a complex condition (e.g. preheaders) we want to avoid here.
209 if (User->getParent() == DestBB) {
210 if (const PHINode *UPN = dyn_cast<PHINode>(User))
211 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
212 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
213 if (Insn && Insn->getParent() == BB &&
214 Insn->getParent() != UPN->getIncomingBlock(I))
215 return false;
216 }
217 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000218 }
219 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000220
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000221 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
222 // and DestBB may have conflicting incoming values for the block. If so, we
223 // can't merge the block.
224 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
225 if (!DestBBPN) return true; // no conflict.
Eric Christopher692bf6b2008-09-24 05:32:41 +0000226
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000227 // Collect the preds of BB.
Chris Lattnerf67f73a2007-11-06 22:07:40 +0000228 SmallPtrSet<const BasicBlock*, 16> BBPreds;
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000229 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
230 // It is faster to get preds from a PHI than with pred_iterator.
231 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
232 BBPreds.insert(BBPN->getIncomingBlock(i));
233 } else {
234 BBPreds.insert(pred_begin(BB), pred_end(BB));
235 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000236
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000237 // Walk the preds of DestBB.
238 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
239 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
240 if (BBPreds.count(Pred)) { // Common predecessor?
241 BBI = DestBB->begin();
242 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
243 const Value *V1 = PN->getIncomingValueForBlock(Pred);
244 const Value *V2 = PN->getIncomingValueForBlock(BB);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000245
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000246 // If V2 is a phi node in BB, look up what the mapped value will be.
247 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
248 if (V2PN->getParent() == BB)
249 V2 = V2PN->getIncomingValueForBlock(Pred);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000250
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000251 // If there is a conflict, bail out.
252 if (V1 != V2) return false;
253 }
254 }
255 }
256
257 return true;
258}
259
260
261/// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
262/// an unconditional branch in it.
263void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
264 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
265 BasicBlock *DestBB = BI->getSuccessor(0);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000266
David Greene68d67fd2010-01-05 01:27:11 +0000267 DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000268
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000269 // If the destination block has a single pred, then this is a trivial edge,
270 // just collapse it.
Chris Lattner9918fb52008-11-27 19:29:14 +0000271 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
Chris Lattnerf5102a02008-11-28 19:54:49 +0000272 if (SinglePred != DestBB) {
273 // Remember if SinglePred was the entry block of the function. If so, we
274 // will need to move BB back to the entry position.
275 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Andreas Neustifterad809812009-09-16 09:26:52 +0000276 MergeBasicBlockIntoOnlyPred(DestBB, this);
Chris Lattner9918fb52008-11-27 19:29:14 +0000277
Chris Lattnerf5102a02008-11-28 19:54:49 +0000278 if (isEntry && BB != &BB->getParent()->getEntryBlock())
279 BB->moveBefore(&BB->getParent()->getEntryBlock());
280
David Greene68d67fd2010-01-05 01:27:11 +0000281 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerf5102a02008-11-28 19:54:49 +0000282 return;
283 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000284 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000285
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000286 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
287 // to handle the new incoming edges it is about to have.
288 PHINode *PN;
289 for (BasicBlock::iterator BBI = DestBB->begin();
290 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
291 // Remove the incoming value for BB, and remember it.
292 Value *InVal = PN->removeIncomingValue(BB, false);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000293
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000294 // Two options: either the InVal is a phi node defined in BB or it is some
295 // value that dominates BB.
296 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
297 if (InValPhi && InValPhi->getParent() == BB) {
298 // Add all of the input values of the input PHI as inputs of this phi.
299 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
300 PN->addIncoming(InValPhi->getIncomingValue(i),
301 InValPhi->getIncomingBlock(i));
302 } else {
303 // Otherwise, add one instance of the dominating value for each edge that
304 // we will be adding.
305 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
306 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
307 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
308 } else {
309 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
310 PN->addIncoming(InVal, *PI);
311 }
312 }
313 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000314
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000315 // The PHIs are now updated, change everything that refers to BB to use
316 // DestBB and remove BB.
317 BB->replaceAllUsesWith(DestBB);
Evan Cheng04149f72009-12-17 09:39:49 +0000318 if (PFI) {
319 PFI->replaceAllUses(BB, DestBB);
320 PFI->removeEdge(ProfileInfo::getEdge(BB, DestBB));
Andreas Neustifterad809812009-09-16 09:26:52 +0000321 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000322 BB->eraseFromParent();
Cameron Zwarich31ff1332011-01-05 17:27:27 +0000323 ++NumBlocksElim;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000324
David Greene68d67fd2010-01-05 01:27:11 +0000325 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000326}
327
Chris Lattner98d5c312010-02-13 05:35:08 +0000328/// FindReusablePredBB - Check all of the predecessors of the block DestPHI
329/// lives in to see if there is a block that we can reuse as a critical edge
330/// from TIBB.
331static BasicBlock *FindReusablePredBB(PHINode *DestPHI, BasicBlock *TIBB) {
332 BasicBlock *Dest = DestPHI->getParent();
333
334 /// TIPHIValues - This array is lazily computed to determine the values of
335 /// PHIs in Dest that TI would provide.
336 SmallVector<Value*, 32> TIPHIValues;
337
338 /// TIBBEntryNo - This is a cache to speed up pred queries for TIBB.
339 unsigned TIBBEntryNo = 0;
340
341 // Check to see if Dest has any blocks that can be used as a split edge for
342 // this terminator.
343 for (unsigned pi = 0, e = DestPHI->getNumIncomingValues(); pi != e; ++pi) {
344 BasicBlock *Pred = DestPHI->getIncomingBlock(pi);
345 // To be usable, the pred has to end with an uncond branch to the dest.
346 BranchInst *PredBr = dyn_cast<BranchInst>(Pred->getTerminator());
347 if (!PredBr || !PredBr->isUnconditional())
348 continue;
349 // Must be empty other than the branch and debug info.
350 BasicBlock::iterator I = Pred->begin();
351 while (isa<DbgInfoIntrinsic>(I))
352 I++;
353 if (&*I != PredBr)
354 continue;
355 // Cannot be the entry block; its label does not get emitted.
356 if (Pred == &Dest->getParent()->getEntryBlock())
357 continue;
358
359 // Finally, since we know that Dest has phi nodes in it, we have to make
360 // sure that jumping to Pred will have the same effect as going to Dest in
361 // terms of PHI values.
362 PHINode *PN;
363 unsigned PHINo = 0;
364 unsigned PredEntryNo = pi;
365
366 bool FoundMatch = true;
367 for (BasicBlock::iterator I = Dest->begin();
368 (PN = dyn_cast<PHINode>(I)); ++I, ++PHINo) {
369 if (PHINo == TIPHIValues.size()) {
370 if (PN->getIncomingBlock(TIBBEntryNo) != TIBB)
371 TIBBEntryNo = PN->getBasicBlockIndex(TIBB);
372 TIPHIValues.push_back(PN->getIncomingValue(TIBBEntryNo));
373 }
374
375 // If the PHI entry doesn't work, we can't use this pred.
376 if (PN->getIncomingBlock(PredEntryNo) != Pred)
377 PredEntryNo = PN->getBasicBlockIndex(Pred);
378
379 if (TIPHIValues[PHINo] != PN->getIncomingValue(PredEntryNo)) {
380 FoundMatch = false;
381 break;
382 }
383 }
384
385 // If we found a workable predecessor, change TI to branch to Succ.
386 if (FoundMatch)
387 return Pred;
388 }
389 return 0;
390}
391
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000392
Chris Lattnerebe80752007-12-24 19:32:55 +0000393/// SplitEdgeNicely - Split the critical edge from TI to its specified
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000394/// successor if it will improve codegen. We only do this if the successor has
395/// phi nodes (otherwise critical edges are ok). If there is already another
396/// predecessor of the succ that is empty (and thus has no phi nodes), use it
397/// instead of introducing a new block.
Evan Chengab631522008-12-19 18:03:11 +0000398static void SplitEdgeNicely(TerminatorInst *TI, unsigned SuccNum,
Mike Stumpfe095f32009-05-04 18:40:41 +0000399 SmallSet<std::pair<const BasicBlock*,
400 const BasicBlock*>, 8> &BackEdges,
Evan Chengab631522008-12-19 18:03:11 +0000401 Pass *P) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000402 BasicBlock *TIBB = TI->getParent();
403 BasicBlock *Dest = TI->getSuccessor(SuccNum);
404 assert(isa<PHINode>(Dest->begin()) &&
405 "This should only be called if Dest has a PHI!");
Chris Lattner3f65b5e2010-02-13 04:04:42 +0000406 PHINode *DestPHI = cast<PHINode>(Dest->begin());
Eric Christopher692bf6b2008-09-24 05:32:41 +0000407
Evan Chengfc0b80d2009-03-13 22:59:14 +0000408 // Do not split edges to EH landing pads.
Chris Lattner3f65b5e2010-02-13 04:04:42 +0000409 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(TI))
Evan Chengfc0b80d2009-03-13 22:59:14 +0000410 if (Invoke->getSuccessor(1) == Dest)
411 return;
Evan Chengfc0b80d2009-03-13 22:59:14 +0000412
Chris Lattnerebe80752007-12-24 19:32:55 +0000413 // As a hack, never split backedges of loops. Even though the copy for any
414 // PHIs inserted on the backedge would be dead for exits from the loop, we
415 // assume that the cost of *splitting* the backedge would be too high.
Evan Chengab631522008-12-19 18:03:11 +0000416 if (BackEdges.count(std::make_pair(TIBB, Dest)))
Chris Lattnerebe80752007-12-24 19:32:55 +0000417 return;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000418
Chris Lattnerc09687b2010-02-13 19:07:06 +0000419 if (BasicBlock *ReuseBB = FindReusablePredBB(DestPHI, TIBB)) {
420 ProfileInfo *PFI = P->getAnalysisIfAvailable<ProfileInfo>();
421 if (PFI)
422 PFI->splitEdge(TIBB, Dest, ReuseBB);
423 Dest->removePredecessor(TIBB);
424 TI->setSuccessor(SuccNum, ReuseBB);
Evan Chengab631522008-12-19 18:03:11 +0000425 return;
426 }
427
Chris Lattnerc09687b2010-02-13 19:07:06 +0000428 SplitCriticalEdge(TI, SuccNum, P, true);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000429}
430
Evan Chengab631522008-12-19 18:03:11 +0000431
Chris Lattnerdd77df32007-04-13 20:30:56 +0000432/// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
Dan Gohmana119de82009-06-14 23:30:43 +0000433/// copy (e.g. it's casting from one pointer type to another, i32->i8 on PPC),
434/// sink it into user blocks to reduce the number of virtual
Dale Johannesence0b2372007-06-12 16:50:17 +0000435/// registers that must be created and coalesced.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000436///
437/// Return true if any changes are made.
Chris Lattner85fa13c2008-11-24 22:44:16 +0000438///
Chris Lattnerdd77df32007-04-13 20:30:56 +0000439static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
Eric Christopher692bf6b2008-09-24 05:32:41 +0000440 // If this is a noop copy,
Owen Andersone50ed302009-08-10 22:56:29 +0000441 EVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
442 EVT DstVT = TLI.getValueType(CI->getType());
Eric Christopher692bf6b2008-09-24 05:32:41 +0000443
Chris Lattnerdd77df32007-04-13 20:30:56 +0000444 // This is an fp<->int conversion?
Duncan Sands83ec4b62008-06-06 12:08:01 +0000445 if (SrcVT.isInteger() != DstVT.isInteger())
Chris Lattnerdd77df32007-04-13 20:30:56 +0000446 return false;
Duncan Sands8e4eb092008-06-08 20:54:56 +0000447
Chris Lattnerdd77df32007-04-13 20:30:56 +0000448 // If this is an extension, it will be a zero or sign extension, which
449 // isn't a noop.
Duncan Sands8e4eb092008-06-08 20:54:56 +0000450 if (SrcVT.bitsLT(DstVT)) return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000451
Chris Lattnerdd77df32007-04-13 20:30:56 +0000452 // If these values will be promoted, find out what they will be promoted
453 // to. This helps us consider truncates on PPC as noop copies when they
454 // are.
Chris Lattneraafe6262010-08-25 23:00:45 +0000455 if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote)
Owen Anderson23b9b192009-08-12 00:36:31 +0000456 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
Chris Lattneraafe6262010-08-25 23:00:45 +0000457 if (TLI.getTypeAction(DstVT) == TargetLowering::Promote)
Owen Anderson23b9b192009-08-12 00:36:31 +0000458 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000459
Chris Lattnerdd77df32007-04-13 20:30:56 +0000460 // If, after promotion, these are the same types, this is a noop copy.
461 if (SrcVT != DstVT)
462 return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000463
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000464 BasicBlock *DefBB = CI->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000465
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000466 /// InsertedCasts - Only insert a cast in each block once.
Dale Johannesence0b2372007-06-12 16:50:17 +0000467 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000468
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000469 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000470 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000471 UI != E; ) {
472 Use &TheUse = UI.getUse();
473 Instruction *User = cast<Instruction>(*UI);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000474
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000475 // Figure out which BB this cast is used in. For PHI's this is the
476 // appropriate predecessor block.
477 BasicBlock *UserBB = User->getParent();
478 if (PHINode *PN = dyn_cast<PHINode>(User)) {
Gabor Greifa36791d2009-01-23 19:40:15 +0000479 UserBB = PN->getIncomingBlock(UI);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000480 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000481
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000482 // Preincrement use iterator so we don't invalidate it.
483 ++UI;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000484
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000485 // If this user is in the same block as the cast, don't change the cast.
486 if (UserBB == DefBB) continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000487
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000488 // If we have already inserted a cast into this block, use it.
489 CastInst *&InsertedCast = InsertedCasts[UserBB];
490
491 if (!InsertedCast) {
Dan Gohman02dea8b2008-05-23 21:05:58 +0000492 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000493
494 InsertedCast =
495 CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000496 InsertPt);
497 MadeChange = true;
498 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000499
Dale Johannesence0b2372007-06-12 16:50:17 +0000500 // Replace a use of the cast with a use of the new cast.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000501 TheUse = InsertedCast;
Cameron Zwarich31ff1332011-01-05 17:27:27 +0000502 ++NumCastUses;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000503 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000504
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000505 // If we removed all uses, nuke the cast.
Duncan Sandse0038132008-01-20 16:51:46 +0000506 if (CI->use_empty()) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000507 CI->eraseFromParent();
Duncan Sandse0038132008-01-20 16:51:46 +0000508 MadeChange = true;
509 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000510
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000511 return MadeChange;
512}
513
Eric Christopher692bf6b2008-09-24 05:32:41 +0000514/// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
Dale Johannesence0b2372007-06-12 16:50:17 +0000515/// the number of virtual registers that must be created and coalesced. This is
Chris Lattner684b22d2007-08-02 16:53:43 +0000516/// a clear win except on targets with multiple condition code registers
517/// (PowerPC), where it might lose; some adjustment may be wanted there.
Dale Johannesence0b2372007-06-12 16:50:17 +0000518///
519/// Return true if any changes are made.
Chris Lattner85fa13c2008-11-24 22:44:16 +0000520static bool OptimizeCmpExpression(CmpInst *CI) {
Dale Johannesence0b2372007-06-12 16:50:17 +0000521 BasicBlock *DefBB = CI->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000522
Dale Johannesence0b2372007-06-12 16:50:17 +0000523 /// InsertedCmp - Only insert a cmp in each block once.
524 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000525
Dale Johannesence0b2372007-06-12 16:50:17 +0000526 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000527 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
Dale Johannesence0b2372007-06-12 16:50:17 +0000528 UI != E; ) {
529 Use &TheUse = UI.getUse();
530 Instruction *User = cast<Instruction>(*UI);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000531
Dale Johannesence0b2372007-06-12 16:50:17 +0000532 // Preincrement use iterator so we don't invalidate it.
533 ++UI;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000534
Dale Johannesence0b2372007-06-12 16:50:17 +0000535 // Don't bother for PHI nodes.
536 if (isa<PHINode>(User))
537 continue;
538
539 // Figure out which BB this cmp is used in.
540 BasicBlock *UserBB = User->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000541
Dale Johannesence0b2372007-06-12 16:50:17 +0000542 // If this user is in the same block as the cmp, don't change the cmp.
543 if (UserBB == DefBB) continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000544
Dale Johannesence0b2372007-06-12 16:50:17 +0000545 // If we have already inserted a cmp into this block, use it.
546 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
547
548 if (!InsertedCmp) {
Dan Gohman02dea8b2008-05-23 21:05:58 +0000549 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000550
551 InsertedCmp =
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000552 CmpInst::Create(CI->getOpcode(),
Owen Anderson333c4002009-07-09 23:48:35 +0000553 CI->getPredicate(), CI->getOperand(0),
Dale Johannesence0b2372007-06-12 16:50:17 +0000554 CI->getOperand(1), "", InsertPt);
555 MadeChange = true;
556 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000557
Dale Johannesence0b2372007-06-12 16:50:17 +0000558 // Replace a use of the cmp with a use of the new cmp.
559 TheUse = InsertedCmp;
Cameron Zwarich31ff1332011-01-05 17:27:27 +0000560 ++NumCmpUses;
Dale Johannesence0b2372007-06-12 16:50:17 +0000561 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000562
Dale Johannesence0b2372007-06-12 16:50:17 +0000563 // If we removed all uses, nuke the cmp.
564 if (CI->use_empty())
565 CI->eraseFromParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000566
Dale Johannesence0b2372007-06-12 16:50:17 +0000567 return MadeChange;
568}
569
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000570namespace {
571class CodeGenPrepareFortifiedLibCalls : public SimplifyFortifiedLibCalls {
572protected:
573 void replaceCall(Value *With) {
574 CI->replaceAllUsesWith(With);
575 CI->eraseFromParent();
576 }
577 bool isFoldable(unsigned SizeCIOp, unsigned, bool) const {
Gabor Greifa6aac4c2010-07-16 09:38:02 +0000578 if (ConstantInt *SizeCI =
579 dyn_cast<ConstantInt>(CI->getArgOperand(SizeCIOp)))
580 return SizeCI->isAllOnesValue();
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000581 return false;
582 }
583};
584} // end anonymous namespace
585
Eric Christopher040056f2010-03-11 02:41:03 +0000586bool CodeGenPrepare::OptimizeCallInst(CallInst *CI) {
Eric Christopher040056f2010-03-11 02:41:03 +0000587 // Lower all uses of llvm.objectsize.*
588 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
589 if (II && II->getIntrinsicID() == Intrinsic::objectsize) {
Gabor Greifde9f5452010-06-24 00:44:01 +0000590 bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
Eric Christopher040056f2010-03-11 02:41:03 +0000591 const Type *ReturnTy = CI->getType();
592 Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
593 CI->replaceAllUsesWith(RetVal);
594 CI->eraseFromParent();
595 return true;
596 }
597
598 // From here on out we're working with named functions.
599 if (CI->getCalledFunction() == 0) return false;
600
601 // We'll need TargetData from here on out.
602 const TargetData *TD = TLI ? TLI->getTargetData() : 0;
603 if (!TD) return false;
604
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000605 // Lower all default uses of _chk calls. This is very similar
606 // to what InstCombineCalls does, but here we are only lowering calls
Eric Christopher040056f2010-03-11 02:41:03 +0000607 // that have the default "don't know" as the objectsize. Anything else
608 // should be left alone.
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000609 CodeGenPrepareFortifiedLibCalls Simplifier;
610 return Simplifier.fold(CI, TD);
Eric Christopher040056f2010-03-11 02:41:03 +0000611}
Chris Lattner88a5c832008-11-25 07:09:13 +0000612//===----------------------------------------------------------------------===//
Chris Lattner88a5c832008-11-25 07:09:13 +0000613// Memory Optimization
614//===----------------------------------------------------------------------===//
615
Chris Lattnerdd77df32007-04-13 20:30:56 +0000616/// IsNonLocalValue - Return true if the specified values are defined in a
617/// different basic block than BB.
618static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
619 if (Instruction *I = dyn_cast<Instruction>(V))
620 return I->getParent() != BB;
621 return false;
622}
623
Bob Wilson4a8ee232009-12-03 21:47:07 +0000624/// OptimizeMemoryInst - Load and Store Instructions often have
Chris Lattnerdd77df32007-04-13 20:30:56 +0000625/// addressing modes that can do significant amounts of computation. As such,
626/// instruction selection will try to get the load or store to do as much
627/// computation as possible for the program. The problem is that isel can only
628/// see within a single block. As such, we sink as much legal addressing mode
629/// stuff into the block as possible.
Chris Lattner88a5c832008-11-25 07:09:13 +0000630///
631/// This method is used to optimize both load/store and inline asms with memory
632/// operands.
Chris Lattner896617b2008-11-26 03:20:37 +0000633bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
Chris Lattner88a5c832008-11-25 07:09:13 +0000634 const Type *AccessTy,
635 DenseMap<Value*,Value*> &SunkAddrs) {
Owen Anderson35bf4d62010-11-27 08:15:55 +0000636 Value *Repl = Addr;
637
Owen Andersond2f41742010-11-19 22:15:03 +0000638 // Try to collapse single-value PHI nodes. This is necessary to undo
639 // unprofitable PRE transformations.
Cameron Zwarich7cb4fa22011-01-03 06:33:01 +0000640 SmallVector<Value*, 8> worklist;
641 SmallPtrSet<Value*, 16> Visited;
Owen Anderson35bf4d62010-11-27 08:15:55 +0000642 worklist.push_back(Addr);
643
644 // Use a worklist to iteratively look through PHI nodes, and ensure that
645 // the addressing mode obtained from the non-PHI roots of the graph
646 // are equivalent.
647 Value *Consensus = 0;
648 unsigned NumUses = 0;
649 SmallVector<Instruction*, 16> AddrModeInsts;
650 ExtAddrMode AddrMode;
651 while (!worklist.empty()) {
652 Value *V = worklist.back();
653 worklist.pop_back();
654
655 // Break use-def graph loops.
656 if (Visited.count(V)) {
657 Consensus = 0;
658 break;
Owen Andersond2f41742010-11-19 22:15:03 +0000659 }
660
Owen Anderson35bf4d62010-11-27 08:15:55 +0000661 Visited.insert(V);
662
663 // For a PHI node, push all of its incoming values.
664 if (PHINode *P = dyn_cast<PHINode>(V)) {
665 for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i)
666 worklist.push_back(P->getIncomingValue(i));
667 continue;
668 }
669
670 // For non-PHIs, determine the addressing mode being computed.
671 SmallVector<Instruction*, 16> NewAddrModeInsts;
672 ExtAddrMode NewAddrMode =
673 AddressingModeMatcher::Match(V, AccessTy,MemoryInst,
674 NewAddrModeInsts, *TLI);
675
676 // Ensure that the obtained addressing mode is equivalent to that obtained
677 // for all other roots of the PHI traversal. Also, when choosing one
678 // such root as representative, select the one with the most uses in order
679 // to keep the cost modeling heuristics in AddressingModeMatcher applicable.
680 if (!Consensus || NewAddrMode == AddrMode) {
681 if (V->getNumUses() > NumUses) {
682 Consensus = V;
683 NumUses = V->getNumUses();
684 AddrMode = NewAddrMode;
685 AddrModeInsts = NewAddrModeInsts;
686 }
687 continue;
688 }
689
690 Consensus = 0;
691 break;
Owen Andersond2f41742010-11-19 22:15:03 +0000692 }
693
Owen Anderson35bf4d62010-11-27 08:15:55 +0000694 // If the addressing mode couldn't be determined, or if multiple different
695 // ones were determined, bail out now.
696 if (!Consensus) return false;
697
Chris Lattnerdd77df32007-04-13 20:30:56 +0000698 // Check to see if any of the instructions supersumed by this addr mode are
699 // non-local to I's BB.
700 bool AnyNonLocal = false;
701 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
Chris Lattner896617b2008-11-26 03:20:37 +0000702 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
Chris Lattnerdd77df32007-04-13 20:30:56 +0000703 AnyNonLocal = true;
704 break;
705 }
706 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000707
Chris Lattnerdd77df32007-04-13 20:30:56 +0000708 // If all the instructions matched are already in this BB, don't do anything.
709 if (!AnyNonLocal) {
David Greene68d67fd2010-01-05 01:27:11 +0000710 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000711 return false;
712 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000713
Chris Lattnerdd77df32007-04-13 20:30:56 +0000714 // Insert this computation right after this user. Since our caller is
715 // scanning from the top of the BB to the bottom, reuse of the expr are
716 // guaranteed to happen later.
Chris Lattner896617b2008-11-26 03:20:37 +0000717 BasicBlock::iterator InsertPt = MemoryInst;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000718
Chris Lattnerdd77df32007-04-13 20:30:56 +0000719 // Now that we determined the addressing expression we want to use and know
720 // that we have to sink it into this block. Check to see if we have already
721 // done this for some other load/store instr in this block. If so, reuse the
722 // computation.
723 Value *&SunkAddr = SunkAddrs[Addr];
724 if (SunkAddr) {
David Greene68d67fd2010-01-05 01:27:11 +0000725 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
Dan Gohman6c1980b2009-07-25 01:13:51 +0000726 << *MemoryInst);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000727 if (SunkAddr->getType() != Addr->getType())
728 SunkAddr = new BitCastInst(SunkAddr, Addr->getType(), "tmp", InsertPt);
729 } else {
David Greene68d67fd2010-01-05 01:27:11 +0000730 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Dan Gohman6c1980b2009-07-25 01:13:51 +0000731 << *MemoryInst);
Owen Anderson1d0be152009-08-13 21:58:54 +0000732 const Type *IntPtrTy =
733 TLI->getTargetData()->getIntPtrType(AccessTy->getContext());
Eric Christopher692bf6b2008-09-24 05:32:41 +0000734
Chris Lattnerdd77df32007-04-13 20:30:56 +0000735 Value *Result = 0;
Dan Gohmand8d0b6a2010-01-19 22:45:06 +0000736
737 // Start with the base register. Do this first so that subsequent address
738 // matching finds it last, which will prevent it from trying to match it
739 // as the scaled value in case it happens to be a mul. That would be
740 // problematic if we've sunk a different mul for the scale, because then
741 // we'd end up sinking both muls.
742 if (AddrMode.BaseReg) {
743 Value *V = AddrMode.BaseReg;
Duncan Sands1df98592010-02-16 11:11:14 +0000744 if (V->getType()->isPointerTy())
Dan Gohmand8d0b6a2010-01-19 22:45:06 +0000745 V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
746 if (V->getType() != IntPtrTy)
747 V = CastInst::CreateIntegerCast(V, IntPtrTy, /*isSigned=*/true,
748 "sunkaddr", InsertPt);
749 Result = V;
750 }
751
752 // Add the scale value.
Chris Lattnerdd77df32007-04-13 20:30:56 +0000753 if (AddrMode.Scale) {
754 Value *V = AddrMode.ScaledReg;
755 if (V->getType() == IntPtrTy) {
756 // done.
Duncan Sands1df98592010-02-16 11:11:14 +0000757 } else if (V->getType()->isPointerTy()) {
Chris Lattnerdd77df32007-04-13 20:30:56 +0000758 V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
759 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
760 cast<IntegerType>(V->getType())->getBitWidth()) {
761 V = new TruncInst(V, IntPtrTy, "sunkaddr", InsertPt);
762 } else {
763 V = new SExtInst(V, IntPtrTy, "sunkaddr", InsertPt);
764 }
765 if (AddrMode.Scale != 1)
Owen Andersoneed707b2009-07-24 23:12:02 +0000766 V = BinaryOperator::CreateMul(V, ConstantInt::get(IntPtrTy,
Owen Andersond672ecb2009-07-03 00:17:18 +0000767 AddrMode.Scale),
Chris Lattnerdd77df32007-04-13 20:30:56 +0000768 "sunkaddr", InsertPt);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000769 if (Result)
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000770 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000771 else
772 Result = V;
773 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000774
Chris Lattnerdd77df32007-04-13 20:30:56 +0000775 // Add in the BaseGV if present.
776 if (AddrMode.BaseGV) {
777 Value *V = new PtrToIntInst(AddrMode.BaseGV, IntPtrTy, "sunkaddr",
778 InsertPt);
779 if (Result)
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000780 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000781 else
782 Result = V;
783 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000784
Chris Lattnerdd77df32007-04-13 20:30:56 +0000785 // Add in the Base Offset if present.
786 if (AddrMode.BaseOffs) {
Owen Andersoneed707b2009-07-24 23:12:02 +0000787 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000788 if (Result)
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000789 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000790 else
791 Result = V;
792 }
793
794 if (Result == 0)
Owen Andersona7235ea2009-07-31 20:28:14 +0000795 SunkAddr = Constant::getNullValue(Addr->getType());
Chris Lattnerdd77df32007-04-13 20:30:56 +0000796 else
797 SunkAddr = new IntToPtrInst(Result, Addr->getType(), "sunkaddr",InsertPt);
798 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000799
Owen Andersond2f41742010-11-19 22:15:03 +0000800 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000801
Owen Andersond2f41742010-11-19 22:15:03 +0000802 if (Repl->use_empty()) {
803 RecursivelyDeleteTriviallyDeadInstructions(Repl);
Dale Johannesen536d31b2010-03-31 20:37:15 +0000804 // This address is now available for reassignment, so erase the table entry;
805 // we don't want to match some completely different instruction.
806 SunkAddrs[Addr] = 0;
807 }
Cameron Zwarich31ff1332011-01-05 17:27:27 +0000808 ++NumMemoryInsts;
Chris Lattnerdd77df32007-04-13 20:30:56 +0000809 return true;
810}
811
Evan Cheng9bf12b52008-02-26 02:42:37 +0000812/// OptimizeInlineAsmInst - If there are any memory operands, use
Chris Lattner88a5c832008-11-25 07:09:13 +0000813/// OptimizeMemoryInst to sink their address computing into the block when
Evan Cheng9bf12b52008-02-26 02:42:37 +0000814/// possible / profitable.
815bool CodeGenPrepare::OptimizeInlineAsmInst(Instruction *I, CallSite CS,
816 DenseMap<Value*,Value*> &SunkAddrs) {
817 bool MadeChange = false;
Evan Cheng9bf12b52008-02-26 02:42:37 +0000818
John Thompson44ab89e2010-10-29 17:29:13 +0000819 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI->ParseConstraints(CS);
Dale Johannesen677c6ec2010-09-16 18:30:55 +0000820 unsigned ArgNo = 0;
John Thompsoneac6e1d2010-09-13 18:15:37 +0000821 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
822 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
823
Evan Cheng9bf12b52008-02-26 02:42:37 +0000824 // Compute the constraint code and ConstraintType to use.
Dale Johannesen1784d162010-06-25 21:55:36 +0000825 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Evan Cheng9bf12b52008-02-26 02:42:37 +0000826
Eli Friedman9ec80952008-02-26 18:37:49 +0000827 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
828 OpInfo.isIndirect) {
Dale Johannesen677c6ec2010-09-16 18:30:55 +0000829 Value *OpVal = const_cast<Value *>(CS.getArgument(ArgNo++));
Chris Lattner88a5c832008-11-25 07:09:13 +0000830 MadeChange |= OptimizeMemoryInst(I, OpVal, OpVal->getType(), SunkAddrs);
Dale Johannesen677c6ec2010-09-16 18:30:55 +0000831 } else if (OpInfo.Type == InlineAsm::isInput)
832 ArgNo++;
Evan Cheng9bf12b52008-02-26 02:42:37 +0000833 }
834
835 return MadeChange;
836}
837
Dan Gohmanb00f2362009-10-16 20:59:35 +0000838/// MoveExtToFormExtLoad - Move a zext or sext fed by a load into the same
839/// basic block as the load, unless conditions are unfavorable. This allows
840/// SelectionDAG to fold the extend into the load.
841///
842bool CodeGenPrepare::MoveExtToFormExtLoad(Instruction *I) {
843 // Look for a load being extended.
844 LoadInst *LI = dyn_cast<LoadInst>(I->getOperand(0));
845 if (!LI) return false;
846
847 // If they're already in the same block, there's nothing to do.
848 if (LI->getParent() == I->getParent())
849 return false;
850
851 // If the load has other users and the truncate is not free, this probably
852 // isn't worthwhile.
853 if (!LI->hasOneUse() &&
Bob Wilsonec57a1a2010-09-22 18:44:56 +0000854 TLI && (TLI->isTypeLegal(TLI->getValueType(LI->getType())) ||
855 !TLI->isTypeLegal(TLI->getValueType(I->getType()))) &&
Bob Wilson71dc4d92010-09-21 21:54:27 +0000856 !TLI->isTruncateFree(I->getType(), LI->getType()))
Dan Gohmanb00f2362009-10-16 20:59:35 +0000857 return false;
858
859 // Check whether the target supports casts folded into loads.
860 unsigned LType;
861 if (isa<ZExtInst>(I))
862 LType = ISD::ZEXTLOAD;
863 else {
864 assert(isa<SExtInst>(I) && "Unexpected ext type!");
865 LType = ISD::SEXTLOAD;
866 }
867 if (TLI && !TLI->isLoadExtLegal(LType, TLI->getValueType(LI->getType())))
868 return false;
869
870 // Move the extend into the same block as the load, so that SelectionDAG
871 // can fold it.
872 I->removeFromParent();
873 I->insertAfter(LI);
Cameron Zwarich31ff1332011-01-05 17:27:27 +0000874 ++NumExtsMoved;
Dan Gohmanb00f2362009-10-16 20:59:35 +0000875 return true;
876}
877
Evan Chengbdcb7262007-12-05 23:58:20 +0000878bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
879 BasicBlock *DefBB = I->getParent();
880
Bob Wilson9120f5c2010-09-21 21:44:14 +0000881 // If the result of a {s|z}ext and its source are both live out, rewrite all
Evan Chengbdcb7262007-12-05 23:58:20 +0000882 // other uses of the source with result of extension.
883 Value *Src = I->getOperand(0);
884 if (Src->hasOneUse())
885 return false;
886
Evan Cheng696e5c02007-12-13 07:50:36 +0000887 // Only do this xform if truncating is free.
Gabor Greif53bdbd72008-02-26 19:13:21 +0000888 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
Evan Chengf9785f92007-12-13 03:32:53 +0000889 return false;
890
Evan Cheng772de512007-12-12 00:51:06 +0000891 // Only safe to perform the optimization if the source is also defined in
Evan Cheng765dff22007-12-12 02:53:41 +0000892 // this block.
893 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
Evan Cheng772de512007-12-12 00:51:06 +0000894 return false;
895
Evan Chengbdcb7262007-12-05 23:58:20 +0000896 bool DefIsLiveOut = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000897 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
Evan Chengbdcb7262007-12-05 23:58:20 +0000898 UI != E; ++UI) {
899 Instruction *User = cast<Instruction>(*UI);
900
901 // Figure out which BB this ext is used in.
902 BasicBlock *UserBB = User->getParent();
903 if (UserBB == DefBB) continue;
904 DefIsLiveOut = true;
905 break;
906 }
907 if (!DefIsLiveOut)
908 return false;
909
Evan Cheng765dff22007-12-12 02:53:41 +0000910 // Make sure non of the uses are PHI nodes.
Eric Christopher692bf6b2008-09-24 05:32:41 +0000911 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
Evan Cheng765dff22007-12-12 02:53:41 +0000912 UI != E; ++UI) {
913 Instruction *User = cast<Instruction>(*UI);
Evan Chengf9785f92007-12-13 03:32:53 +0000914 BasicBlock *UserBB = User->getParent();
915 if (UserBB == DefBB) continue;
916 // Be conservative. We don't want this xform to end up introducing
917 // reloads just before load / store instructions.
918 if (isa<PHINode>(User) || isa<LoadInst>(User) || isa<StoreInst>(User))
Evan Cheng765dff22007-12-12 02:53:41 +0000919 return false;
920 }
921
Evan Chengbdcb7262007-12-05 23:58:20 +0000922 // InsertedTruncs - Only insert one trunc in each block once.
923 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
924
925 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000926 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
Evan Chengbdcb7262007-12-05 23:58:20 +0000927 UI != E; ++UI) {
928 Use &TheUse = UI.getUse();
929 Instruction *User = cast<Instruction>(*UI);
930
931 // Figure out which BB this ext is used in.
932 BasicBlock *UserBB = User->getParent();
933 if (UserBB == DefBB) continue;
934
935 // Both src and def are live in this block. Rewrite the use.
936 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
937
938 if (!InsertedTrunc) {
Dan Gohman02dea8b2008-05-23 21:05:58 +0000939 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000940
Evan Chengbdcb7262007-12-05 23:58:20 +0000941 InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
942 }
943
944 // Replace a use of the {s|z}ext source with a use of the result.
945 TheUse = InsertedTrunc;
Cameron Zwarich31ff1332011-01-05 17:27:27 +0000946 ++NumExtUses;
Evan Chengbdcb7262007-12-05 23:58:20 +0000947 MadeChange = true;
948 }
949
950 return MadeChange;
951}
952
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000953// In this pass we look for GEP and cast instructions that are used
954// across basic blocks and rewrite them to improve basic-block-at-a-time
955// selection.
956bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
957 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000958
Evan Chengab631522008-12-19 18:03:11 +0000959 // Split all critical edges where the dest block has a PHI.
Evan Chenge1bcb442010-08-17 01:34:49 +0000960 if (CriticalEdgeSplit) {
961 TerminatorInst *BBTI = BB.getTerminator();
962 if (BBTI->getNumSuccessors() > 1 && !isa<IndirectBrInst>(BBTI)) {
963 for (unsigned i = 0, e = BBTI->getNumSuccessors(); i != e; ++i) {
964 BasicBlock *SuccBB = BBTI->getSuccessor(i);
965 if (isa<PHINode>(SuccBB->begin()) && isCriticalEdge(BBTI, i, true))
966 SplitEdgeNicely(BBTI, i, BackEdges, this);
967 }
Evan Chengab631522008-12-19 18:03:11 +0000968 }
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000969 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000970
Chris Lattnerdd77df32007-04-13 20:30:56 +0000971 // Keep track of non-local addresses that have been sunk into this block.
972 // This allows us to avoid inserting duplicate code for blocks with multiple
973 // load/stores of the same address.
974 DenseMap<Value*, Value*> SunkAddrs;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000975
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000976 for (BasicBlock::iterator BBI = BB.begin(), E = BB.end(); BBI != E; ) {
977 Instruction *I = BBI++;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000978
Owen Andersond5f86842010-12-23 20:57:35 +0000979 if (PHINode *P = dyn_cast<PHINode>(I)) {
980 // It is possible for very late stage optimizations (such as SimplifyCFG)
981 // to introduce PHI nodes too late to be cleaned up. If we detect such a
982 // trivial PHI, go ahead and zap it here.
983 if (Value *V = SimplifyInstruction(P)) {
984 P->replaceAllUsesWith(V);
985 P->eraseFromParent();
Cameron Zwarich073057f2011-01-05 17:47:38 +0000986 ++NumPHIsElim;
Owen Andersond5f86842010-12-23 20:57:35 +0000987 }
988 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000989 // If the source of the cast is a constant, then this should have
990 // already been constant folded. The only reason NOT to constant fold
991 // it is if something (e.g. LSR) was careful to place the constant
992 // evaluation in a block other than then one that uses it (e.g. to hoist
993 // the address of globals out of a loop). If this is the case, we don't
994 // want to forward-subst the cast.
995 if (isa<Constant>(CI->getOperand(0)))
996 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000997
Evan Chengbdcb7262007-12-05 23:58:20 +0000998 bool Change = false;
999 if (TLI) {
1000 Change = OptimizeNoopCopyExpression(CI, *TLI);
1001 MadeChange |= Change;
1002 }
1003
Dan Gohmanb00f2362009-10-16 20:59:35 +00001004 if (!Change && (isa<ZExtInst>(I) || isa<SExtInst>(I))) {
1005 MadeChange |= MoveExtToFormExtLoad(I);
Evan Chengbdcb7262007-12-05 23:58:20 +00001006 MadeChange |= OptimizeExtUses(I);
Dan Gohmanb00f2362009-10-16 20:59:35 +00001007 }
Dale Johannesence0b2372007-06-12 16:50:17 +00001008 } else if (CmpInst *CI = dyn_cast<CmpInst>(I)) {
1009 MadeChange |= OptimizeCmpExpression(CI);
Chris Lattnerdd77df32007-04-13 20:30:56 +00001010 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
1011 if (TLI)
Chris Lattner88a5c832008-11-25 07:09:13 +00001012 MadeChange |= OptimizeMemoryInst(I, I->getOperand(0), LI->getType(),
1013 SunkAddrs);
Chris Lattnerdd77df32007-04-13 20:30:56 +00001014 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
1015 if (TLI)
Chris Lattner88a5c832008-11-25 07:09:13 +00001016 MadeChange |= OptimizeMemoryInst(I, SI->getOperand(1),
1017 SI->getOperand(0)->getType(),
1018 SunkAddrs);
Chris Lattnerdd77df32007-04-13 20:30:56 +00001019 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Chris Lattnerf25646b2007-04-14 00:17:39 +00001020 if (GEPI->hasAllZeroIndices()) {
Chris Lattnerdd77df32007-04-13 20:30:56 +00001021 /// The GEP operand must be a pointer, so must its result -> BitCast
Eric Christopher692bf6b2008-09-24 05:32:41 +00001022 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
Chris Lattnerdd77df32007-04-13 20:30:56 +00001023 GEPI->getName(), GEPI);
1024 GEPI->replaceAllUsesWith(NC);
1025 GEPI->eraseFromParent();
Cameron Zwarich073057f2011-01-05 17:47:38 +00001026 ++NumGEPsElim;
Chris Lattnerdd77df32007-04-13 20:30:56 +00001027 MadeChange = true;
1028 BBI = NC;
1029 }
1030 } else if (CallInst *CI = dyn_cast<CallInst>(I)) {
1031 // If we found an inline asm expession, and if the target knows how to
1032 // lower it to normal LLVM code, do so now.
Chris Lattner8850b362009-07-20 17:52:52 +00001033 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
1034 if (TLI->ExpandInlineAsm(CI)) {
1035 BBI = BB.begin();
1036 // Avoid processing instructions out of order, which could cause
1037 // reuse before a value is defined.
1038 SunkAddrs.clear();
1039 } else
1040 // Sink address computing for memory operands into the block.
1041 MadeChange |= OptimizeInlineAsmInst(I, &(*CI), SunkAddrs);
Eric Christopher040056f2010-03-11 02:41:03 +00001042 } else {
1043 // Other CallInst optimizations that don't need to muck with the
1044 // enclosing iterator here.
1045 MadeChange |= OptimizeCallInst(CI);
Chris Lattner8850b362009-07-20 17:52:52 +00001046 }
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001047 }
1048 }
Eric Christopher692bf6b2008-09-24 05:32:41 +00001049
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001050 return MadeChange;
1051}