blob: 2b42c75d14d744966f59c1b5c1d90b80ca243bee [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"
Hans Wennborg93ba1332012-09-19 07:48:16 +000021#include "llvm/GlobalVariable.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000022#include "llvm/IRBuilder.h"
Evan Cheng9bf12b52008-02-26 02:42:37 +000023#include "llvm/InlineAsm.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000024#include "llvm/Instructions.h"
Dale Johannesen6aae1d62009-03-26 01:15:07 +000025#include "llvm/IntrinsicInst.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000026#include "llvm/Pass.h"
Chris Lattnerdd77df32007-04-13 20:30:56 +000027#include "llvm/ADT/DenseMap.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000028#include "llvm/ADT/SmallSet.h"
Jakob Stoklund Olesen7eb589d2010-09-30 20:51:52 +000029#include "llvm/ADT/Statistic.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000030#include "llvm/Analysis/Dominators.h"
Richard Smithc1f7ae12012-10-23 06:19:46 +000031#include "llvm/Analysis/DominatorInternals.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000032#include "llvm/Analysis/InstructionSimplify.h"
33#include "llvm/Analysis/ProfileInfo.h"
Dan Gohman03ce0422009-02-13 17:45:12 +000034#include "llvm/Assembly/Writer.h"
Evan Cheng9bf12b52008-02-26 02:42:37 +000035#include "llvm/Support/CallSite.h"
Evan Chenge1bcb442010-08-17 01:34:49 +000036#include "llvm/Support/CommandLine.h"
Evan Chengbdcb7262007-12-05 23:58:20 +000037#include "llvm/Support/Debug.h"
Chris Lattnerdd77df32007-04-13 20:30:56 +000038#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner088a1e82008-11-25 04:42:10 +000039#include "llvm/Support/PatternMatch.h"
Chris Lattner94e8e0c2011-01-15 07:25:29 +000040#include "llvm/Support/ValueHandle.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000041#include "llvm/Support/raw_ostream.h"
Micah Villmow3574eca2012-10-08 16:38:25 +000042#include "llvm/DataLayout.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000043#include "llvm/Target/TargetLibraryInfo.h"
44#include "llvm/Target/TargetLowering.h"
45#include "llvm/Transforms/Utils/AddrModeMatcher.h"
46#include "llvm/Transforms/Utils/BasicBlockUtils.h"
47#include "llvm/Transforms/Utils/BuildLibCalls.h"
Preston Gurd2e2efd92012-09-04 18:22:17 +000048#include "llvm/Transforms/Utils/BypassSlowDivision.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000049#include "llvm/Transforms/Utils/Local.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000050using namespace llvm;
Chris Lattner088a1e82008-11-25 04:42:10 +000051using namespace llvm::PatternMatch;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000052
Cameron Zwarich31ff1332011-01-05 17:27:27 +000053STATISTIC(NumBlocksElim, "Number of blocks eliminated");
Evan Cheng485fafc2011-03-21 01:19:09 +000054STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated");
55STATISTIC(NumGEPsElim, "Number of GEPs converted to casts");
Cameron Zwarich31ff1332011-01-05 17:27:27 +000056STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "
57 "sunken Cmps");
58STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
59 "of sunken Casts");
60STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "
61 "computations were sunk");
Evan Cheng485fafc2011-03-21 01:19:09 +000062STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads");
63STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized");
64STATISTIC(NumRetsDup, "Number of return instructions duplicated");
Devang Patelf56ea612011-08-18 00:50:51 +000065STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved");
Benjamin Kramer59957502012-05-05 12:49:22 +000066STATISTIC(NumSelectsExpanded, "Number of selects turned into branches");
Jakob Stoklund Olesen7eb589d2010-09-30 20:51:52 +000067
Cameron Zwarich899eaa32011-03-11 21:52:04 +000068static cl::opt<bool> DisableBranchOpts(
69 "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
70 cl::desc("Disable branch optimizations in CodeGenPrepare"));
71
Benjamin Kramer77c4ef82012-05-06 14:25:16 +000072static cl::opt<bool> DisableSelectToBranch(
73 "disable-cgp-select2branch", cl::Hidden, cl::init(false),
74 cl::desc("Disable select to branch conversion."));
Benjamin Kramer59957502012-05-05 12:49:22 +000075
Eric Christopher692bf6b2008-09-24 05:32:41 +000076namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +000077 class CodeGenPrepare : public FunctionPass {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000078 /// TLI - Keep a pointer of a TargetLowering to consult for determining
79 /// transformation profitability.
80 const TargetLowering *TLI;
Chad Rosier618c1db2011-12-01 03:08:23 +000081 const TargetLibraryInfo *TLInfo;
Cameron Zwarich80f6a502011-01-08 17:01:52 +000082 DominatorTree *DT;
Evan Cheng04149f72009-12-17 09:39:49 +000083 ProfileInfo *PFI;
Nadav Rotema94d6e82012-07-24 10:51:42 +000084
Chris Lattner75796092011-01-15 07:14:54 +000085 /// CurInstIterator - As we scan instructions optimizing them, this is the
86 /// next instruction to optimize. Xforms that can invalidate this should
87 /// update it.
88 BasicBlock::iterator CurInstIterator;
Evan Chengab631522008-12-19 18:03:11 +000089
Evan Cheng485fafc2011-03-21 01:19:09 +000090 /// Keeps track of non-local addresses that have been sunk into a block.
91 /// This allows us to avoid inserting duplicate code for blocks with
92 /// multiple load/stores of the same address.
Cameron Zwarich8c3527e2011-01-06 00:42:50 +000093 DenseMap<Value*, Value*> SunkAddrs;
94
Devang Patel52e37df2011-03-24 15:35:25 +000095 /// ModifiedDT - If CFG is modified in anyway, dominator tree may need to
Evan Cheng485fafc2011-03-21 01:19:09 +000096 /// be updated.
Devang Patel52e37df2011-03-24 15:35:25 +000097 bool ModifiedDT;
Evan Cheng485fafc2011-03-21 01:19:09 +000098
Benjamin Kramer59957502012-05-05 12:49:22 +000099 /// OptSize - True if optimizing for size.
100 bool OptSize;
101
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000102 public:
Nick Lewyckyecd94c82007-05-06 13:37:16 +0000103 static char ID; // Pass identification, replacement for typeid
Dan Gohmanc2bbfc12007-08-01 15:32:29 +0000104 explicit CodeGenPrepare(const TargetLowering *tli = 0)
Owen Anderson081c34b2010-10-19 17:21:58 +0000105 : FunctionPass(ID), TLI(tli) {
106 initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
107 }
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000108 bool runOnFunction(Function &F);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000109
Andreas Neustifterad809812009-09-16 09:26:52 +0000110 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Cameron Zwarich80f6a502011-01-08 17:01:52 +0000111 AU.addPreserved<DominatorTree>();
Andreas Neustifterad809812009-09-16 09:26:52 +0000112 AU.addPreserved<ProfileInfo>();
Chad Rosier618c1db2011-12-01 03:08:23 +0000113 AU.addRequired<TargetLibraryInfo>();
Andreas Neustifterad809812009-09-16 09:26:52 +0000114 }
115
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000116 private:
Nadav Rotem3e883732012-08-14 05:19:07 +0000117 bool EliminateFallThrough(Function &F);
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000118 bool EliminateMostlyEmptyBlocks(Function &F);
119 bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
120 void EliminateMostlyEmptyBlock(BasicBlock *BB);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000121 bool OptimizeBlock(BasicBlock &BB);
Cameron Zwarichc0611012011-01-06 02:37:26 +0000122 bool OptimizeInst(Instruction *I);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000123 bool OptimizeMemoryInst(Instruction *I, Value *Addr, Type *AccessTy);
Chris Lattner75796092011-01-15 07:14:54 +0000124 bool OptimizeInlineAsmInst(CallInst *CS);
Eric Christopher040056f2010-03-11 02:41:03 +0000125 bool OptimizeCallInst(CallInst *CI);
Dan Gohmanb00f2362009-10-16 20:59:35 +0000126 bool MoveExtToFormExtLoad(Instruction *I);
Evan Chengbdcb7262007-12-05 23:58:20 +0000127 bool OptimizeExtUses(Instruction *I);
Benjamin Kramer59957502012-05-05 12:49:22 +0000128 bool OptimizeSelectInst(SelectInst *SI);
Evan Cheng485fafc2011-03-21 01:19:09 +0000129 bool DupRetToEnableTailCallOpts(ReturnInst *RI);
Devang Patelf56ea612011-08-18 00:50:51 +0000130 bool PlaceDbgValues(Function &F);
Hans Wennborg93ba1332012-09-19 07:48:16 +0000131 bool ConvertLoadToSwitch(LoadInst *LI);
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>();
Bill Wendling67658342012-10-09 07:45:08 +0000153 OptSize = F.getFnAttributes().hasAttribute(Attributes::OptimizeForSize);
Evan Cheng485fafc2011-03-21 01:19:09 +0000154
Preston Gurd2e2efd92012-09-04 18:22:17 +0000155 /// This optimization identifies DIV instructions that can be
156 /// profitably bypassed and carried out with a shorter, faster divide.
157 if (TLI && TLI->isSlowDivBypassed()) {
Preston Gurd8d662b52012-10-04 21:33:40 +0000158 const DenseMap<unsigned int, unsigned int> &BypassWidths =
159 TLI->getBypassSlowDivWidths();
Evan Cheng911908d2012-09-14 21:25:34 +0000160 for (Function::iterator I = F.begin(); I != F.end(); I++)
Preston Gurd8d662b52012-10-04 21:33:40 +0000161 EverMadeChange |= bypassSlowDivision(F, I, BypassWidths);
Preston Gurd2e2efd92012-09-04 18:22:17 +0000162 }
163
164 // Eliminate blocks that contain only PHI nodes and an
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000165 // unconditional branch.
166 EverMadeChange |= EliminateMostlyEmptyBlocks(F);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000167
Devang Patelf56ea612011-08-18 00:50:51 +0000168 // llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotema94d6e82012-07-24 10:51:42 +0000169 // handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patelf56ea612011-08-18 00:50:51 +0000170 // find a node corresponding to the value.
171 EverMadeChange |= PlaceDbgValues(F);
172
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000173 bool MadeChange = true;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000174 while (MadeChange) {
175 MadeChange = false;
Hans Wennborg93ba1332012-09-19 07:48:16 +0000176 for (Function::iterator I = F.begin(); I != F.end(); ) {
Evan Cheng485fafc2011-03-21 01:19:09 +0000177 BasicBlock *BB = I++;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000178 MadeChange |= OptimizeBlock(*BB);
Evan Cheng485fafc2011-03-21 01:19:09 +0000179 }
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000180 EverMadeChange |= MadeChange;
181 }
Cameron Zwarich8c3527e2011-01-06 00:42:50 +0000182
183 SunkAddrs.clear();
184
Cameron Zwarich899eaa32011-03-11 21:52:04 +0000185 if (!DisableBranchOpts) {
186 MadeChange = false;
Bill Wendlinge3e394d2012-03-04 10:46:01 +0000187 SmallPtrSet<BasicBlock*, 8> WorkList;
188 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
189 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
Frits van Bommel5649ba72011-05-22 16:24:18 +0000190 MadeChange |= ConstantFoldTerminator(BB, true);
Bill Wendlinge3e394d2012-03-04 10:46:01 +0000191 if (!MadeChange) continue;
192
193 for (SmallVectorImpl<BasicBlock*>::iterator
194 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
195 if (pred_begin(*II) == pred_end(*II))
196 WorkList.insert(*II);
197 }
198
Bill Wendling8dd2e5b2012-08-15 21:18:10 +0000199 for (SmallPtrSet<BasicBlock*, 8>::iterator
200 I = WorkList.begin(), E = WorkList.end(); I != E; ++I)
201 DeleteDeadBlock(*I);
Cameron Zwarich899eaa32011-03-11 21:52:04 +0000202
Nadav Rotem3e883732012-08-14 05:19:07 +0000203 // Merge pairs of basic blocks with unconditional branches, connected by
204 // a single edge.
205 if (EverMadeChange || MadeChange)
206 MadeChange |= EliminateFallThrough(F);
207
Evan Cheng485fafc2011-03-21 01:19:09 +0000208 if (MadeChange)
Devang Patel52e37df2011-03-24 15:35:25 +0000209 ModifiedDT = true;
Cameron Zwarich899eaa32011-03-11 21:52:04 +0000210 EverMadeChange |= MadeChange;
211 }
212
Devang Patel52e37df2011-03-24 15:35:25 +0000213 if (ModifiedDT && DT)
Evan Cheng485fafc2011-03-21 01:19:09 +0000214 DT->DT->recalculate(F);
215
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000216 return EverMadeChange;
217}
218
Nadav Rotem3e883732012-08-14 05:19:07 +0000219/// EliminateFallThrough - Merge basic blocks which are connected
220/// by a single edge, where one of the basic blocks has a single successor
221/// pointing to the other basic block, which has a single predecessor.
222bool CodeGenPrepare::EliminateFallThrough(Function &F) {
223 bool Changed = false;
224 // Scan all of the blocks in the function, except for the entry block.
225 for (Function::iterator I = ++F.begin(), E = F.end(); I != E; ) {
226 BasicBlock *BB = I++;
227 // If the destination block has a single pred, then this is a trivial
228 // edge, just collapse it.
229 BasicBlock *SinglePred = BB->getSinglePredecessor();
230
Evan Cheng46597072012-09-28 23:58:57 +0000231 // Don't merge if BB's address is taken.
232 if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue;
Nadav Rotem3e883732012-08-14 05:19:07 +0000233
234 BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
235 if (Term && !Term->isConditional()) {
236 Changed = true;
Michael Liao787ed032012-08-21 05:55:22 +0000237 DEBUG(dbgs() << "To merge:\n"<< *SinglePred << "\n\n\n");
Nadav Rotem3e883732012-08-14 05:19:07 +0000238 // Remember if SinglePred was the entry block of the function.
239 // If so, we will need to move BB back to the entry position.
240 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
241 MergeBasicBlockIntoOnlyPred(BB, this);
242
243 if (isEntry && BB != &BB->getParent()->getEntryBlock())
244 BB->moveBefore(&BB->getParent()->getEntryBlock());
245
246 // We have erased a block. Update the iterator.
247 I = BB;
Nadav Rotem3e883732012-08-14 05:19:07 +0000248 }
249 }
250 return Changed;
251}
252
Dale Johannesen2d697242009-03-27 01:13:37 +0000253/// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes,
254/// debug info directives, and an unconditional branch. Passes before isel
255/// (e.g. LSR/loopsimplify) often split edges in ways that are non-optimal for
256/// isel. Start by eliminating these blocks so we can split them the way we
257/// want them.
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000258bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
259 bool MadeChange = false;
260 // Note that this intentionally skips the entry block.
261 for (Function::iterator I = ++F.begin(), E = F.end(); I != E; ) {
262 BasicBlock *BB = I++;
263
264 // If this block doesn't end with an uncond branch, ignore it.
265 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
266 if (!BI || !BI->isUnconditional())
267 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000268
Dale Johannesen2d697242009-03-27 01:13:37 +0000269 // If the instruction before the branch (skipping debug info) isn't a phi
270 // node, then other stuff is happening here.
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000271 BasicBlock::iterator BBI = BI;
272 if (BBI != BB->begin()) {
273 --BBI;
Dale Johannesen2d697242009-03-27 01:13:37 +0000274 while (isa<DbgInfoIntrinsic>(BBI)) {
275 if (BBI == BB->begin())
276 break;
277 --BBI;
278 }
279 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
280 continue;
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000281 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000282
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000283 // Do not break infinite loops.
284 BasicBlock *DestBB = BI->getSuccessor(0);
285 if (DestBB == BB)
286 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000287
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000288 if (!CanMergeBlocks(BB, DestBB))
289 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000290
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000291 EliminateMostlyEmptyBlock(BB);
292 MadeChange = true;
293 }
294 return MadeChange;
295}
296
297/// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
298/// single uncond branch between them, and BB contains no other non-phi
299/// instructions.
300bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
301 const BasicBlock *DestBB) const {
302 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
303 // the successor. If there are more complex condition (e.g. preheaders),
304 // don't mess around with them.
305 BasicBlock::const_iterator BBI = BB->begin();
306 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
Gabor Greif60ad7812010-03-25 23:06:16 +0000307 for (Value::const_use_iterator UI = PN->use_begin(), E = PN->use_end();
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000308 UI != E; ++UI) {
309 const Instruction *User = cast<Instruction>(*UI);
310 if (User->getParent() != DestBB || !isa<PHINode>(User))
311 return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000312 // If User is inside DestBB block and it is a PHINode then check
313 // incoming value. If incoming value is not from BB then this is
Devang Patel75abc1e2007-04-25 00:37:04 +0000314 // a complex condition (e.g. preheaders) we want to avoid here.
315 if (User->getParent() == DestBB) {
316 if (const PHINode *UPN = dyn_cast<PHINode>(User))
317 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
318 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
319 if (Insn && Insn->getParent() == BB &&
320 Insn->getParent() != UPN->getIncomingBlock(I))
321 return false;
322 }
323 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000324 }
325 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000326
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000327 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
328 // and DestBB may have conflicting incoming values for the block. If so, we
329 // can't merge the block.
330 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
331 if (!DestBBPN) return true; // no conflict.
Eric Christopher692bf6b2008-09-24 05:32:41 +0000332
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000333 // Collect the preds of BB.
Chris Lattnerf67f73a2007-11-06 22:07:40 +0000334 SmallPtrSet<const BasicBlock*, 16> BBPreds;
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000335 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
336 // It is faster to get preds from a PHI than with pred_iterator.
337 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
338 BBPreds.insert(BBPN->getIncomingBlock(i));
339 } else {
340 BBPreds.insert(pred_begin(BB), pred_end(BB));
341 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000342
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000343 // Walk the preds of DestBB.
344 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
345 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
346 if (BBPreds.count(Pred)) { // Common predecessor?
347 BBI = DestBB->begin();
348 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
349 const Value *V1 = PN->getIncomingValueForBlock(Pred);
350 const Value *V2 = PN->getIncomingValueForBlock(BB);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000351
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000352 // If V2 is a phi node in BB, look up what the mapped value will be.
353 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
354 if (V2PN->getParent() == BB)
355 V2 = V2PN->getIncomingValueForBlock(Pred);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000356
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000357 // If there is a conflict, bail out.
358 if (V1 != V2) return false;
359 }
360 }
361 }
362
363 return true;
364}
365
366
367/// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
368/// an unconditional branch in it.
369void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
370 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
371 BasicBlock *DestBB = BI->getSuccessor(0);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000372
David Greene68d67fd2010-01-05 01:27:11 +0000373 DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000374
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000375 // If the destination block has a single pred, then this is a trivial edge,
376 // just collapse it.
Chris Lattner9918fb52008-11-27 19:29:14 +0000377 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
Chris Lattnerf5102a02008-11-28 19:54:49 +0000378 if (SinglePred != DestBB) {
379 // Remember if SinglePred was the entry block of the function. If so, we
380 // will need to move BB back to the entry position.
381 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Andreas Neustifterad809812009-09-16 09:26:52 +0000382 MergeBasicBlockIntoOnlyPred(DestBB, this);
Chris Lattner9918fb52008-11-27 19:29:14 +0000383
Chris Lattnerf5102a02008-11-28 19:54:49 +0000384 if (isEntry && BB != &BB->getParent()->getEntryBlock())
385 BB->moveBefore(&BB->getParent()->getEntryBlock());
Nadav Rotema94d6e82012-07-24 10:51:42 +0000386
David Greene68d67fd2010-01-05 01:27:11 +0000387 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerf5102a02008-11-28 19:54:49 +0000388 return;
389 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000390 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000391
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000392 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
393 // to handle the new incoming edges it is about to have.
394 PHINode *PN;
395 for (BasicBlock::iterator BBI = DestBB->begin();
396 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
397 // Remove the incoming value for BB, and remember it.
398 Value *InVal = PN->removeIncomingValue(BB, false);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000399
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000400 // Two options: either the InVal is a phi node defined in BB or it is some
401 // value that dominates BB.
402 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
403 if (InValPhi && InValPhi->getParent() == BB) {
404 // Add all of the input values of the input PHI as inputs of this phi.
405 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
406 PN->addIncoming(InValPhi->getIncomingValue(i),
407 InValPhi->getIncomingBlock(i));
408 } else {
409 // Otherwise, add one instance of the dominating value for each edge that
410 // we will be adding.
411 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
412 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
413 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
414 } else {
415 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
416 PN->addIncoming(InVal, *PI);
417 }
418 }
419 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000420
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000421 // The PHIs are now updated, change everything that refers to BB to use
422 // DestBB and remove BB.
423 BB->replaceAllUsesWith(DestBB);
Devang Patel52e37df2011-03-24 15:35:25 +0000424 if (DT && !ModifiedDT) {
Cameron Zwarich80f6a502011-01-08 17:01:52 +0000425 BasicBlock *BBIDom = DT->getNode(BB)->getIDom()->getBlock();
426 BasicBlock *DestBBIDom = DT->getNode(DestBB)->getIDom()->getBlock();
427 BasicBlock *NewIDom = DT->findNearestCommonDominator(BBIDom, DestBBIDom);
428 DT->changeImmediateDominator(DestBB, NewIDom);
429 DT->eraseNode(BB);
430 }
Evan Cheng04149f72009-12-17 09:39:49 +0000431 if (PFI) {
432 PFI->replaceAllUses(BB, DestBB);
433 PFI->removeEdge(ProfileInfo::getEdge(BB, DestBB));
Andreas Neustifterad809812009-09-16 09:26:52 +0000434 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000435 BB->eraseFromParent();
Cameron Zwarich31ff1332011-01-05 17:27:27 +0000436 ++NumBlocksElim;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000437
David Greene68d67fd2010-01-05 01:27:11 +0000438 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000439}
440
Chris Lattnerdd77df32007-04-13 20:30:56 +0000441/// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
Dan Gohmana119de82009-06-14 23:30:43 +0000442/// copy (e.g. it's casting from one pointer type to another, i32->i8 on PPC),
443/// sink it into user blocks to reduce the number of virtual
Dale Johannesence0b2372007-06-12 16:50:17 +0000444/// registers that must be created and coalesced.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000445///
446/// Return true if any changes are made.
Chris Lattner85fa13c2008-11-24 22:44:16 +0000447///
Chris Lattnerdd77df32007-04-13 20:30:56 +0000448static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
Eric Christopher692bf6b2008-09-24 05:32:41 +0000449 // If this is a noop copy,
Owen Andersone50ed302009-08-10 22:56:29 +0000450 EVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
451 EVT DstVT = TLI.getValueType(CI->getType());
Eric Christopher692bf6b2008-09-24 05:32:41 +0000452
Chris Lattnerdd77df32007-04-13 20:30:56 +0000453 // This is an fp<->int conversion?
Duncan Sands83ec4b62008-06-06 12:08:01 +0000454 if (SrcVT.isInteger() != DstVT.isInteger())
Chris Lattnerdd77df32007-04-13 20:30:56 +0000455 return false;
Duncan Sands8e4eb092008-06-08 20:54:56 +0000456
Chris Lattnerdd77df32007-04-13 20:30:56 +0000457 // If this is an extension, it will be a zero or sign extension, which
458 // isn't a noop.
Duncan Sands8e4eb092008-06-08 20:54:56 +0000459 if (SrcVT.bitsLT(DstVT)) return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000460
Chris Lattnerdd77df32007-04-13 20:30:56 +0000461 // If these values will be promoted, find out what they will be promoted
462 // to. This helps us consider truncates on PPC as noop copies when they
463 // are.
Nadav Rotem0ccc12a2011-05-29 08:10:47 +0000464 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
465 TargetLowering::TypePromoteInteger)
Owen Anderson23b9b192009-08-12 00:36:31 +0000466 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
Nadav Rotem0ccc12a2011-05-29 08:10:47 +0000467 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
468 TargetLowering::TypePromoteInteger)
Owen Anderson23b9b192009-08-12 00:36:31 +0000469 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000470
Chris Lattnerdd77df32007-04-13 20:30:56 +0000471 // If, after promotion, these are the same types, this is a noop copy.
472 if (SrcVT != DstVT)
473 return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000474
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000475 BasicBlock *DefBB = CI->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000476
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000477 /// InsertedCasts - Only insert a cast in each block once.
Dale Johannesence0b2372007-06-12 16:50:17 +0000478 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000479
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000480 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000481 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000482 UI != E; ) {
483 Use &TheUse = UI.getUse();
484 Instruction *User = cast<Instruction>(*UI);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000485
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000486 // Figure out which BB this cast is used in. For PHI's this is the
487 // appropriate predecessor block.
488 BasicBlock *UserBB = User->getParent();
489 if (PHINode *PN = dyn_cast<PHINode>(User)) {
Gabor Greifa36791d2009-01-23 19:40:15 +0000490 UserBB = PN->getIncomingBlock(UI);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000491 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000492
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000493 // Preincrement use iterator so we don't invalidate it.
494 ++UI;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000495
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000496 // If this user is in the same block as the cast, don't change the cast.
497 if (UserBB == DefBB) continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000498
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000499 // If we have already inserted a cast into this block, use it.
500 CastInst *&InsertedCast = InsertedCasts[UserBB];
501
502 if (!InsertedCast) {
Bill Wendling5b6f42f2011-08-16 20:45:24 +0000503 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000504 InsertedCast =
505 CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000506 InsertPt);
507 MadeChange = true;
508 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000509
Dale Johannesence0b2372007-06-12 16:50:17 +0000510 // Replace a use of the cast with a use of the new cast.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000511 TheUse = InsertedCast;
Cameron Zwarich31ff1332011-01-05 17:27:27 +0000512 ++NumCastUses;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000513 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000514
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000515 // If we removed all uses, nuke the cast.
Duncan Sandse0038132008-01-20 16:51:46 +0000516 if (CI->use_empty()) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000517 CI->eraseFromParent();
Duncan Sandse0038132008-01-20 16:51:46 +0000518 MadeChange = true;
519 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000520
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000521 return MadeChange;
522}
523
Eric Christopher692bf6b2008-09-24 05:32:41 +0000524/// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
Dale Johannesence0b2372007-06-12 16:50:17 +0000525/// the number of virtual registers that must be created and coalesced. This is
Chris Lattner684b22d2007-08-02 16:53:43 +0000526/// a clear win except on targets with multiple condition code registers
527/// (PowerPC), where it might lose; some adjustment may be wanted there.
Dale Johannesence0b2372007-06-12 16:50:17 +0000528///
529/// Return true if any changes are made.
Chris Lattner85fa13c2008-11-24 22:44:16 +0000530static bool OptimizeCmpExpression(CmpInst *CI) {
Dale Johannesence0b2372007-06-12 16:50:17 +0000531 BasicBlock *DefBB = CI->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000532
Dale Johannesence0b2372007-06-12 16:50:17 +0000533 /// InsertedCmp - Only insert a cmp in each block once.
534 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000535
Dale Johannesence0b2372007-06-12 16:50:17 +0000536 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000537 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
Dale Johannesence0b2372007-06-12 16:50:17 +0000538 UI != E; ) {
539 Use &TheUse = UI.getUse();
540 Instruction *User = cast<Instruction>(*UI);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000541
Dale Johannesence0b2372007-06-12 16:50:17 +0000542 // Preincrement use iterator so we don't invalidate it.
543 ++UI;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000544
Dale Johannesence0b2372007-06-12 16:50:17 +0000545 // Don't bother for PHI nodes.
546 if (isa<PHINode>(User))
547 continue;
548
549 // Figure out which BB this cmp is used in.
550 BasicBlock *UserBB = User->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000551
Dale Johannesence0b2372007-06-12 16:50:17 +0000552 // If this user is in the same block as the cmp, don't change the cmp.
553 if (UserBB == DefBB) continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000554
Dale Johannesence0b2372007-06-12 16:50:17 +0000555 // If we have already inserted a cmp into this block, use it.
556 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
557
558 if (!InsertedCmp) {
Bill Wendling5b6f42f2011-08-16 20:45:24 +0000559 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000560 InsertedCmp =
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000561 CmpInst::Create(CI->getOpcode(),
Owen Anderson333c4002009-07-09 23:48:35 +0000562 CI->getPredicate(), CI->getOperand(0),
Dale Johannesence0b2372007-06-12 16:50:17 +0000563 CI->getOperand(1), "", InsertPt);
564 MadeChange = true;
565 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000566
Dale Johannesence0b2372007-06-12 16:50:17 +0000567 // Replace a use of the cmp with a use of the new cmp.
568 TheUse = InsertedCmp;
Cameron Zwarich31ff1332011-01-05 17:27:27 +0000569 ++NumCmpUses;
Dale Johannesence0b2372007-06-12 16:50:17 +0000570 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000571
Dale Johannesence0b2372007-06-12 16:50:17 +0000572 // If we removed all uses, nuke the cmp.
573 if (CI->use_empty())
574 CI->eraseFromParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000575
Dale Johannesence0b2372007-06-12 16:50:17 +0000576 return MadeChange;
577}
578
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000579namespace {
580class CodeGenPrepareFortifiedLibCalls : public SimplifyFortifiedLibCalls {
581protected:
582 void replaceCall(Value *With) {
583 CI->replaceAllUsesWith(With);
584 CI->eraseFromParent();
585 }
586 bool isFoldable(unsigned SizeCIOp, unsigned, bool) const {
Gabor Greifa6aac4c2010-07-16 09:38:02 +0000587 if (ConstantInt *SizeCI =
588 dyn_cast<ConstantInt>(CI->getArgOperand(SizeCIOp)))
589 return SizeCI->isAllOnesValue();
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000590 return false;
591 }
592};
593} // end anonymous namespace
594
Eric Christopher040056f2010-03-11 02:41:03 +0000595bool CodeGenPrepare::OptimizeCallInst(CallInst *CI) {
Chris Lattner75796092011-01-15 07:14:54 +0000596 BasicBlock *BB = CI->getParent();
Nadav Rotema94d6e82012-07-24 10:51:42 +0000597
Chris Lattner75796092011-01-15 07:14:54 +0000598 // Lower inline assembly if we can.
599 // If we found an inline asm expession, and if the target knows how to
600 // lower it to normal LLVM code, do so now.
601 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
602 if (TLI->ExpandInlineAsm(CI)) {
603 // Avoid invalidating the iterator.
604 CurInstIterator = BB->begin();
605 // Avoid processing instructions out of order, which could cause
606 // reuse before a value is defined.
607 SunkAddrs.clear();
608 return true;
609 }
610 // Sink address computing for memory operands into the block.
611 if (OptimizeInlineAsmInst(CI))
612 return true;
613 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000614
Eric Christopher040056f2010-03-11 02:41:03 +0000615 // Lower all uses of llvm.objectsize.*
616 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
617 if (II && II->getIntrinsicID() == Intrinsic::objectsize) {
Gabor Greifde9f5452010-06-24 00:44:01 +0000618 bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000619 Type *ReturnTy = CI->getType();
Nadav Rotema94d6e82012-07-24 10:51:42 +0000620 Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
621
Chris Lattner94e8e0c2011-01-15 07:25:29 +0000622 // Substituting this can cause recursive simplifications, which can
623 // invalidate our iterator. Use a WeakVH to hold onto it in case this
624 // happens.
625 WeakVH IterHandle(CurInstIterator);
Nadav Rotema94d6e82012-07-24 10:51:42 +0000626
Micah Villmow3574eca2012-10-08 16:38:25 +0000627 replaceAndRecursivelySimplify(CI, RetVal, TLI ? TLI->getDataLayout() : 0,
Chandler Carruth6b980542012-03-24 21:11:24 +0000628 TLInfo, ModifiedDT ? 0 : DT);
Chris Lattner94e8e0c2011-01-15 07:25:29 +0000629
630 // If the iterator instruction was recursively deleted, start over at the
631 // start of the block.
Chris Lattner435b4d22011-01-18 20:53:04 +0000632 if (IterHandle != CurInstIterator) {
Chris Lattner94e8e0c2011-01-15 07:25:29 +0000633 CurInstIterator = BB->begin();
Chris Lattner435b4d22011-01-18 20:53:04 +0000634 SunkAddrs.clear();
635 }
Eric Christopher040056f2010-03-11 02:41:03 +0000636 return true;
637 }
638
Pete Cooperf210b682012-03-13 20:59:56 +0000639 if (II && TLI) {
640 SmallVector<Value*, 2> PtrOps;
641 Type *AccessTy;
642 if (TLI->GetAddrModeArguments(II, PtrOps, AccessTy))
643 while (!PtrOps.empty())
644 if (OptimizeMemoryInst(II, PtrOps.pop_back_val(), AccessTy))
645 return true;
646 }
647
Eric Christopher040056f2010-03-11 02:41:03 +0000648 // From here on out we're working with named functions.
649 if (CI->getCalledFunction() == 0) return false;
Devang Patel97de92c2011-05-26 21:51:06 +0000650
Micah Villmow3574eca2012-10-08 16:38:25 +0000651 // We'll need DataLayout from here on out.
652 const DataLayout *TD = TLI ? TLI->getDataLayout() : 0;
Eric Christopher040056f2010-03-11 02:41:03 +0000653 if (!TD) return false;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000654
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000655 // Lower all default uses of _chk calls. This is very similar
656 // to what InstCombineCalls does, but here we are only lowering calls
Eric Christopher040056f2010-03-11 02:41:03 +0000657 // that have the default "don't know" as the objectsize. Anything else
658 // should be left alone.
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000659 CodeGenPrepareFortifiedLibCalls Simplifier;
Nuno Lopes51004df2012-07-25 16:46:31 +0000660 return Simplifier.fold(CI, TD, TLInfo);
Eric Christopher040056f2010-03-11 02:41:03 +0000661}
Chris Lattner94e8e0c2011-01-15 07:25:29 +0000662
Evan Cheng485fafc2011-03-21 01:19:09 +0000663/// DupRetToEnableTailCallOpts - Look for opportunities to duplicate return
664/// instructions to the predecessor to enable tail call optimizations. The
665/// case it is currently looking for is:
Dmitri Gribenko2d9eb722012-09-13 12:34:29 +0000666/// @code
Evan Cheng485fafc2011-03-21 01:19:09 +0000667/// bb0:
668/// %tmp0 = tail call i32 @f0()
669/// br label %return
670/// bb1:
671/// %tmp1 = tail call i32 @f1()
672/// br label %return
673/// bb2:
674/// %tmp2 = tail call i32 @f2()
675/// br label %return
676/// return:
677/// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
678/// ret i32 %retval
Dmitri Gribenko2d9eb722012-09-13 12:34:29 +0000679/// @endcode
Evan Cheng485fafc2011-03-21 01:19:09 +0000680///
681/// =>
682///
Dmitri Gribenko2d9eb722012-09-13 12:34:29 +0000683/// @code
Evan Cheng485fafc2011-03-21 01:19:09 +0000684/// bb0:
685/// %tmp0 = tail call i32 @f0()
686/// ret i32 %tmp0
687/// bb1:
688/// %tmp1 = tail call i32 @f1()
689/// ret i32 %tmp1
690/// bb2:
691/// %tmp2 = tail call i32 @f2()
692/// ret i32 %tmp2
Dmitri Gribenko2d9eb722012-09-13 12:34:29 +0000693/// @endcode
Evan Cheng485fafc2011-03-21 01:19:09 +0000694bool CodeGenPrepare::DupRetToEnableTailCallOpts(ReturnInst *RI) {
Cameron Zwarich661a3902011-03-24 04:51:51 +0000695 if (!TLI)
696 return false;
697
Evan Cheng9c777a42012-07-27 21:21:26 +0000698 PHINode *PN = 0;
699 BitCastInst *BCI = 0;
Evan Cheng485fafc2011-03-21 01:19:09 +0000700 Value *V = RI->getReturnValue();
Evan Cheng9c777a42012-07-27 21:21:26 +0000701 if (V) {
702 BCI = dyn_cast<BitCastInst>(V);
703 if (BCI)
704 V = BCI->getOperand(0);
705
706 PN = dyn_cast<PHINode>(V);
707 if (!PN)
708 return false;
709 }
Evan Cheng485fafc2011-03-21 01:19:09 +0000710
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000711 BasicBlock *BB = RI->getParent();
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000712 if (PN && PN->getParent() != BB)
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000713 return false;
Evan Cheng485fafc2011-03-21 01:19:09 +0000714
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000715 // It's not safe to eliminate the sign / zero extension of the return value.
716 // See llvm::isInTailCallPosition().
717 const Function *F = BB->getParent();
Kostya Serebryany164b86b2012-01-20 17:56:17 +0000718 Attributes CallerRetAttr = F->getAttributes().getRetAttributes();
Bill Wendling67658342012-10-09 07:45:08 +0000719 if (CallerRetAttr.hasAttribute(Attributes::ZExt) ||
720 CallerRetAttr.hasAttribute(Attributes::SExt))
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000721 return false;
Evan Cheng485fafc2011-03-21 01:19:09 +0000722
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000723 // Make sure there are no instructions between the PHI and return, or that the
724 // return is the first instruction in the block.
725 if (PN) {
726 BasicBlock::iterator BI = BB->begin();
727 do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
Evan Cheng9c777a42012-07-27 21:21:26 +0000728 if (&*BI == BCI)
729 // Also skip over the bitcast.
730 ++BI;
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000731 if (&*BI != RI)
732 return false;
733 } else {
Cameron Zwarich90354842011-03-24 16:34:59 +0000734 BasicBlock::iterator BI = BB->begin();
735 while (isa<DbgInfoIntrinsic>(BI)) ++BI;
736 if (&*BI != RI)
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000737 return false;
738 }
Evan Cheng485fafc2011-03-21 01:19:09 +0000739
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000740 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
741 /// call.
742 SmallVector<CallInst*, 4> TailCalls;
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000743 if (PN) {
744 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
745 CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
746 // Make sure the phi value is indeed produced by the tail call.
747 if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
748 TLI->mayBeEmittedAsTailCall(CI))
749 TailCalls.push_back(CI);
750 }
751 } else {
752 SmallPtrSet<BasicBlock*, 4> VisitedBBs;
753 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
754 if (!VisitedBBs.insert(*PI))
755 continue;
756
757 BasicBlock::InstListType &InstList = (*PI)->getInstList();
758 BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
759 BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
Cameron Zwarich90354842011-03-24 16:34:59 +0000760 do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
761 if (RI == RE)
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000762 continue;
Cameron Zwarich90354842011-03-24 16:34:59 +0000763
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000764 CallInst *CI = dyn_cast<CallInst>(&*RI);
Cameron Zwarichdc31cfe2011-03-24 15:54:11 +0000765 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI))
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000766 TailCalls.push_back(CI);
767 }
Evan Cheng485fafc2011-03-21 01:19:09 +0000768 }
769
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000770 bool Changed = false;
771 for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
772 CallInst *CI = TailCalls[i];
773 CallSite CS(CI);
774
775 // Conservatively require the attributes of the call to match those of the
776 // return. Ignore noalias because it doesn't affect the call sequence.
Kostya Serebryany164b86b2012-01-20 17:56:17 +0000777 Attributes CalleeRetAttr = CS.getAttributes().getRetAttributes();
Bill Wendling702cc912012-10-15 20:35:56 +0000778 if (AttrBuilder(CalleeRetAttr).
Bill Wendling3756e702012-10-14 06:56:13 +0000779 removeAttribute(Attributes::NoAlias) !=
Bill Wendling702cc912012-10-15 20:35:56 +0000780 AttrBuilder(CallerRetAttr).
Bill Wendling3756e702012-10-14 06:56:13 +0000781 removeAttribute(Attributes::NoAlias))
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000782 continue;
783
784 // Make sure the call instruction is followed by an unconditional branch to
785 // the return block.
786 BasicBlock *CallBB = CI->getParent();
787 BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
788 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
789 continue;
790
791 // Duplicate the return into CallBB.
792 (void)FoldReturnIntoUncondBranch(RI, BB, CallBB);
Devang Patel52e37df2011-03-24 15:35:25 +0000793 ModifiedDT = Changed = true;
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000794 ++NumRetsDup;
795 }
796
797 // If we eliminated all predecessors of the block, delete the block now.
Evan Cheng46597072012-09-28 23:58:57 +0000798 if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000799 BB->eraseFromParent();
800
801 return Changed;
Evan Cheng485fafc2011-03-21 01:19:09 +0000802}
803
Chris Lattner88a5c832008-11-25 07:09:13 +0000804//===----------------------------------------------------------------------===//
Chris Lattner88a5c832008-11-25 07:09:13 +0000805// Memory Optimization
806//===----------------------------------------------------------------------===//
807
Chris Lattnerdd77df32007-04-13 20:30:56 +0000808/// IsNonLocalValue - Return true if the specified values are defined in a
809/// different basic block than BB.
810static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
811 if (Instruction *I = dyn_cast<Instruction>(V))
812 return I->getParent() != BB;
813 return false;
814}
815
Bob Wilson4a8ee232009-12-03 21:47:07 +0000816/// OptimizeMemoryInst - Load and Store Instructions often have
Chris Lattnerdd77df32007-04-13 20:30:56 +0000817/// addressing modes that can do significant amounts of computation. As such,
818/// instruction selection will try to get the load or store to do as much
819/// computation as possible for the program. The problem is that isel can only
820/// see within a single block. As such, we sink as much legal addressing mode
821/// stuff into the block as possible.
Chris Lattner88a5c832008-11-25 07:09:13 +0000822///
823/// This method is used to optimize both load/store and inline asms with memory
824/// operands.
Chris Lattner896617b2008-11-26 03:20:37 +0000825bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000826 Type *AccessTy) {
Owen Anderson35bf4d62010-11-27 08:15:55 +0000827 Value *Repl = Addr;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000828
829 // Try to collapse single-value PHI nodes. This is necessary to undo
Owen Andersond2f41742010-11-19 22:15:03 +0000830 // unprofitable PRE transformations.
Cameron Zwarich7cb4fa22011-01-03 06:33:01 +0000831 SmallVector<Value*, 8> worklist;
832 SmallPtrSet<Value*, 16> Visited;
Owen Anderson35bf4d62010-11-27 08:15:55 +0000833 worklist.push_back(Addr);
Nadav Rotema94d6e82012-07-24 10:51:42 +0000834
Owen Anderson35bf4d62010-11-27 08:15:55 +0000835 // Use a worklist to iteratively look through PHI nodes, and ensure that
836 // the addressing mode obtained from the non-PHI roots of the graph
837 // are equivalent.
838 Value *Consensus = 0;
Cameron Zwarich4c078f02011-03-01 21:13:53 +0000839 unsigned NumUsesConsensus = 0;
Cameron Zwarich7c8d3512011-03-05 08:12:26 +0000840 bool IsNumUsesConsensusValid = false;
Owen Anderson35bf4d62010-11-27 08:15:55 +0000841 SmallVector<Instruction*, 16> AddrModeInsts;
842 ExtAddrMode AddrMode;
843 while (!worklist.empty()) {
844 Value *V = worklist.back();
845 worklist.pop_back();
Nadav Rotema94d6e82012-07-24 10:51:42 +0000846
Owen Anderson35bf4d62010-11-27 08:15:55 +0000847 // Break use-def graph loops.
Nick Lewycky48105282011-09-29 23:40:12 +0000848 if (!Visited.insert(V)) {
Owen Anderson35bf4d62010-11-27 08:15:55 +0000849 Consensus = 0;
850 break;
Owen Andersond2f41742010-11-19 22:15:03 +0000851 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000852
Owen Anderson35bf4d62010-11-27 08:15:55 +0000853 // For a PHI node, push all of its incoming values.
854 if (PHINode *P = dyn_cast<PHINode>(V)) {
855 for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i)
856 worklist.push_back(P->getIncomingValue(i));
857 continue;
858 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000859
Owen Anderson35bf4d62010-11-27 08:15:55 +0000860 // For non-PHIs, determine the addressing mode being computed.
861 SmallVector<Instruction*, 16> NewAddrModeInsts;
862 ExtAddrMode NewAddrMode =
Nick Lewycky48105282011-09-29 23:40:12 +0000863 AddressingModeMatcher::Match(V, AccessTy, MemoryInst,
Owen Anderson35bf4d62010-11-27 08:15:55 +0000864 NewAddrModeInsts, *TLI);
Cameron Zwarich7c8d3512011-03-05 08:12:26 +0000865
866 // This check is broken into two cases with very similar code to avoid using
867 // getNumUses() as much as possible. Some values have a lot of uses, so
868 // calling getNumUses() unconditionally caused a significant compile-time
869 // regression.
870 if (!Consensus) {
871 Consensus = V;
872 AddrMode = NewAddrMode;
873 AddrModeInsts = NewAddrModeInsts;
874 continue;
875 } else if (NewAddrMode == AddrMode) {
876 if (!IsNumUsesConsensusValid) {
877 NumUsesConsensus = Consensus->getNumUses();
878 IsNumUsesConsensusValid = true;
879 }
880
881 // Ensure that the obtained addressing mode is equivalent to that obtained
882 // for all other roots of the PHI traversal. Also, when choosing one
883 // such root as representative, select the one with the most uses in order
884 // to keep the cost modeling heuristics in AddressingModeMatcher
885 // applicable.
Cameron Zwarich4c078f02011-03-01 21:13:53 +0000886 unsigned NumUses = V->getNumUses();
887 if (NumUses > NumUsesConsensus) {
Owen Anderson35bf4d62010-11-27 08:15:55 +0000888 Consensus = V;
Cameron Zwarich4c078f02011-03-01 21:13:53 +0000889 NumUsesConsensus = NumUses;
Owen Anderson35bf4d62010-11-27 08:15:55 +0000890 AddrModeInsts = NewAddrModeInsts;
891 }
892 continue;
893 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000894
Owen Anderson35bf4d62010-11-27 08:15:55 +0000895 Consensus = 0;
896 break;
Owen Andersond2f41742010-11-19 22:15:03 +0000897 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000898
Owen Anderson35bf4d62010-11-27 08:15:55 +0000899 // If the addressing mode couldn't be determined, or if multiple different
900 // ones were determined, bail out now.
901 if (!Consensus) return false;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000902
Chris Lattnerdd77df32007-04-13 20:30:56 +0000903 // Check to see if any of the instructions supersumed by this addr mode are
904 // non-local to I's BB.
905 bool AnyNonLocal = false;
906 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
Chris Lattner896617b2008-11-26 03:20:37 +0000907 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
Chris Lattnerdd77df32007-04-13 20:30:56 +0000908 AnyNonLocal = true;
909 break;
910 }
911 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000912
Chris Lattnerdd77df32007-04-13 20:30:56 +0000913 // If all the instructions matched are already in this BB, don't do anything.
914 if (!AnyNonLocal) {
David Greene68d67fd2010-01-05 01:27:11 +0000915 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000916 return false;
917 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000918
Chris Lattnerdd77df32007-04-13 20:30:56 +0000919 // Insert this computation right after this user. Since our caller is
920 // scanning from the top of the BB to the bottom, reuse of the expr are
921 // guaranteed to happen later.
Devang Patel2048c372011-09-06 18:49:53 +0000922 IRBuilder<> Builder(MemoryInst);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000923
Chris Lattnerdd77df32007-04-13 20:30:56 +0000924 // Now that we determined the addressing expression we want to use and know
925 // that we have to sink it into this block. Check to see if we have already
926 // done this for some other load/store instr in this block. If so, reuse the
927 // computation.
928 Value *&SunkAddr = SunkAddrs[Addr];
929 if (SunkAddr) {
David Greene68d67fd2010-01-05 01:27:11 +0000930 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
Dan Gohman6c1980b2009-07-25 01:13:51 +0000931 << *MemoryInst);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000932 if (SunkAddr->getType() != Addr->getType())
Benjamin Kramera9390a42011-09-27 20:39:19 +0000933 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
Chris Lattnerdd77df32007-04-13 20:30:56 +0000934 } else {
David Greene68d67fd2010-01-05 01:27:11 +0000935 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Dan Gohman6c1980b2009-07-25 01:13:51 +0000936 << *MemoryInst);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000937 Type *IntPtrTy =
Micah Villmow3574eca2012-10-08 16:38:25 +0000938 TLI->getDataLayout()->getIntPtrType(AccessTy->getContext());
Eric Christopher692bf6b2008-09-24 05:32:41 +0000939
Chris Lattnerdd77df32007-04-13 20:30:56 +0000940 Value *Result = 0;
Dan Gohmand8d0b6a2010-01-19 22:45:06 +0000941
942 // Start with the base register. Do this first so that subsequent address
943 // matching finds it last, which will prevent it from trying to match it
944 // as the scaled value in case it happens to be a mul. That would be
945 // problematic if we've sunk a different mul for the scale, because then
946 // we'd end up sinking both muls.
947 if (AddrMode.BaseReg) {
948 Value *V = AddrMode.BaseReg;
Duncan Sands1df98592010-02-16 11:11:14 +0000949 if (V->getType()->isPointerTy())
Devang Patel2048c372011-09-06 18:49:53 +0000950 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Dan Gohmand8d0b6a2010-01-19 22:45:06 +0000951 if (V->getType() != IntPtrTy)
Devang Patel2048c372011-09-06 18:49:53 +0000952 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
Dan Gohmand8d0b6a2010-01-19 22:45:06 +0000953 Result = V;
954 }
955
956 // Add the scale value.
Chris Lattnerdd77df32007-04-13 20:30:56 +0000957 if (AddrMode.Scale) {
958 Value *V = AddrMode.ScaledReg;
959 if (V->getType() == IntPtrTy) {
960 // done.
Duncan Sands1df98592010-02-16 11:11:14 +0000961 } else if (V->getType()->isPointerTy()) {
Devang Patel2048c372011-09-06 18:49:53 +0000962 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000963 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
964 cast<IntegerType>(V->getType())->getBitWidth()) {
Devang Patel2048c372011-09-06 18:49:53 +0000965 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000966 } else {
Devang Patel2048c372011-09-06 18:49:53 +0000967 V = Builder.CreateSExt(V, IntPtrTy, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000968 }
969 if (AddrMode.Scale != 1)
Devang Patel2048c372011-09-06 18:49:53 +0000970 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
971 "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000972 if (Result)
Devang Patel2048c372011-09-06 18:49:53 +0000973 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000974 else
975 Result = V;
976 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000977
Chris Lattnerdd77df32007-04-13 20:30:56 +0000978 // Add in the BaseGV if present.
979 if (AddrMode.BaseGV) {
Devang Patel2048c372011-09-06 18:49:53 +0000980 Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000981 if (Result)
Devang Patel2048c372011-09-06 18:49:53 +0000982 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000983 else
984 Result = V;
985 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000986
Chris Lattnerdd77df32007-04-13 20:30:56 +0000987 // Add in the Base Offset if present.
988 if (AddrMode.BaseOffs) {
Owen Andersoneed707b2009-07-24 23:12:02 +0000989 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000990 if (Result)
Devang Patel2048c372011-09-06 18:49:53 +0000991 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000992 else
993 Result = V;
994 }
995
996 if (Result == 0)
Owen Andersona7235ea2009-07-31 20:28:14 +0000997 SunkAddr = Constant::getNullValue(Addr->getType());
Chris Lattnerdd77df32007-04-13 20:30:56 +0000998 else
Devang Patel2048c372011-09-06 18:49:53 +0000999 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +00001000 }
Eric Christopher692bf6b2008-09-24 05:32:41 +00001001
Owen Andersond2f41742010-11-19 22:15:03 +00001002 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
Eric Christopher692bf6b2008-09-24 05:32:41 +00001003
Chris Lattner0403b472011-04-09 07:05:44 +00001004 // If we have no uses, recursively delete the value and all dead instructions
1005 // using it.
Owen Andersond2f41742010-11-19 22:15:03 +00001006 if (Repl->use_empty()) {
Chris Lattner0403b472011-04-09 07:05:44 +00001007 // This can cause recursive deletion, which can invalidate our iterator.
1008 // Use a WeakVH to hold onto it in case this happens.
1009 WeakVH IterHandle(CurInstIterator);
1010 BasicBlock *BB = CurInstIterator->getParent();
Nadav Rotema94d6e82012-07-24 10:51:42 +00001011
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +00001012 RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
Chris Lattner0403b472011-04-09 07:05:44 +00001013
1014 if (IterHandle != CurInstIterator) {
1015 // If the iterator instruction was recursively deleted, start over at the
1016 // start of the block.
1017 CurInstIterator = BB->begin();
1018 SunkAddrs.clear();
1019 } else {
1020 // This address is now available for reassignment, so erase the table
1021 // entry; we don't want to match some completely different instruction.
1022 SunkAddrs[Addr] = 0;
Nadav Rotema94d6e82012-07-24 10:51:42 +00001023 }
Dale Johannesen536d31b2010-03-31 20:37:15 +00001024 }
Cameron Zwarich31ff1332011-01-05 17:27:27 +00001025 ++NumMemoryInsts;
Chris Lattnerdd77df32007-04-13 20:30:56 +00001026 return true;
1027}
1028
Evan Cheng9bf12b52008-02-26 02:42:37 +00001029/// OptimizeInlineAsmInst - If there are any memory operands, use
Chris Lattner88a5c832008-11-25 07:09:13 +00001030/// OptimizeMemoryInst to sink their address computing into the block when
Evan Cheng9bf12b52008-02-26 02:42:37 +00001031/// possible / profitable.
Chris Lattner75796092011-01-15 07:14:54 +00001032bool CodeGenPrepare::OptimizeInlineAsmInst(CallInst *CS) {
Evan Cheng9bf12b52008-02-26 02:42:37 +00001033 bool MadeChange = false;
Evan Cheng9bf12b52008-02-26 02:42:37 +00001034
Nadav Rotema94d6e82012-07-24 10:51:42 +00001035 TargetLowering::AsmOperandInfoVector
Chris Lattner75796092011-01-15 07:14:54 +00001036 TargetConstraints = TLI->ParseConstraints(CS);
Dale Johannesen677c6ec2010-09-16 18:30:55 +00001037 unsigned ArgNo = 0;
John Thompsoneac6e1d2010-09-13 18:15:37 +00001038 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
1039 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Nadav Rotema94d6e82012-07-24 10:51:42 +00001040
Evan Cheng9bf12b52008-02-26 02:42:37 +00001041 // Compute the constraint code and ConstraintType to use.
Dale Johannesen1784d162010-06-25 21:55:36 +00001042 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Evan Cheng9bf12b52008-02-26 02:42:37 +00001043
Eli Friedman9ec80952008-02-26 18:37:49 +00001044 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
1045 OpInfo.isIndirect) {
Chris Lattner75796092011-01-15 07:14:54 +00001046 Value *OpVal = CS->getArgOperand(ArgNo++);
Chris Lattner1a8943a2011-01-15 07:29:01 +00001047 MadeChange |= OptimizeMemoryInst(CS, OpVal, OpVal->getType());
Dale Johannesen677c6ec2010-09-16 18:30:55 +00001048 } else if (OpInfo.Type == InlineAsm::isInput)
1049 ArgNo++;
Evan Cheng9bf12b52008-02-26 02:42:37 +00001050 }
1051
1052 return MadeChange;
1053}
1054
Dan Gohmanb00f2362009-10-16 20:59:35 +00001055/// MoveExtToFormExtLoad - Move a zext or sext fed by a load into the same
1056/// basic block as the load, unless conditions are unfavorable. This allows
1057/// SelectionDAG to fold the extend into the load.
1058///
1059bool CodeGenPrepare::MoveExtToFormExtLoad(Instruction *I) {
1060 // Look for a load being extended.
1061 LoadInst *LI = dyn_cast<LoadInst>(I->getOperand(0));
1062 if (!LI) return false;
1063
1064 // If they're already in the same block, there's nothing to do.
1065 if (LI->getParent() == I->getParent())
1066 return false;
1067
1068 // If the load has other users and the truncate is not free, this probably
1069 // isn't worthwhile.
1070 if (!LI->hasOneUse() &&
Bob Wilsonec57a1a2010-09-22 18:44:56 +00001071 TLI && (TLI->isTypeLegal(TLI->getValueType(LI->getType())) ||
1072 !TLI->isTypeLegal(TLI->getValueType(I->getType()))) &&
Bob Wilson71dc4d92010-09-21 21:54:27 +00001073 !TLI->isTruncateFree(I->getType(), LI->getType()))
Dan Gohmanb00f2362009-10-16 20:59:35 +00001074 return false;
1075
1076 // Check whether the target supports casts folded into loads.
1077 unsigned LType;
1078 if (isa<ZExtInst>(I))
1079 LType = ISD::ZEXTLOAD;
1080 else {
1081 assert(isa<SExtInst>(I) && "Unexpected ext type!");
1082 LType = ISD::SEXTLOAD;
1083 }
1084 if (TLI && !TLI->isLoadExtLegal(LType, TLI->getValueType(LI->getType())))
1085 return false;
1086
1087 // Move the extend into the same block as the load, so that SelectionDAG
1088 // can fold it.
1089 I->removeFromParent();
1090 I->insertAfter(LI);
Cameron Zwarich31ff1332011-01-05 17:27:27 +00001091 ++NumExtsMoved;
Dan Gohmanb00f2362009-10-16 20:59:35 +00001092 return true;
1093}
1094
Evan Chengbdcb7262007-12-05 23:58:20 +00001095bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
1096 BasicBlock *DefBB = I->getParent();
1097
Bob Wilson9120f5c2010-09-21 21:44:14 +00001098 // If the result of a {s|z}ext and its source are both live out, rewrite all
Evan Chengbdcb7262007-12-05 23:58:20 +00001099 // other uses of the source with result of extension.
1100 Value *Src = I->getOperand(0);
1101 if (Src->hasOneUse())
1102 return false;
1103
Evan Cheng696e5c02007-12-13 07:50:36 +00001104 // Only do this xform if truncating is free.
Gabor Greif53bdbd72008-02-26 19:13:21 +00001105 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
Evan Chengf9785f92007-12-13 03:32:53 +00001106 return false;
1107
Evan Cheng772de512007-12-12 00:51:06 +00001108 // Only safe to perform the optimization if the source is also defined in
Evan Cheng765dff22007-12-12 02:53:41 +00001109 // this block.
1110 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
Evan Cheng772de512007-12-12 00:51:06 +00001111 return false;
1112
Evan Chengbdcb7262007-12-05 23:58:20 +00001113 bool DefIsLiveOut = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001114 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
Evan Chengbdcb7262007-12-05 23:58:20 +00001115 UI != E; ++UI) {
1116 Instruction *User = cast<Instruction>(*UI);
1117
1118 // Figure out which BB this ext is used in.
1119 BasicBlock *UserBB = User->getParent();
1120 if (UserBB == DefBB) continue;
1121 DefIsLiveOut = true;
1122 break;
1123 }
1124 if (!DefIsLiveOut)
1125 return false;
1126
Evan Cheng765dff22007-12-12 02:53:41 +00001127 // Make sure non of the uses are PHI nodes.
Eric Christopher692bf6b2008-09-24 05:32:41 +00001128 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
Evan Cheng765dff22007-12-12 02:53:41 +00001129 UI != E; ++UI) {
1130 Instruction *User = cast<Instruction>(*UI);
Evan Chengf9785f92007-12-13 03:32:53 +00001131 BasicBlock *UserBB = User->getParent();
1132 if (UserBB == DefBB) continue;
1133 // Be conservative. We don't want this xform to end up introducing
1134 // reloads just before load / store instructions.
1135 if (isa<PHINode>(User) || isa<LoadInst>(User) || isa<StoreInst>(User))
Evan Cheng765dff22007-12-12 02:53:41 +00001136 return false;
1137 }
1138
Evan Chengbdcb7262007-12-05 23:58:20 +00001139 // InsertedTruncs - Only insert one trunc in each block once.
1140 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
1141
1142 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001143 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
Evan Chengbdcb7262007-12-05 23:58:20 +00001144 UI != E; ++UI) {
1145 Use &TheUse = UI.getUse();
1146 Instruction *User = cast<Instruction>(*UI);
1147
1148 // Figure out which BB this ext is used in.
1149 BasicBlock *UserBB = User->getParent();
1150 if (UserBB == DefBB) continue;
1151
1152 // Both src and def are live in this block. Rewrite the use.
1153 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
1154
1155 if (!InsertedTrunc) {
Bill Wendling5b6f42f2011-08-16 20:45:24 +00001156 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Evan Chengbdcb7262007-12-05 23:58:20 +00001157 InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
1158 }
1159
1160 // Replace a use of the {s|z}ext source with a use of the result.
1161 TheUse = InsertedTrunc;
Cameron Zwarich31ff1332011-01-05 17:27:27 +00001162 ++NumExtUses;
Evan Chengbdcb7262007-12-05 23:58:20 +00001163 MadeChange = true;
1164 }
1165
1166 return MadeChange;
1167}
1168
Benjamin Kramer59957502012-05-05 12:49:22 +00001169/// isFormingBranchFromSelectProfitable - Returns true if a SelectInst should be
1170/// turned into an explicit branch.
1171static bool isFormingBranchFromSelectProfitable(SelectInst *SI) {
1172 // FIXME: This should use the same heuristics as IfConversion to determine
1173 // whether a select is better represented as a branch. This requires that
1174 // branch probability metadata is preserved for the select, which is not the
1175 // case currently.
1176
1177 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
1178
1179 // If the branch is predicted right, an out of order CPU can avoid blocking on
1180 // the compare. Emit cmovs on compares with a memory operand as branches to
1181 // avoid stalls on the load from memory. If the compare has more than one use
1182 // there's probably another cmov or setcc around so it's not worth emitting a
1183 // branch.
1184 if (!Cmp)
1185 return false;
1186
1187 Value *CmpOp0 = Cmp->getOperand(0);
1188 Value *CmpOp1 = Cmp->getOperand(1);
1189
1190 // We check that the memory operand has one use to avoid uses of the loaded
1191 // value directly after the compare, making branches unprofitable.
1192 return Cmp->hasOneUse() &&
1193 ((isa<LoadInst>(CmpOp0) && CmpOp0->hasOneUse()) ||
1194 (isa<LoadInst>(CmpOp1) && CmpOp1->hasOneUse()));
1195}
1196
1197
Nadav Rotem9f40cb32012-09-02 12:10:19 +00001198/// If we have a SelectInst that will likely profit from branch prediction,
1199/// turn it into a branch.
Benjamin Kramer59957502012-05-05 12:49:22 +00001200bool CodeGenPrepare::OptimizeSelectInst(SelectInst *SI) {
Nadav Rotem9f40cb32012-09-02 12:10:19 +00001201 bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
1202
1203 // Can we convert the 'select' to CF ?
1204 if (DisableSelectToBranch || OptSize || !TLI || VectorCond)
Benjamin Kramer59957502012-05-05 12:49:22 +00001205 return false;
1206
Nadav Rotem9f40cb32012-09-02 12:10:19 +00001207 TargetLowering::SelectSupportKind SelectKind;
1208 if (VectorCond)
1209 SelectKind = TargetLowering::VectorMaskSelect;
1210 else if (SI->getType()->isVectorTy())
1211 SelectKind = TargetLowering::ScalarCondVectorVal;
1212 else
1213 SelectKind = TargetLowering::ScalarValSelect;
1214
1215 // Do we have efficient codegen support for this kind of 'selects' ?
1216 if (TLI->isSelectSupported(SelectKind)) {
1217 // We have efficient codegen support for the select instruction.
1218 // Check if it is profitable to keep this 'select'.
1219 if (!TLI->isPredictableSelectExpensive() ||
1220 !isFormingBranchFromSelectProfitable(SI))
1221 return false;
1222 }
Benjamin Kramer59957502012-05-05 12:49:22 +00001223
1224 ModifiedDT = true;
1225
1226 // First, we split the block containing the select into 2 blocks.
1227 BasicBlock *StartBlock = SI->getParent();
1228 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(SI));
1229 BasicBlock *NextBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
1230
1231 // Create a new block serving as the landing pad for the branch.
1232 BasicBlock *SmallBlock = BasicBlock::Create(SI->getContext(), "select.mid",
1233 NextBlock->getParent(), NextBlock);
1234
1235 // Move the unconditional branch from the block with the select in it into our
1236 // landing pad block.
1237 StartBlock->getTerminator()->eraseFromParent();
1238 BranchInst::Create(NextBlock, SmallBlock);
1239
1240 // Insert the real conditional branch based on the original condition.
1241 BranchInst::Create(NextBlock, SmallBlock, SI->getCondition(), SI);
1242
1243 // The select itself is replaced with a PHI Node.
1244 PHINode *PN = PHINode::Create(SI->getType(), 2, "", NextBlock->begin());
1245 PN->takeName(SI);
1246 PN->addIncoming(SI->getTrueValue(), StartBlock);
1247 PN->addIncoming(SI->getFalseValue(), SmallBlock);
1248 SI->replaceAllUsesWith(PN);
1249 SI->eraseFromParent();
1250
1251 // Instruct OptimizeBlock to skip to the next block.
1252 CurInstIterator = StartBlock->end();
1253 ++NumSelectsExpanded;
1254 return true;
1255}
1256
Cameron Zwarichc0611012011-01-06 02:37:26 +00001257bool CodeGenPrepare::OptimizeInst(Instruction *I) {
Cameron Zwarichc0611012011-01-06 02:37:26 +00001258 if (PHINode *P = dyn_cast<PHINode>(I)) {
1259 // It is possible for very late stage optimizations (such as SimplifyCFG)
1260 // to introduce PHI nodes too late to be cleaned up. If we detect such a
1261 // trivial PHI, go ahead and zap it here.
1262 if (Value *V = SimplifyInstruction(P)) {
1263 P->replaceAllUsesWith(V);
1264 P->eraseFromParent();
1265 ++NumPHIsElim;
Chris Lattner1a8943a2011-01-15 07:29:01 +00001266 return true;
Cameron Zwarichc0611012011-01-06 02:37:26 +00001267 }
Chris Lattner1a8943a2011-01-15 07:29:01 +00001268 return false;
1269 }
Nadav Rotema94d6e82012-07-24 10:51:42 +00001270
Chris Lattner1a8943a2011-01-15 07:29:01 +00001271 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Cameron Zwarichc0611012011-01-06 02:37:26 +00001272 // If the source of the cast is a constant, then this should have
1273 // already been constant folded. The only reason NOT to constant fold
1274 // it is if something (e.g. LSR) was careful to place the constant
1275 // evaluation in a block other than then one that uses it (e.g. to hoist
1276 // the address of globals out of a loop). If this is the case, we don't
1277 // want to forward-subst the cast.
1278 if (isa<Constant>(CI->getOperand(0)))
1279 return false;
1280
Chris Lattner1a8943a2011-01-15 07:29:01 +00001281 if (TLI && OptimizeNoopCopyExpression(CI, *TLI))
1282 return true;
Cameron Zwarichc0611012011-01-06 02:37:26 +00001283
Chris Lattner1a8943a2011-01-15 07:29:01 +00001284 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
1285 bool MadeChange = MoveExtToFormExtLoad(I);
1286 return MadeChange | OptimizeExtUses(I);
Cameron Zwarichc0611012011-01-06 02:37:26 +00001287 }
Chris Lattner1a8943a2011-01-15 07:29:01 +00001288 return false;
1289 }
Nadav Rotema94d6e82012-07-24 10:51:42 +00001290
Chris Lattner1a8943a2011-01-15 07:29:01 +00001291 if (CmpInst *CI = dyn_cast<CmpInst>(I))
1292 return OptimizeCmpExpression(CI);
Nadav Rotema94d6e82012-07-24 10:51:42 +00001293
Chris Lattner1a8943a2011-01-15 07:29:01 +00001294 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Hans Wennborg93ba1332012-09-19 07:48:16 +00001295 bool Changed = false;
Cameron Zwarichc0611012011-01-06 02:37:26 +00001296 if (TLI)
Hans Wennborg93ba1332012-09-19 07:48:16 +00001297 Changed |= OptimizeMemoryInst(I, I->getOperand(0), LI->getType());
1298 Changed |= ConvertLoadToSwitch(LI);
1299 return Changed;
Chris Lattner1a8943a2011-01-15 07:29:01 +00001300 }
Nadav Rotema94d6e82012-07-24 10:51:42 +00001301
Chris Lattner1a8943a2011-01-15 07:29:01 +00001302 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Cameron Zwarichc0611012011-01-06 02:37:26 +00001303 if (TLI)
Chris Lattner1a8943a2011-01-15 07:29:01 +00001304 return OptimizeMemoryInst(I, SI->getOperand(1),
1305 SI->getOperand(0)->getType());
1306 return false;
1307 }
Nadav Rotema94d6e82012-07-24 10:51:42 +00001308
Chris Lattner1a8943a2011-01-15 07:29:01 +00001309 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Cameron Zwarich865ae1a2011-01-06 02:44:52 +00001310 if (GEPI->hasAllZeroIndices()) {
1311 /// The GEP operand must be a pointer, so must its result -> BitCast
1312 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
1313 GEPI->getName(), GEPI);
1314 GEPI->replaceAllUsesWith(NC);
1315 GEPI->eraseFromParent();
1316 ++NumGEPsElim;
Cameron Zwarich865ae1a2011-01-06 02:44:52 +00001317 OptimizeInst(NC);
Chris Lattner1a8943a2011-01-15 07:29:01 +00001318 return true;
Cameron Zwarich865ae1a2011-01-06 02:44:52 +00001319 }
Chris Lattner1a8943a2011-01-15 07:29:01 +00001320 return false;
Cameron Zwarichc0611012011-01-06 02:37:26 +00001321 }
Nadav Rotema94d6e82012-07-24 10:51:42 +00001322
Chris Lattner1a8943a2011-01-15 07:29:01 +00001323 if (CallInst *CI = dyn_cast<CallInst>(I))
1324 return OptimizeCallInst(CI);
Cameron Zwarichc0611012011-01-06 02:37:26 +00001325
Evan Cheng485fafc2011-03-21 01:19:09 +00001326 if (ReturnInst *RI = dyn_cast<ReturnInst>(I))
1327 return DupRetToEnableTailCallOpts(RI);
1328
Benjamin Kramer59957502012-05-05 12:49:22 +00001329 if (SelectInst *SI = dyn_cast<SelectInst>(I))
1330 return OptimizeSelectInst(SI);
1331
Chris Lattner1a8943a2011-01-15 07:29:01 +00001332 return false;
Cameron Zwarichc0611012011-01-06 02:37:26 +00001333}
1334
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001335// In this pass we look for GEP and cast instructions that are used
1336// across basic blocks and rewrite them to improve basic-block-at-a-time
1337// selection.
1338bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
Cameron Zwarich8c3527e2011-01-06 00:42:50 +00001339 SunkAddrs.clear();
Cameron Zwarich56e37932011-03-02 03:31:46 +00001340 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001341
Chris Lattner75796092011-01-15 07:14:54 +00001342 CurInstIterator = BB.begin();
Hans Wennborg93ba1332012-09-19 07:48:16 +00001343 while (CurInstIterator != BB.end())
Chris Lattner94e8e0c2011-01-15 07:25:29 +00001344 MadeChange |= OptimizeInst(CurInstIterator++);
Eric Christopher692bf6b2008-09-24 05:32:41 +00001345
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001346 return MadeChange;
1347}
Devang Patelf56ea612011-08-18 00:50:51 +00001348
1349// llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotema94d6e82012-07-24 10:51:42 +00001350// handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patelf56ea612011-08-18 00:50:51 +00001351// find a node corresponding to the value.
1352bool CodeGenPrepare::PlaceDbgValues(Function &F) {
1353 bool MadeChange = false;
1354 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
1355 Instruction *PrevNonDbgInst = NULL;
1356 for (BasicBlock::iterator BI = I->begin(), BE = I->end(); BI != BE;) {
1357 Instruction *Insn = BI; ++BI;
1358 DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
1359 if (!DVI) {
1360 PrevNonDbgInst = Insn;
1361 continue;
1362 }
1363
1364 Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
1365 if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
1366 DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
1367 DVI->removeFromParent();
1368 if (isa<PHINode>(VI))
1369 DVI->insertBefore(VI->getParent()->getFirstInsertionPt());
1370 else
1371 DVI->insertAfter(VI);
1372 MadeChange = true;
1373 ++NumDbgValueMoved;
1374 }
1375 }
1376 }
1377 return MadeChange;
1378}
Hans Wennborg93ba1332012-09-19 07:48:16 +00001379
1380static bool TargetSupportsJumpTables(const TargetLowering &TLI) {
1381 return TLI.supportJumpTables() &&
1382 (TLI.isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
1383 TLI.isOperationLegalOrCustom(ISD::BRIND, MVT::Other));
1384}
1385
1386/// ConvertLoadToSwitch - Convert loads from constant lookup tables into
1387/// switches. This undos the switch-to-lookup table transformation in
1388/// SimplifyCFG for targets where that is inprofitable.
1389bool CodeGenPrepare::ConvertLoadToSwitch(LoadInst *LI) {
1390 // This only applies to targets that don't support jump tables.
1391 if (!TLI || TargetSupportsJumpTables(*TLI))
1392 return false;
1393
1394 // FIXME: In the future, it would be desirable to have enough target
1395 // information in SimplifyCFG, so we could decide at that stage whether to
1396 // transform the switch to a lookup table or not, and this
1397 // reverse-transformation could be removed.
1398
1399 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getPointerOperand());
1400 if (!GEP || !GEP->isInBounds() || GEP->getPointerAddressSpace())
1401 return false;
1402 if (GEP->getNumIndices() != 2)
1403 return false;
1404 Value *FirstIndex = GEP->idx_begin()[0];
1405 ConstantInt *FirstIndexInt = dyn_cast<ConstantInt>(FirstIndex);
1406 if (!FirstIndexInt || !FirstIndexInt->isZero())
1407 return false;
1408
1409 Value *TableIndex = GEP->idx_begin()[1];
1410 IntegerType *TableIndexTy = cast<IntegerType>(TableIndex->getType());
1411
1412 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getPointerOperand());
1413 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
1414 return false;
1415
1416 Constant *Arr = GV->getInitializer();
1417 uint64_t NumElements;
1418 if (ConstantArray *CA = dyn_cast<ConstantArray>(Arr))
1419 NumElements = CA->getType()->getNumElements();
1420 else if (ConstantDataArray *CDA = dyn_cast<ConstantDataArray>(Arr))
1421 NumElements = CDA->getNumElements();
1422 else
1423 return false;
1424 if (NumElements < 2)
1425 return false;
1426
1427 // Split the block.
1428 BasicBlock *OriginalBB = LI->getParent();
1429 BasicBlock *PostSwitchBB = OriginalBB->splitBasicBlock(LI);
1430
1431 // Replace OriginalBB's terminator with a switch.
1432 IRBuilder<> Builder(OriginalBB->getTerminator());
1433 SwitchInst *Switch = Builder.CreateSwitch(TableIndex, PostSwitchBB,
1434 NumElements - 1);
1435 OriginalBB->getTerminator()->eraseFromParent();
1436
1437 // Count the frequency of each value to decide which to use as default.
1438 SmallDenseMap<Constant*, uint64_t> ValueFreq;
1439 for (uint64_t I = 0; I < NumElements; ++I)
1440 ++ValueFreq[Arr->getAggregateElement(I)];
1441 uint64_t MaxCount = 0;
1442 Constant *DefaultValue = NULL;
1443 for (SmallDenseMap<Constant*, uint64_t>::iterator I = ValueFreq.begin(),
1444 E = ValueFreq.end(); I != E; ++I) {
1445 if (I->second > MaxCount) {
1446 MaxCount = I->second;
1447 DefaultValue = I->first;
1448 }
1449 }
1450 assert(DefaultValue && "No values in the array?");
1451
1452 // Create the phi node in PostSwitchBB, which will replace the load.
1453 Builder.SetInsertPoint(PostSwitchBB->begin());
1454 PHINode *PHI = Builder.CreatePHI(LI->getType(), NumElements);
1455 PHI->addIncoming(DefaultValue, OriginalBB);
1456
1457 // Build basic blocks to target with the switch.
1458 for (uint64_t I = 0; I < NumElements; ++I) {
1459 Constant *C = Arr->getAggregateElement(I);
1460 if (C == DefaultValue) continue; // Already covered by the default case.
1461
1462 BasicBlock *BB = BasicBlock::Create(PostSwitchBB->getContext(),
1463 "lookup.bb",
1464 PostSwitchBB->getParent(),
1465 PostSwitchBB);
1466 Switch->addCase(ConstantInt::get(TableIndexTy, I), BB);
1467 Builder.SetInsertPoint(BB);
1468 Builder.CreateBr(PostSwitchBB);
1469 PHI->addIncoming(C, BB);
1470 }
1471
1472 // Remove the load.
1473 LI->replaceAllUsesWith(PHI);
1474 LI->eraseFromParent();
1475
1476 // Clean up.
1477 if (GEP->use_empty())
1478 GEP->eraseFromParent();
1479 if (GV->hasUnnamedAddr() && GV->hasPrivateLinkage() && GV->use_empty())
1480 GV->eraseFromParent();
1481
1482 CurInstIterator = Switch;
1483 return true;
1484}