blob: 4b4a8c598fc3bce7b4adce50939f15f471864062 [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"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000021#include "llvm/IRBuilder.h"
Evan Cheng9bf12b52008-02-26 02:42:37 +000022#include "llvm/InlineAsm.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000023#include "llvm/Instructions.h"
Dale Johannesen6aae1d62009-03-26 01:15:07 +000024#include "llvm/IntrinsicInst.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000025#include "llvm/Pass.h"
Chris Lattnerdd77df32007-04-13 20:30:56 +000026#include "llvm/ADT/DenseMap.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000027#include "llvm/ADT/SmallSet.h"
Jakob Stoklund Olesen7eb589d2010-09-30 20:51:52 +000028#include "llvm/ADT/Statistic.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000029#include "llvm/Analysis/Dominators.h"
30#include "llvm/Analysis/InstructionSimplify.h"
31#include "llvm/Analysis/ProfileInfo.h"
Dan Gohman03ce0422009-02-13 17:45:12 +000032#include "llvm/Assembly/Writer.h"
Evan Cheng9bf12b52008-02-26 02:42:37 +000033#include "llvm/Support/CallSite.h"
Evan Chenge1bcb442010-08-17 01:34:49 +000034#include "llvm/Support/CommandLine.h"
Evan Chengbdcb7262007-12-05 23:58:20 +000035#include "llvm/Support/Debug.h"
Chris Lattnerdd77df32007-04-13 20:30:56 +000036#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner088a1e82008-11-25 04:42:10 +000037#include "llvm/Support/PatternMatch.h"
Chris Lattner94e8e0c2011-01-15 07:25:29 +000038#include "llvm/Support/ValueHandle.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000039#include "llvm/Support/raw_ostream.h"
40#include "llvm/Target/TargetData.h"
41#include "llvm/Target/TargetLibraryInfo.h"
42#include "llvm/Target/TargetLowering.h"
43#include "llvm/Transforms/Utils/AddrModeMatcher.h"
44#include "llvm/Transforms/Utils/BasicBlockUtils.h"
45#include "llvm/Transforms/Utils/BuildLibCalls.h"
46#include "llvm/Transforms/Utils/Local.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000047using namespace llvm;
Chris Lattner088a1e82008-11-25 04:42:10 +000048using namespace llvm::PatternMatch;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000049
Cameron Zwarich31ff1332011-01-05 17:27:27 +000050STATISTIC(NumBlocksElim, "Number of blocks eliminated");
Evan Cheng485fafc2011-03-21 01:19:09 +000051STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated");
52STATISTIC(NumGEPsElim, "Number of GEPs converted to casts");
Cameron Zwarich31ff1332011-01-05 17:27:27 +000053STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "
54 "sunken Cmps");
55STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
56 "of sunken Casts");
57STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "
58 "computations were sunk");
Evan Cheng485fafc2011-03-21 01:19:09 +000059STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads");
60STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized");
61STATISTIC(NumRetsDup, "Number of return instructions duplicated");
Devang Patelf56ea612011-08-18 00:50:51 +000062STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved");
Benjamin Kramer59957502012-05-05 12:49:22 +000063STATISTIC(NumSelectsExpanded, "Number of selects turned into branches");
Jakob Stoklund Olesen7eb589d2010-09-30 20:51:52 +000064
Cameron Zwarich899eaa32011-03-11 21:52:04 +000065static cl::opt<bool> DisableBranchOpts(
66 "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
67 cl::desc("Disable branch optimizations in CodeGenPrepare"));
68
Bill Wendlinge3e394d2012-03-04 10:46:01 +000069// FIXME: Remove this abomination once all of the tests pass without it!
70static cl::opt<bool> DisableDeleteDeadBlocks(
71 "disable-cgp-delete-dead-blocks", cl::Hidden, cl::init(false),
72 cl::desc("Disable deleting dead blocks in CodeGenPrepare"));
73
Benjamin Kramer77c4ef82012-05-06 14:25:16 +000074static cl::opt<bool> DisableSelectToBranch(
75 "disable-cgp-select2branch", cl::Hidden, cl::init(false),
76 cl::desc("Disable select to branch conversion."));
Benjamin Kramer59957502012-05-05 12:49:22 +000077
Eric Christopher692bf6b2008-09-24 05:32:41 +000078namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +000079 class CodeGenPrepare : public FunctionPass {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000080 /// TLI - Keep a pointer of a TargetLowering to consult for determining
81 /// transformation profitability.
82 const TargetLowering *TLI;
Chad Rosier618c1db2011-12-01 03:08:23 +000083 const TargetLibraryInfo *TLInfo;
Cameron Zwarich80f6a502011-01-08 17:01:52 +000084 DominatorTree *DT;
Evan Cheng04149f72009-12-17 09:39:49 +000085 ProfileInfo *PFI;
Nadav Rotema94d6e82012-07-24 10:51:42 +000086
Chris Lattner75796092011-01-15 07:14:54 +000087 /// CurInstIterator - As we scan instructions optimizing them, this is the
88 /// next instruction to optimize. Xforms that can invalidate this should
89 /// update it.
90 BasicBlock::iterator CurInstIterator;
Evan Chengab631522008-12-19 18:03:11 +000091
Evan Cheng485fafc2011-03-21 01:19:09 +000092 /// Keeps track of non-local addresses that have been sunk into a block.
93 /// This allows us to avoid inserting duplicate code for blocks with
94 /// multiple load/stores of the same address.
Cameron Zwarich8c3527e2011-01-06 00:42:50 +000095 DenseMap<Value*, Value*> SunkAddrs;
96
Devang Patel52e37df2011-03-24 15:35:25 +000097 /// ModifiedDT - If CFG is modified in anyway, dominator tree may need to
Evan Cheng485fafc2011-03-21 01:19:09 +000098 /// be updated.
Devang Patel52e37df2011-03-24 15:35:25 +000099 bool ModifiedDT;
Evan Cheng485fafc2011-03-21 01:19:09 +0000100
Benjamin Kramer59957502012-05-05 12:49:22 +0000101 /// OptSize - True if optimizing for size.
102 bool OptSize;
103
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000104 public:
Nick Lewyckyecd94c82007-05-06 13:37:16 +0000105 static char ID; // Pass identification, replacement for typeid
Dan Gohmanc2bbfc12007-08-01 15:32:29 +0000106 explicit CodeGenPrepare(const TargetLowering *tli = 0)
Owen Anderson081c34b2010-10-19 17:21:58 +0000107 : FunctionPass(ID), TLI(tli) {
108 initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
109 }
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000110 bool runOnFunction(Function &F);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000111
Andreas Neustifterad809812009-09-16 09:26:52 +0000112 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Cameron Zwarich80f6a502011-01-08 17:01:52 +0000113 AU.addPreserved<DominatorTree>();
Andreas Neustifterad809812009-09-16 09:26:52 +0000114 AU.addPreserved<ProfileInfo>();
Chad Rosier618c1db2011-12-01 03:08:23 +0000115 AU.addRequired<TargetLibraryInfo>();
Andreas Neustifterad809812009-09-16 09:26:52 +0000116 }
117
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000118 private:
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000119 bool EliminateMostlyEmptyBlocks(Function &F);
120 bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
121 void EliminateMostlyEmptyBlock(BasicBlock *BB);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000122 bool OptimizeBlock(BasicBlock &BB);
Cameron Zwarichc0611012011-01-06 02:37:26 +0000123 bool OptimizeInst(Instruction *I);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000124 bool OptimizeMemoryInst(Instruction *I, Value *Addr, Type *AccessTy);
Chris Lattner75796092011-01-15 07:14:54 +0000125 bool OptimizeInlineAsmInst(CallInst *CS);
Eric Christopher040056f2010-03-11 02:41:03 +0000126 bool OptimizeCallInst(CallInst *CI);
Dan Gohmanb00f2362009-10-16 20:59:35 +0000127 bool MoveExtToFormExtLoad(Instruction *I);
Evan Chengbdcb7262007-12-05 23:58:20 +0000128 bool OptimizeExtUses(Instruction *I);
Benjamin Kramer59957502012-05-05 12:49:22 +0000129 bool OptimizeSelectInst(SelectInst *SI);
Evan Cheng485fafc2011-03-21 01:19:09 +0000130 bool DupRetToEnableTailCallOpts(ReturnInst *RI);
Devang Patelf56ea612011-08-18 00:50:51 +0000131 bool PlaceDbgValues(Function &F);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000132 };
133}
Devang Patel794fd752007-05-01 21:15:47 +0000134
Devang Patel19974732007-05-03 01:11:54 +0000135char CodeGenPrepare::ID = 0;
Chad Rosier618c1db2011-12-01 03:08:23 +0000136INITIALIZE_PASS_BEGIN(CodeGenPrepare, "codegenprepare",
137 "Optimize for code generation", false, false)
138INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
139INITIALIZE_PASS_END(CodeGenPrepare, "codegenprepare",
Owen Andersonce665bd2010-10-07 22:25:06 +0000140 "Optimize for code generation", false, false)
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000141
142FunctionPass *llvm::createCodeGenPreparePass(const TargetLowering *TLI) {
143 return new CodeGenPrepare(TLI);
144}
145
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000146bool CodeGenPrepare::runOnFunction(Function &F) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000147 bool EverMadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000148
Devang Patel52e37df2011-03-24 15:35:25 +0000149 ModifiedDT = false;
Chad Rosier618c1db2011-12-01 03:08:23 +0000150 TLInfo = &getAnalysis<TargetLibraryInfo>();
Cameron Zwarich80f6a502011-01-08 17:01:52 +0000151 DT = getAnalysisIfAvailable<DominatorTree>();
Evan Cheng04149f72009-12-17 09:39:49 +0000152 PFI = getAnalysisIfAvailable<ProfileInfo>();
Benjamin Kramer59957502012-05-05 12:49:22 +0000153 OptSize = F.hasFnAttr(Attribute::OptimizeForSize);
Evan Cheng485fafc2011-03-21 01:19:09 +0000154
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000155 // First pass, eliminate blocks that contain only PHI nodes and an
156 // unconditional branch.
157 EverMadeChange |= EliminateMostlyEmptyBlocks(F);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000158
Devang Patelf56ea612011-08-18 00:50:51 +0000159 // llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotema94d6e82012-07-24 10:51:42 +0000160 // handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patelf56ea612011-08-18 00:50:51 +0000161 // find a node corresponding to the value.
162 EverMadeChange |= PlaceDbgValues(F);
163
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000164 bool MadeChange = true;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000165 while (MadeChange) {
166 MadeChange = false;
Evan Cheng485fafc2011-03-21 01:19:09 +0000167 for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
168 BasicBlock *BB = I++;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000169 MadeChange |= OptimizeBlock(*BB);
Evan Cheng485fafc2011-03-21 01:19:09 +0000170 }
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000171 EverMadeChange |= MadeChange;
172 }
Cameron Zwarich8c3527e2011-01-06 00:42:50 +0000173
174 SunkAddrs.clear();
175
Cameron Zwarich899eaa32011-03-11 21:52:04 +0000176 if (!DisableBranchOpts) {
177 MadeChange = false;
Bill Wendlinge3e394d2012-03-04 10:46:01 +0000178 SmallPtrSet<BasicBlock*, 8> WorkList;
179 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
180 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
Frits van Bommel5649ba72011-05-22 16:24:18 +0000181 MadeChange |= ConstantFoldTerminator(BB, true);
Bill Wendlinge3e394d2012-03-04 10:46:01 +0000182 if (!MadeChange) continue;
183
184 for (SmallVectorImpl<BasicBlock*>::iterator
185 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
186 if (pred_begin(*II) == pred_end(*II))
187 WorkList.insert(*II);
188 }
189
190 if (!DisableDeleteDeadBlocks)
191 for (SmallPtrSet<BasicBlock*, 8>::iterator
192 I = WorkList.begin(), E = WorkList.end(); I != E; ++I)
193 DeleteDeadBlock(*I);
Cameron Zwarich899eaa32011-03-11 21:52:04 +0000194
Evan Cheng485fafc2011-03-21 01:19:09 +0000195 if (MadeChange)
Devang Patel52e37df2011-03-24 15:35:25 +0000196 ModifiedDT = true;
Cameron Zwarich899eaa32011-03-11 21:52:04 +0000197 EverMadeChange |= MadeChange;
198 }
199
Devang Patel52e37df2011-03-24 15:35:25 +0000200 if (ModifiedDT && DT)
Evan Cheng485fafc2011-03-21 01:19:09 +0000201 DT->DT->recalculate(F);
202
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000203 return EverMadeChange;
204}
205
Dale Johannesen2d697242009-03-27 01:13:37 +0000206/// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes,
207/// debug info directives, and an unconditional branch. Passes before isel
208/// (e.g. LSR/loopsimplify) often split edges in ways that are non-optimal for
209/// isel. Start by eliminating these blocks so we can split them the way we
210/// want them.
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000211bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
212 bool MadeChange = false;
213 // Note that this intentionally skips the entry block.
214 for (Function::iterator I = ++F.begin(), E = F.end(); I != E; ) {
215 BasicBlock *BB = I++;
216
217 // If this block doesn't end with an uncond branch, ignore it.
218 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
219 if (!BI || !BI->isUnconditional())
220 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000221
Dale Johannesen2d697242009-03-27 01:13:37 +0000222 // If the instruction before the branch (skipping debug info) isn't a phi
223 // node, then other stuff is happening here.
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000224 BasicBlock::iterator BBI = BI;
225 if (BBI != BB->begin()) {
226 --BBI;
Dale Johannesen2d697242009-03-27 01:13:37 +0000227 while (isa<DbgInfoIntrinsic>(BBI)) {
228 if (BBI == BB->begin())
229 break;
230 --BBI;
231 }
232 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
233 continue;
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000234 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000235
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000236 // Do not break infinite loops.
237 BasicBlock *DestBB = BI->getSuccessor(0);
238 if (DestBB == BB)
239 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000240
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000241 if (!CanMergeBlocks(BB, DestBB))
242 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000243
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000244 EliminateMostlyEmptyBlock(BB);
245 MadeChange = true;
246 }
247 return MadeChange;
248}
249
250/// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
251/// single uncond branch between them, and BB contains no other non-phi
252/// instructions.
253bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
254 const BasicBlock *DestBB) const {
255 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
256 // the successor. If there are more complex condition (e.g. preheaders),
257 // don't mess around with them.
258 BasicBlock::const_iterator BBI = BB->begin();
259 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
Gabor Greif60ad7812010-03-25 23:06:16 +0000260 for (Value::const_use_iterator UI = PN->use_begin(), E = PN->use_end();
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000261 UI != E; ++UI) {
262 const Instruction *User = cast<Instruction>(*UI);
263 if (User->getParent() != DestBB || !isa<PHINode>(User))
264 return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000265 // If User is inside DestBB block and it is a PHINode then check
266 // incoming value. If incoming value is not from BB then this is
Devang Patel75abc1e2007-04-25 00:37:04 +0000267 // a complex condition (e.g. preheaders) we want to avoid here.
268 if (User->getParent() == DestBB) {
269 if (const PHINode *UPN = dyn_cast<PHINode>(User))
270 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
271 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
272 if (Insn && Insn->getParent() == BB &&
273 Insn->getParent() != UPN->getIncomingBlock(I))
274 return false;
275 }
276 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000277 }
278 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000279
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000280 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
281 // and DestBB may have conflicting incoming values for the block. If so, we
282 // can't merge the block.
283 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
284 if (!DestBBPN) return true; // no conflict.
Eric Christopher692bf6b2008-09-24 05:32:41 +0000285
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000286 // Collect the preds of BB.
Chris Lattnerf67f73a2007-11-06 22:07:40 +0000287 SmallPtrSet<const BasicBlock*, 16> BBPreds;
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000288 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
289 // It is faster to get preds from a PHI than with pred_iterator.
290 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
291 BBPreds.insert(BBPN->getIncomingBlock(i));
292 } else {
293 BBPreds.insert(pred_begin(BB), pred_end(BB));
294 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000295
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000296 // Walk the preds of DestBB.
297 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
298 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
299 if (BBPreds.count(Pred)) { // Common predecessor?
300 BBI = DestBB->begin();
301 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
302 const Value *V1 = PN->getIncomingValueForBlock(Pred);
303 const Value *V2 = PN->getIncomingValueForBlock(BB);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000304
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000305 // If V2 is a phi node in BB, look up what the mapped value will be.
306 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
307 if (V2PN->getParent() == BB)
308 V2 = V2PN->getIncomingValueForBlock(Pred);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000309
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000310 // If there is a conflict, bail out.
311 if (V1 != V2) return false;
312 }
313 }
314 }
315
316 return true;
317}
318
319
320/// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
321/// an unconditional branch in it.
322void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
323 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
324 BasicBlock *DestBB = BI->getSuccessor(0);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000325
David Greene68d67fd2010-01-05 01:27:11 +0000326 DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000327
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000328 // If the destination block has a single pred, then this is a trivial edge,
329 // just collapse it.
Chris Lattner9918fb52008-11-27 19:29:14 +0000330 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
Chris Lattnerf5102a02008-11-28 19:54:49 +0000331 if (SinglePred != DestBB) {
332 // Remember if SinglePred was the entry block of the function. If so, we
333 // will need to move BB back to the entry position.
334 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Andreas Neustifterad809812009-09-16 09:26:52 +0000335 MergeBasicBlockIntoOnlyPred(DestBB, this);
Chris Lattner9918fb52008-11-27 19:29:14 +0000336
Chris Lattnerf5102a02008-11-28 19:54:49 +0000337 if (isEntry && BB != &BB->getParent()->getEntryBlock())
338 BB->moveBefore(&BB->getParent()->getEntryBlock());
Nadav Rotema94d6e82012-07-24 10:51:42 +0000339
David Greene68d67fd2010-01-05 01:27:11 +0000340 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerf5102a02008-11-28 19:54:49 +0000341 return;
342 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000343 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000344
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000345 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
346 // to handle the new incoming edges it is about to have.
347 PHINode *PN;
348 for (BasicBlock::iterator BBI = DestBB->begin();
349 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
350 // Remove the incoming value for BB, and remember it.
351 Value *InVal = PN->removeIncomingValue(BB, false);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000352
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000353 // Two options: either the InVal is a phi node defined in BB or it is some
354 // value that dominates BB.
355 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
356 if (InValPhi && InValPhi->getParent() == BB) {
357 // Add all of the input values of the input PHI as inputs of this phi.
358 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
359 PN->addIncoming(InValPhi->getIncomingValue(i),
360 InValPhi->getIncomingBlock(i));
361 } else {
362 // Otherwise, add one instance of the dominating value for each edge that
363 // we will be adding.
364 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
365 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
366 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
367 } else {
368 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
369 PN->addIncoming(InVal, *PI);
370 }
371 }
372 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000373
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000374 // The PHIs are now updated, change everything that refers to BB to use
375 // DestBB and remove BB.
376 BB->replaceAllUsesWith(DestBB);
Devang Patel52e37df2011-03-24 15:35:25 +0000377 if (DT && !ModifiedDT) {
Cameron Zwarich80f6a502011-01-08 17:01:52 +0000378 BasicBlock *BBIDom = DT->getNode(BB)->getIDom()->getBlock();
379 BasicBlock *DestBBIDom = DT->getNode(DestBB)->getIDom()->getBlock();
380 BasicBlock *NewIDom = DT->findNearestCommonDominator(BBIDom, DestBBIDom);
381 DT->changeImmediateDominator(DestBB, NewIDom);
382 DT->eraseNode(BB);
383 }
Evan Cheng04149f72009-12-17 09:39:49 +0000384 if (PFI) {
385 PFI->replaceAllUses(BB, DestBB);
386 PFI->removeEdge(ProfileInfo::getEdge(BB, DestBB));
Andreas Neustifterad809812009-09-16 09:26:52 +0000387 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000388 BB->eraseFromParent();
Cameron Zwarich31ff1332011-01-05 17:27:27 +0000389 ++NumBlocksElim;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000390
David Greene68d67fd2010-01-05 01:27:11 +0000391 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000392}
393
Chris Lattnerdd77df32007-04-13 20:30:56 +0000394/// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
Dan Gohmana119de82009-06-14 23:30:43 +0000395/// copy (e.g. it's casting from one pointer type to another, i32->i8 on PPC),
396/// sink it into user blocks to reduce the number of virtual
Dale Johannesence0b2372007-06-12 16:50:17 +0000397/// registers that must be created and coalesced.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000398///
399/// Return true if any changes are made.
Chris Lattner85fa13c2008-11-24 22:44:16 +0000400///
Chris Lattnerdd77df32007-04-13 20:30:56 +0000401static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
Eric Christopher692bf6b2008-09-24 05:32:41 +0000402 // If this is a noop copy,
Owen Andersone50ed302009-08-10 22:56:29 +0000403 EVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
404 EVT DstVT = TLI.getValueType(CI->getType());
Eric Christopher692bf6b2008-09-24 05:32:41 +0000405
Chris Lattnerdd77df32007-04-13 20:30:56 +0000406 // This is an fp<->int conversion?
Duncan Sands83ec4b62008-06-06 12:08:01 +0000407 if (SrcVT.isInteger() != DstVT.isInteger())
Chris Lattnerdd77df32007-04-13 20:30:56 +0000408 return false;
Duncan Sands8e4eb092008-06-08 20:54:56 +0000409
Chris Lattnerdd77df32007-04-13 20:30:56 +0000410 // If this is an extension, it will be a zero or sign extension, which
411 // isn't a noop.
Duncan Sands8e4eb092008-06-08 20:54:56 +0000412 if (SrcVT.bitsLT(DstVT)) return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000413
Chris Lattnerdd77df32007-04-13 20:30:56 +0000414 // If these values will be promoted, find out what they will be promoted
415 // to. This helps us consider truncates on PPC as noop copies when they
416 // are.
Nadav Rotem0ccc12a2011-05-29 08:10:47 +0000417 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
418 TargetLowering::TypePromoteInteger)
Owen Anderson23b9b192009-08-12 00:36:31 +0000419 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
Nadav Rotem0ccc12a2011-05-29 08:10:47 +0000420 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
421 TargetLowering::TypePromoteInteger)
Owen Anderson23b9b192009-08-12 00:36:31 +0000422 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000423
Chris Lattnerdd77df32007-04-13 20:30:56 +0000424 // If, after promotion, these are the same types, this is a noop copy.
425 if (SrcVT != DstVT)
426 return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000427
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000428 BasicBlock *DefBB = CI->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000429
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000430 /// InsertedCasts - Only insert a cast in each block once.
Dale Johannesence0b2372007-06-12 16:50:17 +0000431 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000432
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000433 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000434 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000435 UI != E; ) {
436 Use &TheUse = UI.getUse();
437 Instruction *User = cast<Instruction>(*UI);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000438
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000439 // Figure out which BB this cast is used in. For PHI's this is the
440 // appropriate predecessor block.
441 BasicBlock *UserBB = User->getParent();
442 if (PHINode *PN = dyn_cast<PHINode>(User)) {
Gabor Greifa36791d2009-01-23 19:40:15 +0000443 UserBB = PN->getIncomingBlock(UI);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000444 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000445
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000446 // Preincrement use iterator so we don't invalidate it.
447 ++UI;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000448
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000449 // If this user is in the same block as the cast, don't change the cast.
450 if (UserBB == DefBB) continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000451
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000452 // If we have already inserted a cast into this block, use it.
453 CastInst *&InsertedCast = InsertedCasts[UserBB];
454
455 if (!InsertedCast) {
Bill Wendling5b6f42f2011-08-16 20:45:24 +0000456 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000457 InsertedCast =
458 CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000459 InsertPt);
460 MadeChange = true;
461 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000462
Dale Johannesence0b2372007-06-12 16:50:17 +0000463 // Replace a use of the cast with a use of the new cast.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000464 TheUse = InsertedCast;
Cameron Zwarich31ff1332011-01-05 17:27:27 +0000465 ++NumCastUses;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000466 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000467
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000468 // If we removed all uses, nuke the cast.
Duncan Sandse0038132008-01-20 16:51:46 +0000469 if (CI->use_empty()) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000470 CI->eraseFromParent();
Duncan Sandse0038132008-01-20 16:51:46 +0000471 MadeChange = true;
472 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000473
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000474 return MadeChange;
475}
476
Eric Christopher692bf6b2008-09-24 05:32:41 +0000477/// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
Dale Johannesence0b2372007-06-12 16:50:17 +0000478/// the number of virtual registers that must be created and coalesced. This is
Chris Lattner684b22d2007-08-02 16:53:43 +0000479/// a clear win except on targets with multiple condition code registers
480/// (PowerPC), where it might lose; some adjustment may be wanted there.
Dale Johannesence0b2372007-06-12 16:50:17 +0000481///
482/// Return true if any changes are made.
Chris Lattner85fa13c2008-11-24 22:44:16 +0000483static bool OptimizeCmpExpression(CmpInst *CI) {
Dale Johannesence0b2372007-06-12 16:50:17 +0000484 BasicBlock *DefBB = CI->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000485
Dale Johannesence0b2372007-06-12 16:50:17 +0000486 /// InsertedCmp - Only insert a cmp in each block once.
487 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000488
Dale Johannesence0b2372007-06-12 16:50:17 +0000489 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000490 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
Dale Johannesence0b2372007-06-12 16:50:17 +0000491 UI != E; ) {
492 Use &TheUse = UI.getUse();
493 Instruction *User = cast<Instruction>(*UI);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000494
Dale Johannesence0b2372007-06-12 16:50:17 +0000495 // Preincrement use iterator so we don't invalidate it.
496 ++UI;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000497
Dale Johannesence0b2372007-06-12 16:50:17 +0000498 // Don't bother for PHI nodes.
499 if (isa<PHINode>(User))
500 continue;
501
502 // Figure out which BB this cmp is used in.
503 BasicBlock *UserBB = User->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000504
Dale Johannesence0b2372007-06-12 16:50:17 +0000505 // If this user is in the same block as the cmp, don't change the cmp.
506 if (UserBB == DefBB) continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000507
Dale Johannesence0b2372007-06-12 16:50:17 +0000508 // If we have already inserted a cmp into this block, use it.
509 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
510
511 if (!InsertedCmp) {
Bill Wendling5b6f42f2011-08-16 20:45:24 +0000512 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000513 InsertedCmp =
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000514 CmpInst::Create(CI->getOpcode(),
Owen Anderson333c4002009-07-09 23:48:35 +0000515 CI->getPredicate(), CI->getOperand(0),
Dale Johannesence0b2372007-06-12 16:50:17 +0000516 CI->getOperand(1), "", InsertPt);
517 MadeChange = true;
518 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000519
Dale Johannesence0b2372007-06-12 16:50:17 +0000520 // Replace a use of the cmp with a use of the new cmp.
521 TheUse = InsertedCmp;
Cameron Zwarich31ff1332011-01-05 17:27:27 +0000522 ++NumCmpUses;
Dale Johannesence0b2372007-06-12 16:50:17 +0000523 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000524
Dale Johannesence0b2372007-06-12 16:50:17 +0000525 // If we removed all uses, nuke the cmp.
526 if (CI->use_empty())
527 CI->eraseFromParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000528
Dale Johannesence0b2372007-06-12 16:50:17 +0000529 return MadeChange;
530}
531
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000532namespace {
533class CodeGenPrepareFortifiedLibCalls : public SimplifyFortifiedLibCalls {
534protected:
535 void replaceCall(Value *With) {
536 CI->replaceAllUsesWith(With);
537 CI->eraseFromParent();
538 }
539 bool isFoldable(unsigned SizeCIOp, unsigned, bool) const {
Gabor Greifa6aac4c2010-07-16 09:38:02 +0000540 if (ConstantInt *SizeCI =
541 dyn_cast<ConstantInt>(CI->getArgOperand(SizeCIOp)))
542 return SizeCI->isAllOnesValue();
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000543 return false;
544 }
545};
546} // end anonymous namespace
547
Eric Christopher040056f2010-03-11 02:41:03 +0000548bool CodeGenPrepare::OptimizeCallInst(CallInst *CI) {
Chris Lattner75796092011-01-15 07:14:54 +0000549 BasicBlock *BB = CI->getParent();
Nadav Rotema94d6e82012-07-24 10:51:42 +0000550
Chris Lattner75796092011-01-15 07:14:54 +0000551 // Lower inline assembly if we can.
552 // If we found an inline asm expession, and if the target knows how to
553 // lower it to normal LLVM code, do so now.
554 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
555 if (TLI->ExpandInlineAsm(CI)) {
556 // Avoid invalidating the iterator.
557 CurInstIterator = BB->begin();
558 // Avoid processing instructions out of order, which could cause
559 // reuse before a value is defined.
560 SunkAddrs.clear();
561 return true;
562 }
563 // Sink address computing for memory operands into the block.
564 if (OptimizeInlineAsmInst(CI))
565 return true;
566 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000567
Eric Christopher040056f2010-03-11 02:41:03 +0000568 // Lower all uses of llvm.objectsize.*
569 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
570 if (II && II->getIntrinsicID() == Intrinsic::objectsize) {
Gabor Greifde9f5452010-06-24 00:44:01 +0000571 bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000572 Type *ReturnTy = CI->getType();
Nadav Rotema94d6e82012-07-24 10:51:42 +0000573 Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
574
Chris Lattner94e8e0c2011-01-15 07:25:29 +0000575 // Substituting this can cause recursive simplifications, which can
576 // invalidate our iterator. Use a WeakVH to hold onto it in case this
577 // happens.
578 WeakVH IterHandle(CurInstIterator);
Nadav Rotema94d6e82012-07-24 10:51:42 +0000579
Chandler Carruth6b980542012-03-24 21:11:24 +0000580 replaceAndRecursivelySimplify(CI, RetVal, TLI ? TLI->getTargetData() : 0,
581 TLInfo, ModifiedDT ? 0 : DT);
Chris Lattner94e8e0c2011-01-15 07:25:29 +0000582
583 // If the iterator instruction was recursively deleted, start over at the
584 // start of the block.
Chris Lattner435b4d22011-01-18 20:53:04 +0000585 if (IterHandle != CurInstIterator) {
Chris Lattner94e8e0c2011-01-15 07:25:29 +0000586 CurInstIterator = BB->begin();
Chris Lattner435b4d22011-01-18 20:53:04 +0000587 SunkAddrs.clear();
588 }
Eric Christopher040056f2010-03-11 02:41:03 +0000589 return true;
590 }
591
Pete Cooperf210b682012-03-13 20:59:56 +0000592 if (II && TLI) {
593 SmallVector<Value*, 2> PtrOps;
594 Type *AccessTy;
595 if (TLI->GetAddrModeArguments(II, PtrOps, AccessTy))
596 while (!PtrOps.empty())
597 if (OptimizeMemoryInst(II, PtrOps.pop_back_val(), AccessTy))
598 return true;
599 }
600
Eric Christopher040056f2010-03-11 02:41:03 +0000601 // From here on out we're working with named functions.
602 if (CI->getCalledFunction() == 0) return false;
Devang Patel97de92c2011-05-26 21:51:06 +0000603
Eric Christopher040056f2010-03-11 02:41:03 +0000604 // We'll need TargetData from here on out.
605 const TargetData *TD = TLI ? TLI->getTargetData() : 0;
606 if (!TD) return false;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000607
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000608 // Lower all default uses of _chk calls. This is very similar
609 // to what InstCombineCalls does, but here we are only lowering calls
Eric Christopher040056f2010-03-11 02:41:03 +0000610 // that have the default "don't know" as the objectsize. Anything else
611 // should be left alone.
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000612 CodeGenPrepareFortifiedLibCalls Simplifier;
Nuno Lopes51004df2012-07-25 16:46:31 +0000613 return Simplifier.fold(CI, TD, TLInfo);
Eric Christopher040056f2010-03-11 02:41:03 +0000614}
Chris Lattner94e8e0c2011-01-15 07:25:29 +0000615
Evan Cheng485fafc2011-03-21 01:19:09 +0000616/// DupRetToEnableTailCallOpts - Look for opportunities to duplicate return
617/// instructions to the predecessor to enable tail call optimizations. The
618/// case it is currently looking for is:
619/// bb0:
620/// %tmp0 = tail call i32 @f0()
621/// br label %return
622/// bb1:
623/// %tmp1 = tail call i32 @f1()
624/// br label %return
625/// bb2:
626/// %tmp2 = tail call i32 @f2()
627/// br label %return
628/// return:
629/// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
630/// ret i32 %retval
631///
632/// =>
633///
634/// bb0:
635/// %tmp0 = tail call i32 @f0()
636/// ret i32 %tmp0
637/// bb1:
638/// %tmp1 = tail call i32 @f1()
639/// ret i32 %tmp1
640/// bb2:
641/// %tmp2 = tail call i32 @f2()
642/// ret i32 %tmp2
643///
644bool CodeGenPrepare::DupRetToEnableTailCallOpts(ReturnInst *RI) {
Cameron Zwarich661a3902011-03-24 04:51:51 +0000645 if (!TLI)
646 return false;
647
Evan Cheng9c777a42012-07-27 21:21:26 +0000648 PHINode *PN = 0;
649 BitCastInst *BCI = 0;
Evan Cheng485fafc2011-03-21 01:19:09 +0000650 Value *V = RI->getReturnValue();
Evan Cheng9c777a42012-07-27 21:21:26 +0000651 if (V) {
652 BCI = dyn_cast<BitCastInst>(V);
653 if (BCI)
654 V = BCI->getOperand(0);
655
656 PN = dyn_cast<PHINode>(V);
657 if (!PN)
658 return false;
659 }
Evan Cheng485fafc2011-03-21 01:19:09 +0000660
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000661 BasicBlock *BB = RI->getParent();
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000662 if (PN && PN->getParent() != BB)
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000663 return false;
Evan Cheng485fafc2011-03-21 01:19:09 +0000664
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000665 // It's not safe to eliminate the sign / zero extension of the return value.
666 // See llvm::isInTailCallPosition().
667 const Function *F = BB->getParent();
Kostya Serebryany164b86b2012-01-20 17:56:17 +0000668 Attributes CallerRetAttr = F->getAttributes().getRetAttributes();
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000669 if ((CallerRetAttr & Attribute::ZExt) || (CallerRetAttr & Attribute::SExt))
670 return false;
Evan Cheng485fafc2011-03-21 01:19:09 +0000671
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000672 // Make sure there are no instructions between the PHI and return, or that the
673 // return is the first instruction in the block.
674 if (PN) {
675 BasicBlock::iterator BI = BB->begin();
676 do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
Evan Cheng9c777a42012-07-27 21:21:26 +0000677 if (&*BI == BCI)
678 // Also skip over the bitcast.
679 ++BI;
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000680 if (&*BI != RI)
681 return false;
682 } else {
Cameron Zwarich90354842011-03-24 16:34:59 +0000683 BasicBlock::iterator BI = BB->begin();
684 while (isa<DbgInfoIntrinsic>(BI)) ++BI;
685 if (&*BI != RI)
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000686 return false;
687 }
Evan Cheng485fafc2011-03-21 01:19:09 +0000688
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000689 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
690 /// call.
691 SmallVector<CallInst*, 4> TailCalls;
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000692 if (PN) {
693 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
694 CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
695 // Make sure the phi value is indeed produced by the tail call.
696 if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
697 TLI->mayBeEmittedAsTailCall(CI))
698 TailCalls.push_back(CI);
699 }
700 } else {
701 SmallPtrSet<BasicBlock*, 4> VisitedBBs;
702 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
703 if (!VisitedBBs.insert(*PI))
704 continue;
705
706 BasicBlock::InstListType &InstList = (*PI)->getInstList();
707 BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
708 BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
Cameron Zwarich90354842011-03-24 16:34:59 +0000709 do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
710 if (RI == RE)
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000711 continue;
Cameron Zwarich90354842011-03-24 16:34:59 +0000712
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000713 CallInst *CI = dyn_cast<CallInst>(&*RI);
Cameron Zwarichdc31cfe2011-03-24 15:54:11 +0000714 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI))
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000715 TailCalls.push_back(CI);
716 }
Evan Cheng485fafc2011-03-21 01:19:09 +0000717 }
718
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000719 bool Changed = false;
720 for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
721 CallInst *CI = TailCalls[i];
722 CallSite CS(CI);
723
724 // Conservatively require the attributes of the call to match those of the
725 // return. Ignore noalias because it doesn't affect the call sequence.
Kostya Serebryany164b86b2012-01-20 17:56:17 +0000726 Attributes CalleeRetAttr = CS.getAttributes().getRetAttributes();
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000727 if ((CalleeRetAttr ^ CallerRetAttr) & ~Attribute::NoAlias)
728 continue;
729
730 // Make sure the call instruction is followed by an unconditional branch to
731 // the return block.
732 BasicBlock *CallBB = CI->getParent();
733 BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
734 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
735 continue;
736
737 // Duplicate the return into CallBB.
738 (void)FoldReturnIntoUncondBranch(RI, BB, CallBB);
Devang Patel52e37df2011-03-24 15:35:25 +0000739 ModifiedDT = Changed = true;
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000740 ++NumRetsDup;
741 }
742
743 // If we eliminated all predecessors of the block, delete the block now.
744 if (Changed && pred_begin(BB) == pred_end(BB))
745 BB->eraseFromParent();
746
747 return Changed;
Evan Cheng485fafc2011-03-21 01:19:09 +0000748}
749
Chris Lattner88a5c832008-11-25 07:09:13 +0000750//===----------------------------------------------------------------------===//
Chris Lattner88a5c832008-11-25 07:09:13 +0000751// Memory Optimization
752//===----------------------------------------------------------------------===//
753
Chris Lattnerdd77df32007-04-13 20:30:56 +0000754/// IsNonLocalValue - Return true if the specified values are defined in a
755/// different basic block than BB.
756static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
757 if (Instruction *I = dyn_cast<Instruction>(V))
758 return I->getParent() != BB;
759 return false;
760}
761
Bob Wilson4a8ee232009-12-03 21:47:07 +0000762/// OptimizeMemoryInst - Load and Store Instructions often have
Chris Lattnerdd77df32007-04-13 20:30:56 +0000763/// addressing modes that can do significant amounts of computation. As such,
764/// instruction selection will try to get the load or store to do as much
765/// computation as possible for the program. The problem is that isel can only
766/// see within a single block. As such, we sink as much legal addressing mode
767/// stuff into the block as possible.
Chris Lattner88a5c832008-11-25 07:09:13 +0000768///
769/// This method is used to optimize both load/store and inline asms with memory
770/// operands.
Chris Lattner896617b2008-11-26 03:20:37 +0000771bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000772 Type *AccessTy) {
Owen Anderson35bf4d62010-11-27 08:15:55 +0000773 Value *Repl = Addr;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000774
775 // Try to collapse single-value PHI nodes. This is necessary to undo
Owen Andersond2f41742010-11-19 22:15:03 +0000776 // unprofitable PRE transformations.
Cameron Zwarich7cb4fa22011-01-03 06:33:01 +0000777 SmallVector<Value*, 8> worklist;
778 SmallPtrSet<Value*, 16> Visited;
Owen Anderson35bf4d62010-11-27 08:15:55 +0000779 worklist.push_back(Addr);
Nadav Rotema94d6e82012-07-24 10:51:42 +0000780
Owen Anderson35bf4d62010-11-27 08:15:55 +0000781 // Use a worklist to iteratively look through PHI nodes, and ensure that
782 // the addressing mode obtained from the non-PHI roots of the graph
783 // are equivalent.
784 Value *Consensus = 0;
Cameron Zwarich4c078f02011-03-01 21:13:53 +0000785 unsigned NumUsesConsensus = 0;
Cameron Zwarich7c8d3512011-03-05 08:12:26 +0000786 bool IsNumUsesConsensusValid = false;
Owen Anderson35bf4d62010-11-27 08:15:55 +0000787 SmallVector<Instruction*, 16> AddrModeInsts;
788 ExtAddrMode AddrMode;
789 while (!worklist.empty()) {
790 Value *V = worklist.back();
791 worklist.pop_back();
Nadav Rotema94d6e82012-07-24 10:51:42 +0000792
Owen Anderson35bf4d62010-11-27 08:15:55 +0000793 // Break use-def graph loops.
Nick Lewycky48105282011-09-29 23:40:12 +0000794 if (!Visited.insert(V)) {
Owen Anderson35bf4d62010-11-27 08:15:55 +0000795 Consensus = 0;
796 break;
Owen Andersond2f41742010-11-19 22:15:03 +0000797 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000798
Owen Anderson35bf4d62010-11-27 08:15:55 +0000799 // For a PHI node, push all of its incoming values.
800 if (PHINode *P = dyn_cast<PHINode>(V)) {
801 for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i)
802 worklist.push_back(P->getIncomingValue(i));
803 continue;
804 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000805
Owen Anderson35bf4d62010-11-27 08:15:55 +0000806 // For non-PHIs, determine the addressing mode being computed.
807 SmallVector<Instruction*, 16> NewAddrModeInsts;
808 ExtAddrMode NewAddrMode =
Nick Lewycky48105282011-09-29 23:40:12 +0000809 AddressingModeMatcher::Match(V, AccessTy, MemoryInst,
Owen Anderson35bf4d62010-11-27 08:15:55 +0000810 NewAddrModeInsts, *TLI);
Cameron Zwarich7c8d3512011-03-05 08:12:26 +0000811
812 // This check is broken into two cases with very similar code to avoid using
813 // getNumUses() as much as possible. Some values have a lot of uses, so
814 // calling getNumUses() unconditionally caused a significant compile-time
815 // regression.
816 if (!Consensus) {
817 Consensus = V;
818 AddrMode = NewAddrMode;
819 AddrModeInsts = NewAddrModeInsts;
820 continue;
821 } else if (NewAddrMode == AddrMode) {
822 if (!IsNumUsesConsensusValid) {
823 NumUsesConsensus = Consensus->getNumUses();
824 IsNumUsesConsensusValid = true;
825 }
826
827 // Ensure that the obtained addressing mode is equivalent to that obtained
828 // for all other roots of the PHI traversal. Also, when choosing one
829 // such root as representative, select the one with the most uses in order
830 // to keep the cost modeling heuristics in AddressingModeMatcher
831 // applicable.
Cameron Zwarich4c078f02011-03-01 21:13:53 +0000832 unsigned NumUses = V->getNumUses();
833 if (NumUses > NumUsesConsensus) {
Owen Anderson35bf4d62010-11-27 08:15:55 +0000834 Consensus = V;
Cameron Zwarich4c078f02011-03-01 21:13:53 +0000835 NumUsesConsensus = NumUses;
Owen Anderson35bf4d62010-11-27 08:15:55 +0000836 AddrModeInsts = NewAddrModeInsts;
837 }
838 continue;
839 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000840
Owen Anderson35bf4d62010-11-27 08:15:55 +0000841 Consensus = 0;
842 break;
Owen Andersond2f41742010-11-19 22:15:03 +0000843 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000844
Owen Anderson35bf4d62010-11-27 08:15:55 +0000845 // If the addressing mode couldn't be determined, or if multiple different
846 // ones were determined, bail out now.
847 if (!Consensus) return false;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000848
Chris Lattnerdd77df32007-04-13 20:30:56 +0000849 // Check to see if any of the instructions supersumed by this addr mode are
850 // non-local to I's BB.
851 bool AnyNonLocal = false;
852 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
Chris Lattner896617b2008-11-26 03:20:37 +0000853 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
Chris Lattnerdd77df32007-04-13 20:30:56 +0000854 AnyNonLocal = true;
855 break;
856 }
857 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000858
Chris Lattnerdd77df32007-04-13 20:30:56 +0000859 // If all the instructions matched are already in this BB, don't do anything.
860 if (!AnyNonLocal) {
David Greene68d67fd2010-01-05 01:27:11 +0000861 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000862 return false;
863 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000864
Chris Lattnerdd77df32007-04-13 20:30:56 +0000865 // Insert this computation right after this user. Since our caller is
866 // scanning from the top of the BB to the bottom, reuse of the expr are
867 // guaranteed to happen later.
Devang Patel2048c372011-09-06 18:49:53 +0000868 IRBuilder<> Builder(MemoryInst);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000869
Chris Lattnerdd77df32007-04-13 20:30:56 +0000870 // Now that we determined the addressing expression we want to use and know
871 // that we have to sink it into this block. Check to see if we have already
872 // done this for some other load/store instr in this block. If so, reuse the
873 // computation.
874 Value *&SunkAddr = SunkAddrs[Addr];
875 if (SunkAddr) {
David Greene68d67fd2010-01-05 01:27:11 +0000876 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
Dan Gohman6c1980b2009-07-25 01:13:51 +0000877 << *MemoryInst);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000878 if (SunkAddr->getType() != Addr->getType())
Benjamin Kramera9390a42011-09-27 20:39:19 +0000879 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
Chris Lattnerdd77df32007-04-13 20:30:56 +0000880 } else {
David Greene68d67fd2010-01-05 01:27:11 +0000881 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Dan Gohman6c1980b2009-07-25 01:13:51 +0000882 << *MemoryInst);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000883 Type *IntPtrTy =
Owen Anderson1d0be152009-08-13 21:58:54 +0000884 TLI->getTargetData()->getIntPtrType(AccessTy->getContext());
Eric Christopher692bf6b2008-09-24 05:32:41 +0000885
Chris Lattnerdd77df32007-04-13 20:30:56 +0000886 Value *Result = 0;
Dan Gohmand8d0b6a2010-01-19 22:45:06 +0000887
888 // Start with the base register. Do this first so that subsequent address
889 // matching finds it last, which will prevent it from trying to match it
890 // as the scaled value in case it happens to be a mul. That would be
891 // problematic if we've sunk a different mul for the scale, because then
892 // we'd end up sinking both muls.
893 if (AddrMode.BaseReg) {
894 Value *V = AddrMode.BaseReg;
Duncan Sands1df98592010-02-16 11:11:14 +0000895 if (V->getType()->isPointerTy())
Devang Patel2048c372011-09-06 18:49:53 +0000896 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Dan Gohmand8d0b6a2010-01-19 22:45:06 +0000897 if (V->getType() != IntPtrTy)
Devang Patel2048c372011-09-06 18:49:53 +0000898 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
Dan Gohmand8d0b6a2010-01-19 22:45:06 +0000899 Result = V;
900 }
901
902 // Add the scale value.
Chris Lattnerdd77df32007-04-13 20:30:56 +0000903 if (AddrMode.Scale) {
904 Value *V = AddrMode.ScaledReg;
905 if (V->getType() == IntPtrTy) {
906 // done.
Duncan Sands1df98592010-02-16 11:11:14 +0000907 } else if (V->getType()->isPointerTy()) {
Devang Patel2048c372011-09-06 18:49:53 +0000908 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000909 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
910 cast<IntegerType>(V->getType())->getBitWidth()) {
Devang Patel2048c372011-09-06 18:49:53 +0000911 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000912 } else {
Devang Patel2048c372011-09-06 18:49:53 +0000913 V = Builder.CreateSExt(V, IntPtrTy, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000914 }
915 if (AddrMode.Scale != 1)
Devang Patel2048c372011-09-06 18:49:53 +0000916 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
917 "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000918 if (Result)
Devang Patel2048c372011-09-06 18:49:53 +0000919 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000920 else
921 Result = V;
922 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000923
Chris Lattnerdd77df32007-04-13 20:30:56 +0000924 // Add in the BaseGV if present.
925 if (AddrMode.BaseGV) {
Devang Patel2048c372011-09-06 18:49:53 +0000926 Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000927 if (Result)
Devang Patel2048c372011-09-06 18:49:53 +0000928 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000929 else
930 Result = V;
931 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000932
Chris Lattnerdd77df32007-04-13 20:30:56 +0000933 // Add in the Base Offset if present.
934 if (AddrMode.BaseOffs) {
Owen Andersoneed707b2009-07-24 23:12:02 +0000935 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000936 if (Result)
Devang Patel2048c372011-09-06 18:49:53 +0000937 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000938 else
939 Result = V;
940 }
941
942 if (Result == 0)
Owen Andersona7235ea2009-07-31 20:28:14 +0000943 SunkAddr = Constant::getNullValue(Addr->getType());
Chris Lattnerdd77df32007-04-13 20:30:56 +0000944 else
Devang Patel2048c372011-09-06 18:49:53 +0000945 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000946 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000947
Owen Andersond2f41742010-11-19 22:15:03 +0000948 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000949
Chris Lattner0403b472011-04-09 07:05:44 +0000950 // If we have no uses, recursively delete the value and all dead instructions
951 // using it.
Owen Andersond2f41742010-11-19 22:15:03 +0000952 if (Repl->use_empty()) {
Chris Lattner0403b472011-04-09 07:05:44 +0000953 // This can cause recursive deletion, which can invalidate our iterator.
954 // Use a WeakVH to hold onto it in case this happens.
955 WeakVH IterHandle(CurInstIterator);
956 BasicBlock *BB = CurInstIterator->getParent();
Nadav Rotema94d6e82012-07-24 10:51:42 +0000957
Owen Andersond2f41742010-11-19 22:15:03 +0000958 RecursivelyDeleteTriviallyDeadInstructions(Repl);
Chris Lattner0403b472011-04-09 07:05:44 +0000959
960 if (IterHandle != CurInstIterator) {
961 // If the iterator instruction was recursively deleted, start over at the
962 // start of the block.
963 CurInstIterator = BB->begin();
964 SunkAddrs.clear();
965 } else {
966 // This address is now available for reassignment, so erase the table
967 // entry; we don't want to match some completely different instruction.
968 SunkAddrs[Addr] = 0;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000969 }
Dale Johannesen536d31b2010-03-31 20:37:15 +0000970 }
Cameron Zwarich31ff1332011-01-05 17:27:27 +0000971 ++NumMemoryInsts;
Chris Lattnerdd77df32007-04-13 20:30:56 +0000972 return true;
973}
974
Evan Cheng9bf12b52008-02-26 02:42:37 +0000975/// OptimizeInlineAsmInst - If there are any memory operands, use
Chris Lattner88a5c832008-11-25 07:09:13 +0000976/// OptimizeMemoryInst to sink their address computing into the block when
Evan Cheng9bf12b52008-02-26 02:42:37 +0000977/// possible / profitable.
Chris Lattner75796092011-01-15 07:14:54 +0000978bool CodeGenPrepare::OptimizeInlineAsmInst(CallInst *CS) {
Evan Cheng9bf12b52008-02-26 02:42:37 +0000979 bool MadeChange = false;
Evan Cheng9bf12b52008-02-26 02:42:37 +0000980
Nadav Rotema94d6e82012-07-24 10:51:42 +0000981 TargetLowering::AsmOperandInfoVector
Chris Lattner75796092011-01-15 07:14:54 +0000982 TargetConstraints = TLI->ParseConstraints(CS);
Dale Johannesen677c6ec2010-09-16 18:30:55 +0000983 unsigned ArgNo = 0;
John Thompsoneac6e1d2010-09-13 18:15:37 +0000984 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
985 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Nadav Rotema94d6e82012-07-24 10:51:42 +0000986
Evan Cheng9bf12b52008-02-26 02:42:37 +0000987 // Compute the constraint code and ConstraintType to use.
Dale Johannesen1784d162010-06-25 21:55:36 +0000988 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Evan Cheng9bf12b52008-02-26 02:42:37 +0000989
Eli Friedman9ec80952008-02-26 18:37:49 +0000990 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
991 OpInfo.isIndirect) {
Chris Lattner75796092011-01-15 07:14:54 +0000992 Value *OpVal = CS->getArgOperand(ArgNo++);
Chris Lattner1a8943a2011-01-15 07:29:01 +0000993 MadeChange |= OptimizeMemoryInst(CS, OpVal, OpVal->getType());
Dale Johannesen677c6ec2010-09-16 18:30:55 +0000994 } else if (OpInfo.Type == InlineAsm::isInput)
995 ArgNo++;
Evan Cheng9bf12b52008-02-26 02:42:37 +0000996 }
997
998 return MadeChange;
999}
1000
Dan Gohmanb00f2362009-10-16 20:59:35 +00001001/// MoveExtToFormExtLoad - Move a zext or sext fed by a load into the same
1002/// basic block as the load, unless conditions are unfavorable. This allows
1003/// SelectionDAG to fold the extend into the load.
1004///
1005bool CodeGenPrepare::MoveExtToFormExtLoad(Instruction *I) {
1006 // Look for a load being extended.
1007 LoadInst *LI = dyn_cast<LoadInst>(I->getOperand(0));
1008 if (!LI) return false;
1009
1010 // If they're already in the same block, there's nothing to do.
1011 if (LI->getParent() == I->getParent())
1012 return false;
1013
1014 // If the load has other users and the truncate is not free, this probably
1015 // isn't worthwhile.
1016 if (!LI->hasOneUse() &&
Bob Wilsonec57a1a2010-09-22 18:44:56 +00001017 TLI && (TLI->isTypeLegal(TLI->getValueType(LI->getType())) ||
1018 !TLI->isTypeLegal(TLI->getValueType(I->getType()))) &&
Bob Wilson71dc4d92010-09-21 21:54:27 +00001019 !TLI->isTruncateFree(I->getType(), LI->getType()))
Dan Gohmanb00f2362009-10-16 20:59:35 +00001020 return false;
1021
1022 // Check whether the target supports casts folded into loads.
1023 unsigned LType;
1024 if (isa<ZExtInst>(I))
1025 LType = ISD::ZEXTLOAD;
1026 else {
1027 assert(isa<SExtInst>(I) && "Unexpected ext type!");
1028 LType = ISD::SEXTLOAD;
1029 }
1030 if (TLI && !TLI->isLoadExtLegal(LType, TLI->getValueType(LI->getType())))
1031 return false;
1032
1033 // Move the extend into the same block as the load, so that SelectionDAG
1034 // can fold it.
1035 I->removeFromParent();
1036 I->insertAfter(LI);
Cameron Zwarich31ff1332011-01-05 17:27:27 +00001037 ++NumExtsMoved;
Dan Gohmanb00f2362009-10-16 20:59:35 +00001038 return true;
1039}
1040
Evan Chengbdcb7262007-12-05 23:58:20 +00001041bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
1042 BasicBlock *DefBB = I->getParent();
1043
Bob Wilson9120f5c2010-09-21 21:44:14 +00001044 // If the result of a {s|z}ext and its source are both live out, rewrite all
Evan Chengbdcb7262007-12-05 23:58:20 +00001045 // other uses of the source with result of extension.
1046 Value *Src = I->getOperand(0);
1047 if (Src->hasOneUse())
1048 return false;
1049
Evan Cheng696e5c02007-12-13 07:50:36 +00001050 // Only do this xform if truncating is free.
Gabor Greif53bdbd72008-02-26 19:13:21 +00001051 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
Evan Chengf9785f92007-12-13 03:32:53 +00001052 return false;
1053
Evan Cheng772de512007-12-12 00:51:06 +00001054 // Only safe to perform the optimization if the source is also defined in
Evan Cheng765dff22007-12-12 02:53:41 +00001055 // this block.
1056 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
Evan Cheng772de512007-12-12 00:51:06 +00001057 return false;
1058
Evan Chengbdcb7262007-12-05 23:58:20 +00001059 bool DefIsLiveOut = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001060 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
Evan Chengbdcb7262007-12-05 23:58:20 +00001061 UI != E; ++UI) {
1062 Instruction *User = cast<Instruction>(*UI);
1063
1064 // Figure out which BB this ext is used in.
1065 BasicBlock *UserBB = User->getParent();
1066 if (UserBB == DefBB) continue;
1067 DefIsLiveOut = true;
1068 break;
1069 }
1070 if (!DefIsLiveOut)
1071 return false;
1072
Evan Cheng765dff22007-12-12 02:53:41 +00001073 // Make sure non of the uses are PHI nodes.
Eric Christopher692bf6b2008-09-24 05:32:41 +00001074 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
Evan Cheng765dff22007-12-12 02:53:41 +00001075 UI != E; ++UI) {
1076 Instruction *User = cast<Instruction>(*UI);
Evan Chengf9785f92007-12-13 03:32:53 +00001077 BasicBlock *UserBB = User->getParent();
1078 if (UserBB == DefBB) continue;
1079 // Be conservative. We don't want this xform to end up introducing
1080 // reloads just before load / store instructions.
1081 if (isa<PHINode>(User) || isa<LoadInst>(User) || isa<StoreInst>(User))
Evan Cheng765dff22007-12-12 02:53:41 +00001082 return false;
1083 }
1084
Evan Chengbdcb7262007-12-05 23:58:20 +00001085 // InsertedTruncs - Only insert one trunc in each block once.
1086 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
1087
1088 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001089 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
Evan Chengbdcb7262007-12-05 23:58:20 +00001090 UI != E; ++UI) {
1091 Use &TheUse = UI.getUse();
1092 Instruction *User = cast<Instruction>(*UI);
1093
1094 // Figure out which BB this ext is used in.
1095 BasicBlock *UserBB = User->getParent();
1096 if (UserBB == DefBB) continue;
1097
1098 // Both src and def are live in this block. Rewrite the use.
1099 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
1100
1101 if (!InsertedTrunc) {
Bill Wendling5b6f42f2011-08-16 20:45:24 +00001102 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Evan Chengbdcb7262007-12-05 23:58:20 +00001103 InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
1104 }
1105
1106 // Replace a use of the {s|z}ext source with a use of the result.
1107 TheUse = InsertedTrunc;
Cameron Zwarich31ff1332011-01-05 17:27:27 +00001108 ++NumExtUses;
Evan Chengbdcb7262007-12-05 23:58:20 +00001109 MadeChange = true;
1110 }
1111
1112 return MadeChange;
1113}
1114
Benjamin Kramer59957502012-05-05 12:49:22 +00001115/// isFormingBranchFromSelectProfitable - Returns true if a SelectInst should be
1116/// turned into an explicit branch.
1117static bool isFormingBranchFromSelectProfitable(SelectInst *SI) {
1118 // FIXME: This should use the same heuristics as IfConversion to determine
1119 // whether a select is better represented as a branch. This requires that
1120 // branch probability metadata is preserved for the select, which is not the
1121 // case currently.
1122
1123 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
1124
1125 // If the branch is predicted right, an out of order CPU can avoid blocking on
1126 // the compare. Emit cmovs on compares with a memory operand as branches to
1127 // avoid stalls on the load from memory. If the compare has more than one use
1128 // there's probably another cmov or setcc around so it's not worth emitting a
1129 // branch.
1130 if (!Cmp)
1131 return false;
1132
1133 Value *CmpOp0 = Cmp->getOperand(0);
1134 Value *CmpOp1 = Cmp->getOperand(1);
1135
1136 // We check that the memory operand has one use to avoid uses of the loaded
1137 // value directly after the compare, making branches unprofitable.
1138 return Cmp->hasOneUse() &&
1139 ((isa<LoadInst>(CmpOp0) && CmpOp0->hasOneUse()) ||
1140 (isa<LoadInst>(CmpOp1) && CmpOp1->hasOneUse()));
1141}
1142
1143
1144bool CodeGenPrepare::OptimizeSelectInst(SelectInst *SI) {
1145 // If we have a SelectInst that will likely profit from branch prediction,
1146 // turn it into a branch.
Benjamin Kramer6c505512012-06-29 19:58:21 +00001147 if (DisableSelectToBranch || OptSize || !TLI ||
1148 !TLI->isPredictableSelectExpensive())
Benjamin Kramer59957502012-05-05 12:49:22 +00001149 return false;
1150
1151 if (!SI->getCondition()->getType()->isIntegerTy(1) ||
1152 !isFormingBranchFromSelectProfitable(SI))
1153 return false;
1154
1155 ModifiedDT = true;
1156
1157 // First, we split the block containing the select into 2 blocks.
1158 BasicBlock *StartBlock = SI->getParent();
1159 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(SI));
1160 BasicBlock *NextBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
1161
1162 // Create a new block serving as the landing pad for the branch.
1163 BasicBlock *SmallBlock = BasicBlock::Create(SI->getContext(), "select.mid",
1164 NextBlock->getParent(), NextBlock);
1165
1166 // Move the unconditional branch from the block with the select in it into our
1167 // landing pad block.
1168 StartBlock->getTerminator()->eraseFromParent();
1169 BranchInst::Create(NextBlock, SmallBlock);
1170
1171 // Insert the real conditional branch based on the original condition.
1172 BranchInst::Create(NextBlock, SmallBlock, SI->getCondition(), SI);
1173
1174 // The select itself is replaced with a PHI Node.
1175 PHINode *PN = PHINode::Create(SI->getType(), 2, "", NextBlock->begin());
1176 PN->takeName(SI);
1177 PN->addIncoming(SI->getTrueValue(), StartBlock);
1178 PN->addIncoming(SI->getFalseValue(), SmallBlock);
1179 SI->replaceAllUsesWith(PN);
1180 SI->eraseFromParent();
1181
1182 // Instruct OptimizeBlock to skip to the next block.
1183 CurInstIterator = StartBlock->end();
1184 ++NumSelectsExpanded;
1185 return true;
1186}
1187
Cameron Zwarichc0611012011-01-06 02:37:26 +00001188bool CodeGenPrepare::OptimizeInst(Instruction *I) {
Cameron Zwarichc0611012011-01-06 02:37:26 +00001189 if (PHINode *P = dyn_cast<PHINode>(I)) {
1190 // It is possible for very late stage optimizations (such as SimplifyCFG)
1191 // to introduce PHI nodes too late to be cleaned up. If we detect such a
1192 // trivial PHI, go ahead and zap it here.
1193 if (Value *V = SimplifyInstruction(P)) {
1194 P->replaceAllUsesWith(V);
1195 P->eraseFromParent();
1196 ++NumPHIsElim;
Chris Lattner1a8943a2011-01-15 07:29:01 +00001197 return true;
Cameron Zwarichc0611012011-01-06 02:37:26 +00001198 }
Chris Lattner1a8943a2011-01-15 07:29:01 +00001199 return false;
1200 }
Nadav Rotema94d6e82012-07-24 10:51:42 +00001201
Chris Lattner1a8943a2011-01-15 07:29:01 +00001202 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Cameron Zwarichc0611012011-01-06 02:37:26 +00001203 // If the source of the cast is a constant, then this should have
1204 // already been constant folded. The only reason NOT to constant fold
1205 // it is if something (e.g. LSR) was careful to place the constant
1206 // evaluation in a block other than then one that uses it (e.g. to hoist
1207 // the address of globals out of a loop). If this is the case, we don't
1208 // want to forward-subst the cast.
1209 if (isa<Constant>(CI->getOperand(0)))
1210 return false;
1211
Chris Lattner1a8943a2011-01-15 07:29:01 +00001212 if (TLI && OptimizeNoopCopyExpression(CI, *TLI))
1213 return true;
Cameron Zwarichc0611012011-01-06 02:37:26 +00001214
Chris Lattner1a8943a2011-01-15 07:29:01 +00001215 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
1216 bool MadeChange = MoveExtToFormExtLoad(I);
1217 return MadeChange | OptimizeExtUses(I);
Cameron Zwarichc0611012011-01-06 02:37:26 +00001218 }
Chris Lattner1a8943a2011-01-15 07:29:01 +00001219 return false;
1220 }
Nadav Rotema94d6e82012-07-24 10:51:42 +00001221
Chris Lattner1a8943a2011-01-15 07:29:01 +00001222 if (CmpInst *CI = dyn_cast<CmpInst>(I))
1223 return OptimizeCmpExpression(CI);
Nadav Rotema94d6e82012-07-24 10:51:42 +00001224
Chris Lattner1a8943a2011-01-15 07:29:01 +00001225 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Cameron Zwarichc0611012011-01-06 02:37:26 +00001226 if (TLI)
Chris Lattner1a8943a2011-01-15 07:29:01 +00001227 return OptimizeMemoryInst(I, I->getOperand(0), LI->getType());
1228 return false;
1229 }
Nadav Rotema94d6e82012-07-24 10:51:42 +00001230
Chris Lattner1a8943a2011-01-15 07:29:01 +00001231 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Cameron Zwarichc0611012011-01-06 02:37:26 +00001232 if (TLI)
Chris Lattner1a8943a2011-01-15 07:29:01 +00001233 return OptimizeMemoryInst(I, SI->getOperand(1),
1234 SI->getOperand(0)->getType());
1235 return false;
1236 }
Nadav Rotema94d6e82012-07-24 10:51:42 +00001237
Chris Lattner1a8943a2011-01-15 07:29:01 +00001238 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Cameron Zwarich865ae1a2011-01-06 02:44:52 +00001239 if (GEPI->hasAllZeroIndices()) {
1240 /// The GEP operand must be a pointer, so must its result -> BitCast
1241 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
1242 GEPI->getName(), GEPI);
1243 GEPI->replaceAllUsesWith(NC);
1244 GEPI->eraseFromParent();
1245 ++NumGEPsElim;
Cameron Zwarich865ae1a2011-01-06 02:44:52 +00001246 OptimizeInst(NC);
Chris Lattner1a8943a2011-01-15 07:29:01 +00001247 return true;
Cameron Zwarich865ae1a2011-01-06 02:44:52 +00001248 }
Chris Lattner1a8943a2011-01-15 07:29:01 +00001249 return false;
Cameron Zwarichc0611012011-01-06 02:37:26 +00001250 }
Nadav Rotema94d6e82012-07-24 10:51:42 +00001251
Chris Lattner1a8943a2011-01-15 07:29:01 +00001252 if (CallInst *CI = dyn_cast<CallInst>(I))
1253 return OptimizeCallInst(CI);
Cameron Zwarichc0611012011-01-06 02:37:26 +00001254
Evan Cheng485fafc2011-03-21 01:19:09 +00001255 if (ReturnInst *RI = dyn_cast<ReturnInst>(I))
1256 return DupRetToEnableTailCallOpts(RI);
1257
Benjamin Kramer59957502012-05-05 12:49:22 +00001258 if (SelectInst *SI = dyn_cast<SelectInst>(I))
1259 return OptimizeSelectInst(SI);
1260
Chris Lattner1a8943a2011-01-15 07:29:01 +00001261 return false;
Cameron Zwarichc0611012011-01-06 02:37:26 +00001262}
1263
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001264// In this pass we look for GEP and cast instructions that are used
1265// across basic blocks and rewrite them to improve basic-block-at-a-time
1266// selection.
1267bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
Cameron Zwarich8c3527e2011-01-06 00:42:50 +00001268 SunkAddrs.clear();
Cameron Zwarich56e37932011-03-02 03:31:46 +00001269 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001270
Chris Lattner75796092011-01-15 07:14:54 +00001271 CurInstIterator = BB.begin();
Chris Lattner94e8e0c2011-01-15 07:25:29 +00001272 for (BasicBlock::iterator E = BB.end(); CurInstIterator != E; )
1273 MadeChange |= OptimizeInst(CurInstIterator++);
Eric Christopher692bf6b2008-09-24 05:32:41 +00001274
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001275 return MadeChange;
1276}
Devang Patelf56ea612011-08-18 00:50:51 +00001277
1278// llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotema94d6e82012-07-24 10:51:42 +00001279// handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patelf56ea612011-08-18 00:50:51 +00001280// find a node corresponding to the value.
1281bool CodeGenPrepare::PlaceDbgValues(Function &F) {
1282 bool MadeChange = false;
1283 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
1284 Instruction *PrevNonDbgInst = NULL;
1285 for (BasicBlock::iterator BI = I->begin(), BE = I->end(); BI != BE;) {
1286 Instruction *Insn = BI; ++BI;
1287 DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
1288 if (!DVI) {
1289 PrevNonDbgInst = Insn;
1290 continue;
1291 }
1292
1293 Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
1294 if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
1295 DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
1296 DVI->removeFromParent();
1297 if (isa<PHINode>(VI))
1298 DVI->insertBefore(VI->getParent()->getFirstInsertionPt());
1299 else
1300 DVI->insertAfter(VI);
1301 MadeChange = true;
1302 ++NumDbgValueMoved;
1303 }
1304 }
1305 }
1306 return MadeChange;
1307}