blob: 495cdc632143c65d654c3d67b6132e2f26aa5962 [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"
41#include "llvm/Target/TargetData.h"
42#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>();
Benjamin Kramer59957502012-05-05 12:49:22 +0000152 OptSize = F.hasFnAttr(Attribute::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()) {
Evan Cheng911908d2012-09-14 21:25:34 +0000157 const DenseMap<Type*, Type*> &BypassTypeMap = TLI->getBypassSlowDivTypes();
158 for (Function::iterator I = F.begin(); I != F.end(); I++)
159 EverMadeChange |= bypassSlowDivision(F, I, BypassTypeMap);
Preston Gurd2e2efd92012-09-04 18:22:17 +0000160 }
161
162 // Eliminate blocks that contain only PHI nodes and an
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000163 // unconditional branch.
164 EverMadeChange |= EliminateMostlyEmptyBlocks(F);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000165
Devang Patelf56ea612011-08-18 00:50:51 +0000166 // llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotema94d6e82012-07-24 10:51:42 +0000167 // handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patelf56ea612011-08-18 00:50:51 +0000168 // find a node corresponding to the value.
169 EverMadeChange |= PlaceDbgValues(F);
170
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000171 bool MadeChange = true;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000172 while (MadeChange) {
173 MadeChange = false;
Hans Wennborg93ba1332012-09-19 07:48:16 +0000174 for (Function::iterator I = F.begin(); I != F.end(); ) {
Evan Cheng485fafc2011-03-21 01:19:09 +0000175 BasicBlock *BB = I++;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000176 MadeChange |= OptimizeBlock(*BB);
Evan Cheng485fafc2011-03-21 01:19:09 +0000177 }
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000178 EverMadeChange |= MadeChange;
179 }
Cameron Zwarich8c3527e2011-01-06 00:42:50 +0000180
181 SunkAddrs.clear();
182
Cameron Zwarich899eaa32011-03-11 21:52:04 +0000183 if (!DisableBranchOpts) {
184 MadeChange = false;
Bill Wendlinge3e394d2012-03-04 10:46:01 +0000185 SmallPtrSet<BasicBlock*, 8> WorkList;
186 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
187 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
Frits van Bommel5649ba72011-05-22 16:24:18 +0000188 MadeChange |= ConstantFoldTerminator(BB, true);
Bill Wendlinge3e394d2012-03-04 10:46:01 +0000189 if (!MadeChange) continue;
190
191 for (SmallVectorImpl<BasicBlock*>::iterator
192 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
193 if (pred_begin(*II) == pred_end(*II))
194 WorkList.insert(*II);
195 }
196
Bill Wendling8dd2e5b2012-08-15 21:18:10 +0000197 for (SmallPtrSet<BasicBlock*, 8>::iterator
198 I = WorkList.begin(), E = WorkList.end(); I != E; ++I)
199 DeleteDeadBlock(*I);
Cameron Zwarich899eaa32011-03-11 21:52:04 +0000200
Nadav Rotem3e883732012-08-14 05:19:07 +0000201 // Merge pairs of basic blocks with unconditional branches, connected by
202 // a single edge.
203 if (EverMadeChange || MadeChange)
204 MadeChange |= EliminateFallThrough(F);
205
Evan Cheng485fafc2011-03-21 01:19:09 +0000206 if (MadeChange)
Devang Patel52e37df2011-03-24 15:35:25 +0000207 ModifiedDT = true;
Cameron Zwarich899eaa32011-03-11 21:52:04 +0000208 EverMadeChange |= MadeChange;
209 }
210
Devang Patel52e37df2011-03-24 15:35:25 +0000211 if (ModifiedDT && DT)
Evan Cheng485fafc2011-03-21 01:19:09 +0000212 DT->DT->recalculate(F);
213
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000214 return EverMadeChange;
215}
216
Nadav Rotem3e883732012-08-14 05:19:07 +0000217/// EliminateFallThrough - Merge basic blocks which are connected
218/// by a single edge, where one of the basic blocks has a single successor
219/// pointing to the other basic block, which has a single predecessor.
220bool CodeGenPrepare::EliminateFallThrough(Function &F) {
221 bool Changed = false;
222 // Scan all of the blocks in the function, except for the entry block.
223 for (Function::iterator I = ++F.begin(), E = F.end(); I != E; ) {
224 BasicBlock *BB = I++;
225 // If the destination block has a single pred, then this is a trivial
226 // edge, just collapse it.
227 BasicBlock *SinglePred = BB->getSinglePredecessor();
228
229 if (!SinglePred || SinglePred == BB) continue;
230
231 BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
232 if (Term && !Term->isConditional()) {
233 Changed = true;
Michael Liao787ed032012-08-21 05:55:22 +0000234 DEBUG(dbgs() << "To merge:\n"<< *SinglePred << "\n\n\n");
Nadav Rotem3e883732012-08-14 05:19:07 +0000235 // Remember if SinglePred was the entry block of the function.
236 // If so, we will need to move BB back to the entry position.
237 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
238 MergeBasicBlockIntoOnlyPred(BB, this);
239
240 if (isEntry && BB != &BB->getParent()->getEntryBlock())
241 BB->moveBefore(&BB->getParent()->getEntryBlock());
242
243 // We have erased a block. Update the iterator.
244 I = BB;
Nadav Rotem3e883732012-08-14 05:19:07 +0000245 }
246 }
247 return Changed;
248}
249
Dale Johannesen2d697242009-03-27 01:13:37 +0000250/// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes,
251/// debug info directives, and an unconditional branch. Passes before isel
252/// (e.g. LSR/loopsimplify) often split edges in ways that are non-optimal for
253/// isel. Start by eliminating these blocks so we can split them the way we
254/// want them.
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000255bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
256 bool MadeChange = false;
257 // Note that this intentionally skips the entry block.
258 for (Function::iterator I = ++F.begin(), E = F.end(); I != E; ) {
259 BasicBlock *BB = I++;
260
261 // If this block doesn't end with an uncond branch, ignore it.
262 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
263 if (!BI || !BI->isUnconditional())
264 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000265
Dale Johannesen2d697242009-03-27 01:13:37 +0000266 // If the instruction before the branch (skipping debug info) isn't a phi
267 // node, then other stuff is happening here.
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000268 BasicBlock::iterator BBI = BI;
269 if (BBI != BB->begin()) {
270 --BBI;
Dale Johannesen2d697242009-03-27 01:13:37 +0000271 while (isa<DbgInfoIntrinsic>(BBI)) {
272 if (BBI == BB->begin())
273 break;
274 --BBI;
275 }
276 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
277 continue;
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000278 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000279
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000280 // Do not break infinite loops.
281 BasicBlock *DestBB = BI->getSuccessor(0);
282 if (DestBB == BB)
283 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000284
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000285 if (!CanMergeBlocks(BB, DestBB))
286 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000287
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000288 EliminateMostlyEmptyBlock(BB);
289 MadeChange = true;
290 }
291 return MadeChange;
292}
293
294/// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
295/// single uncond branch between them, and BB contains no other non-phi
296/// instructions.
297bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
298 const BasicBlock *DestBB) const {
299 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
300 // the successor. If there are more complex condition (e.g. preheaders),
301 // don't mess around with them.
302 BasicBlock::const_iterator BBI = BB->begin();
303 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
Gabor Greif60ad7812010-03-25 23:06:16 +0000304 for (Value::const_use_iterator UI = PN->use_begin(), E = PN->use_end();
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000305 UI != E; ++UI) {
306 const Instruction *User = cast<Instruction>(*UI);
307 if (User->getParent() != DestBB || !isa<PHINode>(User))
308 return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000309 // If User is inside DestBB block and it is a PHINode then check
310 // incoming value. If incoming value is not from BB then this is
Devang Patel75abc1e2007-04-25 00:37:04 +0000311 // a complex condition (e.g. preheaders) we want to avoid here.
312 if (User->getParent() == DestBB) {
313 if (const PHINode *UPN = dyn_cast<PHINode>(User))
314 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
315 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
316 if (Insn && Insn->getParent() == BB &&
317 Insn->getParent() != UPN->getIncomingBlock(I))
318 return false;
319 }
320 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000321 }
322 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000323
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000324 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
325 // and DestBB may have conflicting incoming values for the block. If so, we
326 // can't merge the block.
327 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
328 if (!DestBBPN) return true; // no conflict.
Eric Christopher692bf6b2008-09-24 05:32:41 +0000329
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000330 // Collect the preds of BB.
Chris Lattnerf67f73a2007-11-06 22:07:40 +0000331 SmallPtrSet<const BasicBlock*, 16> BBPreds;
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000332 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
333 // It is faster to get preds from a PHI than with pred_iterator.
334 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
335 BBPreds.insert(BBPN->getIncomingBlock(i));
336 } else {
337 BBPreds.insert(pred_begin(BB), pred_end(BB));
338 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000339
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000340 // Walk the preds of DestBB.
341 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
342 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
343 if (BBPreds.count(Pred)) { // Common predecessor?
344 BBI = DestBB->begin();
345 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
346 const Value *V1 = PN->getIncomingValueForBlock(Pred);
347 const Value *V2 = PN->getIncomingValueForBlock(BB);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000348
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000349 // If V2 is a phi node in BB, look up what the mapped value will be.
350 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
351 if (V2PN->getParent() == BB)
352 V2 = V2PN->getIncomingValueForBlock(Pred);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000353
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000354 // If there is a conflict, bail out.
355 if (V1 != V2) return false;
356 }
357 }
358 }
359
360 return true;
361}
362
363
364/// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
365/// an unconditional branch in it.
366void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
367 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
368 BasicBlock *DestBB = BI->getSuccessor(0);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000369
David Greene68d67fd2010-01-05 01:27:11 +0000370 DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000371
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000372 // If the destination block has a single pred, then this is a trivial edge,
373 // just collapse it.
Chris Lattner9918fb52008-11-27 19:29:14 +0000374 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
Chris Lattnerf5102a02008-11-28 19:54:49 +0000375 if (SinglePred != DestBB) {
376 // Remember if SinglePred was the entry block of the function. If so, we
377 // will need to move BB back to the entry position.
378 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Andreas Neustifterad809812009-09-16 09:26:52 +0000379 MergeBasicBlockIntoOnlyPred(DestBB, this);
Chris Lattner9918fb52008-11-27 19:29:14 +0000380
Chris Lattnerf5102a02008-11-28 19:54:49 +0000381 if (isEntry && BB != &BB->getParent()->getEntryBlock())
382 BB->moveBefore(&BB->getParent()->getEntryBlock());
Nadav Rotema94d6e82012-07-24 10:51:42 +0000383
David Greene68d67fd2010-01-05 01:27:11 +0000384 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerf5102a02008-11-28 19:54:49 +0000385 return;
386 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000387 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000388
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000389 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
390 // to handle the new incoming edges it is about to have.
391 PHINode *PN;
392 for (BasicBlock::iterator BBI = DestBB->begin();
393 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
394 // Remove the incoming value for BB, and remember it.
395 Value *InVal = PN->removeIncomingValue(BB, false);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000396
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000397 // Two options: either the InVal is a phi node defined in BB or it is some
398 // value that dominates BB.
399 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
400 if (InValPhi && InValPhi->getParent() == BB) {
401 // Add all of the input values of the input PHI as inputs of this phi.
402 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
403 PN->addIncoming(InValPhi->getIncomingValue(i),
404 InValPhi->getIncomingBlock(i));
405 } else {
406 // Otherwise, add one instance of the dominating value for each edge that
407 // we will be adding.
408 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
409 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
410 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
411 } else {
412 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
413 PN->addIncoming(InVal, *PI);
414 }
415 }
416 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000417
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000418 // The PHIs are now updated, change everything that refers to BB to use
419 // DestBB and remove BB.
420 BB->replaceAllUsesWith(DestBB);
Devang Patel52e37df2011-03-24 15:35:25 +0000421 if (DT && !ModifiedDT) {
Cameron Zwarich80f6a502011-01-08 17:01:52 +0000422 BasicBlock *BBIDom = DT->getNode(BB)->getIDom()->getBlock();
423 BasicBlock *DestBBIDom = DT->getNode(DestBB)->getIDom()->getBlock();
424 BasicBlock *NewIDom = DT->findNearestCommonDominator(BBIDom, DestBBIDom);
425 DT->changeImmediateDominator(DestBB, NewIDom);
426 DT->eraseNode(BB);
427 }
Evan Cheng04149f72009-12-17 09:39:49 +0000428 if (PFI) {
429 PFI->replaceAllUses(BB, DestBB);
430 PFI->removeEdge(ProfileInfo::getEdge(BB, DestBB));
Andreas Neustifterad809812009-09-16 09:26:52 +0000431 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000432 BB->eraseFromParent();
Cameron Zwarich31ff1332011-01-05 17:27:27 +0000433 ++NumBlocksElim;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000434
David Greene68d67fd2010-01-05 01:27:11 +0000435 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000436}
437
Chris Lattnerdd77df32007-04-13 20:30:56 +0000438/// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
Dan Gohmana119de82009-06-14 23:30:43 +0000439/// copy (e.g. it's casting from one pointer type to another, i32->i8 on PPC),
440/// sink it into user blocks to reduce the number of virtual
Dale Johannesence0b2372007-06-12 16:50:17 +0000441/// registers that must be created and coalesced.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000442///
443/// Return true if any changes are made.
Chris Lattner85fa13c2008-11-24 22:44:16 +0000444///
Chris Lattnerdd77df32007-04-13 20:30:56 +0000445static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
Eric Christopher692bf6b2008-09-24 05:32:41 +0000446 // If this is a noop copy,
Owen Andersone50ed302009-08-10 22:56:29 +0000447 EVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
448 EVT DstVT = TLI.getValueType(CI->getType());
Eric Christopher692bf6b2008-09-24 05:32:41 +0000449
Chris Lattnerdd77df32007-04-13 20:30:56 +0000450 // This is an fp<->int conversion?
Duncan Sands83ec4b62008-06-06 12:08:01 +0000451 if (SrcVT.isInteger() != DstVT.isInteger())
Chris Lattnerdd77df32007-04-13 20:30:56 +0000452 return false;
Duncan Sands8e4eb092008-06-08 20:54:56 +0000453
Chris Lattnerdd77df32007-04-13 20:30:56 +0000454 // If this is an extension, it will be a zero or sign extension, which
455 // isn't a noop.
Duncan Sands8e4eb092008-06-08 20:54:56 +0000456 if (SrcVT.bitsLT(DstVT)) return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000457
Chris Lattnerdd77df32007-04-13 20:30:56 +0000458 // If these values will be promoted, find out what they will be promoted
459 // to. This helps us consider truncates on PPC as noop copies when they
460 // are.
Nadav Rotem0ccc12a2011-05-29 08:10:47 +0000461 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
462 TargetLowering::TypePromoteInteger)
Owen Anderson23b9b192009-08-12 00:36:31 +0000463 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
Nadav Rotem0ccc12a2011-05-29 08:10:47 +0000464 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
465 TargetLowering::TypePromoteInteger)
Owen Anderson23b9b192009-08-12 00:36:31 +0000466 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000467
Chris Lattnerdd77df32007-04-13 20:30:56 +0000468 // If, after promotion, these are the same types, this is a noop copy.
469 if (SrcVT != DstVT)
470 return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000471
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000472 BasicBlock *DefBB = CI->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000473
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000474 /// InsertedCasts - Only insert a cast in each block once.
Dale Johannesence0b2372007-06-12 16:50:17 +0000475 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000476
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000477 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000478 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000479 UI != E; ) {
480 Use &TheUse = UI.getUse();
481 Instruction *User = cast<Instruction>(*UI);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000482
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000483 // Figure out which BB this cast is used in. For PHI's this is the
484 // appropriate predecessor block.
485 BasicBlock *UserBB = User->getParent();
486 if (PHINode *PN = dyn_cast<PHINode>(User)) {
Gabor Greifa36791d2009-01-23 19:40:15 +0000487 UserBB = PN->getIncomingBlock(UI);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000488 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000489
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000490 // Preincrement use iterator so we don't invalidate it.
491 ++UI;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000492
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000493 // If this user is in the same block as the cast, don't change the cast.
494 if (UserBB == DefBB) continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000495
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000496 // If we have already inserted a cast into this block, use it.
497 CastInst *&InsertedCast = InsertedCasts[UserBB];
498
499 if (!InsertedCast) {
Bill Wendling5b6f42f2011-08-16 20:45:24 +0000500 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000501 InsertedCast =
502 CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000503 InsertPt);
504 MadeChange = true;
505 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000506
Dale Johannesence0b2372007-06-12 16:50:17 +0000507 // Replace a use of the cast with a use of the new cast.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000508 TheUse = InsertedCast;
Cameron Zwarich31ff1332011-01-05 17:27:27 +0000509 ++NumCastUses;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000510 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000511
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000512 // If we removed all uses, nuke the cast.
Duncan Sandse0038132008-01-20 16:51:46 +0000513 if (CI->use_empty()) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000514 CI->eraseFromParent();
Duncan Sandse0038132008-01-20 16:51:46 +0000515 MadeChange = true;
516 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000517
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000518 return MadeChange;
519}
520
Eric Christopher692bf6b2008-09-24 05:32:41 +0000521/// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
Dale Johannesence0b2372007-06-12 16:50:17 +0000522/// the number of virtual registers that must be created and coalesced. This is
Chris Lattner684b22d2007-08-02 16:53:43 +0000523/// a clear win except on targets with multiple condition code registers
524/// (PowerPC), where it might lose; some adjustment may be wanted there.
Dale Johannesence0b2372007-06-12 16:50:17 +0000525///
526/// Return true if any changes are made.
Chris Lattner85fa13c2008-11-24 22:44:16 +0000527static bool OptimizeCmpExpression(CmpInst *CI) {
Dale Johannesence0b2372007-06-12 16:50:17 +0000528 BasicBlock *DefBB = CI->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000529
Dale Johannesence0b2372007-06-12 16:50:17 +0000530 /// InsertedCmp - Only insert a cmp in each block once.
531 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000532
Dale Johannesence0b2372007-06-12 16:50:17 +0000533 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000534 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
Dale Johannesence0b2372007-06-12 16:50:17 +0000535 UI != E; ) {
536 Use &TheUse = UI.getUse();
537 Instruction *User = cast<Instruction>(*UI);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000538
Dale Johannesence0b2372007-06-12 16:50:17 +0000539 // Preincrement use iterator so we don't invalidate it.
540 ++UI;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000541
Dale Johannesence0b2372007-06-12 16:50:17 +0000542 // Don't bother for PHI nodes.
543 if (isa<PHINode>(User))
544 continue;
545
546 // Figure out which BB this cmp is used in.
547 BasicBlock *UserBB = User->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000548
Dale Johannesence0b2372007-06-12 16:50:17 +0000549 // If this user is in the same block as the cmp, don't change the cmp.
550 if (UserBB == DefBB) continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000551
Dale Johannesence0b2372007-06-12 16:50:17 +0000552 // If we have already inserted a cmp into this block, use it.
553 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
554
555 if (!InsertedCmp) {
Bill Wendling5b6f42f2011-08-16 20:45:24 +0000556 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000557 InsertedCmp =
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000558 CmpInst::Create(CI->getOpcode(),
Owen Anderson333c4002009-07-09 23:48:35 +0000559 CI->getPredicate(), CI->getOperand(0),
Dale Johannesence0b2372007-06-12 16:50:17 +0000560 CI->getOperand(1), "", InsertPt);
561 MadeChange = true;
562 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000563
Dale Johannesence0b2372007-06-12 16:50:17 +0000564 // Replace a use of the cmp with a use of the new cmp.
565 TheUse = InsertedCmp;
Cameron Zwarich31ff1332011-01-05 17:27:27 +0000566 ++NumCmpUses;
Dale Johannesence0b2372007-06-12 16:50:17 +0000567 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000568
Dale Johannesence0b2372007-06-12 16:50:17 +0000569 // If we removed all uses, nuke the cmp.
570 if (CI->use_empty())
571 CI->eraseFromParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000572
Dale Johannesence0b2372007-06-12 16:50:17 +0000573 return MadeChange;
574}
575
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000576namespace {
577class CodeGenPrepareFortifiedLibCalls : public SimplifyFortifiedLibCalls {
578protected:
579 void replaceCall(Value *With) {
580 CI->replaceAllUsesWith(With);
581 CI->eraseFromParent();
582 }
583 bool isFoldable(unsigned SizeCIOp, unsigned, bool) const {
Gabor Greifa6aac4c2010-07-16 09:38:02 +0000584 if (ConstantInt *SizeCI =
585 dyn_cast<ConstantInt>(CI->getArgOperand(SizeCIOp)))
586 return SizeCI->isAllOnesValue();
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000587 return false;
588 }
589};
590} // end anonymous namespace
591
Eric Christopher040056f2010-03-11 02:41:03 +0000592bool CodeGenPrepare::OptimizeCallInst(CallInst *CI) {
Chris Lattner75796092011-01-15 07:14:54 +0000593 BasicBlock *BB = CI->getParent();
Nadav Rotema94d6e82012-07-24 10:51:42 +0000594
Chris Lattner75796092011-01-15 07:14:54 +0000595 // Lower inline assembly if we can.
596 // If we found an inline asm expession, and if the target knows how to
597 // lower it to normal LLVM code, do so now.
598 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
599 if (TLI->ExpandInlineAsm(CI)) {
600 // Avoid invalidating the iterator.
601 CurInstIterator = BB->begin();
602 // Avoid processing instructions out of order, which could cause
603 // reuse before a value is defined.
604 SunkAddrs.clear();
605 return true;
606 }
607 // Sink address computing for memory operands into the block.
608 if (OptimizeInlineAsmInst(CI))
609 return true;
610 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000611
Eric Christopher040056f2010-03-11 02:41:03 +0000612 // Lower all uses of llvm.objectsize.*
613 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
614 if (II && II->getIntrinsicID() == Intrinsic::objectsize) {
Gabor Greifde9f5452010-06-24 00:44:01 +0000615 bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000616 Type *ReturnTy = CI->getType();
Nadav Rotema94d6e82012-07-24 10:51:42 +0000617 Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
618
Chris Lattner94e8e0c2011-01-15 07:25:29 +0000619 // Substituting this can cause recursive simplifications, which can
620 // invalidate our iterator. Use a WeakVH to hold onto it in case this
621 // happens.
622 WeakVH IterHandle(CurInstIterator);
Nadav Rotema94d6e82012-07-24 10:51:42 +0000623
Chandler Carruth6b980542012-03-24 21:11:24 +0000624 replaceAndRecursivelySimplify(CI, RetVal, TLI ? TLI->getTargetData() : 0,
625 TLInfo, ModifiedDT ? 0 : DT);
Chris Lattner94e8e0c2011-01-15 07:25:29 +0000626
627 // If the iterator instruction was recursively deleted, start over at the
628 // start of the block.
Chris Lattner435b4d22011-01-18 20:53:04 +0000629 if (IterHandle != CurInstIterator) {
Chris Lattner94e8e0c2011-01-15 07:25:29 +0000630 CurInstIterator = BB->begin();
Chris Lattner435b4d22011-01-18 20:53:04 +0000631 SunkAddrs.clear();
632 }
Eric Christopher040056f2010-03-11 02:41:03 +0000633 return true;
634 }
635
Pete Cooperf210b682012-03-13 20:59:56 +0000636 if (II && TLI) {
637 SmallVector<Value*, 2> PtrOps;
638 Type *AccessTy;
639 if (TLI->GetAddrModeArguments(II, PtrOps, AccessTy))
640 while (!PtrOps.empty())
641 if (OptimizeMemoryInst(II, PtrOps.pop_back_val(), AccessTy))
642 return true;
643 }
644
Eric Christopher040056f2010-03-11 02:41:03 +0000645 // From here on out we're working with named functions.
646 if (CI->getCalledFunction() == 0) return false;
Devang Patel97de92c2011-05-26 21:51:06 +0000647
Eric Christopher040056f2010-03-11 02:41:03 +0000648 // We'll need TargetData from here on out.
649 const TargetData *TD = TLI ? TLI->getTargetData() : 0;
650 if (!TD) return false;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000651
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000652 // Lower all default uses of _chk calls. This is very similar
653 // to what InstCombineCalls does, but here we are only lowering calls
Eric Christopher040056f2010-03-11 02:41:03 +0000654 // that have the default "don't know" as the objectsize. Anything else
655 // should be left alone.
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000656 CodeGenPrepareFortifiedLibCalls Simplifier;
Nuno Lopes51004df2012-07-25 16:46:31 +0000657 return Simplifier.fold(CI, TD, TLInfo);
Eric Christopher040056f2010-03-11 02:41:03 +0000658}
Chris Lattner94e8e0c2011-01-15 07:25:29 +0000659
Evan Cheng485fafc2011-03-21 01:19:09 +0000660/// DupRetToEnableTailCallOpts - Look for opportunities to duplicate return
661/// instructions to the predecessor to enable tail call optimizations. The
662/// case it is currently looking for is:
Dmitri Gribenko2d9eb722012-09-13 12:34:29 +0000663/// @code
Evan Cheng485fafc2011-03-21 01:19:09 +0000664/// bb0:
665/// %tmp0 = tail call i32 @f0()
666/// br label %return
667/// bb1:
668/// %tmp1 = tail call i32 @f1()
669/// br label %return
670/// bb2:
671/// %tmp2 = tail call i32 @f2()
672/// br label %return
673/// return:
674/// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
675/// ret i32 %retval
Dmitri Gribenko2d9eb722012-09-13 12:34:29 +0000676/// @endcode
Evan Cheng485fafc2011-03-21 01:19:09 +0000677///
678/// =>
679///
Dmitri Gribenko2d9eb722012-09-13 12:34:29 +0000680/// @code
Evan Cheng485fafc2011-03-21 01:19:09 +0000681/// bb0:
682/// %tmp0 = tail call i32 @f0()
683/// ret i32 %tmp0
684/// bb1:
685/// %tmp1 = tail call i32 @f1()
686/// ret i32 %tmp1
687/// bb2:
688/// %tmp2 = tail call i32 @f2()
689/// ret i32 %tmp2
Dmitri Gribenko2d9eb722012-09-13 12:34:29 +0000690/// @endcode
Evan Cheng485fafc2011-03-21 01:19:09 +0000691bool CodeGenPrepare::DupRetToEnableTailCallOpts(ReturnInst *RI) {
Cameron Zwarich661a3902011-03-24 04:51:51 +0000692 if (!TLI)
693 return false;
694
Evan Cheng9c777a42012-07-27 21:21:26 +0000695 PHINode *PN = 0;
696 BitCastInst *BCI = 0;
Evan Cheng485fafc2011-03-21 01:19:09 +0000697 Value *V = RI->getReturnValue();
Evan Cheng9c777a42012-07-27 21:21:26 +0000698 if (V) {
699 BCI = dyn_cast<BitCastInst>(V);
700 if (BCI)
701 V = BCI->getOperand(0);
702
703 PN = dyn_cast<PHINode>(V);
704 if (!PN)
705 return false;
706 }
Evan Cheng485fafc2011-03-21 01:19:09 +0000707
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000708 BasicBlock *BB = RI->getParent();
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000709 if (PN && PN->getParent() != BB)
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000710 return false;
Evan Cheng485fafc2011-03-21 01:19:09 +0000711
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000712 // It's not safe to eliminate the sign / zero extension of the return value.
713 // See llvm::isInTailCallPosition().
714 const Function *F = BB->getParent();
Kostya Serebryany164b86b2012-01-20 17:56:17 +0000715 Attributes CallerRetAttr = F->getAttributes().getRetAttributes();
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000716 if ((CallerRetAttr & Attribute::ZExt) || (CallerRetAttr & Attribute::SExt))
717 return false;
Evan Cheng485fafc2011-03-21 01:19:09 +0000718
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000719 // Make sure there are no instructions between the PHI and return, or that the
720 // return is the first instruction in the block.
721 if (PN) {
722 BasicBlock::iterator BI = BB->begin();
723 do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
Evan Cheng9c777a42012-07-27 21:21:26 +0000724 if (&*BI == BCI)
725 // Also skip over the bitcast.
726 ++BI;
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000727 if (&*BI != RI)
728 return false;
729 } else {
Cameron Zwarich90354842011-03-24 16:34:59 +0000730 BasicBlock::iterator BI = BB->begin();
731 while (isa<DbgInfoIntrinsic>(BI)) ++BI;
732 if (&*BI != RI)
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000733 return false;
734 }
Evan Cheng485fafc2011-03-21 01:19:09 +0000735
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000736 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
737 /// call.
738 SmallVector<CallInst*, 4> TailCalls;
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000739 if (PN) {
740 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
741 CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
742 // Make sure the phi value is indeed produced by the tail call.
743 if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
744 TLI->mayBeEmittedAsTailCall(CI))
745 TailCalls.push_back(CI);
746 }
747 } else {
748 SmallPtrSet<BasicBlock*, 4> VisitedBBs;
749 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
750 if (!VisitedBBs.insert(*PI))
751 continue;
752
753 BasicBlock::InstListType &InstList = (*PI)->getInstList();
754 BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
755 BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
Cameron Zwarich90354842011-03-24 16:34:59 +0000756 do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
757 if (RI == RE)
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000758 continue;
Cameron Zwarich90354842011-03-24 16:34:59 +0000759
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000760 CallInst *CI = dyn_cast<CallInst>(&*RI);
Cameron Zwarichdc31cfe2011-03-24 15:54:11 +0000761 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI))
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000762 TailCalls.push_back(CI);
763 }
Evan Cheng485fafc2011-03-21 01:19:09 +0000764 }
765
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000766 bool Changed = false;
767 for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
768 CallInst *CI = TailCalls[i];
769 CallSite CS(CI);
770
771 // Conservatively require the attributes of the call to match those of the
772 // return. Ignore noalias because it doesn't affect the call sequence.
Kostya Serebryany164b86b2012-01-20 17:56:17 +0000773 Attributes CalleeRetAttr = CS.getAttributes().getRetAttributes();
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000774 if ((CalleeRetAttr ^ CallerRetAttr) & ~Attribute::NoAlias)
775 continue;
776
777 // Make sure the call instruction is followed by an unconditional branch to
778 // the return block.
779 BasicBlock *CallBB = CI->getParent();
780 BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
781 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
782 continue;
783
784 // Duplicate the return into CallBB.
785 (void)FoldReturnIntoUncondBranch(RI, BB, CallBB);
Devang Patel52e37df2011-03-24 15:35:25 +0000786 ModifiedDT = Changed = true;
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000787 ++NumRetsDup;
788 }
789
790 // If we eliminated all predecessors of the block, delete the block now.
791 if (Changed && pred_begin(BB) == pred_end(BB))
792 BB->eraseFromParent();
793
794 return Changed;
Evan Cheng485fafc2011-03-21 01:19:09 +0000795}
796
Chris Lattner88a5c832008-11-25 07:09:13 +0000797//===----------------------------------------------------------------------===//
Chris Lattner88a5c832008-11-25 07:09:13 +0000798// Memory Optimization
799//===----------------------------------------------------------------------===//
800
Chris Lattnerdd77df32007-04-13 20:30:56 +0000801/// IsNonLocalValue - Return true if the specified values are defined in a
802/// different basic block than BB.
803static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
804 if (Instruction *I = dyn_cast<Instruction>(V))
805 return I->getParent() != BB;
806 return false;
807}
808
Bob Wilson4a8ee232009-12-03 21:47:07 +0000809/// OptimizeMemoryInst - Load and Store Instructions often have
Chris Lattnerdd77df32007-04-13 20:30:56 +0000810/// addressing modes that can do significant amounts of computation. As such,
811/// instruction selection will try to get the load or store to do as much
812/// computation as possible for the program. The problem is that isel can only
813/// see within a single block. As such, we sink as much legal addressing mode
814/// stuff into the block as possible.
Chris Lattner88a5c832008-11-25 07:09:13 +0000815///
816/// This method is used to optimize both load/store and inline asms with memory
817/// operands.
Chris Lattner896617b2008-11-26 03:20:37 +0000818bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000819 Type *AccessTy) {
Owen Anderson35bf4d62010-11-27 08:15:55 +0000820 Value *Repl = Addr;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000821
822 // Try to collapse single-value PHI nodes. This is necessary to undo
Owen Andersond2f41742010-11-19 22:15:03 +0000823 // unprofitable PRE transformations.
Cameron Zwarich7cb4fa22011-01-03 06:33:01 +0000824 SmallVector<Value*, 8> worklist;
825 SmallPtrSet<Value*, 16> Visited;
Owen Anderson35bf4d62010-11-27 08:15:55 +0000826 worklist.push_back(Addr);
Nadav Rotema94d6e82012-07-24 10:51:42 +0000827
Owen Anderson35bf4d62010-11-27 08:15:55 +0000828 // Use a worklist to iteratively look through PHI nodes, and ensure that
829 // the addressing mode obtained from the non-PHI roots of the graph
830 // are equivalent.
831 Value *Consensus = 0;
Cameron Zwarich4c078f02011-03-01 21:13:53 +0000832 unsigned NumUsesConsensus = 0;
Cameron Zwarich7c8d3512011-03-05 08:12:26 +0000833 bool IsNumUsesConsensusValid = false;
Owen Anderson35bf4d62010-11-27 08:15:55 +0000834 SmallVector<Instruction*, 16> AddrModeInsts;
835 ExtAddrMode AddrMode;
836 while (!worklist.empty()) {
837 Value *V = worklist.back();
838 worklist.pop_back();
Nadav Rotema94d6e82012-07-24 10:51:42 +0000839
Owen Anderson35bf4d62010-11-27 08:15:55 +0000840 // Break use-def graph loops.
Nick Lewycky48105282011-09-29 23:40:12 +0000841 if (!Visited.insert(V)) {
Owen Anderson35bf4d62010-11-27 08:15:55 +0000842 Consensus = 0;
843 break;
Owen Andersond2f41742010-11-19 22:15:03 +0000844 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000845
Owen Anderson35bf4d62010-11-27 08:15:55 +0000846 // For a PHI node, push all of its incoming values.
847 if (PHINode *P = dyn_cast<PHINode>(V)) {
848 for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i)
849 worklist.push_back(P->getIncomingValue(i));
850 continue;
851 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000852
Owen Anderson35bf4d62010-11-27 08:15:55 +0000853 // For non-PHIs, determine the addressing mode being computed.
854 SmallVector<Instruction*, 16> NewAddrModeInsts;
855 ExtAddrMode NewAddrMode =
Nick Lewycky48105282011-09-29 23:40:12 +0000856 AddressingModeMatcher::Match(V, AccessTy, MemoryInst,
Owen Anderson35bf4d62010-11-27 08:15:55 +0000857 NewAddrModeInsts, *TLI);
Cameron Zwarich7c8d3512011-03-05 08:12:26 +0000858
859 // This check is broken into two cases with very similar code to avoid using
860 // getNumUses() as much as possible. Some values have a lot of uses, so
861 // calling getNumUses() unconditionally caused a significant compile-time
862 // regression.
863 if (!Consensus) {
864 Consensus = V;
865 AddrMode = NewAddrMode;
866 AddrModeInsts = NewAddrModeInsts;
867 continue;
868 } else if (NewAddrMode == AddrMode) {
869 if (!IsNumUsesConsensusValid) {
870 NumUsesConsensus = Consensus->getNumUses();
871 IsNumUsesConsensusValid = true;
872 }
873
874 // Ensure that the obtained addressing mode is equivalent to that obtained
875 // for all other roots of the PHI traversal. Also, when choosing one
876 // such root as representative, select the one with the most uses in order
877 // to keep the cost modeling heuristics in AddressingModeMatcher
878 // applicable.
Cameron Zwarich4c078f02011-03-01 21:13:53 +0000879 unsigned NumUses = V->getNumUses();
880 if (NumUses > NumUsesConsensus) {
Owen Anderson35bf4d62010-11-27 08:15:55 +0000881 Consensus = V;
Cameron Zwarich4c078f02011-03-01 21:13:53 +0000882 NumUsesConsensus = NumUses;
Owen Anderson35bf4d62010-11-27 08:15:55 +0000883 AddrModeInsts = NewAddrModeInsts;
884 }
885 continue;
886 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000887
Owen Anderson35bf4d62010-11-27 08:15:55 +0000888 Consensus = 0;
889 break;
Owen Andersond2f41742010-11-19 22:15:03 +0000890 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000891
Owen Anderson35bf4d62010-11-27 08:15:55 +0000892 // If the addressing mode couldn't be determined, or if multiple different
893 // ones were determined, bail out now.
894 if (!Consensus) return false;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000895
Chris Lattnerdd77df32007-04-13 20:30:56 +0000896 // Check to see if any of the instructions supersumed by this addr mode are
897 // non-local to I's BB.
898 bool AnyNonLocal = false;
899 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
Chris Lattner896617b2008-11-26 03:20:37 +0000900 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
Chris Lattnerdd77df32007-04-13 20:30:56 +0000901 AnyNonLocal = true;
902 break;
903 }
904 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000905
Chris Lattnerdd77df32007-04-13 20:30:56 +0000906 // If all the instructions matched are already in this BB, don't do anything.
907 if (!AnyNonLocal) {
David Greene68d67fd2010-01-05 01:27:11 +0000908 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000909 return false;
910 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000911
Chris Lattnerdd77df32007-04-13 20:30:56 +0000912 // Insert this computation right after this user. Since our caller is
913 // scanning from the top of the BB to the bottom, reuse of the expr are
914 // guaranteed to happen later.
Devang Patel2048c372011-09-06 18:49:53 +0000915 IRBuilder<> Builder(MemoryInst);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000916
Chris Lattnerdd77df32007-04-13 20:30:56 +0000917 // Now that we determined the addressing expression we want to use and know
918 // that we have to sink it into this block. Check to see if we have already
919 // done this for some other load/store instr in this block. If so, reuse the
920 // computation.
921 Value *&SunkAddr = SunkAddrs[Addr];
922 if (SunkAddr) {
David Greene68d67fd2010-01-05 01:27:11 +0000923 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
Dan Gohman6c1980b2009-07-25 01:13:51 +0000924 << *MemoryInst);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000925 if (SunkAddr->getType() != Addr->getType())
Benjamin Kramera9390a42011-09-27 20:39:19 +0000926 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
Chris Lattnerdd77df32007-04-13 20:30:56 +0000927 } else {
David Greene68d67fd2010-01-05 01:27:11 +0000928 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Dan Gohman6c1980b2009-07-25 01:13:51 +0000929 << *MemoryInst);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000930 Type *IntPtrTy =
Owen Anderson1d0be152009-08-13 21:58:54 +0000931 TLI->getTargetData()->getIntPtrType(AccessTy->getContext());
Eric Christopher692bf6b2008-09-24 05:32:41 +0000932
Chris Lattnerdd77df32007-04-13 20:30:56 +0000933 Value *Result = 0;
Dan Gohmand8d0b6a2010-01-19 22:45:06 +0000934
935 // Start with the base register. Do this first so that subsequent address
936 // matching finds it last, which will prevent it from trying to match it
937 // as the scaled value in case it happens to be a mul. That would be
938 // problematic if we've sunk a different mul for the scale, because then
939 // we'd end up sinking both muls.
940 if (AddrMode.BaseReg) {
941 Value *V = AddrMode.BaseReg;
Duncan Sands1df98592010-02-16 11:11:14 +0000942 if (V->getType()->isPointerTy())
Devang Patel2048c372011-09-06 18:49:53 +0000943 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Dan Gohmand8d0b6a2010-01-19 22:45:06 +0000944 if (V->getType() != IntPtrTy)
Devang Patel2048c372011-09-06 18:49:53 +0000945 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
Dan Gohmand8d0b6a2010-01-19 22:45:06 +0000946 Result = V;
947 }
948
949 // Add the scale value.
Chris Lattnerdd77df32007-04-13 20:30:56 +0000950 if (AddrMode.Scale) {
951 Value *V = AddrMode.ScaledReg;
952 if (V->getType() == IntPtrTy) {
953 // done.
Duncan Sands1df98592010-02-16 11:11:14 +0000954 } else if (V->getType()->isPointerTy()) {
Devang Patel2048c372011-09-06 18:49:53 +0000955 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000956 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
957 cast<IntegerType>(V->getType())->getBitWidth()) {
Devang Patel2048c372011-09-06 18:49:53 +0000958 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000959 } else {
Devang Patel2048c372011-09-06 18:49:53 +0000960 V = Builder.CreateSExt(V, IntPtrTy, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000961 }
962 if (AddrMode.Scale != 1)
Devang Patel2048c372011-09-06 18:49:53 +0000963 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
964 "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000965 if (Result)
Devang Patel2048c372011-09-06 18:49:53 +0000966 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000967 else
968 Result = V;
969 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000970
Chris Lattnerdd77df32007-04-13 20:30:56 +0000971 // Add in the BaseGV if present.
972 if (AddrMode.BaseGV) {
Devang Patel2048c372011-09-06 18:49:53 +0000973 Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000974 if (Result)
Devang Patel2048c372011-09-06 18:49:53 +0000975 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000976 else
977 Result = V;
978 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000979
Chris Lattnerdd77df32007-04-13 20:30:56 +0000980 // Add in the Base Offset if present.
981 if (AddrMode.BaseOffs) {
Owen Andersoneed707b2009-07-24 23:12:02 +0000982 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000983 if (Result)
Devang Patel2048c372011-09-06 18:49:53 +0000984 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000985 else
986 Result = V;
987 }
988
989 if (Result == 0)
Owen Andersona7235ea2009-07-31 20:28:14 +0000990 SunkAddr = Constant::getNullValue(Addr->getType());
Chris Lattnerdd77df32007-04-13 20:30:56 +0000991 else
Devang Patel2048c372011-09-06 18:49:53 +0000992 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000993 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000994
Owen Andersond2f41742010-11-19 22:15:03 +0000995 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000996
Chris Lattner0403b472011-04-09 07:05:44 +0000997 // If we have no uses, recursively delete the value and all dead instructions
998 // using it.
Owen Andersond2f41742010-11-19 22:15:03 +0000999 if (Repl->use_empty()) {
Chris Lattner0403b472011-04-09 07:05:44 +00001000 // This can cause recursive deletion, which can invalidate our iterator.
1001 // Use a WeakVH to hold onto it in case this happens.
1002 WeakVH IterHandle(CurInstIterator);
1003 BasicBlock *BB = CurInstIterator->getParent();
Nadav Rotema94d6e82012-07-24 10:51:42 +00001004
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +00001005 RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
Chris Lattner0403b472011-04-09 07:05:44 +00001006
1007 if (IterHandle != CurInstIterator) {
1008 // If the iterator instruction was recursively deleted, start over at the
1009 // start of the block.
1010 CurInstIterator = BB->begin();
1011 SunkAddrs.clear();
1012 } else {
1013 // This address is now available for reassignment, so erase the table
1014 // entry; we don't want to match some completely different instruction.
1015 SunkAddrs[Addr] = 0;
Nadav Rotema94d6e82012-07-24 10:51:42 +00001016 }
Dale Johannesen536d31b2010-03-31 20:37:15 +00001017 }
Cameron Zwarich31ff1332011-01-05 17:27:27 +00001018 ++NumMemoryInsts;
Chris Lattnerdd77df32007-04-13 20:30:56 +00001019 return true;
1020}
1021
Evan Cheng9bf12b52008-02-26 02:42:37 +00001022/// OptimizeInlineAsmInst - If there are any memory operands, use
Chris Lattner88a5c832008-11-25 07:09:13 +00001023/// OptimizeMemoryInst to sink their address computing into the block when
Evan Cheng9bf12b52008-02-26 02:42:37 +00001024/// possible / profitable.
Chris Lattner75796092011-01-15 07:14:54 +00001025bool CodeGenPrepare::OptimizeInlineAsmInst(CallInst *CS) {
Evan Cheng9bf12b52008-02-26 02:42:37 +00001026 bool MadeChange = false;
Evan Cheng9bf12b52008-02-26 02:42:37 +00001027
Nadav Rotema94d6e82012-07-24 10:51:42 +00001028 TargetLowering::AsmOperandInfoVector
Chris Lattner75796092011-01-15 07:14:54 +00001029 TargetConstraints = TLI->ParseConstraints(CS);
Dale Johannesen677c6ec2010-09-16 18:30:55 +00001030 unsigned ArgNo = 0;
John Thompsoneac6e1d2010-09-13 18:15:37 +00001031 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
1032 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Nadav Rotema94d6e82012-07-24 10:51:42 +00001033
Evan Cheng9bf12b52008-02-26 02:42:37 +00001034 // Compute the constraint code and ConstraintType to use.
Dale Johannesen1784d162010-06-25 21:55:36 +00001035 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Evan Cheng9bf12b52008-02-26 02:42:37 +00001036
Eli Friedman9ec80952008-02-26 18:37:49 +00001037 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
1038 OpInfo.isIndirect) {
Chris Lattner75796092011-01-15 07:14:54 +00001039 Value *OpVal = CS->getArgOperand(ArgNo++);
Chris Lattner1a8943a2011-01-15 07:29:01 +00001040 MadeChange |= OptimizeMemoryInst(CS, OpVal, OpVal->getType());
Dale Johannesen677c6ec2010-09-16 18:30:55 +00001041 } else if (OpInfo.Type == InlineAsm::isInput)
1042 ArgNo++;
Evan Cheng9bf12b52008-02-26 02:42:37 +00001043 }
1044
1045 return MadeChange;
1046}
1047
Dan Gohmanb00f2362009-10-16 20:59:35 +00001048/// MoveExtToFormExtLoad - Move a zext or sext fed by a load into the same
1049/// basic block as the load, unless conditions are unfavorable. This allows
1050/// SelectionDAG to fold the extend into the load.
1051///
1052bool CodeGenPrepare::MoveExtToFormExtLoad(Instruction *I) {
1053 // Look for a load being extended.
1054 LoadInst *LI = dyn_cast<LoadInst>(I->getOperand(0));
1055 if (!LI) return false;
1056
1057 // If they're already in the same block, there's nothing to do.
1058 if (LI->getParent() == I->getParent())
1059 return false;
1060
1061 // If the load has other users and the truncate is not free, this probably
1062 // isn't worthwhile.
1063 if (!LI->hasOneUse() &&
Bob Wilsonec57a1a2010-09-22 18:44:56 +00001064 TLI && (TLI->isTypeLegal(TLI->getValueType(LI->getType())) ||
1065 !TLI->isTypeLegal(TLI->getValueType(I->getType()))) &&
Bob Wilson71dc4d92010-09-21 21:54:27 +00001066 !TLI->isTruncateFree(I->getType(), LI->getType()))
Dan Gohmanb00f2362009-10-16 20:59:35 +00001067 return false;
1068
1069 // Check whether the target supports casts folded into loads.
1070 unsigned LType;
1071 if (isa<ZExtInst>(I))
1072 LType = ISD::ZEXTLOAD;
1073 else {
1074 assert(isa<SExtInst>(I) && "Unexpected ext type!");
1075 LType = ISD::SEXTLOAD;
1076 }
1077 if (TLI && !TLI->isLoadExtLegal(LType, TLI->getValueType(LI->getType())))
1078 return false;
1079
1080 // Move the extend into the same block as the load, so that SelectionDAG
1081 // can fold it.
1082 I->removeFromParent();
1083 I->insertAfter(LI);
Cameron Zwarich31ff1332011-01-05 17:27:27 +00001084 ++NumExtsMoved;
Dan Gohmanb00f2362009-10-16 20:59:35 +00001085 return true;
1086}
1087
Evan Chengbdcb7262007-12-05 23:58:20 +00001088bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
1089 BasicBlock *DefBB = I->getParent();
1090
Bob Wilson9120f5c2010-09-21 21:44:14 +00001091 // If the result of a {s|z}ext and its source are both live out, rewrite all
Evan Chengbdcb7262007-12-05 23:58:20 +00001092 // other uses of the source with result of extension.
1093 Value *Src = I->getOperand(0);
1094 if (Src->hasOneUse())
1095 return false;
1096
Evan Cheng696e5c02007-12-13 07:50:36 +00001097 // Only do this xform if truncating is free.
Gabor Greif53bdbd72008-02-26 19:13:21 +00001098 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
Evan Chengf9785f92007-12-13 03:32:53 +00001099 return false;
1100
Evan Cheng772de512007-12-12 00:51:06 +00001101 // Only safe to perform the optimization if the source is also defined in
Evan Cheng765dff22007-12-12 02:53:41 +00001102 // this block.
1103 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
Evan Cheng772de512007-12-12 00:51:06 +00001104 return false;
1105
Evan Chengbdcb7262007-12-05 23:58:20 +00001106 bool DefIsLiveOut = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001107 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
Evan Chengbdcb7262007-12-05 23:58:20 +00001108 UI != E; ++UI) {
1109 Instruction *User = cast<Instruction>(*UI);
1110
1111 // Figure out which BB this ext is used in.
1112 BasicBlock *UserBB = User->getParent();
1113 if (UserBB == DefBB) continue;
1114 DefIsLiveOut = true;
1115 break;
1116 }
1117 if (!DefIsLiveOut)
1118 return false;
1119
Evan Cheng765dff22007-12-12 02:53:41 +00001120 // Make sure non of the uses are PHI nodes.
Eric Christopher692bf6b2008-09-24 05:32:41 +00001121 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
Evan Cheng765dff22007-12-12 02:53:41 +00001122 UI != E; ++UI) {
1123 Instruction *User = cast<Instruction>(*UI);
Evan Chengf9785f92007-12-13 03:32:53 +00001124 BasicBlock *UserBB = User->getParent();
1125 if (UserBB == DefBB) continue;
1126 // Be conservative. We don't want this xform to end up introducing
1127 // reloads just before load / store instructions.
1128 if (isa<PHINode>(User) || isa<LoadInst>(User) || isa<StoreInst>(User))
Evan Cheng765dff22007-12-12 02:53:41 +00001129 return false;
1130 }
1131
Evan Chengbdcb7262007-12-05 23:58:20 +00001132 // InsertedTruncs - Only insert one trunc in each block once.
1133 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
1134
1135 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001136 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
Evan Chengbdcb7262007-12-05 23:58:20 +00001137 UI != E; ++UI) {
1138 Use &TheUse = UI.getUse();
1139 Instruction *User = cast<Instruction>(*UI);
1140
1141 // Figure out which BB this ext is used in.
1142 BasicBlock *UserBB = User->getParent();
1143 if (UserBB == DefBB) continue;
1144
1145 // Both src and def are live in this block. Rewrite the use.
1146 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
1147
1148 if (!InsertedTrunc) {
Bill Wendling5b6f42f2011-08-16 20:45:24 +00001149 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Evan Chengbdcb7262007-12-05 23:58:20 +00001150 InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
1151 }
1152
1153 // Replace a use of the {s|z}ext source with a use of the result.
1154 TheUse = InsertedTrunc;
Cameron Zwarich31ff1332011-01-05 17:27:27 +00001155 ++NumExtUses;
Evan Chengbdcb7262007-12-05 23:58:20 +00001156 MadeChange = true;
1157 }
1158
1159 return MadeChange;
1160}
1161
Benjamin Kramer59957502012-05-05 12:49:22 +00001162/// isFormingBranchFromSelectProfitable - Returns true if a SelectInst should be
1163/// turned into an explicit branch.
1164static bool isFormingBranchFromSelectProfitable(SelectInst *SI) {
1165 // FIXME: This should use the same heuristics as IfConversion to determine
1166 // whether a select is better represented as a branch. This requires that
1167 // branch probability metadata is preserved for the select, which is not the
1168 // case currently.
1169
1170 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
1171
1172 // If the branch is predicted right, an out of order CPU can avoid blocking on
1173 // the compare. Emit cmovs on compares with a memory operand as branches to
1174 // avoid stalls on the load from memory. If the compare has more than one use
1175 // there's probably another cmov or setcc around so it's not worth emitting a
1176 // branch.
1177 if (!Cmp)
1178 return false;
1179
1180 Value *CmpOp0 = Cmp->getOperand(0);
1181 Value *CmpOp1 = Cmp->getOperand(1);
1182
1183 // We check that the memory operand has one use to avoid uses of the loaded
1184 // value directly after the compare, making branches unprofitable.
1185 return Cmp->hasOneUse() &&
1186 ((isa<LoadInst>(CmpOp0) && CmpOp0->hasOneUse()) ||
1187 (isa<LoadInst>(CmpOp1) && CmpOp1->hasOneUse()));
1188}
1189
1190
Nadav Rotem9f40cb32012-09-02 12:10:19 +00001191/// If we have a SelectInst that will likely profit from branch prediction,
1192/// turn it into a branch.
Benjamin Kramer59957502012-05-05 12:49:22 +00001193bool CodeGenPrepare::OptimizeSelectInst(SelectInst *SI) {
Nadav Rotem9f40cb32012-09-02 12:10:19 +00001194 bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
1195
1196 // Can we convert the 'select' to CF ?
1197 if (DisableSelectToBranch || OptSize || !TLI || VectorCond)
Benjamin Kramer59957502012-05-05 12:49:22 +00001198 return false;
1199
Nadav Rotem9f40cb32012-09-02 12:10:19 +00001200 TargetLowering::SelectSupportKind SelectKind;
1201 if (VectorCond)
1202 SelectKind = TargetLowering::VectorMaskSelect;
1203 else if (SI->getType()->isVectorTy())
1204 SelectKind = TargetLowering::ScalarCondVectorVal;
1205 else
1206 SelectKind = TargetLowering::ScalarValSelect;
1207
1208 // Do we have efficient codegen support for this kind of 'selects' ?
1209 if (TLI->isSelectSupported(SelectKind)) {
1210 // We have efficient codegen support for the select instruction.
1211 // Check if it is profitable to keep this 'select'.
1212 if (!TLI->isPredictableSelectExpensive() ||
1213 !isFormingBranchFromSelectProfitable(SI))
1214 return false;
1215 }
Benjamin Kramer59957502012-05-05 12:49:22 +00001216
1217 ModifiedDT = true;
1218
1219 // First, we split the block containing the select into 2 blocks.
1220 BasicBlock *StartBlock = SI->getParent();
1221 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(SI));
1222 BasicBlock *NextBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
1223
1224 // Create a new block serving as the landing pad for the branch.
1225 BasicBlock *SmallBlock = BasicBlock::Create(SI->getContext(), "select.mid",
1226 NextBlock->getParent(), NextBlock);
1227
1228 // Move the unconditional branch from the block with the select in it into our
1229 // landing pad block.
1230 StartBlock->getTerminator()->eraseFromParent();
1231 BranchInst::Create(NextBlock, SmallBlock);
1232
1233 // Insert the real conditional branch based on the original condition.
1234 BranchInst::Create(NextBlock, SmallBlock, SI->getCondition(), SI);
1235
1236 // The select itself is replaced with a PHI Node.
1237 PHINode *PN = PHINode::Create(SI->getType(), 2, "", NextBlock->begin());
1238 PN->takeName(SI);
1239 PN->addIncoming(SI->getTrueValue(), StartBlock);
1240 PN->addIncoming(SI->getFalseValue(), SmallBlock);
1241 SI->replaceAllUsesWith(PN);
1242 SI->eraseFromParent();
1243
1244 // Instruct OptimizeBlock to skip to the next block.
1245 CurInstIterator = StartBlock->end();
1246 ++NumSelectsExpanded;
1247 return true;
1248}
1249
Cameron Zwarichc0611012011-01-06 02:37:26 +00001250bool CodeGenPrepare::OptimizeInst(Instruction *I) {
Cameron Zwarichc0611012011-01-06 02:37:26 +00001251 if (PHINode *P = dyn_cast<PHINode>(I)) {
1252 // It is possible for very late stage optimizations (such as SimplifyCFG)
1253 // to introduce PHI nodes too late to be cleaned up. If we detect such a
1254 // trivial PHI, go ahead and zap it here.
1255 if (Value *V = SimplifyInstruction(P)) {
1256 P->replaceAllUsesWith(V);
1257 P->eraseFromParent();
1258 ++NumPHIsElim;
Chris Lattner1a8943a2011-01-15 07:29:01 +00001259 return true;
Cameron Zwarichc0611012011-01-06 02:37:26 +00001260 }
Chris Lattner1a8943a2011-01-15 07:29:01 +00001261 return false;
1262 }
Nadav Rotema94d6e82012-07-24 10:51:42 +00001263
Chris Lattner1a8943a2011-01-15 07:29:01 +00001264 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Cameron Zwarichc0611012011-01-06 02:37:26 +00001265 // If the source of the cast is a constant, then this should have
1266 // already been constant folded. The only reason NOT to constant fold
1267 // it is if something (e.g. LSR) was careful to place the constant
1268 // evaluation in a block other than then one that uses it (e.g. to hoist
1269 // the address of globals out of a loop). If this is the case, we don't
1270 // want to forward-subst the cast.
1271 if (isa<Constant>(CI->getOperand(0)))
1272 return false;
1273
Chris Lattner1a8943a2011-01-15 07:29:01 +00001274 if (TLI && OptimizeNoopCopyExpression(CI, *TLI))
1275 return true;
Cameron Zwarichc0611012011-01-06 02:37:26 +00001276
Chris Lattner1a8943a2011-01-15 07:29:01 +00001277 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
1278 bool MadeChange = MoveExtToFormExtLoad(I);
1279 return MadeChange | OptimizeExtUses(I);
Cameron Zwarichc0611012011-01-06 02:37:26 +00001280 }
Chris Lattner1a8943a2011-01-15 07:29:01 +00001281 return false;
1282 }
Nadav Rotema94d6e82012-07-24 10:51:42 +00001283
Chris Lattner1a8943a2011-01-15 07:29:01 +00001284 if (CmpInst *CI = dyn_cast<CmpInst>(I))
1285 return OptimizeCmpExpression(CI);
Nadav Rotema94d6e82012-07-24 10:51:42 +00001286
Chris Lattner1a8943a2011-01-15 07:29:01 +00001287 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Hans Wennborg93ba1332012-09-19 07:48:16 +00001288 bool Changed = false;
Cameron Zwarichc0611012011-01-06 02:37:26 +00001289 if (TLI)
Hans Wennborg93ba1332012-09-19 07:48:16 +00001290 Changed |= OptimizeMemoryInst(I, I->getOperand(0), LI->getType());
1291 Changed |= ConvertLoadToSwitch(LI);
1292 return Changed;
Chris Lattner1a8943a2011-01-15 07:29:01 +00001293 }
Nadav Rotema94d6e82012-07-24 10:51:42 +00001294
Chris Lattner1a8943a2011-01-15 07:29:01 +00001295 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Cameron Zwarichc0611012011-01-06 02:37:26 +00001296 if (TLI)
Chris Lattner1a8943a2011-01-15 07:29:01 +00001297 return OptimizeMemoryInst(I, SI->getOperand(1),
1298 SI->getOperand(0)->getType());
1299 return false;
1300 }
Nadav Rotema94d6e82012-07-24 10:51:42 +00001301
Chris Lattner1a8943a2011-01-15 07:29:01 +00001302 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Cameron Zwarich865ae1a2011-01-06 02:44:52 +00001303 if (GEPI->hasAllZeroIndices()) {
1304 /// The GEP operand must be a pointer, so must its result -> BitCast
1305 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
1306 GEPI->getName(), GEPI);
1307 GEPI->replaceAllUsesWith(NC);
1308 GEPI->eraseFromParent();
1309 ++NumGEPsElim;
Cameron Zwarich865ae1a2011-01-06 02:44:52 +00001310 OptimizeInst(NC);
Chris Lattner1a8943a2011-01-15 07:29:01 +00001311 return true;
Cameron Zwarich865ae1a2011-01-06 02:44:52 +00001312 }
Chris Lattner1a8943a2011-01-15 07:29:01 +00001313 return false;
Cameron Zwarichc0611012011-01-06 02:37:26 +00001314 }
Nadav Rotema94d6e82012-07-24 10:51:42 +00001315
Chris Lattner1a8943a2011-01-15 07:29:01 +00001316 if (CallInst *CI = dyn_cast<CallInst>(I))
1317 return OptimizeCallInst(CI);
Cameron Zwarichc0611012011-01-06 02:37:26 +00001318
Evan Cheng485fafc2011-03-21 01:19:09 +00001319 if (ReturnInst *RI = dyn_cast<ReturnInst>(I))
1320 return DupRetToEnableTailCallOpts(RI);
1321
Benjamin Kramer59957502012-05-05 12:49:22 +00001322 if (SelectInst *SI = dyn_cast<SelectInst>(I))
1323 return OptimizeSelectInst(SI);
1324
Chris Lattner1a8943a2011-01-15 07:29:01 +00001325 return false;
Cameron Zwarichc0611012011-01-06 02:37:26 +00001326}
1327
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001328// In this pass we look for GEP and cast instructions that are used
1329// across basic blocks and rewrite them to improve basic-block-at-a-time
1330// selection.
1331bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
Cameron Zwarich8c3527e2011-01-06 00:42:50 +00001332 SunkAddrs.clear();
Cameron Zwarich56e37932011-03-02 03:31:46 +00001333 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001334
Chris Lattner75796092011-01-15 07:14:54 +00001335 CurInstIterator = BB.begin();
Hans Wennborg93ba1332012-09-19 07:48:16 +00001336 while (CurInstIterator != BB.end())
Chris Lattner94e8e0c2011-01-15 07:25:29 +00001337 MadeChange |= OptimizeInst(CurInstIterator++);
Eric Christopher692bf6b2008-09-24 05:32:41 +00001338
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001339 return MadeChange;
1340}
Devang Patelf56ea612011-08-18 00:50:51 +00001341
1342// llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotema94d6e82012-07-24 10:51:42 +00001343// handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patelf56ea612011-08-18 00:50:51 +00001344// find a node corresponding to the value.
1345bool CodeGenPrepare::PlaceDbgValues(Function &F) {
1346 bool MadeChange = false;
1347 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
1348 Instruction *PrevNonDbgInst = NULL;
1349 for (BasicBlock::iterator BI = I->begin(), BE = I->end(); BI != BE;) {
1350 Instruction *Insn = BI; ++BI;
1351 DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
1352 if (!DVI) {
1353 PrevNonDbgInst = Insn;
1354 continue;
1355 }
1356
1357 Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
1358 if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
1359 DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
1360 DVI->removeFromParent();
1361 if (isa<PHINode>(VI))
1362 DVI->insertBefore(VI->getParent()->getFirstInsertionPt());
1363 else
1364 DVI->insertAfter(VI);
1365 MadeChange = true;
1366 ++NumDbgValueMoved;
1367 }
1368 }
1369 }
1370 return MadeChange;
1371}
Hans Wennborg93ba1332012-09-19 07:48:16 +00001372
1373static bool TargetSupportsJumpTables(const TargetLowering &TLI) {
1374 return TLI.supportJumpTables() &&
1375 (TLI.isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
1376 TLI.isOperationLegalOrCustom(ISD::BRIND, MVT::Other));
1377}
1378
1379/// ConvertLoadToSwitch - Convert loads from constant lookup tables into
1380/// switches. This undos the switch-to-lookup table transformation in
1381/// SimplifyCFG for targets where that is inprofitable.
1382bool CodeGenPrepare::ConvertLoadToSwitch(LoadInst *LI) {
1383 // This only applies to targets that don't support jump tables.
1384 if (!TLI || TargetSupportsJumpTables(*TLI))
1385 return false;
1386
1387 // FIXME: In the future, it would be desirable to have enough target
1388 // information in SimplifyCFG, so we could decide at that stage whether to
1389 // transform the switch to a lookup table or not, and this
1390 // reverse-transformation could be removed.
1391
1392 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getPointerOperand());
1393 if (!GEP || !GEP->isInBounds() || GEP->getPointerAddressSpace())
1394 return false;
1395 if (GEP->getNumIndices() != 2)
1396 return false;
1397 Value *FirstIndex = GEP->idx_begin()[0];
1398 ConstantInt *FirstIndexInt = dyn_cast<ConstantInt>(FirstIndex);
1399 if (!FirstIndexInt || !FirstIndexInt->isZero())
1400 return false;
1401
1402 Value *TableIndex = GEP->idx_begin()[1];
1403 IntegerType *TableIndexTy = cast<IntegerType>(TableIndex->getType());
1404
1405 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getPointerOperand());
1406 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
1407 return false;
1408
1409 Constant *Arr = GV->getInitializer();
1410 uint64_t NumElements;
1411 if (ConstantArray *CA = dyn_cast<ConstantArray>(Arr))
1412 NumElements = CA->getType()->getNumElements();
1413 else if (ConstantDataArray *CDA = dyn_cast<ConstantDataArray>(Arr))
1414 NumElements = CDA->getNumElements();
1415 else
1416 return false;
1417 if (NumElements < 2)
1418 return false;
1419
1420 // Split the block.
1421 BasicBlock *OriginalBB = LI->getParent();
1422 BasicBlock *PostSwitchBB = OriginalBB->splitBasicBlock(LI);
1423
1424 // Replace OriginalBB's terminator with a switch.
1425 IRBuilder<> Builder(OriginalBB->getTerminator());
1426 SwitchInst *Switch = Builder.CreateSwitch(TableIndex, PostSwitchBB,
1427 NumElements - 1);
1428 OriginalBB->getTerminator()->eraseFromParent();
1429
1430 // Count the frequency of each value to decide which to use as default.
1431 SmallDenseMap<Constant*, uint64_t> ValueFreq;
1432 for (uint64_t I = 0; I < NumElements; ++I)
1433 ++ValueFreq[Arr->getAggregateElement(I)];
1434 uint64_t MaxCount = 0;
1435 Constant *DefaultValue = NULL;
1436 for (SmallDenseMap<Constant*, uint64_t>::iterator I = ValueFreq.begin(),
1437 E = ValueFreq.end(); I != E; ++I) {
1438 if (I->second > MaxCount) {
1439 MaxCount = I->second;
1440 DefaultValue = I->first;
1441 }
1442 }
1443 assert(DefaultValue && "No values in the array?");
1444
1445 // Create the phi node in PostSwitchBB, which will replace the load.
1446 Builder.SetInsertPoint(PostSwitchBB->begin());
1447 PHINode *PHI = Builder.CreatePHI(LI->getType(), NumElements);
1448 PHI->addIncoming(DefaultValue, OriginalBB);
1449
1450 // Build basic blocks to target with the switch.
1451 for (uint64_t I = 0; I < NumElements; ++I) {
1452 Constant *C = Arr->getAggregateElement(I);
1453 if (C == DefaultValue) continue; // Already covered by the default case.
1454
1455 BasicBlock *BB = BasicBlock::Create(PostSwitchBB->getContext(),
1456 "lookup.bb",
1457 PostSwitchBB->getParent(),
1458 PostSwitchBB);
1459 Switch->addCase(ConstantInt::get(TableIndexTy, I), BB);
1460 Builder.SetInsertPoint(BB);
1461 Builder.CreateBr(PostSwitchBB);
1462 PHI->addIncoming(C, BB);
1463 }
1464
1465 // Remove the load.
1466 LI->replaceAllUsesWith(PHI);
1467 LI->eraseFromParent();
1468
1469 // Clean up.
1470 if (GEP->use_empty())
1471 GEP->eraseFromParent();
1472 if (GV->hasUnnamedAddr() && GV->hasPrivateLinkage() && GV->use_empty())
1473 GV->eraseFromParent();
1474
1475 CurInstIterator = Switch;
1476 return true;
1477}