blob: 57a648f7b9714e2bc4b65c44339fbce4d9464bc1 [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
Benjamin Kramer77c4ef82012-05-06 14:25:16 +000069static cl::opt<bool> DisableSelectToBranch(
70 "disable-cgp-select2branch", cl::Hidden, cl::init(false),
71 cl::desc("Disable select to branch conversion."));
Benjamin Kramer59957502012-05-05 12:49:22 +000072
Eric Christopher692bf6b2008-09-24 05:32:41 +000073namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +000074 class CodeGenPrepare : public FunctionPass {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000075 /// TLI - Keep a pointer of a TargetLowering to consult for determining
76 /// transformation profitability.
77 const TargetLowering *TLI;
Chad Rosier618c1db2011-12-01 03:08:23 +000078 const TargetLibraryInfo *TLInfo;
Cameron Zwarich80f6a502011-01-08 17:01:52 +000079 DominatorTree *DT;
Evan Cheng04149f72009-12-17 09:39:49 +000080 ProfileInfo *PFI;
Nadav Rotema94d6e82012-07-24 10:51:42 +000081
Chris Lattner75796092011-01-15 07:14:54 +000082 /// CurInstIterator - As we scan instructions optimizing them, this is the
83 /// next instruction to optimize. Xforms that can invalidate this should
84 /// update it.
85 BasicBlock::iterator CurInstIterator;
Evan Chengab631522008-12-19 18:03:11 +000086
Evan Cheng485fafc2011-03-21 01:19:09 +000087 /// Keeps track of non-local addresses that have been sunk into a block.
88 /// This allows us to avoid inserting duplicate code for blocks with
89 /// multiple load/stores of the same address.
Cameron Zwarich8c3527e2011-01-06 00:42:50 +000090 DenseMap<Value*, Value*> SunkAddrs;
91
Devang Patel52e37df2011-03-24 15:35:25 +000092 /// ModifiedDT - If CFG is modified in anyway, dominator tree may need to
Evan Cheng485fafc2011-03-21 01:19:09 +000093 /// be updated.
Devang Patel52e37df2011-03-24 15:35:25 +000094 bool ModifiedDT;
Evan Cheng485fafc2011-03-21 01:19:09 +000095
Benjamin Kramer59957502012-05-05 12:49:22 +000096 /// OptSize - True if optimizing for size.
97 bool OptSize;
98
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000099 public:
Nick Lewyckyecd94c82007-05-06 13:37:16 +0000100 static char ID; // Pass identification, replacement for typeid
Dan Gohmanc2bbfc12007-08-01 15:32:29 +0000101 explicit CodeGenPrepare(const TargetLowering *tli = 0)
Owen Anderson081c34b2010-10-19 17:21:58 +0000102 : FunctionPass(ID), TLI(tli) {
103 initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
104 }
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000105 bool runOnFunction(Function &F);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000106
Andreas Neustifterad809812009-09-16 09:26:52 +0000107 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Cameron Zwarich80f6a502011-01-08 17:01:52 +0000108 AU.addPreserved<DominatorTree>();
Andreas Neustifterad809812009-09-16 09:26:52 +0000109 AU.addPreserved<ProfileInfo>();
Chad Rosier618c1db2011-12-01 03:08:23 +0000110 AU.addRequired<TargetLibraryInfo>();
Andreas Neustifterad809812009-09-16 09:26:52 +0000111 }
112
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000113 private:
Nadav Rotem3e883732012-08-14 05:19:07 +0000114 bool EliminateFallThrough(Function &F);
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000115 bool EliminateMostlyEmptyBlocks(Function &F);
116 bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
117 void EliminateMostlyEmptyBlock(BasicBlock *BB);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000118 bool OptimizeBlock(BasicBlock &BB);
Cameron Zwarichc0611012011-01-06 02:37:26 +0000119 bool OptimizeInst(Instruction *I);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000120 bool OptimizeMemoryInst(Instruction *I, Value *Addr, Type *AccessTy);
Chris Lattner75796092011-01-15 07:14:54 +0000121 bool OptimizeInlineAsmInst(CallInst *CS);
Eric Christopher040056f2010-03-11 02:41:03 +0000122 bool OptimizeCallInst(CallInst *CI);
Dan Gohmanb00f2362009-10-16 20:59:35 +0000123 bool MoveExtToFormExtLoad(Instruction *I);
Evan Chengbdcb7262007-12-05 23:58:20 +0000124 bool OptimizeExtUses(Instruction *I);
Benjamin Kramer59957502012-05-05 12:49:22 +0000125 bool OptimizeSelectInst(SelectInst *SI);
Evan Cheng485fafc2011-03-21 01:19:09 +0000126 bool DupRetToEnableTailCallOpts(ReturnInst *RI);
Devang Patelf56ea612011-08-18 00:50:51 +0000127 bool PlaceDbgValues(Function &F);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000128 };
129}
Devang Patel794fd752007-05-01 21:15:47 +0000130
Devang Patel19974732007-05-03 01:11:54 +0000131char CodeGenPrepare::ID = 0;
Chad Rosier618c1db2011-12-01 03:08:23 +0000132INITIALIZE_PASS_BEGIN(CodeGenPrepare, "codegenprepare",
133 "Optimize for code generation", false, false)
134INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
135INITIALIZE_PASS_END(CodeGenPrepare, "codegenprepare",
Owen Andersonce665bd2010-10-07 22:25:06 +0000136 "Optimize for code generation", false, false)
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000137
138FunctionPass *llvm::createCodeGenPreparePass(const TargetLowering *TLI) {
139 return new CodeGenPrepare(TLI);
140}
141
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000142bool CodeGenPrepare::runOnFunction(Function &F) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000143 bool EverMadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000144
Devang Patel52e37df2011-03-24 15:35:25 +0000145 ModifiedDT = false;
Chad Rosier618c1db2011-12-01 03:08:23 +0000146 TLInfo = &getAnalysis<TargetLibraryInfo>();
Cameron Zwarich80f6a502011-01-08 17:01:52 +0000147 DT = getAnalysisIfAvailable<DominatorTree>();
Evan Cheng04149f72009-12-17 09:39:49 +0000148 PFI = getAnalysisIfAvailable<ProfileInfo>();
Benjamin Kramer59957502012-05-05 12:49:22 +0000149 OptSize = F.hasFnAttr(Attribute::OptimizeForSize);
Evan Cheng485fafc2011-03-21 01:19:09 +0000150
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000151 // First pass, eliminate blocks that contain only PHI nodes and an
152 // unconditional branch.
153 EverMadeChange |= EliminateMostlyEmptyBlocks(F);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000154
Devang Patelf56ea612011-08-18 00:50:51 +0000155 // llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotema94d6e82012-07-24 10:51:42 +0000156 // handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patelf56ea612011-08-18 00:50:51 +0000157 // find a node corresponding to the value.
158 EverMadeChange |= PlaceDbgValues(F);
159
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000160 bool MadeChange = true;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000161 while (MadeChange) {
162 MadeChange = false;
Evan Cheng485fafc2011-03-21 01:19:09 +0000163 for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
164 BasicBlock *BB = I++;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000165 MadeChange |= OptimizeBlock(*BB);
Evan Cheng485fafc2011-03-21 01:19:09 +0000166 }
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000167 EverMadeChange |= MadeChange;
168 }
Cameron Zwarich8c3527e2011-01-06 00:42:50 +0000169
170 SunkAddrs.clear();
171
Cameron Zwarich899eaa32011-03-11 21:52:04 +0000172 if (!DisableBranchOpts) {
173 MadeChange = false;
Bill Wendlinge3e394d2012-03-04 10:46:01 +0000174 SmallPtrSet<BasicBlock*, 8> WorkList;
175 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
176 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
Frits van Bommel5649ba72011-05-22 16:24:18 +0000177 MadeChange |= ConstantFoldTerminator(BB, true);
Bill Wendlinge3e394d2012-03-04 10:46:01 +0000178 if (!MadeChange) continue;
179
180 for (SmallVectorImpl<BasicBlock*>::iterator
181 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
182 if (pred_begin(*II) == pred_end(*II))
183 WorkList.insert(*II);
184 }
185
Bill Wendling8dd2e5b2012-08-15 21:18:10 +0000186 for (SmallPtrSet<BasicBlock*, 8>::iterator
187 I = WorkList.begin(), E = WorkList.end(); I != E; ++I)
188 DeleteDeadBlock(*I);
Cameron Zwarich899eaa32011-03-11 21:52:04 +0000189
Nadav Rotem3e883732012-08-14 05:19:07 +0000190 // Merge pairs of basic blocks with unconditional branches, connected by
191 // a single edge.
192 if (EverMadeChange || MadeChange)
193 MadeChange |= EliminateFallThrough(F);
194
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
Nadav Rotem3e883732012-08-14 05:19:07 +0000206/// EliminateFallThrough - Merge basic blocks which are connected
207/// by a single edge, where one of the basic blocks has a single successor
208/// pointing to the other basic block, which has a single predecessor.
209bool CodeGenPrepare::EliminateFallThrough(Function &F) {
210 bool Changed = false;
211 // Scan all of the blocks in the function, except for the entry block.
212 for (Function::iterator I = ++F.begin(), E = F.end(); I != E; ) {
213 BasicBlock *BB = I++;
214 // If the destination block has a single pred, then this is a trivial
215 // edge, just collapse it.
216 BasicBlock *SinglePred = BB->getSinglePredecessor();
217
218 if (!SinglePred || SinglePred == BB) continue;
219
220 BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
221 if (Term && !Term->isConditional()) {
222 Changed = true;
Michael Liao787ed032012-08-21 05:55:22 +0000223 DEBUG(dbgs() << "To merge:\n"<< *SinglePred << "\n\n\n");
Nadav Rotem3e883732012-08-14 05:19:07 +0000224 // Remember if SinglePred was the entry block of the function.
225 // If so, we will need to move BB back to the entry position.
226 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
227 MergeBasicBlockIntoOnlyPred(BB, this);
228
229 if (isEntry && BB != &BB->getParent()->getEntryBlock())
230 BB->moveBefore(&BB->getParent()->getEntryBlock());
231
232 // We have erased a block. Update the iterator.
233 I = BB;
Nadav Rotem3e883732012-08-14 05:19:07 +0000234 }
235 }
236 return Changed;
237}
238
Dale Johannesen2d697242009-03-27 01:13:37 +0000239/// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes,
240/// debug info directives, and an unconditional branch. Passes before isel
241/// (e.g. LSR/loopsimplify) often split edges in ways that are non-optimal for
242/// isel. Start by eliminating these blocks so we can split them the way we
243/// want them.
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000244bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
245 bool MadeChange = false;
246 // Note that this intentionally skips the entry block.
247 for (Function::iterator I = ++F.begin(), E = F.end(); I != E; ) {
248 BasicBlock *BB = I++;
249
250 // If this block doesn't end with an uncond branch, ignore it.
251 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
252 if (!BI || !BI->isUnconditional())
253 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000254
Dale Johannesen2d697242009-03-27 01:13:37 +0000255 // If the instruction before the branch (skipping debug info) isn't a phi
256 // node, then other stuff is happening here.
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000257 BasicBlock::iterator BBI = BI;
258 if (BBI != BB->begin()) {
259 --BBI;
Dale Johannesen2d697242009-03-27 01:13:37 +0000260 while (isa<DbgInfoIntrinsic>(BBI)) {
261 if (BBI == BB->begin())
262 break;
263 --BBI;
264 }
265 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
266 continue;
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000267 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000268
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000269 // Do not break infinite loops.
270 BasicBlock *DestBB = BI->getSuccessor(0);
271 if (DestBB == BB)
272 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000273
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000274 if (!CanMergeBlocks(BB, DestBB))
275 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000276
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000277 EliminateMostlyEmptyBlock(BB);
278 MadeChange = true;
279 }
280 return MadeChange;
281}
282
283/// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
284/// single uncond branch between them, and BB contains no other non-phi
285/// instructions.
286bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
287 const BasicBlock *DestBB) const {
288 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
289 // the successor. If there are more complex condition (e.g. preheaders),
290 // don't mess around with them.
291 BasicBlock::const_iterator BBI = BB->begin();
292 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
Gabor Greif60ad7812010-03-25 23:06:16 +0000293 for (Value::const_use_iterator UI = PN->use_begin(), E = PN->use_end();
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000294 UI != E; ++UI) {
295 const Instruction *User = cast<Instruction>(*UI);
296 if (User->getParent() != DestBB || !isa<PHINode>(User))
297 return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000298 // If User is inside DestBB block and it is a PHINode then check
299 // incoming value. If incoming value is not from BB then this is
Devang Patel75abc1e2007-04-25 00:37:04 +0000300 // a complex condition (e.g. preheaders) we want to avoid here.
301 if (User->getParent() == DestBB) {
302 if (const PHINode *UPN = dyn_cast<PHINode>(User))
303 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
304 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
305 if (Insn && Insn->getParent() == BB &&
306 Insn->getParent() != UPN->getIncomingBlock(I))
307 return false;
308 }
309 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000310 }
311 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000312
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000313 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
314 // and DestBB may have conflicting incoming values for the block. If so, we
315 // can't merge the block.
316 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
317 if (!DestBBPN) return true; // no conflict.
Eric Christopher692bf6b2008-09-24 05:32:41 +0000318
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000319 // Collect the preds of BB.
Chris Lattnerf67f73a2007-11-06 22:07:40 +0000320 SmallPtrSet<const BasicBlock*, 16> BBPreds;
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000321 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
322 // It is faster to get preds from a PHI than with pred_iterator.
323 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
324 BBPreds.insert(BBPN->getIncomingBlock(i));
325 } else {
326 BBPreds.insert(pred_begin(BB), pred_end(BB));
327 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000328
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000329 // Walk the preds of DestBB.
330 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
331 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
332 if (BBPreds.count(Pred)) { // Common predecessor?
333 BBI = DestBB->begin();
334 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
335 const Value *V1 = PN->getIncomingValueForBlock(Pred);
336 const Value *V2 = PN->getIncomingValueForBlock(BB);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000337
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000338 // If V2 is a phi node in BB, look up what the mapped value will be.
339 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
340 if (V2PN->getParent() == BB)
341 V2 = V2PN->getIncomingValueForBlock(Pred);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000342
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000343 // If there is a conflict, bail out.
344 if (V1 != V2) return false;
345 }
346 }
347 }
348
349 return true;
350}
351
352
353/// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
354/// an unconditional branch in it.
355void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
356 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
357 BasicBlock *DestBB = BI->getSuccessor(0);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000358
David Greene68d67fd2010-01-05 01:27:11 +0000359 DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000360
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000361 // If the destination block has a single pred, then this is a trivial edge,
362 // just collapse it.
Chris Lattner9918fb52008-11-27 19:29:14 +0000363 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
Chris Lattnerf5102a02008-11-28 19:54:49 +0000364 if (SinglePred != DestBB) {
365 // Remember if SinglePred was the entry block of the function. If so, we
366 // will need to move BB back to the entry position.
367 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Andreas Neustifterad809812009-09-16 09:26:52 +0000368 MergeBasicBlockIntoOnlyPred(DestBB, this);
Chris Lattner9918fb52008-11-27 19:29:14 +0000369
Chris Lattnerf5102a02008-11-28 19:54:49 +0000370 if (isEntry && BB != &BB->getParent()->getEntryBlock())
371 BB->moveBefore(&BB->getParent()->getEntryBlock());
Nadav Rotema94d6e82012-07-24 10:51:42 +0000372
David Greene68d67fd2010-01-05 01:27:11 +0000373 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerf5102a02008-11-28 19:54:49 +0000374 return;
375 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000376 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000377
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000378 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
379 // to handle the new incoming edges it is about to have.
380 PHINode *PN;
381 for (BasicBlock::iterator BBI = DestBB->begin();
382 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
383 // Remove the incoming value for BB, and remember it.
384 Value *InVal = PN->removeIncomingValue(BB, false);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000385
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000386 // Two options: either the InVal is a phi node defined in BB or it is some
387 // value that dominates BB.
388 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
389 if (InValPhi && InValPhi->getParent() == BB) {
390 // Add all of the input values of the input PHI as inputs of this phi.
391 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
392 PN->addIncoming(InValPhi->getIncomingValue(i),
393 InValPhi->getIncomingBlock(i));
394 } else {
395 // Otherwise, add one instance of the dominating value for each edge that
396 // we will be adding.
397 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
398 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
399 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
400 } else {
401 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
402 PN->addIncoming(InVal, *PI);
403 }
404 }
405 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000406
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000407 // The PHIs are now updated, change everything that refers to BB to use
408 // DestBB and remove BB.
409 BB->replaceAllUsesWith(DestBB);
Devang Patel52e37df2011-03-24 15:35:25 +0000410 if (DT && !ModifiedDT) {
Cameron Zwarich80f6a502011-01-08 17:01:52 +0000411 BasicBlock *BBIDom = DT->getNode(BB)->getIDom()->getBlock();
412 BasicBlock *DestBBIDom = DT->getNode(DestBB)->getIDom()->getBlock();
413 BasicBlock *NewIDom = DT->findNearestCommonDominator(BBIDom, DestBBIDom);
414 DT->changeImmediateDominator(DestBB, NewIDom);
415 DT->eraseNode(BB);
416 }
Evan Cheng04149f72009-12-17 09:39:49 +0000417 if (PFI) {
418 PFI->replaceAllUses(BB, DestBB);
419 PFI->removeEdge(ProfileInfo::getEdge(BB, DestBB));
Andreas Neustifterad809812009-09-16 09:26:52 +0000420 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000421 BB->eraseFromParent();
Cameron Zwarich31ff1332011-01-05 17:27:27 +0000422 ++NumBlocksElim;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000423
David Greene68d67fd2010-01-05 01:27:11 +0000424 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000425}
426
Chris Lattnerdd77df32007-04-13 20:30:56 +0000427/// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
Dan Gohmana119de82009-06-14 23:30:43 +0000428/// copy (e.g. it's casting from one pointer type to another, i32->i8 on PPC),
429/// sink it into user blocks to reduce the number of virtual
Dale Johannesence0b2372007-06-12 16:50:17 +0000430/// registers that must be created and coalesced.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000431///
432/// Return true if any changes are made.
Chris Lattner85fa13c2008-11-24 22:44:16 +0000433///
Chris Lattnerdd77df32007-04-13 20:30:56 +0000434static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
Eric Christopher692bf6b2008-09-24 05:32:41 +0000435 // If this is a noop copy,
Owen Andersone50ed302009-08-10 22:56:29 +0000436 EVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
437 EVT DstVT = TLI.getValueType(CI->getType());
Eric Christopher692bf6b2008-09-24 05:32:41 +0000438
Chris Lattnerdd77df32007-04-13 20:30:56 +0000439 // This is an fp<->int conversion?
Duncan Sands83ec4b62008-06-06 12:08:01 +0000440 if (SrcVT.isInteger() != DstVT.isInteger())
Chris Lattnerdd77df32007-04-13 20:30:56 +0000441 return false;
Duncan Sands8e4eb092008-06-08 20:54:56 +0000442
Chris Lattnerdd77df32007-04-13 20:30:56 +0000443 // If this is an extension, it will be a zero or sign extension, which
444 // isn't a noop.
Duncan Sands8e4eb092008-06-08 20:54:56 +0000445 if (SrcVT.bitsLT(DstVT)) return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000446
Chris Lattnerdd77df32007-04-13 20:30:56 +0000447 // If these values will be promoted, find out what they will be promoted
448 // to. This helps us consider truncates on PPC as noop copies when they
449 // are.
Nadav Rotem0ccc12a2011-05-29 08:10:47 +0000450 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
451 TargetLowering::TypePromoteInteger)
Owen Anderson23b9b192009-08-12 00:36:31 +0000452 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
Nadav Rotem0ccc12a2011-05-29 08:10:47 +0000453 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
454 TargetLowering::TypePromoteInteger)
Owen Anderson23b9b192009-08-12 00:36:31 +0000455 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000456
Chris Lattnerdd77df32007-04-13 20:30:56 +0000457 // If, after promotion, these are the same types, this is a noop copy.
458 if (SrcVT != DstVT)
459 return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000460
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000461 BasicBlock *DefBB = CI->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000462
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000463 /// InsertedCasts - Only insert a cast in each block once.
Dale Johannesence0b2372007-06-12 16:50:17 +0000464 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000465
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000466 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000467 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000468 UI != E; ) {
469 Use &TheUse = UI.getUse();
470 Instruction *User = cast<Instruction>(*UI);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000471
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000472 // Figure out which BB this cast is used in. For PHI's this is the
473 // appropriate predecessor block.
474 BasicBlock *UserBB = User->getParent();
475 if (PHINode *PN = dyn_cast<PHINode>(User)) {
Gabor Greifa36791d2009-01-23 19:40:15 +0000476 UserBB = PN->getIncomingBlock(UI);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000477 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000478
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000479 // Preincrement use iterator so we don't invalidate it.
480 ++UI;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000481
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000482 // If this user is in the same block as the cast, don't change the cast.
483 if (UserBB == DefBB) continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000484
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000485 // If we have already inserted a cast into this block, use it.
486 CastInst *&InsertedCast = InsertedCasts[UserBB];
487
488 if (!InsertedCast) {
Bill Wendling5b6f42f2011-08-16 20:45:24 +0000489 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000490 InsertedCast =
491 CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000492 InsertPt);
493 MadeChange = true;
494 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000495
Dale Johannesence0b2372007-06-12 16:50:17 +0000496 // Replace a use of the cast with a use of the new cast.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000497 TheUse = InsertedCast;
Cameron Zwarich31ff1332011-01-05 17:27:27 +0000498 ++NumCastUses;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000499 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000500
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000501 // If we removed all uses, nuke the cast.
Duncan Sandse0038132008-01-20 16:51:46 +0000502 if (CI->use_empty()) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000503 CI->eraseFromParent();
Duncan Sandse0038132008-01-20 16:51:46 +0000504 MadeChange = true;
505 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000506
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000507 return MadeChange;
508}
509
Eric Christopher692bf6b2008-09-24 05:32:41 +0000510/// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
Dale Johannesence0b2372007-06-12 16:50:17 +0000511/// the number of virtual registers that must be created and coalesced. This is
Chris Lattner684b22d2007-08-02 16:53:43 +0000512/// a clear win except on targets with multiple condition code registers
513/// (PowerPC), where it might lose; some adjustment may be wanted there.
Dale Johannesence0b2372007-06-12 16:50:17 +0000514///
515/// Return true if any changes are made.
Chris Lattner85fa13c2008-11-24 22:44:16 +0000516static bool OptimizeCmpExpression(CmpInst *CI) {
Dale Johannesence0b2372007-06-12 16:50:17 +0000517 BasicBlock *DefBB = CI->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000518
Dale Johannesence0b2372007-06-12 16:50:17 +0000519 /// InsertedCmp - Only insert a cmp in each block once.
520 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000521
Dale Johannesence0b2372007-06-12 16:50:17 +0000522 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000523 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
Dale Johannesence0b2372007-06-12 16:50:17 +0000524 UI != E; ) {
525 Use &TheUse = UI.getUse();
526 Instruction *User = cast<Instruction>(*UI);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000527
Dale Johannesence0b2372007-06-12 16:50:17 +0000528 // Preincrement use iterator so we don't invalidate it.
529 ++UI;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000530
Dale Johannesence0b2372007-06-12 16:50:17 +0000531 // Don't bother for PHI nodes.
532 if (isa<PHINode>(User))
533 continue;
534
535 // Figure out which BB this cmp is used in.
536 BasicBlock *UserBB = User->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000537
Dale Johannesence0b2372007-06-12 16:50:17 +0000538 // If this user is in the same block as the cmp, don't change the cmp.
539 if (UserBB == DefBB) continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000540
Dale Johannesence0b2372007-06-12 16:50:17 +0000541 // If we have already inserted a cmp into this block, use it.
542 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
543
544 if (!InsertedCmp) {
Bill Wendling5b6f42f2011-08-16 20:45:24 +0000545 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000546 InsertedCmp =
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000547 CmpInst::Create(CI->getOpcode(),
Owen Anderson333c4002009-07-09 23:48:35 +0000548 CI->getPredicate(), CI->getOperand(0),
Dale Johannesence0b2372007-06-12 16:50:17 +0000549 CI->getOperand(1), "", InsertPt);
550 MadeChange = true;
551 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000552
Dale Johannesence0b2372007-06-12 16:50:17 +0000553 // Replace a use of the cmp with a use of the new cmp.
554 TheUse = InsertedCmp;
Cameron Zwarich31ff1332011-01-05 17:27:27 +0000555 ++NumCmpUses;
Dale Johannesence0b2372007-06-12 16:50:17 +0000556 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000557
Dale Johannesence0b2372007-06-12 16:50:17 +0000558 // If we removed all uses, nuke the cmp.
559 if (CI->use_empty())
560 CI->eraseFromParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000561
Dale Johannesence0b2372007-06-12 16:50:17 +0000562 return MadeChange;
563}
564
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000565namespace {
566class CodeGenPrepareFortifiedLibCalls : public SimplifyFortifiedLibCalls {
567protected:
568 void replaceCall(Value *With) {
569 CI->replaceAllUsesWith(With);
570 CI->eraseFromParent();
571 }
572 bool isFoldable(unsigned SizeCIOp, unsigned, bool) const {
Gabor Greifa6aac4c2010-07-16 09:38:02 +0000573 if (ConstantInt *SizeCI =
574 dyn_cast<ConstantInt>(CI->getArgOperand(SizeCIOp)))
575 return SizeCI->isAllOnesValue();
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000576 return false;
577 }
578};
579} // end anonymous namespace
580
Eric Christopher040056f2010-03-11 02:41:03 +0000581bool CodeGenPrepare::OptimizeCallInst(CallInst *CI) {
Chris Lattner75796092011-01-15 07:14:54 +0000582 BasicBlock *BB = CI->getParent();
Nadav Rotema94d6e82012-07-24 10:51:42 +0000583
Chris Lattner75796092011-01-15 07:14:54 +0000584 // Lower inline assembly if we can.
585 // If we found an inline asm expession, and if the target knows how to
586 // lower it to normal LLVM code, do so now.
587 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
588 if (TLI->ExpandInlineAsm(CI)) {
589 // Avoid invalidating the iterator.
590 CurInstIterator = BB->begin();
591 // Avoid processing instructions out of order, which could cause
592 // reuse before a value is defined.
593 SunkAddrs.clear();
594 return true;
595 }
596 // Sink address computing for memory operands into the block.
597 if (OptimizeInlineAsmInst(CI))
598 return true;
599 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000600
Eric Christopher040056f2010-03-11 02:41:03 +0000601 // Lower all uses of llvm.objectsize.*
602 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
603 if (II && II->getIntrinsicID() == Intrinsic::objectsize) {
Gabor Greifde9f5452010-06-24 00:44:01 +0000604 bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000605 Type *ReturnTy = CI->getType();
Nadav Rotema94d6e82012-07-24 10:51:42 +0000606 Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
607
Chris Lattner94e8e0c2011-01-15 07:25:29 +0000608 // Substituting this can cause recursive simplifications, which can
609 // invalidate our iterator. Use a WeakVH to hold onto it in case this
610 // happens.
611 WeakVH IterHandle(CurInstIterator);
Nadav Rotema94d6e82012-07-24 10:51:42 +0000612
Chandler Carruth6b980542012-03-24 21:11:24 +0000613 replaceAndRecursivelySimplify(CI, RetVal, TLI ? TLI->getTargetData() : 0,
614 TLInfo, ModifiedDT ? 0 : DT);
Chris Lattner94e8e0c2011-01-15 07:25:29 +0000615
616 // If the iterator instruction was recursively deleted, start over at the
617 // start of the block.
Chris Lattner435b4d22011-01-18 20:53:04 +0000618 if (IterHandle != CurInstIterator) {
Chris Lattner94e8e0c2011-01-15 07:25:29 +0000619 CurInstIterator = BB->begin();
Chris Lattner435b4d22011-01-18 20:53:04 +0000620 SunkAddrs.clear();
621 }
Eric Christopher040056f2010-03-11 02:41:03 +0000622 return true;
623 }
624
Pete Cooperf210b682012-03-13 20:59:56 +0000625 if (II && TLI) {
626 SmallVector<Value*, 2> PtrOps;
627 Type *AccessTy;
628 if (TLI->GetAddrModeArguments(II, PtrOps, AccessTy))
629 while (!PtrOps.empty())
630 if (OptimizeMemoryInst(II, PtrOps.pop_back_val(), AccessTy))
631 return true;
632 }
633
Eric Christopher040056f2010-03-11 02:41:03 +0000634 // From here on out we're working with named functions.
635 if (CI->getCalledFunction() == 0) return false;
Devang Patel97de92c2011-05-26 21:51:06 +0000636
Eric Christopher040056f2010-03-11 02:41:03 +0000637 // We'll need TargetData from here on out.
638 const TargetData *TD = TLI ? TLI->getTargetData() : 0;
639 if (!TD) return false;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000640
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000641 // Lower all default uses of _chk calls. This is very similar
642 // to what InstCombineCalls does, but here we are only lowering calls
Eric Christopher040056f2010-03-11 02:41:03 +0000643 // that have the default "don't know" as the objectsize. Anything else
644 // should be left alone.
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000645 CodeGenPrepareFortifiedLibCalls Simplifier;
Nuno Lopes51004df2012-07-25 16:46:31 +0000646 return Simplifier.fold(CI, TD, TLInfo);
Eric Christopher040056f2010-03-11 02:41:03 +0000647}
Chris Lattner94e8e0c2011-01-15 07:25:29 +0000648
Evan Cheng485fafc2011-03-21 01:19:09 +0000649/// DupRetToEnableTailCallOpts - Look for opportunities to duplicate return
650/// instructions to the predecessor to enable tail call optimizations. The
651/// case it is currently looking for is:
652/// bb0:
653/// %tmp0 = tail call i32 @f0()
654/// br label %return
655/// bb1:
656/// %tmp1 = tail call i32 @f1()
657/// br label %return
658/// bb2:
659/// %tmp2 = tail call i32 @f2()
660/// br label %return
661/// return:
662/// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
663/// ret i32 %retval
664///
665/// =>
666///
667/// bb0:
668/// %tmp0 = tail call i32 @f0()
669/// ret i32 %tmp0
670/// bb1:
671/// %tmp1 = tail call i32 @f1()
672/// ret i32 %tmp1
673/// bb2:
674/// %tmp2 = tail call i32 @f2()
675/// ret i32 %tmp2
676///
677bool CodeGenPrepare::DupRetToEnableTailCallOpts(ReturnInst *RI) {
Cameron Zwarich661a3902011-03-24 04:51:51 +0000678 if (!TLI)
679 return false;
680
Evan Cheng9c777a42012-07-27 21:21:26 +0000681 PHINode *PN = 0;
682 BitCastInst *BCI = 0;
Evan Cheng485fafc2011-03-21 01:19:09 +0000683 Value *V = RI->getReturnValue();
Evan Cheng9c777a42012-07-27 21:21:26 +0000684 if (V) {
685 BCI = dyn_cast<BitCastInst>(V);
686 if (BCI)
687 V = BCI->getOperand(0);
688
689 PN = dyn_cast<PHINode>(V);
690 if (!PN)
691 return false;
692 }
Evan Cheng485fafc2011-03-21 01:19:09 +0000693
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000694 BasicBlock *BB = RI->getParent();
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000695 if (PN && PN->getParent() != BB)
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000696 return false;
Evan Cheng485fafc2011-03-21 01:19:09 +0000697
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000698 // It's not safe to eliminate the sign / zero extension of the return value.
699 // See llvm::isInTailCallPosition().
700 const Function *F = BB->getParent();
Kostya Serebryany164b86b2012-01-20 17:56:17 +0000701 Attributes CallerRetAttr = F->getAttributes().getRetAttributes();
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000702 if ((CallerRetAttr & Attribute::ZExt) || (CallerRetAttr & Attribute::SExt))
703 return false;
Evan Cheng485fafc2011-03-21 01:19:09 +0000704
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000705 // Make sure there are no instructions between the PHI and return, or that the
706 // return is the first instruction in the block.
707 if (PN) {
708 BasicBlock::iterator BI = BB->begin();
709 do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
Evan Cheng9c777a42012-07-27 21:21:26 +0000710 if (&*BI == BCI)
711 // Also skip over the bitcast.
712 ++BI;
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000713 if (&*BI != RI)
714 return false;
715 } else {
Cameron Zwarich90354842011-03-24 16:34:59 +0000716 BasicBlock::iterator BI = BB->begin();
717 while (isa<DbgInfoIntrinsic>(BI)) ++BI;
718 if (&*BI != RI)
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000719 return false;
720 }
Evan Cheng485fafc2011-03-21 01:19:09 +0000721
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000722 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
723 /// call.
724 SmallVector<CallInst*, 4> TailCalls;
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000725 if (PN) {
726 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
727 CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
728 // Make sure the phi value is indeed produced by the tail call.
729 if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
730 TLI->mayBeEmittedAsTailCall(CI))
731 TailCalls.push_back(CI);
732 }
733 } else {
734 SmallPtrSet<BasicBlock*, 4> VisitedBBs;
735 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
736 if (!VisitedBBs.insert(*PI))
737 continue;
738
739 BasicBlock::InstListType &InstList = (*PI)->getInstList();
740 BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
741 BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
Cameron Zwarich90354842011-03-24 16:34:59 +0000742 do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
743 if (RI == RE)
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000744 continue;
Cameron Zwarich90354842011-03-24 16:34:59 +0000745
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000746 CallInst *CI = dyn_cast<CallInst>(&*RI);
Cameron Zwarichdc31cfe2011-03-24 15:54:11 +0000747 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI))
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000748 TailCalls.push_back(CI);
749 }
Evan Cheng485fafc2011-03-21 01:19:09 +0000750 }
751
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000752 bool Changed = false;
753 for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
754 CallInst *CI = TailCalls[i];
755 CallSite CS(CI);
756
757 // Conservatively require the attributes of the call to match those of the
758 // return. Ignore noalias because it doesn't affect the call sequence.
Kostya Serebryany164b86b2012-01-20 17:56:17 +0000759 Attributes CalleeRetAttr = CS.getAttributes().getRetAttributes();
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000760 if ((CalleeRetAttr ^ CallerRetAttr) & ~Attribute::NoAlias)
761 continue;
762
763 // Make sure the call instruction is followed by an unconditional branch to
764 // the return block.
765 BasicBlock *CallBB = CI->getParent();
766 BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
767 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
768 continue;
769
770 // Duplicate the return into CallBB.
771 (void)FoldReturnIntoUncondBranch(RI, BB, CallBB);
Devang Patel52e37df2011-03-24 15:35:25 +0000772 ModifiedDT = Changed = true;
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000773 ++NumRetsDup;
774 }
775
776 // If we eliminated all predecessors of the block, delete the block now.
777 if (Changed && pred_begin(BB) == pred_end(BB))
778 BB->eraseFromParent();
779
780 return Changed;
Evan Cheng485fafc2011-03-21 01:19:09 +0000781}
782
Chris Lattner88a5c832008-11-25 07:09:13 +0000783//===----------------------------------------------------------------------===//
Chris Lattner88a5c832008-11-25 07:09:13 +0000784// Memory Optimization
785//===----------------------------------------------------------------------===//
786
Chris Lattnerdd77df32007-04-13 20:30:56 +0000787/// IsNonLocalValue - Return true if the specified values are defined in a
788/// different basic block than BB.
789static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
790 if (Instruction *I = dyn_cast<Instruction>(V))
791 return I->getParent() != BB;
792 return false;
793}
794
Bob Wilson4a8ee232009-12-03 21:47:07 +0000795/// OptimizeMemoryInst - Load and Store Instructions often have
Chris Lattnerdd77df32007-04-13 20:30:56 +0000796/// addressing modes that can do significant amounts of computation. As such,
797/// instruction selection will try to get the load or store to do as much
798/// computation as possible for the program. The problem is that isel can only
799/// see within a single block. As such, we sink as much legal addressing mode
800/// stuff into the block as possible.
Chris Lattner88a5c832008-11-25 07:09:13 +0000801///
802/// This method is used to optimize both load/store and inline asms with memory
803/// operands.
Chris Lattner896617b2008-11-26 03:20:37 +0000804bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000805 Type *AccessTy) {
Owen Anderson35bf4d62010-11-27 08:15:55 +0000806 Value *Repl = Addr;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000807
808 // Try to collapse single-value PHI nodes. This is necessary to undo
Owen Andersond2f41742010-11-19 22:15:03 +0000809 // unprofitable PRE transformations.
Cameron Zwarich7cb4fa22011-01-03 06:33:01 +0000810 SmallVector<Value*, 8> worklist;
811 SmallPtrSet<Value*, 16> Visited;
Owen Anderson35bf4d62010-11-27 08:15:55 +0000812 worklist.push_back(Addr);
Nadav Rotema94d6e82012-07-24 10:51:42 +0000813
Owen Anderson35bf4d62010-11-27 08:15:55 +0000814 // Use a worklist to iteratively look through PHI nodes, and ensure that
815 // the addressing mode obtained from the non-PHI roots of the graph
816 // are equivalent.
817 Value *Consensus = 0;
Cameron Zwarich4c078f02011-03-01 21:13:53 +0000818 unsigned NumUsesConsensus = 0;
Cameron Zwarich7c8d3512011-03-05 08:12:26 +0000819 bool IsNumUsesConsensusValid = false;
Owen Anderson35bf4d62010-11-27 08:15:55 +0000820 SmallVector<Instruction*, 16> AddrModeInsts;
821 ExtAddrMode AddrMode;
822 while (!worklist.empty()) {
823 Value *V = worklist.back();
824 worklist.pop_back();
Nadav Rotema94d6e82012-07-24 10:51:42 +0000825
Owen Anderson35bf4d62010-11-27 08:15:55 +0000826 // Break use-def graph loops.
Nick Lewycky48105282011-09-29 23:40:12 +0000827 if (!Visited.insert(V)) {
Owen Anderson35bf4d62010-11-27 08:15:55 +0000828 Consensus = 0;
829 break;
Owen Andersond2f41742010-11-19 22:15:03 +0000830 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000831
Owen Anderson35bf4d62010-11-27 08:15:55 +0000832 // For a PHI node, push all of its incoming values.
833 if (PHINode *P = dyn_cast<PHINode>(V)) {
834 for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i)
835 worklist.push_back(P->getIncomingValue(i));
836 continue;
837 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000838
Owen Anderson35bf4d62010-11-27 08:15:55 +0000839 // For non-PHIs, determine the addressing mode being computed.
840 SmallVector<Instruction*, 16> NewAddrModeInsts;
841 ExtAddrMode NewAddrMode =
Nick Lewycky48105282011-09-29 23:40:12 +0000842 AddressingModeMatcher::Match(V, AccessTy, MemoryInst,
Owen Anderson35bf4d62010-11-27 08:15:55 +0000843 NewAddrModeInsts, *TLI);
Cameron Zwarich7c8d3512011-03-05 08:12:26 +0000844
845 // This check is broken into two cases with very similar code to avoid using
846 // getNumUses() as much as possible. Some values have a lot of uses, so
847 // calling getNumUses() unconditionally caused a significant compile-time
848 // regression.
849 if (!Consensus) {
850 Consensus = V;
851 AddrMode = NewAddrMode;
852 AddrModeInsts = NewAddrModeInsts;
853 continue;
854 } else if (NewAddrMode == AddrMode) {
855 if (!IsNumUsesConsensusValid) {
856 NumUsesConsensus = Consensus->getNumUses();
857 IsNumUsesConsensusValid = true;
858 }
859
860 // Ensure that the obtained addressing mode is equivalent to that obtained
861 // for all other roots of the PHI traversal. Also, when choosing one
862 // such root as representative, select the one with the most uses in order
863 // to keep the cost modeling heuristics in AddressingModeMatcher
864 // applicable.
Cameron Zwarich4c078f02011-03-01 21:13:53 +0000865 unsigned NumUses = V->getNumUses();
866 if (NumUses > NumUsesConsensus) {
Owen Anderson35bf4d62010-11-27 08:15:55 +0000867 Consensus = V;
Cameron Zwarich4c078f02011-03-01 21:13:53 +0000868 NumUsesConsensus = NumUses;
Owen Anderson35bf4d62010-11-27 08:15:55 +0000869 AddrModeInsts = NewAddrModeInsts;
870 }
871 continue;
872 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000873
Owen Anderson35bf4d62010-11-27 08:15:55 +0000874 Consensus = 0;
875 break;
Owen Andersond2f41742010-11-19 22:15:03 +0000876 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000877
Owen Anderson35bf4d62010-11-27 08:15:55 +0000878 // If the addressing mode couldn't be determined, or if multiple different
879 // ones were determined, bail out now.
880 if (!Consensus) return false;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000881
Chris Lattnerdd77df32007-04-13 20:30:56 +0000882 // Check to see if any of the instructions supersumed by this addr mode are
883 // non-local to I's BB.
884 bool AnyNonLocal = false;
885 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
Chris Lattner896617b2008-11-26 03:20:37 +0000886 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
Chris Lattnerdd77df32007-04-13 20:30:56 +0000887 AnyNonLocal = true;
888 break;
889 }
890 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000891
Chris Lattnerdd77df32007-04-13 20:30:56 +0000892 // If all the instructions matched are already in this BB, don't do anything.
893 if (!AnyNonLocal) {
David Greene68d67fd2010-01-05 01:27:11 +0000894 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000895 return false;
896 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000897
Chris Lattnerdd77df32007-04-13 20:30:56 +0000898 // Insert this computation right after this user. Since our caller is
899 // scanning from the top of the BB to the bottom, reuse of the expr are
900 // guaranteed to happen later.
Devang Patel2048c372011-09-06 18:49:53 +0000901 IRBuilder<> Builder(MemoryInst);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000902
Chris Lattnerdd77df32007-04-13 20:30:56 +0000903 // Now that we determined the addressing expression we want to use and know
904 // that we have to sink it into this block. Check to see if we have already
905 // done this for some other load/store instr in this block. If so, reuse the
906 // computation.
907 Value *&SunkAddr = SunkAddrs[Addr];
908 if (SunkAddr) {
David Greene68d67fd2010-01-05 01:27:11 +0000909 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
Dan Gohman6c1980b2009-07-25 01:13:51 +0000910 << *MemoryInst);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000911 if (SunkAddr->getType() != Addr->getType())
Benjamin Kramera9390a42011-09-27 20:39:19 +0000912 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
Chris Lattnerdd77df32007-04-13 20:30:56 +0000913 } else {
David Greene68d67fd2010-01-05 01:27:11 +0000914 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Dan Gohman6c1980b2009-07-25 01:13:51 +0000915 << *MemoryInst);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000916 Type *IntPtrTy =
Owen Anderson1d0be152009-08-13 21:58:54 +0000917 TLI->getTargetData()->getIntPtrType(AccessTy->getContext());
Eric Christopher692bf6b2008-09-24 05:32:41 +0000918
Chris Lattnerdd77df32007-04-13 20:30:56 +0000919 Value *Result = 0;
Dan Gohmand8d0b6a2010-01-19 22:45:06 +0000920
921 // Start with the base register. Do this first so that subsequent address
922 // matching finds it last, which will prevent it from trying to match it
923 // as the scaled value in case it happens to be a mul. That would be
924 // problematic if we've sunk a different mul for the scale, because then
925 // we'd end up sinking both muls.
926 if (AddrMode.BaseReg) {
927 Value *V = AddrMode.BaseReg;
Duncan Sands1df98592010-02-16 11:11:14 +0000928 if (V->getType()->isPointerTy())
Devang Patel2048c372011-09-06 18:49:53 +0000929 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Dan Gohmand8d0b6a2010-01-19 22:45:06 +0000930 if (V->getType() != IntPtrTy)
Devang Patel2048c372011-09-06 18:49:53 +0000931 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
Dan Gohmand8d0b6a2010-01-19 22:45:06 +0000932 Result = V;
933 }
934
935 // Add the scale value.
Chris Lattnerdd77df32007-04-13 20:30:56 +0000936 if (AddrMode.Scale) {
937 Value *V = AddrMode.ScaledReg;
938 if (V->getType() == IntPtrTy) {
939 // done.
Duncan Sands1df98592010-02-16 11:11:14 +0000940 } else if (V->getType()->isPointerTy()) {
Devang Patel2048c372011-09-06 18:49:53 +0000941 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000942 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
943 cast<IntegerType>(V->getType())->getBitWidth()) {
Devang Patel2048c372011-09-06 18:49:53 +0000944 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000945 } else {
Devang Patel2048c372011-09-06 18:49:53 +0000946 V = Builder.CreateSExt(V, IntPtrTy, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000947 }
948 if (AddrMode.Scale != 1)
Devang Patel2048c372011-09-06 18:49:53 +0000949 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
950 "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000951 if (Result)
Devang Patel2048c372011-09-06 18:49:53 +0000952 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000953 else
954 Result = V;
955 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000956
Chris Lattnerdd77df32007-04-13 20:30:56 +0000957 // Add in the BaseGV if present.
958 if (AddrMode.BaseGV) {
Devang Patel2048c372011-09-06 18:49:53 +0000959 Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000960 if (Result)
Devang Patel2048c372011-09-06 18:49:53 +0000961 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000962 else
963 Result = V;
964 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000965
Chris Lattnerdd77df32007-04-13 20:30:56 +0000966 // Add in the Base Offset if present.
967 if (AddrMode.BaseOffs) {
Owen Andersoneed707b2009-07-24 23:12:02 +0000968 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000969 if (Result)
Devang Patel2048c372011-09-06 18:49:53 +0000970 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000971 else
972 Result = V;
973 }
974
975 if (Result == 0)
Owen Andersona7235ea2009-07-31 20:28:14 +0000976 SunkAddr = Constant::getNullValue(Addr->getType());
Chris Lattnerdd77df32007-04-13 20:30:56 +0000977 else
Devang Patel2048c372011-09-06 18:49:53 +0000978 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000979 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000980
Owen Andersond2f41742010-11-19 22:15:03 +0000981 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000982
Chris Lattner0403b472011-04-09 07:05:44 +0000983 // If we have no uses, recursively delete the value and all dead instructions
984 // using it.
Owen Andersond2f41742010-11-19 22:15:03 +0000985 if (Repl->use_empty()) {
Chris Lattner0403b472011-04-09 07:05:44 +0000986 // This can cause recursive deletion, which can invalidate our iterator.
987 // Use a WeakVH to hold onto it in case this happens.
988 WeakVH IterHandle(CurInstIterator);
989 BasicBlock *BB = CurInstIterator->getParent();
Nadav Rotema94d6e82012-07-24 10:51:42 +0000990
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000991 RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
Chris Lattner0403b472011-04-09 07:05:44 +0000992
993 if (IterHandle != CurInstIterator) {
994 // If the iterator instruction was recursively deleted, start over at the
995 // start of the block.
996 CurInstIterator = BB->begin();
997 SunkAddrs.clear();
998 } else {
999 // This address is now available for reassignment, so erase the table
1000 // entry; we don't want to match some completely different instruction.
1001 SunkAddrs[Addr] = 0;
Nadav Rotema94d6e82012-07-24 10:51:42 +00001002 }
Dale Johannesen536d31b2010-03-31 20:37:15 +00001003 }
Cameron Zwarich31ff1332011-01-05 17:27:27 +00001004 ++NumMemoryInsts;
Chris Lattnerdd77df32007-04-13 20:30:56 +00001005 return true;
1006}
1007
Evan Cheng9bf12b52008-02-26 02:42:37 +00001008/// OptimizeInlineAsmInst - If there are any memory operands, use
Chris Lattner88a5c832008-11-25 07:09:13 +00001009/// OptimizeMemoryInst to sink their address computing into the block when
Evan Cheng9bf12b52008-02-26 02:42:37 +00001010/// possible / profitable.
Chris Lattner75796092011-01-15 07:14:54 +00001011bool CodeGenPrepare::OptimizeInlineAsmInst(CallInst *CS) {
Evan Cheng9bf12b52008-02-26 02:42:37 +00001012 bool MadeChange = false;
Evan Cheng9bf12b52008-02-26 02:42:37 +00001013
Nadav Rotema94d6e82012-07-24 10:51:42 +00001014 TargetLowering::AsmOperandInfoVector
Chris Lattner75796092011-01-15 07:14:54 +00001015 TargetConstraints = TLI->ParseConstraints(CS);
Dale Johannesen677c6ec2010-09-16 18:30:55 +00001016 unsigned ArgNo = 0;
John Thompsoneac6e1d2010-09-13 18:15:37 +00001017 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
1018 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Nadav Rotema94d6e82012-07-24 10:51:42 +00001019
Evan Cheng9bf12b52008-02-26 02:42:37 +00001020 // Compute the constraint code and ConstraintType to use.
Dale Johannesen1784d162010-06-25 21:55:36 +00001021 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Evan Cheng9bf12b52008-02-26 02:42:37 +00001022
Eli Friedman9ec80952008-02-26 18:37:49 +00001023 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
1024 OpInfo.isIndirect) {
Chris Lattner75796092011-01-15 07:14:54 +00001025 Value *OpVal = CS->getArgOperand(ArgNo++);
Chris Lattner1a8943a2011-01-15 07:29:01 +00001026 MadeChange |= OptimizeMemoryInst(CS, OpVal, OpVal->getType());
Dale Johannesen677c6ec2010-09-16 18:30:55 +00001027 } else if (OpInfo.Type == InlineAsm::isInput)
1028 ArgNo++;
Evan Cheng9bf12b52008-02-26 02:42:37 +00001029 }
1030
1031 return MadeChange;
1032}
1033
Dan Gohmanb00f2362009-10-16 20:59:35 +00001034/// MoveExtToFormExtLoad - Move a zext or sext fed by a load into the same
1035/// basic block as the load, unless conditions are unfavorable. This allows
1036/// SelectionDAG to fold the extend into the load.
1037///
1038bool CodeGenPrepare::MoveExtToFormExtLoad(Instruction *I) {
1039 // Look for a load being extended.
1040 LoadInst *LI = dyn_cast<LoadInst>(I->getOperand(0));
1041 if (!LI) return false;
1042
1043 // If they're already in the same block, there's nothing to do.
1044 if (LI->getParent() == I->getParent())
1045 return false;
1046
1047 // If the load has other users and the truncate is not free, this probably
1048 // isn't worthwhile.
1049 if (!LI->hasOneUse() &&
Bob Wilsonec57a1a2010-09-22 18:44:56 +00001050 TLI && (TLI->isTypeLegal(TLI->getValueType(LI->getType())) ||
1051 !TLI->isTypeLegal(TLI->getValueType(I->getType()))) &&
Bob Wilson71dc4d92010-09-21 21:54:27 +00001052 !TLI->isTruncateFree(I->getType(), LI->getType()))
Dan Gohmanb00f2362009-10-16 20:59:35 +00001053 return false;
1054
1055 // Check whether the target supports casts folded into loads.
1056 unsigned LType;
1057 if (isa<ZExtInst>(I))
1058 LType = ISD::ZEXTLOAD;
1059 else {
1060 assert(isa<SExtInst>(I) && "Unexpected ext type!");
1061 LType = ISD::SEXTLOAD;
1062 }
1063 if (TLI && !TLI->isLoadExtLegal(LType, TLI->getValueType(LI->getType())))
1064 return false;
1065
1066 // Move the extend into the same block as the load, so that SelectionDAG
1067 // can fold it.
1068 I->removeFromParent();
1069 I->insertAfter(LI);
Cameron Zwarich31ff1332011-01-05 17:27:27 +00001070 ++NumExtsMoved;
Dan Gohmanb00f2362009-10-16 20:59:35 +00001071 return true;
1072}
1073
Evan Chengbdcb7262007-12-05 23:58:20 +00001074bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
1075 BasicBlock *DefBB = I->getParent();
1076
Bob Wilson9120f5c2010-09-21 21:44:14 +00001077 // If the result of a {s|z}ext and its source are both live out, rewrite all
Evan Chengbdcb7262007-12-05 23:58:20 +00001078 // other uses of the source with result of extension.
1079 Value *Src = I->getOperand(0);
1080 if (Src->hasOneUse())
1081 return false;
1082
Evan Cheng696e5c02007-12-13 07:50:36 +00001083 // Only do this xform if truncating is free.
Gabor Greif53bdbd72008-02-26 19:13:21 +00001084 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
Evan Chengf9785f92007-12-13 03:32:53 +00001085 return false;
1086
Evan Cheng772de512007-12-12 00:51:06 +00001087 // Only safe to perform the optimization if the source is also defined in
Evan Cheng765dff22007-12-12 02:53:41 +00001088 // this block.
1089 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
Evan Cheng772de512007-12-12 00:51:06 +00001090 return false;
1091
Evan Chengbdcb7262007-12-05 23:58:20 +00001092 bool DefIsLiveOut = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001093 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
Evan Chengbdcb7262007-12-05 23:58:20 +00001094 UI != E; ++UI) {
1095 Instruction *User = cast<Instruction>(*UI);
1096
1097 // Figure out which BB this ext is used in.
1098 BasicBlock *UserBB = User->getParent();
1099 if (UserBB == DefBB) continue;
1100 DefIsLiveOut = true;
1101 break;
1102 }
1103 if (!DefIsLiveOut)
1104 return false;
1105
Evan Cheng765dff22007-12-12 02:53:41 +00001106 // Make sure non of the uses are PHI nodes.
Eric Christopher692bf6b2008-09-24 05:32:41 +00001107 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
Evan Cheng765dff22007-12-12 02:53:41 +00001108 UI != E; ++UI) {
1109 Instruction *User = cast<Instruction>(*UI);
Evan Chengf9785f92007-12-13 03:32:53 +00001110 BasicBlock *UserBB = User->getParent();
1111 if (UserBB == DefBB) continue;
1112 // Be conservative. We don't want this xform to end up introducing
1113 // reloads just before load / store instructions.
1114 if (isa<PHINode>(User) || isa<LoadInst>(User) || isa<StoreInst>(User))
Evan Cheng765dff22007-12-12 02:53:41 +00001115 return false;
1116 }
1117
Evan Chengbdcb7262007-12-05 23:58:20 +00001118 // InsertedTruncs - Only insert one trunc in each block once.
1119 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
1120
1121 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001122 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
Evan Chengbdcb7262007-12-05 23:58:20 +00001123 UI != E; ++UI) {
1124 Use &TheUse = UI.getUse();
1125 Instruction *User = cast<Instruction>(*UI);
1126
1127 // Figure out which BB this ext is used in.
1128 BasicBlock *UserBB = User->getParent();
1129 if (UserBB == DefBB) continue;
1130
1131 // Both src and def are live in this block. Rewrite the use.
1132 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
1133
1134 if (!InsertedTrunc) {
Bill Wendling5b6f42f2011-08-16 20:45:24 +00001135 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Evan Chengbdcb7262007-12-05 23:58:20 +00001136 InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
1137 }
1138
1139 // Replace a use of the {s|z}ext source with a use of the result.
1140 TheUse = InsertedTrunc;
Cameron Zwarich31ff1332011-01-05 17:27:27 +00001141 ++NumExtUses;
Evan Chengbdcb7262007-12-05 23:58:20 +00001142 MadeChange = true;
1143 }
1144
1145 return MadeChange;
1146}
1147
Benjamin Kramer59957502012-05-05 12:49:22 +00001148/// isFormingBranchFromSelectProfitable - Returns true if a SelectInst should be
1149/// turned into an explicit branch.
1150static bool isFormingBranchFromSelectProfitable(SelectInst *SI) {
1151 // FIXME: This should use the same heuristics as IfConversion to determine
1152 // whether a select is better represented as a branch. This requires that
1153 // branch probability metadata is preserved for the select, which is not the
1154 // case currently.
1155
1156 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
1157
1158 // If the branch is predicted right, an out of order CPU can avoid blocking on
1159 // the compare. Emit cmovs on compares with a memory operand as branches to
1160 // avoid stalls on the load from memory. If the compare has more than one use
1161 // there's probably another cmov or setcc around so it's not worth emitting a
1162 // branch.
1163 if (!Cmp)
1164 return false;
1165
1166 Value *CmpOp0 = Cmp->getOperand(0);
1167 Value *CmpOp1 = Cmp->getOperand(1);
1168
1169 // We check that the memory operand has one use to avoid uses of the loaded
1170 // value directly after the compare, making branches unprofitable.
1171 return Cmp->hasOneUse() &&
1172 ((isa<LoadInst>(CmpOp0) && CmpOp0->hasOneUse()) ||
1173 (isa<LoadInst>(CmpOp1) && CmpOp1->hasOneUse()));
1174}
1175
1176
Nadav Rotem9f40cb32012-09-02 12:10:19 +00001177/// If we have a SelectInst that will likely profit from branch prediction,
1178/// turn it into a branch.
Benjamin Kramer59957502012-05-05 12:49:22 +00001179bool CodeGenPrepare::OptimizeSelectInst(SelectInst *SI) {
Nadav Rotem9f40cb32012-09-02 12:10:19 +00001180 bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
1181
1182 // Can we convert the 'select' to CF ?
1183 if (DisableSelectToBranch || OptSize || !TLI || VectorCond)
Benjamin Kramer59957502012-05-05 12:49:22 +00001184 return false;
1185
Nadav Rotem9f40cb32012-09-02 12:10:19 +00001186 TargetLowering::SelectSupportKind SelectKind;
1187 if (VectorCond)
1188 SelectKind = TargetLowering::VectorMaskSelect;
1189 else if (SI->getType()->isVectorTy())
1190 SelectKind = TargetLowering::ScalarCondVectorVal;
1191 else
1192 SelectKind = TargetLowering::ScalarValSelect;
1193
1194 // Do we have efficient codegen support for this kind of 'selects' ?
1195 if (TLI->isSelectSupported(SelectKind)) {
1196 // We have efficient codegen support for the select instruction.
1197 // Check if it is profitable to keep this 'select'.
1198 if (!TLI->isPredictableSelectExpensive() ||
1199 !isFormingBranchFromSelectProfitable(SI))
1200 return false;
1201 }
Benjamin Kramer59957502012-05-05 12:49:22 +00001202
1203 ModifiedDT = true;
1204
1205 // First, we split the block containing the select into 2 blocks.
1206 BasicBlock *StartBlock = SI->getParent();
1207 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(SI));
1208 BasicBlock *NextBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
1209
1210 // Create a new block serving as the landing pad for the branch.
1211 BasicBlock *SmallBlock = BasicBlock::Create(SI->getContext(), "select.mid",
1212 NextBlock->getParent(), NextBlock);
1213
1214 // Move the unconditional branch from the block with the select in it into our
1215 // landing pad block.
1216 StartBlock->getTerminator()->eraseFromParent();
1217 BranchInst::Create(NextBlock, SmallBlock);
1218
1219 // Insert the real conditional branch based on the original condition.
1220 BranchInst::Create(NextBlock, SmallBlock, SI->getCondition(), SI);
1221
1222 // The select itself is replaced with a PHI Node.
1223 PHINode *PN = PHINode::Create(SI->getType(), 2, "", NextBlock->begin());
1224 PN->takeName(SI);
1225 PN->addIncoming(SI->getTrueValue(), StartBlock);
1226 PN->addIncoming(SI->getFalseValue(), SmallBlock);
1227 SI->replaceAllUsesWith(PN);
1228 SI->eraseFromParent();
1229
1230 // Instruct OptimizeBlock to skip to the next block.
1231 CurInstIterator = StartBlock->end();
1232 ++NumSelectsExpanded;
1233 return true;
1234}
1235
Cameron Zwarichc0611012011-01-06 02:37:26 +00001236bool CodeGenPrepare::OptimizeInst(Instruction *I) {
Cameron Zwarichc0611012011-01-06 02:37:26 +00001237 if (PHINode *P = dyn_cast<PHINode>(I)) {
1238 // It is possible for very late stage optimizations (such as SimplifyCFG)
1239 // to introduce PHI nodes too late to be cleaned up. If we detect such a
1240 // trivial PHI, go ahead and zap it here.
1241 if (Value *V = SimplifyInstruction(P)) {
1242 P->replaceAllUsesWith(V);
1243 P->eraseFromParent();
1244 ++NumPHIsElim;
Chris Lattner1a8943a2011-01-15 07:29:01 +00001245 return true;
Cameron Zwarichc0611012011-01-06 02:37:26 +00001246 }
Chris Lattner1a8943a2011-01-15 07:29:01 +00001247 return false;
1248 }
Nadav Rotema94d6e82012-07-24 10:51:42 +00001249
Chris Lattner1a8943a2011-01-15 07:29:01 +00001250 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Cameron Zwarichc0611012011-01-06 02:37:26 +00001251 // If the source of the cast is a constant, then this should have
1252 // already been constant folded. The only reason NOT to constant fold
1253 // it is if something (e.g. LSR) was careful to place the constant
1254 // evaluation in a block other than then one that uses it (e.g. to hoist
1255 // the address of globals out of a loop). If this is the case, we don't
1256 // want to forward-subst the cast.
1257 if (isa<Constant>(CI->getOperand(0)))
1258 return false;
1259
Chris Lattner1a8943a2011-01-15 07:29:01 +00001260 if (TLI && OptimizeNoopCopyExpression(CI, *TLI))
1261 return true;
Cameron Zwarichc0611012011-01-06 02:37:26 +00001262
Chris Lattner1a8943a2011-01-15 07:29:01 +00001263 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
1264 bool MadeChange = MoveExtToFormExtLoad(I);
1265 return MadeChange | OptimizeExtUses(I);
Cameron Zwarichc0611012011-01-06 02:37:26 +00001266 }
Chris Lattner1a8943a2011-01-15 07:29:01 +00001267 return false;
1268 }
Nadav Rotema94d6e82012-07-24 10:51:42 +00001269
Chris Lattner1a8943a2011-01-15 07:29:01 +00001270 if (CmpInst *CI = dyn_cast<CmpInst>(I))
1271 return OptimizeCmpExpression(CI);
Nadav Rotema94d6e82012-07-24 10:51:42 +00001272
Chris Lattner1a8943a2011-01-15 07:29:01 +00001273 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Cameron Zwarichc0611012011-01-06 02:37:26 +00001274 if (TLI)
Chris Lattner1a8943a2011-01-15 07:29:01 +00001275 return OptimizeMemoryInst(I, I->getOperand(0), LI->getType());
1276 return false;
1277 }
Nadav Rotema94d6e82012-07-24 10:51:42 +00001278
Chris Lattner1a8943a2011-01-15 07:29:01 +00001279 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Cameron Zwarichc0611012011-01-06 02:37:26 +00001280 if (TLI)
Chris Lattner1a8943a2011-01-15 07:29:01 +00001281 return OptimizeMemoryInst(I, SI->getOperand(1),
1282 SI->getOperand(0)->getType());
1283 return false;
1284 }
Nadav Rotema94d6e82012-07-24 10:51:42 +00001285
Chris Lattner1a8943a2011-01-15 07:29:01 +00001286 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Cameron Zwarich865ae1a2011-01-06 02:44:52 +00001287 if (GEPI->hasAllZeroIndices()) {
1288 /// The GEP operand must be a pointer, so must its result -> BitCast
1289 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
1290 GEPI->getName(), GEPI);
1291 GEPI->replaceAllUsesWith(NC);
1292 GEPI->eraseFromParent();
1293 ++NumGEPsElim;
Cameron Zwarich865ae1a2011-01-06 02:44:52 +00001294 OptimizeInst(NC);
Chris Lattner1a8943a2011-01-15 07:29:01 +00001295 return true;
Cameron Zwarich865ae1a2011-01-06 02:44:52 +00001296 }
Chris Lattner1a8943a2011-01-15 07:29:01 +00001297 return false;
Cameron Zwarichc0611012011-01-06 02:37:26 +00001298 }
Nadav Rotema94d6e82012-07-24 10:51:42 +00001299
Chris Lattner1a8943a2011-01-15 07:29:01 +00001300 if (CallInst *CI = dyn_cast<CallInst>(I))
1301 return OptimizeCallInst(CI);
Cameron Zwarichc0611012011-01-06 02:37:26 +00001302
Evan Cheng485fafc2011-03-21 01:19:09 +00001303 if (ReturnInst *RI = dyn_cast<ReturnInst>(I))
1304 return DupRetToEnableTailCallOpts(RI);
1305
Benjamin Kramer59957502012-05-05 12:49:22 +00001306 if (SelectInst *SI = dyn_cast<SelectInst>(I))
1307 return OptimizeSelectInst(SI);
1308
Chris Lattner1a8943a2011-01-15 07:29:01 +00001309 return false;
Cameron Zwarichc0611012011-01-06 02:37:26 +00001310}
1311
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001312// In this pass we look for GEP and cast instructions that are used
1313// across basic blocks and rewrite them to improve basic-block-at-a-time
1314// selection.
1315bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
Cameron Zwarich8c3527e2011-01-06 00:42:50 +00001316 SunkAddrs.clear();
Cameron Zwarich56e37932011-03-02 03:31:46 +00001317 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001318
Chris Lattner75796092011-01-15 07:14:54 +00001319 CurInstIterator = BB.begin();
Chris Lattner94e8e0c2011-01-15 07:25:29 +00001320 for (BasicBlock::iterator E = BB.end(); CurInstIterator != E; )
1321 MadeChange |= OptimizeInst(CurInstIterator++);
Eric Christopher692bf6b2008-09-24 05:32:41 +00001322
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001323 return MadeChange;
1324}
Devang Patelf56ea612011-08-18 00:50:51 +00001325
1326// llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotema94d6e82012-07-24 10:51:42 +00001327// handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patelf56ea612011-08-18 00:50:51 +00001328// find a node corresponding to the value.
1329bool CodeGenPrepare::PlaceDbgValues(Function &F) {
1330 bool MadeChange = false;
1331 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
1332 Instruction *PrevNonDbgInst = NULL;
1333 for (BasicBlock::iterator BI = I->begin(), BE = I->end(); BI != BE;) {
1334 Instruction *Insn = BI; ++BI;
1335 DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
1336 if (!DVI) {
1337 PrevNonDbgInst = Insn;
1338 continue;
1339 }
1340
1341 Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
1342 if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
1343 DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
1344 DVI->removeFromParent();
1345 if (isa<PHINode>(VI))
1346 DVI->insertBefore(VI->getParent()->getFirstInsertionPt());
1347 else
1348 DVI->insertAfter(VI);
1349 MadeChange = true;
1350 ++NumDbgValueMoved;
1351 }
1352 }
1353 }
1354 return MadeChange;
1355}