blob: 4d8176bc6c7df36aebd1f8bc9433e7860074e52b [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"
31#include "llvm/Analysis/InstructionSimplify.h"
32#include "llvm/Analysis/ProfileInfo.h"
Dan Gohman03ce0422009-02-13 17:45:12 +000033#include "llvm/Assembly/Writer.h"
Evan Cheng9bf12b52008-02-26 02:42:37 +000034#include "llvm/Support/CallSite.h"
Evan Chenge1bcb442010-08-17 01:34:49 +000035#include "llvm/Support/CommandLine.h"
Evan Chengbdcb7262007-12-05 23:58:20 +000036#include "llvm/Support/Debug.h"
Chris Lattnerdd77df32007-04-13 20:30:56 +000037#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner088a1e82008-11-25 04:42:10 +000038#include "llvm/Support/PatternMatch.h"
Chris Lattner94e8e0c2011-01-15 07:25:29 +000039#include "llvm/Support/ValueHandle.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000040#include "llvm/Support/raw_ostream.h"
Micah Villmow3574eca2012-10-08 16:38:25 +000041#include "llvm/DataLayout.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000042#include "llvm/Target/TargetLibraryInfo.h"
43#include "llvm/Target/TargetLowering.h"
44#include "llvm/Transforms/Utils/AddrModeMatcher.h"
45#include "llvm/Transforms/Utils/BasicBlockUtils.h"
46#include "llvm/Transforms/Utils/BuildLibCalls.h"
Preston Gurd2e2efd92012-09-04 18:22:17 +000047#include "llvm/Transforms/Utils/BypassSlowDivision.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000048#include "llvm/Transforms/Utils/Local.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000049using namespace llvm;
Chris Lattner088a1e82008-11-25 04:42:10 +000050using namespace llvm::PatternMatch;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000051
Cameron Zwarich31ff1332011-01-05 17:27:27 +000052STATISTIC(NumBlocksElim, "Number of blocks eliminated");
Evan Cheng485fafc2011-03-21 01:19:09 +000053STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated");
54STATISTIC(NumGEPsElim, "Number of GEPs converted to casts");
Cameron Zwarich31ff1332011-01-05 17:27:27 +000055STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "
56 "sunken Cmps");
57STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
58 "of sunken Casts");
59STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "
60 "computations were sunk");
Evan Cheng485fafc2011-03-21 01:19:09 +000061STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads");
62STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized");
63STATISTIC(NumRetsDup, "Number of return instructions duplicated");
Devang Patelf56ea612011-08-18 00:50:51 +000064STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved");
Benjamin Kramer59957502012-05-05 12:49:22 +000065STATISTIC(NumSelectsExpanded, "Number of selects turned into branches");
Jakob Stoklund Olesen7eb589d2010-09-30 20:51:52 +000066
Cameron Zwarich899eaa32011-03-11 21:52:04 +000067static cl::opt<bool> DisableBranchOpts(
68 "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
69 cl::desc("Disable branch optimizations in CodeGenPrepare"));
70
Benjamin Kramer77c4ef82012-05-06 14:25:16 +000071static cl::opt<bool> DisableSelectToBranch(
72 "disable-cgp-select2branch", cl::Hidden, cl::init(false),
73 cl::desc("Disable select to branch conversion."));
Benjamin Kramer59957502012-05-05 12:49:22 +000074
Eric Christopher692bf6b2008-09-24 05:32:41 +000075namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +000076 class CodeGenPrepare : public FunctionPass {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000077 /// TLI - Keep a pointer of a TargetLowering to consult for determining
78 /// transformation profitability.
79 const TargetLowering *TLI;
Chad Rosier618c1db2011-12-01 03:08:23 +000080 const TargetLibraryInfo *TLInfo;
Cameron Zwarich80f6a502011-01-08 17:01:52 +000081 DominatorTree *DT;
Evan Cheng04149f72009-12-17 09:39:49 +000082 ProfileInfo *PFI;
Nadav Rotema94d6e82012-07-24 10:51:42 +000083
Chris Lattner75796092011-01-15 07:14:54 +000084 /// CurInstIterator - As we scan instructions optimizing them, this is the
85 /// next instruction to optimize. Xforms that can invalidate this should
86 /// update it.
87 BasicBlock::iterator CurInstIterator;
Evan Chengab631522008-12-19 18:03:11 +000088
Evan Cheng485fafc2011-03-21 01:19:09 +000089 /// Keeps track of non-local addresses that have been sunk into a block.
90 /// This allows us to avoid inserting duplicate code for blocks with
91 /// multiple load/stores of the same address.
Cameron Zwarich8c3527e2011-01-06 00:42:50 +000092 DenseMap<Value*, Value*> SunkAddrs;
93
Devang Patel52e37df2011-03-24 15:35:25 +000094 /// ModifiedDT - If CFG is modified in anyway, dominator tree may need to
Evan Cheng485fafc2011-03-21 01:19:09 +000095 /// be updated.
Devang Patel52e37df2011-03-24 15:35:25 +000096 bool ModifiedDT;
Evan Cheng485fafc2011-03-21 01:19:09 +000097
Benjamin Kramer59957502012-05-05 12:49:22 +000098 /// OptSize - True if optimizing for size.
99 bool OptSize;
100
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000101 public:
Nick Lewyckyecd94c82007-05-06 13:37:16 +0000102 static char ID; // Pass identification, replacement for typeid
Dan Gohmanc2bbfc12007-08-01 15:32:29 +0000103 explicit CodeGenPrepare(const TargetLowering *tli = 0)
Owen Anderson081c34b2010-10-19 17:21:58 +0000104 : FunctionPass(ID), TLI(tli) {
105 initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
106 }
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000107 bool runOnFunction(Function &F);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000108
Andreas Neustifterad809812009-09-16 09:26:52 +0000109 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Cameron Zwarich80f6a502011-01-08 17:01:52 +0000110 AU.addPreserved<DominatorTree>();
Andreas Neustifterad809812009-09-16 09:26:52 +0000111 AU.addPreserved<ProfileInfo>();
Chad Rosier618c1db2011-12-01 03:08:23 +0000112 AU.addRequired<TargetLibraryInfo>();
Andreas Neustifterad809812009-09-16 09:26:52 +0000113 }
114
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000115 private:
Nadav Rotem3e883732012-08-14 05:19:07 +0000116 bool EliminateFallThrough(Function &F);
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000117 bool EliminateMostlyEmptyBlocks(Function &F);
118 bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
119 void EliminateMostlyEmptyBlock(BasicBlock *BB);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000120 bool OptimizeBlock(BasicBlock &BB);
Cameron Zwarichc0611012011-01-06 02:37:26 +0000121 bool OptimizeInst(Instruction *I);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000122 bool OptimizeMemoryInst(Instruction *I, Value *Addr, Type *AccessTy);
Chris Lattner75796092011-01-15 07:14:54 +0000123 bool OptimizeInlineAsmInst(CallInst *CS);
Eric Christopher040056f2010-03-11 02:41:03 +0000124 bool OptimizeCallInst(CallInst *CI);
Dan Gohmanb00f2362009-10-16 20:59:35 +0000125 bool MoveExtToFormExtLoad(Instruction *I);
Evan Chengbdcb7262007-12-05 23:58:20 +0000126 bool OptimizeExtUses(Instruction *I);
Benjamin Kramer59957502012-05-05 12:49:22 +0000127 bool OptimizeSelectInst(SelectInst *SI);
Evan Cheng485fafc2011-03-21 01:19:09 +0000128 bool DupRetToEnableTailCallOpts(ReturnInst *RI);
Devang Patelf56ea612011-08-18 00:50:51 +0000129 bool PlaceDbgValues(Function &F);
Hans Wennborg93ba1332012-09-19 07:48:16 +0000130 bool ConvertLoadToSwitch(LoadInst *LI);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000131 };
132}
Devang Patel794fd752007-05-01 21:15:47 +0000133
Devang Patel19974732007-05-03 01:11:54 +0000134char CodeGenPrepare::ID = 0;
Chad Rosier618c1db2011-12-01 03:08:23 +0000135INITIALIZE_PASS_BEGIN(CodeGenPrepare, "codegenprepare",
136 "Optimize for code generation", false, false)
137INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
138INITIALIZE_PASS_END(CodeGenPrepare, "codegenprepare",
Owen Andersonce665bd2010-10-07 22:25:06 +0000139 "Optimize for code generation", false, false)
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000140
141FunctionPass *llvm::createCodeGenPreparePass(const TargetLowering *TLI) {
142 return new CodeGenPrepare(TLI);
143}
144
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000145bool CodeGenPrepare::runOnFunction(Function &F) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000146 bool EverMadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000147
Devang Patel52e37df2011-03-24 15:35:25 +0000148 ModifiedDT = false;
Chad Rosier618c1db2011-12-01 03:08:23 +0000149 TLInfo = &getAnalysis<TargetLibraryInfo>();
Cameron Zwarich80f6a502011-01-08 17:01:52 +0000150 DT = getAnalysisIfAvailable<DominatorTree>();
Evan Cheng04149f72009-12-17 09:39:49 +0000151 PFI = getAnalysisIfAvailable<ProfileInfo>();
Bill Wendling67658342012-10-09 07:45:08 +0000152 OptSize = F.getFnAttributes().hasAttribute(Attributes::OptimizeForSize);
Evan Cheng485fafc2011-03-21 01:19:09 +0000153
Preston Gurd2e2efd92012-09-04 18:22:17 +0000154 /// This optimization identifies DIV instructions that can be
155 /// profitably bypassed and carried out with a shorter, faster divide.
156 if (TLI && TLI->isSlowDivBypassed()) {
Preston Gurd8d662b52012-10-04 21:33:40 +0000157 const DenseMap<unsigned int, unsigned int> &BypassWidths =
158 TLI->getBypassSlowDivWidths();
Evan Cheng911908d2012-09-14 21:25:34 +0000159 for (Function::iterator I = F.begin(); I != F.end(); I++)
Preston Gurd8d662b52012-10-04 21:33:40 +0000160 EverMadeChange |= bypassSlowDivision(F, I, BypassWidths);
Preston Gurd2e2efd92012-09-04 18:22:17 +0000161 }
162
163 // Eliminate blocks that contain only PHI nodes and an
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000164 // unconditional branch.
165 EverMadeChange |= EliminateMostlyEmptyBlocks(F);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000166
Devang Patelf56ea612011-08-18 00:50:51 +0000167 // llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotema94d6e82012-07-24 10:51:42 +0000168 // handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patelf56ea612011-08-18 00:50:51 +0000169 // find a node corresponding to the value.
170 EverMadeChange |= PlaceDbgValues(F);
171
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000172 bool MadeChange = true;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000173 while (MadeChange) {
174 MadeChange = false;
Hans Wennborg93ba1332012-09-19 07:48:16 +0000175 for (Function::iterator I = F.begin(); I != F.end(); ) {
Evan Cheng485fafc2011-03-21 01:19:09 +0000176 BasicBlock *BB = I++;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000177 MadeChange |= OptimizeBlock(*BB);
Evan Cheng485fafc2011-03-21 01:19:09 +0000178 }
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000179 EverMadeChange |= MadeChange;
180 }
Cameron Zwarich8c3527e2011-01-06 00:42:50 +0000181
182 SunkAddrs.clear();
183
Cameron Zwarich899eaa32011-03-11 21:52:04 +0000184 if (!DisableBranchOpts) {
185 MadeChange = false;
Bill Wendlinge3e394d2012-03-04 10:46:01 +0000186 SmallPtrSet<BasicBlock*, 8> WorkList;
187 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
188 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
Frits van Bommel5649ba72011-05-22 16:24:18 +0000189 MadeChange |= ConstantFoldTerminator(BB, true);
Bill Wendlinge3e394d2012-03-04 10:46:01 +0000190 if (!MadeChange) continue;
191
192 for (SmallVectorImpl<BasicBlock*>::iterator
193 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
194 if (pred_begin(*II) == pred_end(*II))
195 WorkList.insert(*II);
196 }
197
Bill Wendling8dd2e5b2012-08-15 21:18:10 +0000198 for (SmallPtrSet<BasicBlock*, 8>::iterator
199 I = WorkList.begin(), E = WorkList.end(); I != E; ++I)
200 DeleteDeadBlock(*I);
Cameron Zwarich899eaa32011-03-11 21:52:04 +0000201
Nadav Rotem3e883732012-08-14 05:19:07 +0000202 // Merge pairs of basic blocks with unconditional branches, connected by
203 // a single edge.
204 if (EverMadeChange || MadeChange)
205 MadeChange |= EliminateFallThrough(F);
206
Evan Cheng485fafc2011-03-21 01:19:09 +0000207 if (MadeChange)
Devang Patel52e37df2011-03-24 15:35:25 +0000208 ModifiedDT = true;
Cameron Zwarich899eaa32011-03-11 21:52:04 +0000209 EverMadeChange |= MadeChange;
210 }
211
Devang Patel52e37df2011-03-24 15:35:25 +0000212 if (ModifiedDT && DT)
Evan Cheng485fafc2011-03-21 01:19:09 +0000213 DT->DT->recalculate(F);
214
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000215 return EverMadeChange;
216}
217
Nadav Rotem3e883732012-08-14 05:19:07 +0000218/// EliminateFallThrough - Merge basic blocks which are connected
219/// by a single edge, where one of the basic blocks has a single successor
220/// pointing to the other basic block, which has a single predecessor.
221bool CodeGenPrepare::EliminateFallThrough(Function &F) {
222 bool Changed = false;
223 // Scan all of the blocks in the function, except for the entry block.
224 for (Function::iterator I = ++F.begin(), E = F.end(); I != E; ) {
225 BasicBlock *BB = I++;
226 // If the destination block has a single pred, then this is a trivial
227 // edge, just collapse it.
228 BasicBlock *SinglePred = BB->getSinglePredecessor();
229
Evan Cheng46597072012-09-28 23:58:57 +0000230 // Don't merge if BB's address is taken.
231 if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue;
Nadav Rotem3e883732012-08-14 05:19:07 +0000232
233 BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
234 if (Term && !Term->isConditional()) {
235 Changed = true;
Michael Liao787ed032012-08-21 05:55:22 +0000236 DEBUG(dbgs() << "To merge:\n"<< *SinglePred << "\n\n\n");
Nadav Rotem3e883732012-08-14 05:19:07 +0000237 // Remember if SinglePred was the entry block of the function.
238 // If so, we will need to move BB back to the entry position.
239 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
240 MergeBasicBlockIntoOnlyPred(BB, this);
241
242 if (isEntry && BB != &BB->getParent()->getEntryBlock())
243 BB->moveBefore(&BB->getParent()->getEntryBlock());
244
245 // We have erased a block. Update the iterator.
246 I = BB;
Nadav Rotem3e883732012-08-14 05:19:07 +0000247 }
248 }
249 return Changed;
250}
251
Dale Johannesen2d697242009-03-27 01:13:37 +0000252/// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes,
253/// debug info directives, and an unconditional branch. Passes before isel
254/// (e.g. LSR/loopsimplify) often split edges in ways that are non-optimal for
255/// isel. Start by eliminating these blocks so we can split them the way we
256/// want them.
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000257bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
258 bool MadeChange = false;
259 // Note that this intentionally skips the entry block.
260 for (Function::iterator I = ++F.begin(), E = F.end(); I != E; ) {
261 BasicBlock *BB = I++;
262
263 // If this block doesn't end with an uncond branch, ignore it.
264 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
265 if (!BI || !BI->isUnconditional())
266 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000267
Dale Johannesen2d697242009-03-27 01:13:37 +0000268 // If the instruction before the branch (skipping debug info) isn't a phi
269 // node, then other stuff is happening here.
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000270 BasicBlock::iterator BBI = BI;
271 if (BBI != BB->begin()) {
272 --BBI;
Dale Johannesen2d697242009-03-27 01:13:37 +0000273 while (isa<DbgInfoIntrinsic>(BBI)) {
274 if (BBI == BB->begin())
275 break;
276 --BBI;
277 }
278 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
279 continue;
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000280 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000281
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000282 // Do not break infinite loops.
283 BasicBlock *DestBB = BI->getSuccessor(0);
284 if (DestBB == BB)
285 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000286
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000287 if (!CanMergeBlocks(BB, DestBB))
288 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000289
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000290 EliminateMostlyEmptyBlock(BB);
291 MadeChange = true;
292 }
293 return MadeChange;
294}
295
296/// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
297/// single uncond branch between them, and BB contains no other non-phi
298/// instructions.
299bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
300 const BasicBlock *DestBB) const {
301 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
302 // the successor. If there are more complex condition (e.g. preheaders),
303 // don't mess around with them.
304 BasicBlock::const_iterator BBI = BB->begin();
305 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
Gabor Greif60ad7812010-03-25 23:06:16 +0000306 for (Value::const_use_iterator UI = PN->use_begin(), E = PN->use_end();
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000307 UI != E; ++UI) {
308 const Instruction *User = cast<Instruction>(*UI);
309 if (User->getParent() != DestBB || !isa<PHINode>(User))
310 return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000311 // If User is inside DestBB block and it is a PHINode then check
312 // incoming value. If incoming value is not from BB then this is
Devang Patel75abc1e2007-04-25 00:37:04 +0000313 // a complex condition (e.g. preheaders) we want to avoid here.
314 if (User->getParent() == DestBB) {
315 if (const PHINode *UPN = dyn_cast<PHINode>(User))
316 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
317 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
318 if (Insn && Insn->getParent() == BB &&
319 Insn->getParent() != UPN->getIncomingBlock(I))
320 return false;
321 }
322 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000323 }
324 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000325
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000326 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
327 // and DestBB may have conflicting incoming values for the block. If so, we
328 // can't merge the block.
329 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
330 if (!DestBBPN) return true; // no conflict.
Eric Christopher692bf6b2008-09-24 05:32:41 +0000331
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000332 // Collect the preds of BB.
Chris Lattnerf67f73a2007-11-06 22:07:40 +0000333 SmallPtrSet<const BasicBlock*, 16> BBPreds;
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000334 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
335 // It is faster to get preds from a PHI than with pred_iterator.
336 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
337 BBPreds.insert(BBPN->getIncomingBlock(i));
338 } else {
339 BBPreds.insert(pred_begin(BB), pred_end(BB));
340 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000341
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000342 // Walk the preds of DestBB.
343 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
344 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
345 if (BBPreds.count(Pred)) { // Common predecessor?
346 BBI = DestBB->begin();
347 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
348 const Value *V1 = PN->getIncomingValueForBlock(Pred);
349 const Value *V2 = PN->getIncomingValueForBlock(BB);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000350
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000351 // If V2 is a phi node in BB, look up what the mapped value will be.
352 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
353 if (V2PN->getParent() == BB)
354 V2 = V2PN->getIncomingValueForBlock(Pred);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000355
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000356 // If there is a conflict, bail out.
357 if (V1 != V2) return false;
358 }
359 }
360 }
361
362 return true;
363}
364
365
366/// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
367/// an unconditional branch in it.
368void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
369 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
370 BasicBlock *DestBB = BI->getSuccessor(0);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000371
David Greene68d67fd2010-01-05 01:27:11 +0000372 DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000373
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000374 // If the destination block has a single pred, then this is a trivial edge,
375 // just collapse it.
Chris Lattner9918fb52008-11-27 19:29:14 +0000376 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
Chris Lattnerf5102a02008-11-28 19:54:49 +0000377 if (SinglePred != DestBB) {
378 // Remember if SinglePred was the entry block of the function. If so, we
379 // will need to move BB back to the entry position.
380 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Andreas Neustifterad809812009-09-16 09:26:52 +0000381 MergeBasicBlockIntoOnlyPred(DestBB, this);
Chris Lattner9918fb52008-11-27 19:29:14 +0000382
Chris Lattnerf5102a02008-11-28 19:54:49 +0000383 if (isEntry && BB != &BB->getParent()->getEntryBlock())
384 BB->moveBefore(&BB->getParent()->getEntryBlock());
Nadav Rotema94d6e82012-07-24 10:51:42 +0000385
David Greene68d67fd2010-01-05 01:27:11 +0000386 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerf5102a02008-11-28 19:54:49 +0000387 return;
388 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000389 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000390
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000391 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
392 // to handle the new incoming edges it is about to have.
393 PHINode *PN;
394 for (BasicBlock::iterator BBI = DestBB->begin();
395 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
396 // Remove the incoming value for BB, and remember it.
397 Value *InVal = PN->removeIncomingValue(BB, false);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000398
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000399 // Two options: either the InVal is a phi node defined in BB or it is some
400 // value that dominates BB.
401 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
402 if (InValPhi && InValPhi->getParent() == BB) {
403 // Add all of the input values of the input PHI as inputs of this phi.
404 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
405 PN->addIncoming(InValPhi->getIncomingValue(i),
406 InValPhi->getIncomingBlock(i));
407 } else {
408 // Otherwise, add one instance of the dominating value for each edge that
409 // we will be adding.
410 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
411 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
412 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
413 } else {
414 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
415 PN->addIncoming(InVal, *PI);
416 }
417 }
418 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000419
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000420 // The PHIs are now updated, change everything that refers to BB to use
421 // DestBB and remove BB.
422 BB->replaceAllUsesWith(DestBB);
Devang Patel52e37df2011-03-24 15:35:25 +0000423 if (DT && !ModifiedDT) {
Cameron Zwarich80f6a502011-01-08 17:01:52 +0000424 BasicBlock *BBIDom = DT->getNode(BB)->getIDom()->getBlock();
425 BasicBlock *DestBBIDom = DT->getNode(DestBB)->getIDom()->getBlock();
426 BasicBlock *NewIDom = DT->findNearestCommonDominator(BBIDom, DestBBIDom);
427 DT->changeImmediateDominator(DestBB, NewIDom);
428 DT->eraseNode(BB);
429 }
Evan Cheng04149f72009-12-17 09:39:49 +0000430 if (PFI) {
431 PFI->replaceAllUses(BB, DestBB);
432 PFI->removeEdge(ProfileInfo::getEdge(BB, DestBB));
Andreas Neustifterad809812009-09-16 09:26:52 +0000433 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000434 BB->eraseFromParent();
Cameron Zwarich31ff1332011-01-05 17:27:27 +0000435 ++NumBlocksElim;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000436
David Greene68d67fd2010-01-05 01:27:11 +0000437 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000438}
439
Chris Lattnerdd77df32007-04-13 20:30:56 +0000440/// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
Dan Gohmana119de82009-06-14 23:30:43 +0000441/// copy (e.g. it's casting from one pointer type to another, i32->i8 on PPC),
442/// sink it into user blocks to reduce the number of virtual
Dale Johannesence0b2372007-06-12 16:50:17 +0000443/// registers that must be created and coalesced.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000444///
445/// Return true if any changes are made.
Chris Lattner85fa13c2008-11-24 22:44:16 +0000446///
Chris Lattnerdd77df32007-04-13 20:30:56 +0000447static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
Eric Christopher692bf6b2008-09-24 05:32:41 +0000448 // If this is a noop copy,
Owen Andersone50ed302009-08-10 22:56:29 +0000449 EVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
450 EVT DstVT = TLI.getValueType(CI->getType());
Eric Christopher692bf6b2008-09-24 05:32:41 +0000451
Chris Lattnerdd77df32007-04-13 20:30:56 +0000452 // This is an fp<->int conversion?
Duncan Sands83ec4b62008-06-06 12:08:01 +0000453 if (SrcVT.isInteger() != DstVT.isInteger())
Chris Lattnerdd77df32007-04-13 20:30:56 +0000454 return false;
Duncan Sands8e4eb092008-06-08 20:54:56 +0000455
Chris Lattnerdd77df32007-04-13 20:30:56 +0000456 // If this is an extension, it will be a zero or sign extension, which
457 // isn't a noop.
Duncan Sands8e4eb092008-06-08 20:54:56 +0000458 if (SrcVT.bitsLT(DstVT)) return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000459
Chris Lattnerdd77df32007-04-13 20:30:56 +0000460 // If these values will be promoted, find out what they will be promoted
461 // to. This helps us consider truncates on PPC as noop copies when they
462 // are.
Nadav Rotem0ccc12a2011-05-29 08:10:47 +0000463 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
464 TargetLowering::TypePromoteInteger)
Owen Anderson23b9b192009-08-12 00:36:31 +0000465 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
Nadav Rotem0ccc12a2011-05-29 08:10:47 +0000466 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
467 TargetLowering::TypePromoteInteger)
Owen Anderson23b9b192009-08-12 00:36:31 +0000468 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000469
Chris Lattnerdd77df32007-04-13 20:30:56 +0000470 // If, after promotion, these are the same types, this is a noop copy.
471 if (SrcVT != DstVT)
472 return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000473
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000474 BasicBlock *DefBB = CI->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000475
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000476 /// InsertedCasts - Only insert a cast in each block once.
Dale Johannesence0b2372007-06-12 16:50:17 +0000477 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000478
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000479 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000480 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000481 UI != E; ) {
482 Use &TheUse = UI.getUse();
483 Instruction *User = cast<Instruction>(*UI);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000484
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000485 // Figure out which BB this cast is used in. For PHI's this is the
486 // appropriate predecessor block.
487 BasicBlock *UserBB = User->getParent();
488 if (PHINode *PN = dyn_cast<PHINode>(User)) {
Gabor Greifa36791d2009-01-23 19:40:15 +0000489 UserBB = PN->getIncomingBlock(UI);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000490 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000491
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000492 // Preincrement use iterator so we don't invalidate it.
493 ++UI;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000494
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000495 // If this user is in the same block as the cast, don't change the cast.
496 if (UserBB == DefBB) continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000497
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000498 // If we have already inserted a cast into this block, use it.
499 CastInst *&InsertedCast = InsertedCasts[UserBB];
500
501 if (!InsertedCast) {
Bill Wendling5b6f42f2011-08-16 20:45:24 +0000502 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000503 InsertedCast =
504 CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000505 InsertPt);
506 MadeChange = true;
507 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000508
Dale Johannesence0b2372007-06-12 16:50:17 +0000509 // Replace a use of the cast with a use of the new cast.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000510 TheUse = InsertedCast;
Cameron Zwarich31ff1332011-01-05 17:27:27 +0000511 ++NumCastUses;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000512 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000513
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000514 // If we removed all uses, nuke the cast.
Duncan Sandse0038132008-01-20 16:51:46 +0000515 if (CI->use_empty()) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000516 CI->eraseFromParent();
Duncan Sandse0038132008-01-20 16:51:46 +0000517 MadeChange = true;
518 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000519
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000520 return MadeChange;
521}
522
Eric Christopher692bf6b2008-09-24 05:32:41 +0000523/// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
Dale Johannesence0b2372007-06-12 16:50:17 +0000524/// the number of virtual registers that must be created and coalesced. This is
Chris Lattner684b22d2007-08-02 16:53:43 +0000525/// a clear win except on targets with multiple condition code registers
526/// (PowerPC), where it might lose; some adjustment may be wanted there.
Dale Johannesence0b2372007-06-12 16:50:17 +0000527///
528/// Return true if any changes are made.
Chris Lattner85fa13c2008-11-24 22:44:16 +0000529static bool OptimizeCmpExpression(CmpInst *CI) {
Dale Johannesence0b2372007-06-12 16:50:17 +0000530 BasicBlock *DefBB = CI->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000531
Dale Johannesence0b2372007-06-12 16:50:17 +0000532 /// InsertedCmp - Only insert a cmp in each block once.
533 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000534
Dale Johannesence0b2372007-06-12 16:50:17 +0000535 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000536 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
Dale Johannesence0b2372007-06-12 16:50:17 +0000537 UI != E; ) {
538 Use &TheUse = UI.getUse();
539 Instruction *User = cast<Instruction>(*UI);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000540
Dale Johannesence0b2372007-06-12 16:50:17 +0000541 // Preincrement use iterator so we don't invalidate it.
542 ++UI;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000543
Dale Johannesence0b2372007-06-12 16:50:17 +0000544 // Don't bother for PHI nodes.
545 if (isa<PHINode>(User))
546 continue;
547
548 // Figure out which BB this cmp is used in.
549 BasicBlock *UserBB = User->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000550
Dale Johannesence0b2372007-06-12 16:50:17 +0000551 // If this user is in the same block as the cmp, don't change the cmp.
552 if (UserBB == DefBB) continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000553
Dale Johannesence0b2372007-06-12 16:50:17 +0000554 // If we have already inserted a cmp into this block, use it.
555 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
556
557 if (!InsertedCmp) {
Bill Wendling5b6f42f2011-08-16 20:45:24 +0000558 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000559 InsertedCmp =
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000560 CmpInst::Create(CI->getOpcode(),
Owen Anderson333c4002009-07-09 23:48:35 +0000561 CI->getPredicate(), CI->getOperand(0),
Dale Johannesence0b2372007-06-12 16:50:17 +0000562 CI->getOperand(1), "", InsertPt);
563 MadeChange = true;
564 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000565
Dale Johannesence0b2372007-06-12 16:50:17 +0000566 // Replace a use of the cmp with a use of the new cmp.
567 TheUse = InsertedCmp;
Cameron Zwarich31ff1332011-01-05 17:27:27 +0000568 ++NumCmpUses;
Dale Johannesence0b2372007-06-12 16:50:17 +0000569 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000570
Dale Johannesence0b2372007-06-12 16:50:17 +0000571 // If we removed all uses, nuke the cmp.
572 if (CI->use_empty())
573 CI->eraseFromParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000574
Dale Johannesence0b2372007-06-12 16:50:17 +0000575 return MadeChange;
576}
577
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000578namespace {
579class CodeGenPrepareFortifiedLibCalls : public SimplifyFortifiedLibCalls {
580protected:
581 void replaceCall(Value *With) {
582 CI->replaceAllUsesWith(With);
583 CI->eraseFromParent();
584 }
585 bool isFoldable(unsigned SizeCIOp, unsigned, bool) const {
Gabor Greifa6aac4c2010-07-16 09:38:02 +0000586 if (ConstantInt *SizeCI =
587 dyn_cast<ConstantInt>(CI->getArgOperand(SizeCIOp)))
588 return SizeCI->isAllOnesValue();
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000589 return false;
590 }
591};
592} // end anonymous namespace
593
Eric Christopher040056f2010-03-11 02:41:03 +0000594bool CodeGenPrepare::OptimizeCallInst(CallInst *CI) {
Chris Lattner75796092011-01-15 07:14:54 +0000595 BasicBlock *BB = CI->getParent();
Nadav Rotema94d6e82012-07-24 10:51:42 +0000596
Chris Lattner75796092011-01-15 07:14:54 +0000597 // Lower inline assembly if we can.
598 // If we found an inline asm expession, and if the target knows how to
599 // lower it to normal LLVM code, do so now.
600 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
601 if (TLI->ExpandInlineAsm(CI)) {
602 // Avoid invalidating the iterator.
603 CurInstIterator = BB->begin();
604 // Avoid processing instructions out of order, which could cause
605 // reuse before a value is defined.
606 SunkAddrs.clear();
607 return true;
608 }
609 // Sink address computing for memory operands into the block.
610 if (OptimizeInlineAsmInst(CI))
611 return true;
612 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000613
Eric Christopher040056f2010-03-11 02:41:03 +0000614 // Lower all uses of llvm.objectsize.*
615 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
616 if (II && II->getIntrinsicID() == Intrinsic::objectsize) {
Gabor Greifde9f5452010-06-24 00:44:01 +0000617 bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000618 Type *ReturnTy = CI->getType();
Nadav Rotema94d6e82012-07-24 10:51:42 +0000619 Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
620
Chris Lattner94e8e0c2011-01-15 07:25:29 +0000621 // Substituting this can cause recursive simplifications, which can
622 // invalidate our iterator. Use a WeakVH to hold onto it in case this
623 // happens.
624 WeakVH IterHandle(CurInstIterator);
Nadav Rotema94d6e82012-07-24 10:51:42 +0000625
Micah Villmow3574eca2012-10-08 16:38:25 +0000626 replaceAndRecursivelySimplify(CI, RetVal, TLI ? TLI->getDataLayout() : 0,
Chandler Carruth6b980542012-03-24 21:11:24 +0000627 TLInfo, ModifiedDT ? 0 : DT);
Chris Lattner94e8e0c2011-01-15 07:25:29 +0000628
629 // If the iterator instruction was recursively deleted, start over at the
630 // start of the block.
Chris Lattner435b4d22011-01-18 20:53:04 +0000631 if (IterHandle != CurInstIterator) {
Chris Lattner94e8e0c2011-01-15 07:25:29 +0000632 CurInstIterator = BB->begin();
Chris Lattner435b4d22011-01-18 20:53:04 +0000633 SunkAddrs.clear();
634 }
Eric Christopher040056f2010-03-11 02:41:03 +0000635 return true;
636 }
637
Pete Cooperf210b682012-03-13 20:59:56 +0000638 if (II && TLI) {
639 SmallVector<Value*, 2> PtrOps;
640 Type *AccessTy;
641 if (TLI->GetAddrModeArguments(II, PtrOps, AccessTy))
642 while (!PtrOps.empty())
643 if (OptimizeMemoryInst(II, PtrOps.pop_back_val(), AccessTy))
644 return true;
645 }
646
Eric Christopher040056f2010-03-11 02:41:03 +0000647 // From here on out we're working with named functions.
648 if (CI->getCalledFunction() == 0) return false;
Devang Patel97de92c2011-05-26 21:51:06 +0000649
Micah Villmow3574eca2012-10-08 16:38:25 +0000650 // We'll need DataLayout from here on out.
651 const DataLayout *TD = TLI ? TLI->getDataLayout() : 0;
Eric Christopher040056f2010-03-11 02:41:03 +0000652 if (!TD) return false;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000653
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000654 // Lower all default uses of _chk calls. This is very similar
655 // to what InstCombineCalls does, but here we are only lowering calls
Eric Christopher040056f2010-03-11 02:41:03 +0000656 // that have the default "don't know" as the objectsize. Anything else
657 // should be left alone.
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000658 CodeGenPrepareFortifiedLibCalls Simplifier;
Nuno Lopes51004df2012-07-25 16:46:31 +0000659 return Simplifier.fold(CI, TD, TLInfo);
Eric Christopher040056f2010-03-11 02:41:03 +0000660}
Chris Lattner94e8e0c2011-01-15 07:25:29 +0000661
Evan Cheng485fafc2011-03-21 01:19:09 +0000662/// DupRetToEnableTailCallOpts - Look for opportunities to duplicate return
663/// instructions to the predecessor to enable tail call optimizations. The
664/// case it is currently looking for is:
Dmitri Gribenko2d9eb722012-09-13 12:34:29 +0000665/// @code
Evan Cheng485fafc2011-03-21 01:19:09 +0000666/// bb0:
667/// %tmp0 = tail call i32 @f0()
668/// br label %return
669/// bb1:
670/// %tmp1 = tail call i32 @f1()
671/// br label %return
672/// bb2:
673/// %tmp2 = tail call i32 @f2()
674/// br label %return
675/// return:
676/// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
677/// ret i32 %retval
Dmitri Gribenko2d9eb722012-09-13 12:34:29 +0000678/// @endcode
Evan Cheng485fafc2011-03-21 01:19:09 +0000679///
680/// =>
681///
Dmitri Gribenko2d9eb722012-09-13 12:34:29 +0000682/// @code
Evan Cheng485fafc2011-03-21 01:19:09 +0000683/// bb0:
684/// %tmp0 = tail call i32 @f0()
685/// ret i32 %tmp0
686/// bb1:
687/// %tmp1 = tail call i32 @f1()
688/// ret i32 %tmp1
689/// bb2:
690/// %tmp2 = tail call i32 @f2()
691/// ret i32 %tmp2
Dmitri Gribenko2d9eb722012-09-13 12:34:29 +0000692/// @endcode
Evan Cheng485fafc2011-03-21 01:19:09 +0000693bool CodeGenPrepare::DupRetToEnableTailCallOpts(ReturnInst *RI) {
Cameron Zwarich661a3902011-03-24 04:51:51 +0000694 if (!TLI)
695 return false;
696
Evan Cheng9c777a42012-07-27 21:21:26 +0000697 PHINode *PN = 0;
698 BitCastInst *BCI = 0;
Evan Cheng485fafc2011-03-21 01:19:09 +0000699 Value *V = RI->getReturnValue();
Evan Cheng9c777a42012-07-27 21:21:26 +0000700 if (V) {
701 BCI = dyn_cast<BitCastInst>(V);
702 if (BCI)
703 V = BCI->getOperand(0);
704
705 PN = dyn_cast<PHINode>(V);
706 if (!PN)
707 return false;
708 }
Evan Cheng485fafc2011-03-21 01:19:09 +0000709
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000710 BasicBlock *BB = RI->getParent();
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000711 if (PN && PN->getParent() != BB)
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000712 return false;
Evan Cheng485fafc2011-03-21 01:19:09 +0000713
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000714 // It's not safe to eliminate the sign / zero extension of the return value.
715 // See llvm::isInTailCallPosition().
716 const Function *F = BB->getParent();
Kostya Serebryany164b86b2012-01-20 17:56:17 +0000717 Attributes CallerRetAttr = F->getAttributes().getRetAttributes();
Bill Wendling67658342012-10-09 07:45:08 +0000718 if (CallerRetAttr.hasAttribute(Attributes::ZExt) ||
719 CallerRetAttr.hasAttribute(Attributes::SExt))
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000720 return false;
Evan Cheng485fafc2011-03-21 01:19:09 +0000721
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000722 // Make sure there are no instructions between the PHI and return, or that the
723 // return is the first instruction in the block.
724 if (PN) {
725 BasicBlock::iterator BI = BB->begin();
726 do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
Evan Cheng9c777a42012-07-27 21:21:26 +0000727 if (&*BI == BCI)
728 // Also skip over the bitcast.
729 ++BI;
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000730 if (&*BI != RI)
731 return false;
732 } else {
Cameron Zwarich90354842011-03-24 16:34:59 +0000733 BasicBlock::iterator BI = BB->begin();
734 while (isa<DbgInfoIntrinsic>(BI)) ++BI;
735 if (&*BI != RI)
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000736 return false;
737 }
Evan Cheng485fafc2011-03-21 01:19:09 +0000738
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000739 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
740 /// call.
741 SmallVector<CallInst*, 4> TailCalls;
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000742 if (PN) {
743 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
744 CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
745 // Make sure the phi value is indeed produced by the tail call.
746 if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
747 TLI->mayBeEmittedAsTailCall(CI))
748 TailCalls.push_back(CI);
749 }
750 } else {
751 SmallPtrSet<BasicBlock*, 4> VisitedBBs;
752 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
753 if (!VisitedBBs.insert(*PI))
754 continue;
755
756 BasicBlock::InstListType &InstList = (*PI)->getInstList();
757 BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
758 BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
Cameron Zwarich90354842011-03-24 16:34:59 +0000759 do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
760 if (RI == RE)
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000761 continue;
Cameron Zwarich90354842011-03-24 16:34:59 +0000762
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000763 CallInst *CI = dyn_cast<CallInst>(&*RI);
Cameron Zwarichdc31cfe2011-03-24 15:54:11 +0000764 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI))
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000765 TailCalls.push_back(CI);
766 }
Evan Cheng485fafc2011-03-21 01:19:09 +0000767 }
768
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000769 bool Changed = false;
770 for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
771 CallInst *CI = TailCalls[i];
772 CallSite CS(CI);
773
774 // Conservatively require the attributes of the call to match those of the
775 // return. Ignore noalias because it doesn't affect the call sequence.
Kostya Serebryany164b86b2012-01-20 17:56:17 +0000776 Attributes CalleeRetAttr = CS.getAttributes().getRetAttributes();
Bill Wendling702cc912012-10-15 20:35:56 +0000777 if (AttrBuilder(CalleeRetAttr).
Bill Wendling3756e702012-10-14 06:56:13 +0000778 removeAttribute(Attributes::NoAlias) !=
Bill Wendling702cc912012-10-15 20:35:56 +0000779 AttrBuilder(CallerRetAttr).
Bill Wendling3756e702012-10-14 06:56:13 +0000780 removeAttribute(Attributes::NoAlias))
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000781 continue;
782
783 // Make sure the call instruction is followed by an unconditional branch to
784 // the return block.
785 BasicBlock *CallBB = CI->getParent();
786 BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
787 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
788 continue;
789
790 // Duplicate the return into CallBB.
791 (void)FoldReturnIntoUncondBranch(RI, BB, CallBB);
Devang Patel52e37df2011-03-24 15:35:25 +0000792 ModifiedDT = Changed = true;
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000793 ++NumRetsDup;
794 }
795
796 // If we eliminated all predecessors of the block, delete the block now.
Evan Cheng46597072012-09-28 23:58:57 +0000797 if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000798 BB->eraseFromParent();
799
800 return Changed;
Evan Cheng485fafc2011-03-21 01:19:09 +0000801}
802
Chris Lattner88a5c832008-11-25 07:09:13 +0000803//===----------------------------------------------------------------------===//
Chris Lattner88a5c832008-11-25 07:09:13 +0000804// Memory Optimization
805//===----------------------------------------------------------------------===//
806
Chris Lattnerdd77df32007-04-13 20:30:56 +0000807/// IsNonLocalValue - Return true if the specified values are defined in a
808/// different basic block than BB.
809static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
810 if (Instruction *I = dyn_cast<Instruction>(V))
811 return I->getParent() != BB;
812 return false;
813}
814
Bob Wilson4a8ee232009-12-03 21:47:07 +0000815/// OptimizeMemoryInst - Load and Store Instructions often have
Chris Lattnerdd77df32007-04-13 20:30:56 +0000816/// addressing modes that can do significant amounts of computation. As such,
817/// instruction selection will try to get the load or store to do as much
818/// computation as possible for the program. The problem is that isel can only
819/// see within a single block. As such, we sink as much legal addressing mode
820/// stuff into the block as possible.
Chris Lattner88a5c832008-11-25 07:09:13 +0000821///
822/// This method is used to optimize both load/store and inline asms with memory
823/// operands.
Chris Lattner896617b2008-11-26 03:20:37 +0000824bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000825 Type *AccessTy) {
Owen Anderson35bf4d62010-11-27 08:15:55 +0000826 Value *Repl = Addr;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000827
828 // Try to collapse single-value PHI nodes. This is necessary to undo
Owen Andersond2f41742010-11-19 22:15:03 +0000829 // unprofitable PRE transformations.
Cameron Zwarich7cb4fa22011-01-03 06:33:01 +0000830 SmallVector<Value*, 8> worklist;
831 SmallPtrSet<Value*, 16> Visited;
Owen Anderson35bf4d62010-11-27 08:15:55 +0000832 worklist.push_back(Addr);
Nadav Rotema94d6e82012-07-24 10:51:42 +0000833
Owen Anderson35bf4d62010-11-27 08:15:55 +0000834 // Use a worklist to iteratively look through PHI nodes, and ensure that
835 // the addressing mode obtained from the non-PHI roots of the graph
836 // are equivalent.
837 Value *Consensus = 0;
Cameron Zwarich4c078f02011-03-01 21:13:53 +0000838 unsigned NumUsesConsensus = 0;
Cameron Zwarich7c8d3512011-03-05 08:12:26 +0000839 bool IsNumUsesConsensusValid = false;
Owen Anderson35bf4d62010-11-27 08:15:55 +0000840 SmallVector<Instruction*, 16> AddrModeInsts;
841 ExtAddrMode AddrMode;
842 while (!worklist.empty()) {
843 Value *V = worklist.back();
844 worklist.pop_back();
Nadav Rotema94d6e82012-07-24 10:51:42 +0000845
Owen Anderson35bf4d62010-11-27 08:15:55 +0000846 // Break use-def graph loops.
Nick Lewycky48105282011-09-29 23:40:12 +0000847 if (!Visited.insert(V)) {
Owen Anderson35bf4d62010-11-27 08:15:55 +0000848 Consensus = 0;
849 break;
Owen Andersond2f41742010-11-19 22:15:03 +0000850 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000851
Owen Anderson35bf4d62010-11-27 08:15:55 +0000852 // For a PHI node, push all of its incoming values.
853 if (PHINode *P = dyn_cast<PHINode>(V)) {
854 for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i)
855 worklist.push_back(P->getIncomingValue(i));
856 continue;
857 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000858
Owen Anderson35bf4d62010-11-27 08:15:55 +0000859 // For non-PHIs, determine the addressing mode being computed.
860 SmallVector<Instruction*, 16> NewAddrModeInsts;
861 ExtAddrMode NewAddrMode =
Nick Lewycky48105282011-09-29 23:40:12 +0000862 AddressingModeMatcher::Match(V, AccessTy, MemoryInst,
Owen Anderson35bf4d62010-11-27 08:15:55 +0000863 NewAddrModeInsts, *TLI);
Cameron Zwarich7c8d3512011-03-05 08:12:26 +0000864
865 // This check is broken into two cases with very similar code to avoid using
866 // getNumUses() as much as possible. Some values have a lot of uses, so
867 // calling getNumUses() unconditionally caused a significant compile-time
868 // regression.
869 if (!Consensus) {
870 Consensus = V;
871 AddrMode = NewAddrMode;
872 AddrModeInsts = NewAddrModeInsts;
873 continue;
874 } else if (NewAddrMode == AddrMode) {
875 if (!IsNumUsesConsensusValid) {
876 NumUsesConsensus = Consensus->getNumUses();
877 IsNumUsesConsensusValid = true;
878 }
879
880 // Ensure that the obtained addressing mode is equivalent to that obtained
881 // for all other roots of the PHI traversal. Also, when choosing one
882 // such root as representative, select the one with the most uses in order
883 // to keep the cost modeling heuristics in AddressingModeMatcher
884 // applicable.
Cameron Zwarich4c078f02011-03-01 21:13:53 +0000885 unsigned NumUses = V->getNumUses();
886 if (NumUses > NumUsesConsensus) {
Owen Anderson35bf4d62010-11-27 08:15:55 +0000887 Consensus = V;
Cameron Zwarich4c078f02011-03-01 21:13:53 +0000888 NumUsesConsensus = NumUses;
Owen Anderson35bf4d62010-11-27 08:15:55 +0000889 AddrModeInsts = NewAddrModeInsts;
890 }
891 continue;
892 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000893
Owen Anderson35bf4d62010-11-27 08:15:55 +0000894 Consensus = 0;
895 break;
Owen Andersond2f41742010-11-19 22:15:03 +0000896 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000897
Owen Anderson35bf4d62010-11-27 08:15:55 +0000898 // If the addressing mode couldn't be determined, or if multiple different
899 // ones were determined, bail out now.
900 if (!Consensus) return false;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000901
Chris Lattnerdd77df32007-04-13 20:30:56 +0000902 // Check to see if any of the instructions supersumed by this addr mode are
903 // non-local to I's BB.
904 bool AnyNonLocal = false;
905 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
Chris Lattner896617b2008-11-26 03:20:37 +0000906 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
Chris Lattnerdd77df32007-04-13 20:30:56 +0000907 AnyNonLocal = true;
908 break;
909 }
910 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000911
Chris Lattnerdd77df32007-04-13 20:30:56 +0000912 // If all the instructions matched are already in this BB, don't do anything.
913 if (!AnyNonLocal) {
David Greene68d67fd2010-01-05 01:27:11 +0000914 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000915 return false;
916 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000917
Chris Lattnerdd77df32007-04-13 20:30:56 +0000918 // Insert this computation right after this user. Since our caller is
919 // scanning from the top of the BB to the bottom, reuse of the expr are
920 // guaranteed to happen later.
Devang Patel2048c372011-09-06 18:49:53 +0000921 IRBuilder<> Builder(MemoryInst);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000922
Chris Lattnerdd77df32007-04-13 20:30:56 +0000923 // Now that we determined the addressing expression we want to use and know
924 // that we have to sink it into this block. Check to see if we have already
925 // done this for some other load/store instr in this block. If so, reuse the
926 // computation.
927 Value *&SunkAddr = SunkAddrs[Addr];
928 if (SunkAddr) {
David Greene68d67fd2010-01-05 01:27:11 +0000929 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
Dan Gohman6c1980b2009-07-25 01:13:51 +0000930 << *MemoryInst);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000931 if (SunkAddr->getType() != Addr->getType())
Benjamin Kramera9390a42011-09-27 20:39:19 +0000932 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
Chris Lattnerdd77df32007-04-13 20:30:56 +0000933 } else {
David Greene68d67fd2010-01-05 01:27:11 +0000934 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Dan Gohman6c1980b2009-07-25 01:13:51 +0000935 << *MemoryInst);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000936 Type *IntPtrTy =
Micah Villmow3574eca2012-10-08 16:38:25 +0000937 TLI->getDataLayout()->getIntPtrType(AccessTy->getContext());
Eric Christopher692bf6b2008-09-24 05:32:41 +0000938
Chris Lattnerdd77df32007-04-13 20:30:56 +0000939 Value *Result = 0;
Dan Gohmand8d0b6a2010-01-19 22:45:06 +0000940
941 // Start with the base register. Do this first so that subsequent address
942 // matching finds it last, which will prevent it from trying to match it
943 // as the scaled value in case it happens to be a mul. That would be
944 // problematic if we've sunk a different mul for the scale, because then
945 // we'd end up sinking both muls.
946 if (AddrMode.BaseReg) {
947 Value *V = AddrMode.BaseReg;
Duncan Sands1df98592010-02-16 11:11:14 +0000948 if (V->getType()->isPointerTy())
Devang Patel2048c372011-09-06 18:49:53 +0000949 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Dan Gohmand8d0b6a2010-01-19 22:45:06 +0000950 if (V->getType() != IntPtrTy)
Devang Patel2048c372011-09-06 18:49:53 +0000951 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
Dan Gohmand8d0b6a2010-01-19 22:45:06 +0000952 Result = V;
953 }
954
955 // Add the scale value.
Chris Lattnerdd77df32007-04-13 20:30:56 +0000956 if (AddrMode.Scale) {
957 Value *V = AddrMode.ScaledReg;
958 if (V->getType() == IntPtrTy) {
959 // done.
Duncan Sands1df98592010-02-16 11:11:14 +0000960 } else if (V->getType()->isPointerTy()) {
Devang Patel2048c372011-09-06 18:49:53 +0000961 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000962 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
963 cast<IntegerType>(V->getType())->getBitWidth()) {
Devang Patel2048c372011-09-06 18:49:53 +0000964 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000965 } else {
Devang Patel2048c372011-09-06 18:49:53 +0000966 V = Builder.CreateSExt(V, IntPtrTy, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000967 }
968 if (AddrMode.Scale != 1)
Devang Patel2048c372011-09-06 18:49:53 +0000969 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
970 "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000971 if (Result)
Devang Patel2048c372011-09-06 18:49:53 +0000972 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000973 else
974 Result = V;
975 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000976
Chris Lattnerdd77df32007-04-13 20:30:56 +0000977 // Add in the BaseGV if present.
978 if (AddrMode.BaseGV) {
Devang Patel2048c372011-09-06 18:49:53 +0000979 Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000980 if (Result)
Devang Patel2048c372011-09-06 18:49:53 +0000981 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000982 else
983 Result = V;
984 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000985
Chris Lattnerdd77df32007-04-13 20:30:56 +0000986 // Add in the Base Offset if present.
987 if (AddrMode.BaseOffs) {
Owen Andersoneed707b2009-07-24 23:12:02 +0000988 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000989 if (Result)
Devang Patel2048c372011-09-06 18:49:53 +0000990 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000991 else
992 Result = V;
993 }
994
995 if (Result == 0)
Owen Andersona7235ea2009-07-31 20:28:14 +0000996 SunkAddr = Constant::getNullValue(Addr->getType());
Chris Lattnerdd77df32007-04-13 20:30:56 +0000997 else
Devang Patel2048c372011-09-06 18:49:53 +0000998 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000999 }
Eric Christopher692bf6b2008-09-24 05:32:41 +00001000
Owen Andersond2f41742010-11-19 22:15:03 +00001001 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
Eric Christopher692bf6b2008-09-24 05:32:41 +00001002
Chris Lattner0403b472011-04-09 07:05:44 +00001003 // If we have no uses, recursively delete the value and all dead instructions
1004 // using it.
Owen Andersond2f41742010-11-19 22:15:03 +00001005 if (Repl->use_empty()) {
Chris Lattner0403b472011-04-09 07:05:44 +00001006 // This can cause recursive deletion, which can invalidate our iterator.
1007 // Use a WeakVH to hold onto it in case this happens.
1008 WeakVH IterHandle(CurInstIterator);
1009 BasicBlock *BB = CurInstIterator->getParent();
Nadav Rotema94d6e82012-07-24 10:51:42 +00001010
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +00001011 RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
Chris Lattner0403b472011-04-09 07:05:44 +00001012
1013 if (IterHandle != CurInstIterator) {
1014 // If the iterator instruction was recursively deleted, start over at the
1015 // start of the block.
1016 CurInstIterator = BB->begin();
1017 SunkAddrs.clear();
1018 } else {
1019 // This address is now available for reassignment, so erase the table
1020 // entry; we don't want to match some completely different instruction.
1021 SunkAddrs[Addr] = 0;
Nadav Rotema94d6e82012-07-24 10:51:42 +00001022 }
Dale Johannesen536d31b2010-03-31 20:37:15 +00001023 }
Cameron Zwarich31ff1332011-01-05 17:27:27 +00001024 ++NumMemoryInsts;
Chris Lattnerdd77df32007-04-13 20:30:56 +00001025 return true;
1026}
1027
Evan Cheng9bf12b52008-02-26 02:42:37 +00001028/// OptimizeInlineAsmInst - If there are any memory operands, use
Chris Lattner88a5c832008-11-25 07:09:13 +00001029/// OptimizeMemoryInst to sink their address computing into the block when
Evan Cheng9bf12b52008-02-26 02:42:37 +00001030/// possible / profitable.
Chris Lattner75796092011-01-15 07:14:54 +00001031bool CodeGenPrepare::OptimizeInlineAsmInst(CallInst *CS) {
Evan Cheng9bf12b52008-02-26 02:42:37 +00001032 bool MadeChange = false;
Evan Cheng9bf12b52008-02-26 02:42:37 +00001033
Nadav Rotema94d6e82012-07-24 10:51:42 +00001034 TargetLowering::AsmOperandInfoVector
Chris Lattner75796092011-01-15 07:14:54 +00001035 TargetConstraints = TLI->ParseConstraints(CS);
Dale Johannesen677c6ec2010-09-16 18:30:55 +00001036 unsigned ArgNo = 0;
John Thompsoneac6e1d2010-09-13 18:15:37 +00001037 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
1038 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Nadav Rotema94d6e82012-07-24 10:51:42 +00001039
Evan Cheng9bf12b52008-02-26 02:42:37 +00001040 // Compute the constraint code and ConstraintType to use.
Dale Johannesen1784d162010-06-25 21:55:36 +00001041 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Evan Cheng9bf12b52008-02-26 02:42:37 +00001042
Eli Friedman9ec80952008-02-26 18:37:49 +00001043 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
1044 OpInfo.isIndirect) {
Chris Lattner75796092011-01-15 07:14:54 +00001045 Value *OpVal = CS->getArgOperand(ArgNo++);
Chris Lattner1a8943a2011-01-15 07:29:01 +00001046 MadeChange |= OptimizeMemoryInst(CS, OpVal, OpVal->getType());
Dale Johannesen677c6ec2010-09-16 18:30:55 +00001047 } else if (OpInfo.Type == InlineAsm::isInput)
1048 ArgNo++;
Evan Cheng9bf12b52008-02-26 02:42:37 +00001049 }
1050
1051 return MadeChange;
1052}
1053
Dan Gohmanb00f2362009-10-16 20:59:35 +00001054/// MoveExtToFormExtLoad - Move a zext or sext fed by a load into the same
1055/// basic block as the load, unless conditions are unfavorable. This allows
1056/// SelectionDAG to fold the extend into the load.
1057///
1058bool CodeGenPrepare::MoveExtToFormExtLoad(Instruction *I) {
1059 // Look for a load being extended.
1060 LoadInst *LI = dyn_cast<LoadInst>(I->getOperand(0));
1061 if (!LI) return false;
1062
1063 // If they're already in the same block, there's nothing to do.
1064 if (LI->getParent() == I->getParent())
1065 return false;
1066
1067 // If the load has other users and the truncate is not free, this probably
1068 // isn't worthwhile.
1069 if (!LI->hasOneUse() &&
Bob Wilsonec57a1a2010-09-22 18:44:56 +00001070 TLI && (TLI->isTypeLegal(TLI->getValueType(LI->getType())) ||
1071 !TLI->isTypeLegal(TLI->getValueType(I->getType()))) &&
Bob Wilson71dc4d92010-09-21 21:54:27 +00001072 !TLI->isTruncateFree(I->getType(), LI->getType()))
Dan Gohmanb00f2362009-10-16 20:59:35 +00001073 return false;
1074
1075 // Check whether the target supports casts folded into loads.
1076 unsigned LType;
1077 if (isa<ZExtInst>(I))
1078 LType = ISD::ZEXTLOAD;
1079 else {
1080 assert(isa<SExtInst>(I) && "Unexpected ext type!");
1081 LType = ISD::SEXTLOAD;
1082 }
1083 if (TLI && !TLI->isLoadExtLegal(LType, TLI->getValueType(LI->getType())))
1084 return false;
1085
1086 // Move the extend into the same block as the load, so that SelectionDAG
1087 // can fold it.
1088 I->removeFromParent();
1089 I->insertAfter(LI);
Cameron Zwarich31ff1332011-01-05 17:27:27 +00001090 ++NumExtsMoved;
Dan Gohmanb00f2362009-10-16 20:59:35 +00001091 return true;
1092}
1093
Evan Chengbdcb7262007-12-05 23:58:20 +00001094bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
1095 BasicBlock *DefBB = I->getParent();
1096
Bob Wilson9120f5c2010-09-21 21:44:14 +00001097 // If the result of a {s|z}ext and its source are both live out, rewrite all
Evan Chengbdcb7262007-12-05 23:58:20 +00001098 // other uses of the source with result of extension.
1099 Value *Src = I->getOperand(0);
1100 if (Src->hasOneUse())
1101 return false;
1102
Evan Cheng696e5c02007-12-13 07:50:36 +00001103 // Only do this xform if truncating is free.
Gabor Greif53bdbd72008-02-26 19:13:21 +00001104 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
Evan Chengf9785f92007-12-13 03:32:53 +00001105 return false;
1106
Evan Cheng772de512007-12-12 00:51:06 +00001107 // Only safe to perform the optimization if the source is also defined in
Evan Cheng765dff22007-12-12 02:53:41 +00001108 // this block.
1109 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
Evan Cheng772de512007-12-12 00:51:06 +00001110 return false;
1111
Evan Chengbdcb7262007-12-05 23:58:20 +00001112 bool DefIsLiveOut = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001113 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
Evan Chengbdcb7262007-12-05 23:58:20 +00001114 UI != E; ++UI) {
1115 Instruction *User = cast<Instruction>(*UI);
1116
1117 // Figure out which BB this ext is used in.
1118 BasicBlock *UserBB = User->getParent();
1119 if (UserBB == DefBB) continue;
1120 DefIsLiveOut = true;
1121 break;
1122 }
1123 if (!DefIsLiveOut)
1124 return false;
1125
Evan Cheng765dff22007-12-12 02:53:41 +00001126 // Make sure non of the uses are PHI nodes.
Eric Christopher692bf6b2008-09-24 05:32:41 +00001127 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
Evan Cheng765dff22007-12-12 02:53:41 +00001128 UI != E; ++UI) {
1129 Instruction *User = cast<Instruction>(*UI);
Evan Chengf9785f92007-12-13 03:32:53 +00001130 BasicBlock *UserBB = User->getParent();
1131 if (UserBB == DefBB) continue;
1132 // Be conservative. We don't want this xform to end up introducing
1133 // reloads just before load / store instructions.
1134 if (isa<PHINode>(User) || isa<LoadInst>(User) || isa<StoreInst>(User))
Evan Cheng765dff22007-12-12 02:53:41 +00001135 return false;
1136 }
1137
Evan Chengbdcb7262007-12-05 23:58:20 +00001138 // InsertedTruncs - Only insert one trunc in each block once.
1139 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
1140
1141 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001142 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
Evan Chengbdcb7262007-12-05 23:58:20 +00001143 UI != E; ++UI) {
1144 Use &TheUse = UI.getUse();
1145 Instruction *User = cast<Instruction>(*UI);
1146
1147 // Figure out which BB this ext is used in.
1148 BasicBlock *UserBB = User->getParent();
1149 if (UserBB == DefBB) continue;
1150
1151 // Both src and def are live in this block. Rewrite the use.
1152 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
1153
1154 if (!InsertedTrunc) {
Bill Wendling5b6f42f2011-08-16 20:45:24 +00001155 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Evan Chengbdcb7262007-12-05 23:58:20 +00001156 InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
1157 }
1158
1159 // Replace a use of the {s|z}ext source with a use of the result.
1160 TheUse = InsertedTrunc;
Cameron Zwarich31ff1332011-01-05 17:27:27 +00001161 ++NumExtUses;
Evan Chengbdcb7262007-12-05 23:58:20 +00001162 MadeChange = true;
1163 }
1164
1165 return MadeChange;
1166}
1167
Benjamin Kramer59957502012-05-05 12:49:22 +00001168/// isFormingBranchFromSelectProfitable - Returns true if a SelectInst should be
1169/// turned into an explicit branch.
1170static bool isFormingBranchFromSelectProfitable(SelectInst *SI) {
1171 // FIXME: This should use the same heuristics as IfConversion to determine
1172 // whether a select is better represented as a branch. This requires that
1173 // branch probability metadata is preserved for the select, which is not the
1174 // case currently.
1175
1176 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
1177
1178 // If the branch is predicted right, an out of order CPU can avoid blocking on
1179 // the compare. Emit cmovs on compares with a memory operand as branches to
1180 // avoid stalls on the load from memory. If the compare has more than one use
1181 // there's probably another cmov or setcc around so it's not worth emitting a
1182 // branch.
1183 if (!Cmp)
1184 return false;
1185
1186 Value *CmpOp0 = Cmp->getOperand(0);
1187 Value *CmpOp1 = Cmp->getOperand(1);
1188
1189 // We check that the memory operand has one use to avoid uses of the loaded
1190 // value directly after the compare, making branches unprofitable.
1191 return Cmp->hasOneUse() &&
1192 ((isa<LoadInst>(CmpOp0) && CmpOp0->hasOneUse()) ||
1193 (isa<LoadInst>(CmpOp1) && CmpOp1->hasOneUse()));
1194}
1195
1196
Nadav Rotem9f40cb32012-09-02 12:10:19 +00001197/// If we have a SelectInst that will likely profit from branch prediction,
1198/// turn it into a branch.
Benjamin Kramer59957502012-05-05 12:49:22 +00001199bool CodeGenPrepare::OptimizeSelectInst(SelectInst *SI) {
Nadav Rotem9f40cb32012-09-02 12:10:19 +00001200 bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
1201
1202 // Can we convert the 'select' to CF ?
1203 if (DisableSelectToBranch || OptSize || !TLI || VectorCond)
Benjamin Kramer59957502012-05-05 12:49:22 +00001204 return false;
1205
Nadav Rotem9f40cb32012-09-02 12:10:19 +00001206 TargetLowering::SelectSupportKind SelectKind;
1207 if (VectorCond)
1208 SelectKind = TargetLowering::VectorMaskSelect;
1209 else if (SI->getType()->isVectorTy())
1210 SelectKind = TargetLowering::ScalarCondVectorVal;
1211 else
1212 SelectKind = TargetLowering::ScalarValSelect;
1213
1214 // Do we have efficient codegen support for this kind of 'selects' ?
1215 if (TLI->isSelectSupported(SelectKind)) {
1216 // We have efficient codegen support for the select instruction.
1217 // Check if it is profitable to keep this 'select'.
1218 if (!TLI->isPredictableSelectExpensive() ||
1219 !isFormingBranchFromSelectProfitable(SI))
1220 return false;
1221 }
Benjamin Kramer59957502012-05-05 12:49:22 +00001222
1223 ModifiedDT = true;
1224
1225 // First, we split the block containing the select into 2 blocks.
1226 BasicBlock *StartBlock = SI->getParent();
1227 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(SI));
1228 BasicBlock *NextBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
1229
1230 // Create a new block serving as the landing pad for the branch.
1231 BasicBlock *SmallBlock = BasicBlock::Create(SI->getContext(), "select.mid",
1232 NextBlock->getParent(), NextBlock);
1233
1234 // Move the unconditional branch from the block with the select in it into our
1235 // landing pad block.
1236 StartBlock->getTerminator()->eraseFromParent();
1237 BranchInst::Create(NextBlock, SmallBlock);
1238
1239 // Insert the real conditional branch based on the original condition.
1240 BranchInst::Create(NextBlock, SmallBlock, SI->getCondition(), SI);
1241
1242 // The select itself is replaced with a PHI Node.
1243 PHINode *PN = PHINode::Create(SI->getType(), 2, "", NextBlock->begin());
1244 PN->takeName(SI);
1245 PN->addIncoming(SI->getTrueValue(), StartBlock);
1246 PN->addIncoming(SI->getFalseValue(), SmallBlock);
1247 SI->replaceAllUsesWith(PN);
1248 SI->eraseFromParent();
1249
1250 // Instruct OptimizeBlock to skip to the next block.
1251 CurInstIterator = StartBlock->end();
1252 ++NumSelectsExpanded;
1253 return true;
1254}
1255
Cameron Zwarichc0611012011-01-06 02:37:26 +00001256bool CodeGenPrepare::OptimizeInst(Instruction *I) {
Cameron Zwarichc0611012011-01-06 02:37:26 +00001257 if (PHINode *P = dyn_cast<PHINode>(I)) {
1258 // It is possible for very late stage optimizations (such as SimplifyCFG)
1259 // to introduce PHI nodes too late to be cleaned up. If we detect such a
1260 // trivial PHI, go ahead and zap it here.
1261 if (Value *V = SimplifyInstruction(P)) {
1262 P->replaceAllUsesWith(V);
1263 P->eraseFromParent();
1264 ++NumPHIsElim;
Chris Lattner1a8943a2011-01-15 07:29:01 +00001265 return true;
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 (CastInst *CI = dyn_cast<CastInst>(I)) {
Cameron Zwarichc0611012011-01-06 02:37:26 +00001271 // If the source of the cast is a constant, then this should have
1272 // already been constant folded. The only reason NOT to constant fold
1273 // it is if something (e.g. LSR) was careful to place the constant
1274 // evaluation in a block other than then one that uses it (e.g. to hoist
1275 // the address of globals out of a loop). If this is the case, we don't
1276 // want to forward-subst the cast.
1277 if (isa<Constant>(CI->getOperand(0)))
1278 return false;
1279
Chris Lattner1a8943a2011-01-15 07:29:01 +00001280 if (TLI && OptimizeNoopCopyExpression(CI, *TLI))
1281 return true;
Cameron Zwarichc0611012011-01-06 02:37:26 +00001282
Chris Lattner1a8943a2011-01-15 07:29:01 +00001283 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
1284 bool MadeChange = MoveExtToFormExtLoad(I);
1285 return MadeChange | OptimizeExtUses(I);
Cameron Zwarichc0611012011-01-06 02:37:26 +00001286 }
Chris Lattner1a8943a2011-01-15 07:29:01 +00001287 return false;
1288 }
Nadav Rotema94d6e82012-07-24 10:51:42 +00001289
Chris Lattner1a8943a2011-01-15 07:29:01 +00001290 if (CmpInst *CI = dyn_cast<CmpInst>(I))
1291 return OptimizeCmpExpression(CI);
Nadav Rotema94d6e82012-07-24 10:51:42 +00001292
Chris Lattner1a8943a2011-01-15 07:29:01 +00001293 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Hans Wennborg93ba1332012-09-19 07:48:16 +00001294 bool Changed = false;
Cameron Zwarichc0611012011-01-06 02:37:26 +00001295 if (TLI)
Hans Wennborg93ba1332012-09-19 07:48:16 +00001296 Changed |= OptimizeMemoryInst(I, I->getOperand(0), LI->getType());
1297 Changed |= ConvertLoadToSwitch(LI);
1298 return Changed;
Chris Lattner1a8943a2011-01-15 07:29:01 +00001299 }
Nadav Rotema94d6e82012-07-24 10:51:42 +00001300
Chris Lattner1a8943a2011-01-15 07:29:01 +00001301 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Cameron Zwarichc0611012011-01-06 02:37:26 +00001302 if (TLI)
Chris Lattner1a8943a2011-01-15 07:29:01 +00001303 return OptimizeMemoryInst(I, SI->getOperand(1),
1304 SI->getOperand(0)->getType());
1305 return false;
1306 }
Nadav Rotema94d6e82012-07-24 10:51:42 +00001307
Chris Lattner1a8943a2011-01-15 07:29:01 +00001308 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Cameron Zwarich865ae1a2011-01-06 02:44:52 +00001309 if (GEPI->hasAllZeroIndices()) {
1310 /// The GEP operand must be a pointer, so must its result -> BitCast
1311 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
1312 GEPI->getName(), GEPI);
1313 GEPI->replaceAllUsesWith(NC);
1314 GEPI->eraseFromParent();
1315 ++NumGEPsElim;
Cameron Zwarich865ae1a2011-01-06 02:44:52 +00001316 OptimizeInst(NC);
Chris Lattner1a8943a2011-01-15 07:29:01 +00001317 return true;
Cameron Zwarich865ae1a2011-01-06 02:44:52 +00001318 }
Chris Lattner1a8943a2011-01-15 07:29:01 +00001319 return false;
Cameron Zwarichc0611012011-01-06 02:37:26 +00001320 }
Nadav Rotema94d6e82012-07-24 10:51:42 +00001321
Chris Lattner1a8943a2011-01-15 07:29:01 +00001322 if (CallInst *CI = dyn_cast<CallInst>(I))
1323 return OptimizeCallInst(CI);
Cameron Zwarichc0611012011-01-06 02:37:26 +00001324
Evan Cheng485fafc2011-03-21 01:19:09 +00001325 if (ReturnInst *RI = dyn_cast<ReturnInst>(I))
1326 return DupRetToEnableTailCallOpts(RI);
1327
Benjamin Kramer59957502012-05-05 12:49:22 +00001328 if (SelectInst *SI = dyn_cast<SelectInst>(I))
1329 return OptimizeSelectInst(SI);
1330
Chris Lattner1a8943a2011-01-15 07:29:01 +00001331 return false;
Cameron Zwarichc0611012011-01-06 02:37:26 +00001332}
1333
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001334// In this pass we look for GEP and cast instructions that are used
1335// across basic blocks and rewrite them to improve basic-block-at-a-time
1336// selection.
1337bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
Cameron Zwarich8c3527e2011-01-06 00:42:50 +00001338 SunkAddrs.clear();
Cameron Zwarich56e37932011-03-02 03:31:46 +00001339 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001340
Chris Lattner75796092011-01-15 07:14:54 +00001341 CurInstIterator = BB.begin();
Hans Wennborg93ba1332012-09-19 07:48:16 +00001342 while (CurInstIterator != BB.end())
Chris Lattner94e8e0c2011-01-15 07:25:29 +00001343 MadeChange |= OptimizeInst(CurInstIterator++);
Eric Christopher692bf6b2008-09-24 05:32:41 +00001344
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001345 return MadeChange;
1346}
Devang Patelf56ea612011-08-18 00:50:51 +00001347
1348// llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotema94d6e82012-07-24 10:51:42 +00001349// handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patelf56ea612011-08-18 00:50:51 +00001350// find a node corresponding to the value.
1351bool CodeGenPrepare::PlaceDbgValues(Function &F) {
1352 bool MadeChange = false;
1353 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
1354 Instruction *PrevNonDbgInst = NULL;
1355 for (BasicBlock::iterator BI = I->begin(), BE = I->end(); BI != BE;) {
1356 Instruction *Insn = BI; ++BI;
1357 DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
1358 if (!DVI) {
1359 PrevNonDbgInst = Insn;
1360 continue;
1361 }
1362
1363 Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
1364 if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
1365 DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
1366 DVI->removeFromParent();
1367 if (isa<PHINode>(VI))
1368 DVI->insertBefore(VI->getParent()->getFirstInsertionPt());
1369 else
1370 DVI->insertAfter(VI);
1371 MadeChange = true;
1372 ++NumDbgValueMoved;
1373 }
1374 }
1375 }
1376 return MadeChange;
1377}
Hans Wennborg93ba1332012-09-19 07:48:16 +00001378
1379static bool TargetSupportsJumpTables(const TargetLowering &TLI) {
1380 return TLI.supportJumpTables() &&
1381 (TLI.isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
1382 TLI.isOperationLegalOrCustom(ISD::BRIND, MVT::Other));
1383}
1384
1385/// ConvertLoadToSwitch - Convert loads from constant lookup tables into
1386/// switches. This undos the switch-to-lookup table transformation in
1387/// SimplifyCFG for targets where that is inprofitable.
1388bool CodeGenPrepare::ConvertLoadToSwitch(LoadInst *LI) {
1389 // This only applies to targets that don't support jump tables.
1390 if (!TLI || TargetSupportsJumpTables(*TLI))
1391 return false;
1392
1393 // FIXME: In the future, it would be desirable to have enough target
1394 // information in SimplifyCFG, so we could decide at that stage whether to
1395 // transform the switch to a lookup table or not, and this
1396 // reverse-transformation could be removed.
1397
1398 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getPointerOperand());
1399 if (!GEP || !GEP->isInBounds() || GEP->getPointerAddressSpace())
1400 return false;
1401 if (GEP->getNumIndices() != 2)
1402 return false;
1403 Value *FirstIndex = GEP->idx_begin()[0];
1404 ConstantInt *FirstIndexInt = dyn_cast<ConstantInt>(FirstIndex);
1405 if (!FirstIndexInt || !FirstIndexInt->isZero())
1406 return false;
1407
1408 Value *TableIndex = GEP->idx_begin()[1];
1409 IntegerType *TableIndexTy = cast<IntegerType>(TableIndex->getType());
1410
1411 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getPointerOperand());
1412 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
1413 return false;
1414
1415 Constant *Arr = GV->getInitializer();
1416 uint64_t NumElements;
1417 if (ConstantArray *CA = dyn_cast<ConstantArray>(Arr))
1418 NumElements = CA->getType()->getNumElements();
1419 else if (ConstantDataArray *CDA = dyn_cast<ConstantDataArray>(Arr))
1420 NumElements = CDA->getNumElements();
1421 else
1422 return false;
1423 if (NumElements < 2)
1424 return false;
1425
1426 // Split the block.
1427 BasicBlock *OriginalBB = LI->getParent();
1428 BasicBlock *PostSwitchBB = OriginalBB->splitBasicBlock(LI);
1429
1430 // Replace OriginalBB's terminator with a switch.
1431 IRBuilder<> Builder(OriginalBB->getTerminator());
1432 SwitchInst *Switch = Builder.CreateSwitch(TableIndex, PostSwitchBB,
1433 NumElements - 1);
1434 OriginalBB->getTerminator()->eraseFromParent();
1435
1436 // Count the frequency of each value to decide which to use as default.
1437 SmallDenseMap<Constant*, uint64_t> ValueFreq;
1438 for (uint64_t I = 0; I < NumElements; ++I)
1439 ++ValueFreq[Arr->getAggregateElement(I)];
1440 uint64_t MaxCount = 0;
1441 Constant *DefaultValue = NULL;
1442 for (SmallDenseMap<Constant*, uint64_t>::iterator I = ValueFreq.begin(),
1443 E = ValueFreq.end(); I != E; ++I) {
1444 if (I->second > MaxCount) {
1445 MaxCount = I->second;
1446 DefaultValue = I->first;
1447 }
1448 }
1449 assert(DefaultValue && "No values in the array?");
1450
1451 // Create the phi node in PostSwitchBB, which will replace the load.
1452 Builder.SetInsertPoint(PostSwitchBB->begin());
1453 PHINode *PHI = Builder.CreatePHI(LI->getType(), NumElements);
1454 PHI->addIncoming(DefaultValue, OriginalBB);
1455
1456 // Build basic blocks to target with the switch.
1457 for (uint64_t I = 0; I < NumElements; ++I) {
1458 Constant *C = Arr->getAggregateElement(I);
1459 if (C == DefaultValue) continue; // Already covered by the default case.
1460
1461 BasicBlock *BB = BasicBlock::Create(PostSwitchBB->getContext(),
1462 "lookup.bb",
1463 PostSwitchBB->getParent(),
1464 PostSwitchBB);
1465 Switch->addCase(ConstantInt::get(TableIndexTy, I), BB);
1466 Builder.SetInsertPoint(BB);
1467 Builder.CreateBr(PostSwitchBB);
1468 PHI->addIncoming(C, BB);
1469 }
1470
1471 // Remove the load.
1472 LI->replaceAllUsesWith(PHI);
1473 LI->eraseFromParent();
1474
1475 // Clean up.
1476 if (GEP->use_empty())
1477 GEP->eraseFromParent();
1478 if (GV->hasUnnamedAddr() && GV->hasPrivateLinkage() && GV->use_empty())
1479 GV->eraseFromParent();
1480
1481 CurInstIterator = Switch;
1482 return true;
1483}