blob: 0fde256943d12bdc88d05099588d385fe4641952 [file] [log] [blame]
Chris Lattnerf2836d12007-03-31 04:06:36 +00001//===- CodeGenPrepare.cpp - Prepare a function for code generation --------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-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 Lattnerf2836d12007-03-31 04:06:36 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This pass munges the code in the input function to better prepare it for
Gordon Henriksen829046b2008-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 Lattnerf2836d12007-03-31 04:06:36 +000013//
14//===----------------------------------------------------------------------===//
15
16#define DEBUG_TYPE "codegenprepare"
17#include "llvm/Transforms/Scalar.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000018#include "llvm/ADT/DenseMap.h"
19#include "llvm/ADT/SmallSet.h"
20#include "llvm/ADT/Statistic.h"
Nick Lewycky5fb19632013-05-08 09:00:10 +000021#include "llvm/ADT/ValueMap.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000022#include "llvm/Analysis/InstructionSimplify.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000023#include "llvm/IR/Constants.h"
24#include "llvm/IR/DataLayout.h"
25#include "llvm/IR/DerivedTypes.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000026#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000027#include "llvm/IR/Function.h"
28#include "llvm/IR/IRBuilder.h"
29#include "llvm/IR/InlineAsm.h"
30#include "llvm/IR/Instructions.h"
31#include "llvm/IR/IntrinsicInst.h"
Chris Lattnerf2836d12007-03-31 04:06:36 +000032#include "llvm/Pass.h"
Evan Cheng1da25002008-02-26 02:42:37 +000033#include "llvm/Support/CallSite.h"
Evan Cheng8b637b12010-08-17 01:34:49 +000034#include "llvm/Support/CommandLine.h"
Evan Chengd3d80172007-12-05 23:58:20 +000035#include "llvm/Support/Debug.h"
Chris Lattnerfeee64e2007-04-13 20:30:56 +000036#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattnerd616ef52008-11-25 04:42:10 +000037#include "llvm/Support/PatternMatch.h"
Chris Lattner1b93be52011-01-15 07:25:29 +000038#include "llvm/Support/ValueHandle.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000039#include "llvm/Support/raw_ostream.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000040#include "llvm/Target/TargetLibraryInfo.h"
41#include "llvm/Target/TargetLowering.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000042#include "llvm/Transforms/Utils/BasicBlockUtils.h"
43#include "llvm/Transforms/Utils/BuildLibCalls.h"
Preston Gurdcdf540d2012-09-04 18:22:17 +000044#include "llvm/Transforms/Utils/BypassSlowDivision.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000045#include "llvm/Transforms/Utils/Local.h"
Chris Lattnerf2836d12007-03-31 04:06:36 +000046using namespace llvm;
Chris Lattnerd616ef52008-11-25 04:42:10 +000047using namespace llvm::PatternMatch;
Chris Lattnerf2836d12007-03-31 04:06:36 +000048
Cameron Zwarichced753f2011-01-05 17:27:27 +000049STATISTIC(NumBlocksElim, "Number of blocks eliminated");
Evan Cheng0663f232011-03-21 01:19:09 +000050STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated");
51STATISTIC(NumGEPsElim, "Number of GEPs converted to casts");
Cameron Zwarichced753f2011-01-05 17:27:27 +000052STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "
53 "sunken Cmps");
54STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
55 "of sunken Casts");
56STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "
57 "computations were sunk");
Evan Cheng0663f232011-03-21 01:19:09 +000058STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads");
59STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized");
60STATISTIC(NumRetsDup, "Number of return instructions duplicated");
Devang Patel53771ba2011-08-18 00:50:51 +000061STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved");
Benjamin Kramer047d7ca2012-05-05 12:49:22 +000062STATISTIC(NumSelectsExpanded, "Number of selects turned into branches");
Jakob Stoklund Oleseneb12f492010-09-30 20:51:52 +000063
Cameron Zwarich338d3622011-03-11 21:52:04 +000064static cl::opt<bool> DisableBranchOpts(
65 "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
66 cl::desc("Disable branch optimizations in CodeGenPrepare"));
67
Benjamin Kramer3d38c172012-05-06 14:25:16 +000068static cl::opt<bool> DisableSelectToBranch(
69 "disable-cgp-select2branch", cl::Hidden, cl::init(false),
70 cl::desc("Disable select to branch conversion."));
Benjamin Kramer047d7ca2012-05-05 12:49:22 +000071
Eric Christopherc1ea1492008-09-24 05:32:41 +000072namespace {
Quentin Colombet3a4bf042014-02-06 21:44:56 +000073typedef SmallPtrSet<Instruction *, 16> SetOfInstrs;
74typedef DenseMap<Instruction *, Type *> InstrToOrigTy;
75
Chris Lattner2dd09db2009-09-02 06:11:42 +000076 class CodeGenPrepare : public FunctionPass {
Chris Lattnerf2836d12007-03-31 04:06:36 +000077 /// TLI - Keep a pointer of a TargetLowering to consult for determining
78 /// transformation profitability.
Bill Wendling7a639ea2013-06-19 21:07:11 +000079 const TargetMachine *TM;
Chris Lattnerf2836d12007-03-31 04:06:36 +000080 const TargetLowering *TLI;
Chad Rosierc24b86f2011-12-01 03:08:23 +000081 const TargetLibraryInfo *TLInfo;
Cameron Zwarich84986b22011-01-08 17:01:52 +000082 DominatorTree *DT;
Nadav Rotem465834c2012-07-24 10:51:42 +000083
Chris Lattner7a277142011-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 Cheng3b3de7c2008-12-19 18:03:11 +000088
Evan Cheng0663f232011-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.
Nick Lewycky5fb19632013-05-08 09:00:10 +000092 ValueMap<Value*, Value*> SunkAddrs;
Cameron Zwarichce3b9302011-01-06 00:42:50 +000093
Quentin Colombet3a4bf042014-02-06 21:44:56 +000094 /// Keeps track of all truncates inserted for the current function.
95 SetOfInstrs InsertedTruncsSet;
96 /// Keeps track of the type of the related instruction before their
97 /// promotion for the current function.
98 InstrToOrigTy PromotedInsts;
99
Devang Patel8f606d72011-03-24 15:35:25 +0000100 /// ModifiedDT - If CFG is modified in anyway, dominator tree may need to
Evan Cheng0663f232011-03-21 01:19:09 +0000101 /// be updated.
Devang Patel8f606d72011-03-24 15:35:25 +0000102 bool ModifiedDT;
Evan Cheng0663f232011-03-21 01:19:09 +0000103
Benjamin Kramer047d7ca2012-05-05 12:49:22 +0000104 /// OptSize - True if optimizing for size.
105 bool OptSize;
106
Chris Lattnerf2836d12007-03-31 04:06:36 +0000107 public:
Nick Lewyckye7da2d62007-05-06 13:37:16 +0000108 static char ID; // Pass identification, replacement for typeid
Bill Wendling7a639ea2013-06-19 21:07:11 +0000109 explicit CodeGenPrepare(const TargetMachine *TM = 0)
110 : FunctionPass(ID), TM(TM), TLI(0) {
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000111 initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
112 }
Chris Lattnerf2836d12007-03-31 04:06:36 +0000113 bool runOnFunction(Function &F);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000114
Evan Cheng99cafb12012-12-21 01:48:14 +0000115 const char *getPassName() const { return "CodeGen Prepare"; }
116
Andreas Neustifterf8cb7582009-09-16 09:26:52 +0000117 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruth73523022014-01-13 13:07:17 +0000118 AU.addPreserved<DominatorTreeWrapperPass>();
Chad Rosierc24b86f2011-12-01 03:08:23 +0000119 AU.addRequired<TargetLibraryInfo>();
Andreas Neustifterf8cb7582009-09-16 09:26:52 +0000120 }
121
Chris Lattnerf2836d12007-03-31 04:06:36 +0000122 private:
Nadav Rotem70409992012-08-14 05:19:07 +0000123 bool EliminateFallThrough(Function &F);
Chris Lattnerc3748562007-04-02 01:35:34 +0000124 bool EliminateMostlyEmptyBlocks(Function &F);
125 bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
126 void EliminateMostlyEmptyBlock(BasicBlock *BB);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000127 bool OptimizeBlock(BasicBlock &BB);
Cameron Zwarich14ac8652011-01-06 02:37:26 +0000128 bool OptimizeInst(Instruction *I);
Chris Lattner229907c2011-07-18 04:54:35 +0000129 bool OptimizeMemoryInst(Instruction *I, Value *Addr, Type *AccessTy);
Chris Lattner7a277142011-01-15 07:14:54 +0000130 bool OptimizeInlineAsmInst(CallInst *CS);
Eric Christopher4b7948e2010-03-11 02:41:03 +0000131 bool OptimizeCallInst(CallInst *CI);
Dan Gohman99429a02009-10-16 20:59:35 +0000132 bool MoveExtToFormExtLoad(Instruction *I);
Evan Chengd3d80172007-12-05 23:58:20 +0000133 bool OptimizeExtUses(Instruction *I);
Benjamin Kramer047d7ca2012-05-05 12:49:22 +0000134 bool OptimizeSelectInst(SelectInst *SI);
Benjamin Kramer455fa352012-11-23 19:17:06 +0000135 bool DupRetToEnableTailCallOpts(BasicBlock *BB);
Devang Patel53771ba2011-08-18 00:50:51 +0000136 bool PlaceDbgValues(Function &F);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000137 };
138}
Devang Patel09f162c2007-05-01 21:15:47 +0000139
Devang Patel8c78a0b2007-05-03 01:11:54 +0000140char CodeGenPrepare::ID = 0;
Quentin Colombetdc0b2ea2014-01-16 21:44:34 +0000141static void *initializeCodeGenPreparePassOnce(PassRegistry &Registry) {
142 initializeTargetLibraryInfoPass(Registry);
143 PassInfo *PI = new PassInfo(
144 "Optimize for code generation", "codegenprepare", &CodeGenPrepare::ID,
145 PassInfo::NormalCtor_t(callDefaultCtor<CodeGenPrepare>), false, false,
146 PassInfo::TargetMachineCtor_t(callTargetMachineCtor<CodeGenPrepare>));
147 Registry.registerPass(*PI, true);
148 return PI;
149}
150
151void llvm::initializeCodeGenPreparePass(PassRegistry &Registry) {
152 CALL_ONCE_INITIALIZATION(initializeCodeGenPreparePassOnce)
153}
Chris Lattnerf2836d12007-03-31 04:06:36 +0000154
Bill Wendling7a639ea2013-06-19 21:07:11 +0000155FunctionPass *llvm::createCodeGenPreparePass(const TargetMachine *TM) {
156 return new CodeGenPrepare(TM);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000157}
158
Chris Lattnerf2836d12007-03-31 04:06:36 +0000159bool CodeGenPrepare::runOnFunction(Function &F) {
Chris Lattnerf2836d12007-03-31 04:06:36 +0000160 bool EverMadeChange = false;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000161 // Clear per function information.
162 InsertedTruncsSet.clear();
163 PromotedInsts.clear();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000164
Devang Patel8f606d72011-03-24 15:35:25 +0000165 ModifiedDT = false;
Bill Wendling7a639ea2013-06-19 21:07:11 +0000166 if (TM) TLI = TM->getTargetLowering();
Chad Rosierc24b86f2011-12-01 03:08:23 +0000167 TLInfo = &getAnalysis<TargetLibraryInfo>();
Chandler Carruth73523022014-01-13 13:07:17 +0000168 DominatorTreeWrapperPass *DTWP =
169 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
170 DT = DTWP ? &DTWP->getDomTree() : 0;
Bill Wendling698e84f2012-12-30 10:32:01 +0000171 OptSize = F.getAttributes().hasAttribute(AttributeSet::FunctionIndex,
172 Attribute::OptimizeForSize);
Evan Cheng0663f232011-03-21 01:19:09 +0000173
Preston Gurdcdf540d2012-09-04 18:22:17 +0000174 /// This optimization identifies DIV instructions that can be
175 /// profitably bypassed and carried out with a shorter, faster divide.
Preston Gurd485296d2013-03-04 18:13:57 +0000176 if (!OptSize && TLI && TLI->isSlowDivBypassed()) {
Preston Gurd0d67f512012-10-04 21:33:40 +0000177 const DenseMap<unsigned int, unsigned int> &BypassWidths =
178 TLI->getBypassSlowDivWidths();
Evan Cheng71be12b2012-09-14 21:25:34 +0000179 for (Function::iterator I = F.begin(); I != F.end(); I++)
Preston Gurd0d67f512012-10-04 21:33:40 +0000180 EverMadeChange |= bypassSlowDivision(F, I, BypassWidths);
Preston Gurdcdf540d2012-09-04 18:22:17 +0000181 }
182
183 // Eliminate blocks that contain only PHI nodes and an
Chris Lattnerc3748562007-04-02 01:35:34 +0000184 // unconditional branch.
185 EverMadeChange |= EliminateMostlyEmptyBlocks(F);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000186
Devang Patel53771ba2011-08-18 00:50:51 +0000187 // llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotem465834c2012-07-24 10:51:42 +0000188 // handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patel53771ba2011-08-18 00:50:51 +0000189 // find a node corresponding to the value.
190 EverMadeChange |= PlaceDbgValues(F);
191
Chris Lattnerc3748562007-04-02 01:35:34 +0000192 bool MadeChange = true;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000193 while (MadeChange) {
194 MadeChange = false;
Hans Wennborg02fbc712012-09-19 07:48:16 +0000195 for (Function::iterator I = F.begin(); I != F.end(); ) {
Evan Cheng0663f232011-03-21 01:19:09 +0000196 BasicBlock *BB = I++;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000197 MadeChange |= OptimizeBlock(*BB);
Evan Cheng0663f232011-03-21 01:19:09 +0000198 }
Chris Lattnerf2836d12007-03-31 04:06:36 +0000199 EverMadeChange |= MadeChange;
200 }
Cameron Zwarichce3b9302011-01-06 00:42:50 +0000201
202 SunkAddrs.clear();
203
Cameron Zwarich338d3622011-03-11 21:52:04 +0000204 if (!DisableBranchOpts) {
205 MadeChange = false;
Bill Wendling97b93592012-03-04 10:46:01 +0000206 SmallPtrSet<BasicBlock*, 8> WorkList;
207 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
208 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
Frits van Bommelad964552011-05-22 16:24:18 +0000209 MadeChange |= ConstantFoldTerminator(BB, true);
Bill Wendling97b93592012-03-04 10:46:01 +0000210 if (!MadeChange) continue;
211
212 for (SmallVectorImpl<BasicBlock*>::iterator
213 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
214 if (pred_begin(*II) == pred_end(*II))
215 WorkList.insert(*II);
216 }
217
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000218 // Delete the dead blocks and any of their dead successors.
Bill Wendlingab417b62012-12-06 00:30:20 +0000219 MadeChange |= !WorkList.empty();
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000220 while (!WorkList.empty()) {
221 BasicBlock *BB = *WorkList.begin();
222 WorkList.erase(BB);
223 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
224
225 DeleteDeadBlock(BB);
Stephen Lin837bba12013-07-15 17:55:02 +0000226
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000227 for (SmallVectorImpl<BasicBlock*>::iterator
228 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
229 if (pred_begin(*II) == pred_end(*II))
230 WorkList.insert(*II);
231 }
Cameron Zwarich338d3622011-03-11 21:52:04 +0000232
Nadav Rotem70409992012-08-14 05:19:07 +0000233 // Merge pairs of basic blocks with unconditional branches, connected by
234 // a single edge.
235 if (EverMadeChange || MadeChange)
236 MadeChange |= EliminateFallThrough(F);
237
Evan Cheng0663f232011-03-21 01:19:09 +0000238 if (MadeChange)
Devang Patel8f606d72011-03-24 15:35:25 +0000239 ModifiedDT = true;
Cameron Zwarich338d3622011-03-11 21:52:04 +0000240 EverMadeChange |= MadeChange;
241 }
242
Devang Patel8f606d72011-03-24 15:35:25 +0000243 if (ModifiedDT && DT)
Chandler Carruth73523022014-01-13 13:07:17 +0000244 DT->recalculate(F);
Evan Cheng0663f232011-03-21 01:19:09 +0000245
Chris Lattnerf2836d12007-03-31 04:06:36 +0000246 return EverMadeChange;
247}
248
Nadav Rotem70409992012-08-14 05:19:07 +0000249/// EliminateFallThrough - Merge basic blocks which are connected
250/// by a single edge, where one of the basic blocks has a single successor
251/// pointing to the other basic block, which has a single predecessor.
252bool CodeGenPrepare::EliminateFallThrough(Function &F) {
253 bool Changed = false;
254 // Scan all of the blocks in the function, except for the entry block.
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000255 for (Function::iterator I = llvm::next(F.begin()), E = F.end(); I != E; ) {
Nadav Rotem70409992012-08-14 05:19:07 +0000256 BasicBlock *BB = I++;
257 // If the destination block has a single pred, then this is a trivial
258 // edge, just collapse it.
259 BasicBlock *SinglePred = BB->getSinglePredecessor();
260
Evan Cheng64a223a2012-09-28 23:58:57 +0000261 // Don't merge if BB's address is taken.
262 if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue;
Nadav Rotem70409992012-08-14 05:19:07 +0000263
264 BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
265 if (Term && !Term->isConditional()) {
266 Changed = true;
Michael Liao6e12d122012-08-21 05:55:22 +0000267 DEBUG(dbgs() << "To merge:\n"<< *SinglePred << "\n\n\n");
Nadav Rotem70409992012-08-14 05:19:07 +0000268 // Remember if SinglePred was the entry block of the function.
269 // If so, we will need to move BB back to the entry position.
270 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
271 MergeBasicBlockIntoOnlyPred(BB, this);
272
273 if (isEntry && BB != &BB->getParent()->getEntryBlock())
274 BB->moveBefore(&BB->getParent()->getEntryBlock());
275
276 // We have erased a block. Update the iterator.
277 I = BB;
Nadav Rotem70409992012-08-14 05:19:07 +0000278 }
279 }
280 return Changed;
281}
282
Dale Johannesen4026b042009-03-27 01:13:37 +0000283/// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes,
284/// debug info directives, and an unconditional branch. Passes before isel
285/// (e.g. LSR/loopsimplify) often split edges in ways that are non-optimal for
286/// isel. Start by eliminating these blocks so we can split them the way we
287/// want them.
Chris Lattnerc3748562007-04-02 01:35:34 +0000288bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
289 bool MadeChange = false;
290 // Note that this intentionally skips the entry block.
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000291 for (Function::iterator I = llvm::next(F.begin()), E = F.end(); I != E; ) {
Chris Lattnerc3748562007-04-02 01:35:34 +0000292 BasicBlock *BB = I++;
293
294 // If this block doesn't end with an uncond branch, ignore it.
295 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
296 if (!BI || !BI->isUnconditional())
297 continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000298
Dale Johannesen4026b042009-03-27 01:13:37 +0000299 // If the instruction before the branch (skipping debug info) isn't a phi
300 // node, then other stuff is happening here.
Chris Lattnerc3748562007-04-02 01:35:34 +0000301 BasicBlock::iterator BBI = BI;
302 if (BBI != BB->begin()) {
303 --BBI;
Dale Johannesen4026b042009-03-27 01:13:37 +0000304 while (isa<DbgInfoIntrinsic>(BBI)) {
305 if (BBI == BB->begin())
306 break;
307 --BBI;
308 }
309 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
310 continue;
Chris Lattnerc3748562007-04-02 01:35:34 +0000311 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000312
Chris Lattnerc3748562007-04-02 01:35:34 +0000313 // Do not break infinite loops.
314 BasicBlock *DestBB = BI->getSuccessor(0);
315 if (DestBB == BB)
316 continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000317
Chris Lattnerc3748562007-04-02 01:35:34 +0000318 if (!CanMergeBlocks(BB, DestBB))
319 continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000320
Chris Lattnerc3748562007-04-02 01:35:34 +0000321 EliminateMostlyEmptyBlock(BB);
322 MadeChange = true;
323 }
324 return MadeChange;
325}
326
327/// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
328/// single uncond branch between them, and BB contains no other non-phi
329/// instructions.
330bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
331 const BasicBlock *DestBB) const {
332 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
333 // the successor. If there are more complex condition (e.g. preheaders),
334 // don't mess around with them.
335 BasicBlock::const_iterator BBI = BB->begin();
336 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
Gabor Greifc78d7202010-03-25 23:06:16 +0000337 for (Value::const_use_iterator UI = PN->use_begin(), E = PN->use_end();
Chris Lattnerc3748562007-04-02 01:35:34 +0000338 UI != E; ++UI) {
339 const Instruction *User = cast<Instruction>(*UI);
340 if (User->getParent() != DestBB || !isa<PHINode>(User))
341 return false;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000342 // If User is inside DestBB block and it is a PHINode then check
343 // incoming value. If incoming value is not from BB then this is
Devang Pateld3208522007-04-25 00:37:04 +0000344 // a complex condition (e.g. preheaders) we want to avoid here.
345 if (User->getParent() == DestBB) {
346 if (const PHINode *UPN = dyn_cast<PHINode>(User))
347 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
348 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
349 if (Insn && Insn->getParent() == BB &&
350 Insn->getParent() != UPN->getIncomingBlock(I))
351 return false;
352 }
353 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000354 }
355 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000356
Chris Lattnerc3748562007-04-02 01:35:34 +0000357 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
358 // and DestBB may have conflicting incoming values for the block. If so, we
359 // can't merge the block.
360 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
361 if (!DestBBPN) return true; // no conflict.
Eric Christopherc1ea1492008-09-24 05:32:41 +0000362
Chris Lattnerc3748562007-04-02 01:35:34 +0000363 // Collect the preds of BB.
Chris Lattner8201a9b2007-11-06 22:07:40 +0000364 SmallPtrSet<const BasicBlock*, 16> BBPreds;
Chris Lattnerc3748562007-04-02 01:35:34 +0000365 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
366 // It is faster to get preds from a PHI than with pred_iterator.
367 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
368 BBPreds.insert(BBPN->getIncomingBlock(i));
369 } else {
370 BBPreds.insert(pred_begin(BB), pred_end(BB));
371 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000372
Chris Lattnerc3748562007-04-02 01:35:34 +0000373 // Walk the preds of DestBB.
374 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
375 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
376 if (BBPreds.count(Pred)) { // Common predecessor?
377 BBI = DestBB->begin();
378 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
379 const Value *V1 = PN->getIncomingValueForBlock(Pred);
380 const Value *V2 = PN->getIncomingValueForBlock(BB);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000381
Chris Lattnerc3748562007-04-02 01:35:34 +0000382 // If V2 is a phi node in BB, look up what the mapped value will be.
383 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
384 if (V2PN->getParent() == BB)
385 V2 = V2PN->getIncomingValueForBlock(Pred);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000386
Chris Lattnerc3748562007-04-02 01:35:34 +0000387 // If there is a conflict, bail out.
388 if (V1 != V2) return false;
389 }
390 }
391 }
392
393 return true;
394}
395
396
397/// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
398/// an unconditional branch in it.
399void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
400 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
401 BasicBlock *DestBB = BI->getSuccessor(0);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000402
David Greene74e2d492010-01-05 01:27:11 +0000403 DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000404
Chris Lattnerc3748562007-04-02 01:35:34 +0000405 // If the destination block has a single pred, then this is a trivial edge,
406 // just collapse it.
Chris Lattner4059f432008-11-27 19:29:14 +0000407 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
Chris Lattner8a172da2008-11-28 19:54:49 +0000408 if (SinglePred != DestBB) {
409 // Remember if SinglePred was the entry block of the function. If so, we
410 // will need to move BB back to the entry position.
411 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Andreas Neustifterf8cb7582009-09-16 09:26:52 +0000412 MergeBasicBlockIntoOnlyPred(DestBB, this);
Chris Lattner4059f432008-11-27 19:29:14 +0000413
Chris Lattner8a172da2008-11-28 19:54:49 +0000414 if (isEntry && BB != &BB->getParent()->getEntryBlock())
415 BB->moveBefore(&BB->getParent()->getEntryBlock());
Nadav Rotem465834c2012-07-24 10:51:42 +0000416
David Greene74e2d492010-01-05 01:27:11 +0000417 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattner8a172da2008-11-28 19:54:49 +0000418 return;
419 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000420 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000421
Chris Lattnerc3748562007-04-02 01:35:34 +0000422 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
423 // to handle the new incoming edges it is about to have.
424 PHINode *PN;
425 for (BasicBlock::iterator BBI = DestBB->begin();
426 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
427 // Remove the incoming value for BB, and remember it.
428 Value *InVal = PN->removeIncomingValue(BB, false);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000429
Chris Lattnerc3748562007-04-02 01:35:34 +0000430 // Two options: either the InVal is a phi node defined in BB or it is some
431 // value that dominates BB.
432 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
433 if (InValPhi && InValPhi->getParent() == BB) {
434 // Add all of the input values of the input PHI as inputs of this phi.
435 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
436 PN->addIncoming(InValPhi->getIncomingValue(i),
437 InValPhi->getIncomingBlock(i));
438 } else {
439 // Otherwise, add one instance of the dominating value for each edge that
440 // we will be adding.
441 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
442 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
443 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
444 } else {
445 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
446 PN->addIncoming(InVal, *PI);
447 }
448 }
449 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000450
Chris Lattnerc3748562007-04-02 01:35:34 +0000451 // The PHIs are now updated, change everything that refers to BB to use
452 // DestBB and remove BB.
453 BB->replaceAllUsesWith(DestBB);
Devang Patel8f606d72011-03-24 15:35:25 +0000454 if (DT && !ModifiedDT) {
Cameron Zwarich84986b22011-01-08 17:01:52 +0000455 BasicBlock *BBIDom = DT->getNode(BB)->getIDom()->getBlock();
456 BasicBlock *DestBBIDom = DT->getNode(DestBB)->getIDom()->getBlock();
457 BasicBlock *NewIDom = DT->findNearestCommonDominator(BBIDom, DestBBIDom);
458 DT->changeImmediateDominator(DestBB, NewIDom);
459 DT->eraseNode(BB);
460 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000461 BB->eraseFromParent();
Cameron Zwarichced753f2011-01-05 17:27:27 +0000462 ++NumBlocksElim;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000463
David Greene74e2d492010-01-05 01:27:11 +0000464 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerc3748562007-04-02 01:35:34 +0000465}
466
Chris Lattnerfeee64e2007-04-13 20:30:56 +0000467/// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
Dan Gohman4fe64de2009-06-14 23:30:43 +0000468/// copy (e.g. it's casting from one pointer type to another, i32->i8 on PPC),
469/// sink it into user blocks to reduce the number of virtual
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000470/// registers that must be created and coalesced.
Chris Lattnerf2836d12007-03-31 04:06:36 +0000471///
472/// Return true if any changes are made.
Chris Lattner6416a6b2008-11-24 22:44:16 +0000473///
Chris Lattnerfeee64e2007-04-13 20:30:56 +0000474static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
Eric Christopherc1ea1492008-09-24 05:32:41 +0000475 // If this is a noop copy,
Owen Anderson53aa7a92009-08-10 22:56:29 +0000476 EVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
477 EVT DstVT = TLI.getValueType(CI->getType());
Eric Christopherc1ea1492008-09-24 05:32:41 +0000478
Chris Lattnerfeee64e2007-04-13 20:30:56 +0000479 // This is an fp<->int conversion?
Duncan Sands13237ac2008-06-06 12:08:01 +0000480 if (SrcVT.isInteger() != DstVT.isInteger())
Chris Lattnerfeee64e2007-04-13 20:30:56 +0000481 return false;
Duncan Sands11dd4242008-06-08 20:54:56 +0000482
Chris Lattnerfeee64e2007-04-13 20:30:56 +0000483 // If this is an extension, it will be a zero or sign extension, which
484 // isn't a noop.
Duncan Sands11dd4242008-06-08 20:54:56 +0000485 if (SrcVT.bitsLT(DstVT)) return false;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000486
Chris Lattnerfeee64e2007-04-13 20:30:56 +0000487 // If these values will be promoted, find out what they will be promoted
488 // to. This helps us consider truncates on PPC as noop copies when they
489 // are.
Nadav Rotem707f2d72011-05-29 08:10:47 +0000490 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
491 TargetLowering::TypePromoteInteger)
Owen Anderson117c9e82009-08-12 00:36:31 +0000492 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
Nadav Rotem707f2d72011-05-29 08:10:47 +0000493 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
494 TargetLowering::TypePromoteInteger)
Owen Anderson117c9e82009-08-12 00:36:31 +0000495 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000496
Chris Lattnerfeee64e2007-04-13 20:30:56 +0000497 // If, after promotion, these are the same types, this is a noop copy.
498 if (SrcVT != DstVT)
499 return false;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000500
Chris Lattnerf2836d12007-03-31 04:06:36 +0000501 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000502
Chris Lattnerf2836d12007-03-31 04:06:36 +0000503 /// InsertedCasts - Only insert a cast in each block once.
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000504 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000505
Chris Lattnerf2836d12007-03-31 04:06:36 +0000506 bool MadeChange = false;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000507 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
Chris Lattnerf2836d12007-03-31 04:06:36 +0000508 UI != E; ) {
509 Use &TheUse = UI.getUse();
510 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000511
Chris Lattnerf2836d12007-03-31 04:06:36 +0000512 // Figure out which BB this cast is used in. For PHI's this is the
513 // appropriate predecessor block.
514 BasicBlock *UserBB = User->getParent();
515 if (PHINode *PN = dyn_cast<PHINode>(User)) {
Gabor Greifeb61fcf2009-01-23 19:40:15 +0000516 UserBB = PN->getIncomingBlock(UI);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000517 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000518
Chris Lattnerf2836d12007-03-31 04:06:36 +0000519 // Preincrement use iterator so we don't invalidate it.
520 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000521
Chris Lattnerf2836d12007-03-31 04:06:36 +0000522 // If this user is in the same block as the cast, don't change the cast.
523 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000524
Chris Lattnerf2836d12007-03-31 04:06:36 +0000525 // If we have already inserted a cast into this block, use it.
526 CastInst *&InsertedCast = InsertedCasts[UserBB];
527
528 if (!InsertedCast) {
Bill Wendling8ddfc092011-08-16 20:45:24 +0000529 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000530 InsertedCast =
531 CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
Chris Lattnerf2836d12007-03-31 04:06:36 +0000532 InsertPt);
533 MadeChange = true;
534 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000535
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000536 // Replace a use of the cast with a use of the new cast.
Chris Lattnerf2836d12007-03-31 04:06:36 +0000537 TheUse = InsertedCast;
Cameron Zwarichced753f2011-01-05 17:27:27 +0000538 ++NumCastUses;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000539 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000540
Chris Lattnerf2836d12007-03-31 04:06:36 +0000541 // If we removed all uses, nuke the cast.
Duncan Sandsafa84da42008-01-20 16:51:46 +0000542 if (CI->use_empty()) {
Chris Lattnerf2836d12007-03-31 04:06:36 +0000543 CI->eraseFromParent();
Duncan Sandsafa84da42008-01-20 16:51:46 +0000544 MadeChange = true;
545 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000546
Chris Lattnerf2836d12007-03-31 04:06:36 +0000547 return MadeChange;
548}
549
Eric Christopherc1ea1492008-09-24 05:32:41 +0000550/// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000551/// the number of virtual registers that must be created and coalesced. This is
Chris Lattner27406942007-08-02 16:53:43 +0000552/// a clear win except on targets with multiple condition code registers
553/// (PowerPC), where it might lose; some adjustment may be wanted there.
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000554///
555/// Return true if any changes are made.
Chris Lattner6416a6b2008-11-24 22:44:16 +0000556static bool OptimizeCmpExpression(CmpInst *CI) {
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000557 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000558
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000559 /// InsertedCmp - Only insert a cmp in each block once.
560 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000561
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000562 bool MadeChange = false;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000563 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000564 UI != E; ) {
565 Use &TheUse = UI.getUse();
566 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000567
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000568 // Preincrement use iterator so we don't invalidate it.
569 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000570
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000571 // Don't bother for PHI nodes.
572 if (isa<PHINode>(User))
573 continue;
574
575 // Figure out which BB this cmp is used in.
576 BasicBlock *UserBB = User->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000577
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000578 // If this user is in the same block as the cmp, don't change the cmp.
579 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000580
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000581 // If we have already inserted a cmp into this block, use it.
582 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
583
584 if (!InsertedCmp) {
Bill Wendling8ddfc092011-08-16 20:45:24 +0000585 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000586 InsertedCmp =
Dan Gohmanad1f0a12009-08-25 23:17:54 +0000587 CmpInst::Create(CI->getOpcode(),
Owen Anderson1e5f00e2009-07-09 23:48:35 +0000588 CI->getPredicate(), CI->getOperand(0),
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000589 CI->getOperand(1), "", InsertPt);
590 MadeChange = true;
591 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000592
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000593 // Replace a use of the cmp with a use of the new cmp.
594 TheUse = InsertedCmp;
Cameron Zwarichced753f2011-01-05 17:27:27 +0000595 ++NumCmpUses;
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000596 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000597
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000598 // If we removed all uses, nuke the cmp.
599 if (CI->use_empty())
600 CI->eraseFromParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000601
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000602 return MadeChange;
603}
604
Benjamin Kramer7b88a492010-03-12 09:27:41 +0000605namespace {
606class CodeGenPrepareFortifiedLibCalls : public SimplifyFortifiedLibCalls {
607protected:
608 void replaceCall(Value *With) {
609 CI->replaceAllUsesWith(With);
610 CI->eraseFromParent();
611 }
612 bool isFoldable(unsigned SizeCIOp, unsigned, bool) const {
Gabor Greif6d673952010-07-16 09:38:02 +0000613 if (ConstantInt *SizeCI =
614 dyn_cast<ConstantInt>(CI->getArgOperand(SizeCIOp)))
615 return SizeCI->isAllOnesValue();
Benjamin Kramer7b88a492010-03-12 09:27:41 +0000616 return false;
617 }
618};
619} // end anonymous namespace
620
Eric Christopher4b7948e2010-03-11 02:41:03 +0000621bool CodeGenPrepare::OptimizeCallInst(CallInst *CI) {
Chris Lattner7a277142011-01-15 07:14:54 +0000622 BasicBlock *BB = CI->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +0000623
Chris Lattner7a277142011-01-15 07:14:54 +0000624 // Lower inline assembly if we can.
625 // If we found an inline asm expession, and if the target knows how to
626 // lower it to normal LLVM code, do so now.
627 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
628 if (TLI->ExpandInlineAsm(CI)) {
629 // Avoid invalidating the iterator.
630 CurInstIterator = BB->begin();
631 // Avoid processing instructions out of order, which could cause
632 // reuse before a value is defined.
633 SunkAddrs.clear();
634 return true;
635 }
636 // Sink address computing for memory operands into the block.
637 if (OptimizeInlineAsmInst(CI))
638 return true;
639 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000640
Eric Christopher4b7948e2010-03-11 02:41:03 +0000641 // Lower all uses of llvm.objectsize.*
642 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
643 if (II && II->getIntrinsicID() == Intrinsic::objectsize) {
Gabor Greif4a39b842010-06-24 00:44:01 +0000644 bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
Chris Lattner229907c2011-07-18 04:54:35 +0000645 Type *ReturnTy = CI->getType();
Nadav Rotem465834c2012-07-24 10:51:42 +0000646 Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
647
Chris Lattner1b93be52011-01-15 07:25:29 +0000648 // Substituting this can cause recursive simplifications, which can
649 // invalidate our iterator. Use a WeakVH to hold onto it in case this
650 // happens.
651 WeakVH IterHandle(CurInstIterator);
Nadav Rotem465834c2012-07-24 10:51:42 +0000652
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000653 replaceAndRecursivelySimplify(CI, RetVal, TLI ? TLI->getDataLayout() : 0,
Chandler Carruthcf1b5852012-03-24 21:11:24 +0000654 TLInfo, ModifiedDT ? 0 : DT);
Chris Lattner1b93be52011-01-15 07:25:29 +0000655
656 // If the iterator instruction was recursively deleted, start over at the
657 // start of the block.
Chris Lattner86d56c62011-01-18 20:53:04 +0000658 if (IterHandle != CurInstIterator) {
Chris Lattner1b93be52011-01-15 07:25:29 +0000659 CurInstIterator = BB->begin();
Chris Lattner86d56c62011-01-18 20:53:04 +0000660 SunkAddrs.clear();
661 }
Eric Christopher4b7948e2010-03-11 02:41:03 +0000662 return true;
663 }
664
Pete Cooper615fd892012-03-13 20:59:56 +0000665 if (II && TLI) {
666 SmallVector<Value*, 2> PtrOps;
667 Type *AccessTy;
668 if (TLI->GetAddrModeArguments(II, PtrOps, AccessTy))
669 while (!PtrOps.empty())
670 if (OptimizeMemoryInst(II, PtrOps.pop_back_val(), AccessTy))
671 return true;
672 }
673
Eric Christopher4b7948e2010-03-11 02:41:03 +0000674 // From here on out we're working with named functions.
675 if (CI->getCalledFunction() == 0) return false;
Devang Patel0da52502011-05-26 21:51:06 +0000676
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000677 // We'll need DataLayout from here on out.
678 const DataLayout *TD = TLI ? TLI->getDataLayout() : 0;
Eric Christopher4b7948e2010-03-11 02:41:03 +0000679 if (!TD) return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000680
Benjamin Kramer7b88a492010-03-12 09:27:41 +0000681 // Lower all default uses of _chk calls. This is very similar
682 // to what InstCombineCalls does, but here we are only lowering calls
Eric Christopher4b7948e2010-03-11 02:41:03 +0000683 // that have the default "don't know" as the objectsize. Anything else
684 // should be left alone.
Benjamin Kramer7b88a492010-03-12 09:27:41 +0000685 CodeGenPrepareFortifiedLibCalls Simplifier;
Nuno Lopes89702e92012-07-25 16:46:31 +0000686 return Simplifier.fold(CI, TD, TLInfo);
Eric Christopher4b7948e2010-03-11 02:41:03 +0000687}
Chris Lattner1b93be52011-01-15 07:25:29 +0000688
Evan Cheng0663f232011-03-21 01:19:09 +0000689/// DupRetToEnableTailCallOpts - Look for opportunities to duplicate return
690/// instructions to the predecessor to enable tail call optimizations. The
691/// case it is currently looking for is:
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +0000692/// @code
Evan Cheng0663f232011-03-21 01:19:09 +0000693/// bb0:
694/// %tmp0 = tail call i32 @f0()
695/// br label %return
696/// bb1:
697/// %tmp1 = tail call i32 @f1()
698/// br label %return
699/// bb2:
700/// %tmp2 = tail call i32 @f2()
701/// br label %return
702/// return:
703/// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
704/// ret i32 %retval
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +0000705/// @endcode
Evan Cheng0663f232011-03-21 01:19:09 +0000706///
707/// =>
708///
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +0000709/// @code
Evan Cheng0663f232011-03-21 01:19:09 +0000710/// bb0:
711/// %tmp0 = tail call i32 @f0()
712/// ret i32 %tmp0
713/// bb1:
714/// %tmp1 = tail call i32 @f1()
715/// ret i32 %tmp1
716/// bb2:
717/// %tmp2 = tail call i32 @f2()
718/// ret i32 %tmp2
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +0000719/// @endcode
Benjamin Kramer455fa352012-11-23 19:17:06 +0000720bool CodeGenPrepare::DupRetToEnableTailCallOpts(BasicBlock *BB) {
Cameron Zwarich47e71752011-03-24 04:51:51 +0000721 if (!TLI)
722 return false;
723
Benjamin Kramer455fa352012-11-23 19:17:06 +0000724 ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
725 if (!RI)
726 return false;
727
Evan Cheng249716e2012-07-27 21:21:26 +0000728 PHINode *PN = 0;
729 BitCastInst *BCI = 0;
Evan Cheng0663f232011-03-21 01:19:09 +0000730 Value *V = RI->getReturnValue();
Evan Cheng249716e2012-07-27 21:21:26 +0000731 if (V) {
732 BCI = dyn_cast<BitCastInst>(V);
733 if (BCI)
734 V = BCI->getOperand(0);
735
736 PN = dyn_cast<PHINode>(V);
737 if (!PN)
738 return false;
739 }
Evan Cheng0663f232011-03-21 01:19:09 +0000740
Cameron Zwarich4649f172011-03-24 04:52:10 +0000741 if (PN && PN->getParent() != BB)
Cameron Zwarich0e331c02011-03-24 04:52:07 +0000742 return false;
Evan Cheng0663f232011-03-21 01:19:09 +0000743
Cameron Zwarich0e331c02011-03-24 04:52:07 +0000744 // It's not safe to eliminate the sign / zero extension of the return value.
745 // See llvm::isInTailCallPosition().
746 const Function *F = BB->getParent();
Bill Wendling658d24d2013-01-18 21:53:16 +0000747 AttributeSet CallerAttrs = F->getAttributes();
748 if (CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::ZExt) ||
749 CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::SExt))
Cameron Zwarich0e331c02011-03-24 04:52:07 +0000750 return false;
Evan Cheng0663f232011-03-21 01:19:09 +0000751
Cameron Zwarich4649f172011-03-24 04:52:10 +0000752 // Make sure there are no instructions between the PHI and return, or that the
753 // return is the first instruction in the block.
754 if (PN) {
755 BasicBlock::iterator BI = BB->begin();
756 do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
Evan Cheng249716e2012-07-27 21:21:26 +0000757 if (&*BI == BCI)
758 // Also skip over the bitcast.
759 ++BI;
Cameron Zwarich4649f172011-03-24 04:52:10 +0000760 if (&*BI != RI)
761 return false;
762 } else {
Cameron Zwarich74157ab2011-03-24 16:34:59 +0000763 BasicBlock::iterator BI = BB->begin();
764 while (isa<DbgInfoIntrinsic>(BI)) ++BI;
765 if (&*BI != RI)
Cameron Zwarich4649f172011-03-24 04:52:10 +0000766 return false;
767 }
Evan Cheng0663f232011-03-21 01:19:09 +0000768
Cameron Zwarich0e331c02011-03-24 04:52:07 +0000769 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
770 /// call.
771 SmallVector<CallInst*, 4> TailCalls;
Cameron Zwarich4649f172011-03-24 04:52:10 +0000772 if (PN) {
773 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
774 CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
775 // Make sure the phi value is indeed produced by the tail call.
776 if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
777 TLI->mayBeEmittedAsTailCall(CI))
778 TailCalls.push_back(CI);
779 }
780 } else {
781 SmallPtrSet<BasicBlock*, 4> VisitedBBs;
782 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
783 if (!VisitedBBs.insert(*PI))
784 continue;
785
786 BasicBlock::InstListType &InstList = (*PI)->getInstList();
787 BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
788 BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
Cameron Zwarich74157ab2011-03-24 16:34:59 +0000789 do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
790 if (RI == RE)
Cameron Zwarich4649f172011-03-24 04:52:10 +0000791 continue;
Cameron Zwarich74157ab2011-03-24 16:34:59 +0000792
Cameron Zwarich4649f172011-03-24 04:52:10 +0000793 CallInst *CI = dyn_cast<CallInst>(&*RI);
Cameron Zwarich2edfe772011-03-24 15:54:11 +0000794 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI))
Cameron Zwarich4649f172011-03-24 04:52:10 +0000795 TailCalls.push_back(CI);
796 }
Evan Cheng0663f232011-03-21 01:19:09 +0000797 }
798
Cameron Zwarich0e331c02011-03-24 04:52:07 +0000799 bool Changed = false;
800 for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
801 CallInst *CI = TailCalls[i];
802 CallSite CS(CI);
803
804 // Conservatively require the attributes of the call to match those of the
805 // return. Ignore noalias because it doesn't affect the call sequence.
Bill Wendling658d24d2013-01-18 21:53:16 +0000806 AttributeSet CalleeAttrs = CS.getAttributes();
807 if (AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
Bill Wendling3d7b0b82012-12-19 07:18:57 +0000808 removeAttribute(Attribute::NoAlias) !=
Bill Wendling658d24d2013-01-18 21:53:16 +0000809 AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
Bill Wendling3d7b0b82012-12-19 07:18:57 +0000810 removeAttribute(Attribute::NoAlias))
Cameron Zwarich0e331c02011-03-24 04:52:07 +0000811 continue;
812
813 // Make sure the call instruction is followed by an unconditional branch to
814 // the return block.
815 BasicBlock *CallBB = CI->getParent();
816 BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
817 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
818 continue;
819
820 // Duplicate the return into CallBB.
821 (void)FoldReturnIntoUncondBranch(RI, BB, CallBB);
Devang Patel8f606d72011-03-24 15:35:25 +0000822 ModifiedDT = Changed = true;
Cameron Zwarich0e331c02011-03-24 04:52:07 +0000823 ++NumRetsDup;
824 }
825
826 // If we eliminated all predecessors of the block, delete the block now.
Evan Cheng64a223a2012-09-28 23:58:57 +0000827 if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
Cameron Zwarich0e331c02011-03-24 04:52:07 +0000828 BB->eraseFromParent();
829
830 return Changed;
Evan Cheng0663f232011-03-21 01:19:09 +0000831}
832
Chris Lattner728f9022008-11-25 07:09:13 +0000833//===----------------------------------------------------------------------===//
Chris Lattner728f9022008-11-25 07:09:13 +0000834// Memory Optimization
835//===----------------------------------------------------------------------===//
836
Chandler Carruthc8925912013-01-05 02:09:22 +0000837namespace {
838
839/// ExtAddrMode - This is an extended version of TargetLowering::AddrMode
840/// which holds actual Value*'s for register values.
Chandler Carruth95f83e02013-01-07 15:14:13 +0000841struct ExtAddrMode : public TargetLowering::AddrMode {
Chandler Carruthc8925912013-01-05 02:09:22 +0000842 Value *BaseReg;
843 Value *ScaledReg;
844 ExtAddrMode() : BaseReg(0), ScaledReg(0) {}
845 void print(raw_ostream &OS) const;
846 void dump() const;
Stephen Lin837bba12013-07-15 17:55:02 +0000847
Chandler Carruthc8925912013-01-05 02:09:22 +0000848 bool operator==(const ExtAddrMode& O) const {
849 return (BaseReg == O.BaseReg) && (ScaledReg == O.ScaledReg) &&
850 (BaseGV == O.BaseGV) && (BaseOffs == O.BaseOffs) &&
851 (HasBaseReg == O.HasBaseReg) && (Scale == O.Scale);
852 }
853};
854
Eli Friedmanc1f1f852013-09-10 23:09:24 +0000855#ifndef NDEBUG
856static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
857 AM.print(OS);
858 return OS;
859}
860#endif
861
Chandler Carruthc8925912013-01-05 02:09:22 +0000862void ExtAddrMode::print(raw_ostream &OS) const {
863 bool NeedPlus = false;
864 OS << "[";
865 if (BaseGV) {
866 OS << (NeedPlus ? " + " : "")
867 << "GV:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +0000868 BaseGV->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +0000869 NeedPlus = true;
870 }
871
872 if (BaseOffs)
873 OS << (NeedPlus ? " + " : "") << BaseOffs, NeedPlus = true;
874
875 if (BaseReg) {
876 OS << (NeedPlus ? " + " : "")
877 << "Base:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +0000878 BaseReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +0000879 NeedPlus = true;
880 }
881 if (Scale) {
882 OS << (NeedPlus ? " + " : "")
883 << Scale << "*";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +0000884 ScaledReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +0000885 }
886
887 OS << ']';
888}
889
890#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
891void ExtAddrMode::dump() const {
892 print(dbgs());
893 dbgs() << '\n';
894}
895#endif
896
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000897/// \brief This class provides transaction based operation on the IR.
898/// Every change made through this class is recorded in the internal state and
899/// can be undone (rollback) until commit is called.
900class TypePromotionTransaction {
901
902 /// \brief This represents the common interface of the individual transaction.
903 /// Each class implements the logic for doing one specific modification on
904 /// the IR via the TypePromotionTransaction.
905 class TypePromotionAction {
906 protected:
907 /// The Instruction modified.
908 Instruction *Inst;
909
910 public:
911 /// \brief Constructor of the action.
912 /// The constructor performs the related action on the IR.
913 TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
914
915 virtual ~TypePromotionAction() {}
916
917 /// \brief Undo the modification done by this action.
918 /// When this method is called, the IR must be in the same state as it was
919 /// before this action was applied.
920 /// \pre Undoing the action works if and only if the IR is in the exact same
921 /// state as it was directly after this action was applied.
922 virtual void undo() = 0;
923
924 /// \brief Advocate every change made by this action.
925 /// When the results on the IR of the action are to be kept, it is important
926 /// to call this function, otherwise hidden information may be kept forever.
927 virtual void commit() {
928 // Nothing to be done, this action is not doing anything.
929 }
930 };
931
932 /// \brief Utility to remember the position of an instruction.
933 class InsertionHandler {
934 /// Position of an instruction.
935 /// Either an instruction:
936 /// - Is the first in a basic block: BB is used.
937 /// - Has a previous instructon: PrevInst is used.
938 union {
939 Instruction *PrevInst;
940 BasicBlock *BB;
941 } Point;
942 /// Remember whether or not the instruction had a previous instruction.
943 bool HasPrevInstruction;
944
945 public:
946 /// \brief Record the position of \p Inst.
947 InsertionHandler(Instruction *Inst) {
948 BasicBlock::iterator It = Inst;
949 HasPrevInstruction = (It != (Inst->getParent()->begin()));
950 if (HasPrevInstruction)
951 Point.PrevInst = --It;
952 else
953 Point.BB = Inst->getParent();
954 }
955
956 /// \brief Insert \p Inst at the recorded position.
957 void insert(Instruction *Inst) {
958 if (HasPrevInstruction) {
959 if (Inst->getParent())
960 Inst->removeFromParent();
961 Inst->insertAfter(Point.PrevInst);
962 } else {
963 Instruction *Position = Point.BB->getFirstInsertionPt();
964 if (Inst->getParent())
965 Inst->moveBefore(Position);
966 else
967 Inst->insertBefore(Position);
968 }
969 }
970 };
971
972 /// \brief Move an instruction before another.
973 class InstructionMoveBefore : public TypePromotionAction {
974 /// Original position of the instruction.
975 InsertionHandler Position;
976
977 public:
978 /// \brief Move \p Inst before \p Before.
979 InstructionMoveBefore(Instruction *Inst, Instruction *Before)
980 : TypePromotionAction(Inst), Position(Inst) {
981 DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before << "\n");
982 Inst->moveBefore(Before);
983 }
984
985 /// \brief Move the instruction back to its original position.
986 void undo() {
987 DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n");
988 Position.insert(Inst);
989 }
990 };
991
992 /// \brief Set the operand of an instruction with a new value.
993 class OperandSetter : public TypePromotionAction {
994 /// Original operand of the instruction.
995 Value *Origin;
996 /// Index of the modified instruction.
997 unsigned Idx;
998
999 public:
1000 /// \brief Set \p Idx operand of \p Inst with \p NewVal.
1001 OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
1002 : TypePromotionAction(Inst), Idx(Idx) {
1003 DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"
1004 << "for:" << *Inst << "\n"
1005 << "with:" << *NewVal << "\n");
1006 Origin = Inst->getOperand(Idx);
1007 Inst->setOperand(Idx, NewVal);
1008 }
1009
1010 /// \brief Restore the original value of the instruction.
1011 void undo() {
1012 DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"
1013 << "for: " << *Inst << "\n"
1014 << "with: " << *Origin << "\n");
1015 Inst->setOperand(Idx, Origin);
1016 }
1017 };
1018
1019 /// \brief Hide the operands of an instruction.
1020 /// Do as if this instruction was not using any of its operands.
1021 class OperandsHider : public TypePromotionAction {
1022 /// The list of original operands.
1023 SmallVector<Value *, 4> OriginalValues;
1024
1025 public:
1026 /// \brief Remove \p Inst from the uses of the operands of \p Inst.
1027 OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
1028 DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n");
1029 unsigned NumOpnds = Inst->getNumOperands();
1030 OriginalValues.reserve(NumOpnds);
1031 for (unsigned It = 0; It < NumOpnds; ++It) {
1032 // Save the current operand.
1033 Value *Val = Inst->getOperand(It);
1034 OriginalValues.push_back(Val);
1035 // Set a dummy one.
1036 // We could use OperandSetter here, but that would implied an overhead
1037 // that we are not willing to pay.
1038 Inst->setOperand(It, UndefValue::get(Val->getType()));
1039 }
1040 }
1041
1042 /// \brief Restore the original list of uses.
1043 void undo() {
1044 DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n");
1045 for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
1046 Inst->setOperand(It, OriginalValues[It]);
1047 }
1048 };
1049
1050 /// \brief Build a truncate instruction.
1051 class TruncBuilder : public TypePromotionAction {
1052 public:
1053 /// \brief Build a truncate instruction of \p Opnd producing a \p Ty
1054 /// result.
1055 /// trunc Opnd to Ty.
1056 TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
1057 IRBuilder<> Builder(Opnd);
1058 Inst = cast<Instruction>(Builder.CreateTrunc(Opnd, Ty, "promoted"));
1059 DEBUG(dbgs() << "Do: TruncBuilder: " << *Inst << "\n");
1060 }
1061
1062 /// \brief Get the built instruction.
1063 Instruction *getBuiltInstruction() { return Inst; }
1064
1065 /// \brief Remove the built instruction.
1066 void undo() {
1067 DEBUG(dbgs() << "Undo: TruncBuilder: " << *Inst << "\n");
1068 Inst->eraseFromParent();
1069 }
1070 };
1071
1072 /// \brief Build a sign extension instruction.
1073 class SExtBuilder : public TypePromotionAction {
1074 public:
1075 /// \brief Build a sign extension instruction of \p Opnd producing a \p Ty
1076 /// result.
1077 /// sext Opnd to Ty.
1078 SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
1079 : TypePromotionAction(Inst) {
1080 IRBuilder<> Builder(InsertPt);
1081 Inst = cast<Instruction>(Builder.CreateSExt(Opnd, Ty, "promoted"));
1082 DEBUG(dbgs() << "Do: SExtBuilder: " << *Inst << "\n");
1083 }
1084
1085 /// \brief Get the built instruction.
1086 Instruction *getBuiltInstruction() { return Inst; }
1087
1088 /// \brief Remove the built instruction.
1089 void undo() {
1090 DEBUG(dbgs() << "Undo: SExtBuilder: " << *Inst << "\n");
1091 Inst->eraseFromParent();
1092 }
1093 };
1094
1095 /// \brief Mutate an instruction to another type.
1096 class TypeMutator : public TypePromotionAction {
1097 /// Record the original type.
1098 Type *OrigTy;
1099
1100 public:
1101 /// \brief Mutate the type of \p Inst into \p NewTy.
1102 TypeMutator(Instruction *Inst, Type *NewTy)
1103 : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
1104 DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy
1105 << "\n");
1106 Inst->mutateType(NewTy);
1107 }
1108
1109 /// \brief Mutate the instruction back to its original type.
1110 void undo() {
1111 DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy
1112 << "\n");
1113 Inst->mutateType(OrigTy);
1114 }
1115 };
1116
1117 /// \brief Replace the uses of an instruction by another instruction.
1118 class UsesReplacer : public TypePromotionAction {
1119 /// Helper structure to keep track of the replaced uses.
1120 struct InstructionAndIdx {
1121 /// The instruction using the instruction.
1122 Instruction *Inst;
1123 /// The index where this instruction is used for Inst.
1124 unsigned Idx;
1125 InstructionAndIdx(Instruction *Inst, unsigned Idx)
1126 : Inst(Inst), Idx(Idx) {}
1127 };
1128
1129 /// Keep track of the original uses (pair Instruction, Index).
1130 SmallVector<InstructionAndIdx, 4> OriginalUses;
1131 typedef SmallVectorImpl<InstructionAndIdx>::iterator use_iterator;
1132
1133 public:
1134 /// \brief Replace all the use of \p Inst by \p New.
1135 UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) {
1136 DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New
1137 << "\n");
1138 // Record the original uses.
1139 for (Value::use_iterator UseIt = Inst->use_begin(),
1140 EndIt = Inst->use_end();
1141 UseIt != EndIt; ++UseIt) {
1142 Instruction *Use = cast<Instruction>(*UseIt);
1143 OriginalUses.push_back(InstructionAndIdx(Use, UseIt.getOperandNo()));
1144 }
1145 // Now, we can replace the uses.
1146 Inst->replaceAllUsesWith(New);
1147 }
1148
1149 /// \brief Reassign the original uses of Inst to Inst.
1150 void undo() {
1151 DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n");
1152 for (use_iterator UseIt = OriginalUses.begin(),
1153 EndIt = OriginalUses.end();
1154 UseIt != EndIt; ++UseIt) {
1155 UseIt->Inst->setOperand(UseIt->Idx, Inst);
1156 }
1157 }
1158 };
1159
1160 /// \brief Remove an instruction from the IR.
1161 class InstructionRemover : public TypePromotionAction {
1162 /// Original position of the instruction.
1163 InsertionHandler Inserter;
1164 /// Helper structure to hide all the link to the instruction. In other
1165 /// words, this helps to do as if the instruction was removed.
1166 OperandsHider Hider;
1167 /// Keep track of the uses replaced, if any.
1168 UsesReplacer *Replacer;
1169
1170 public:
1171 /// \brief Remove all reference of \p Inst and optinally replace all its
1172 /// uses with New.
1173 /// \pre If !Inst->use_empty(), then New != NULL
1174 InstructionRemover(Instruction *Inst, Value *New = NULL)
1175 : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
1176 Replacer(NULL) {
1177 if (New)
1178 Replacer = new UsesReplacer(Inst, New);
1179 DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n");
1180 Inst->removeFromParent();
1181 }
1182
1183 ~InstructionRemover() { delete Replacer; }
1184
1185 /// \brief Really remove the instruction.
1186 void commit() { delete Inst; }
1187
1188 /// \brief Resurrect the instruction and reassign it to the proper uses if
1189 /// new value was provided when build this action.
1190 void undo() {
1191 DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n");
1192 Inserter.insert(Inst);
1193 if (Replacer)
1194 Replacer->undo();
1195 Hider.undo();
1196 }
1197 };
1198
1199public:
1200 /// Restoration point.
1201 /// The restoration point is a pointer to an action instead of an iterator
1202 /// because the iterator may be invalidated but not the pointer.
1203 typedef const TypePromotionAction *ConstRestorationPt;
1204 /// Advocate every changes made in that transaction.
1205 void commit();
1206 /// Undo all the changes made after the given point.
1207 void rollback(ConstRestorationPt Point);
1208 /// Get the current restoration point.
1209 ConstRestorationPt getRestorationPoint() const;
1210
1211 /// \name API for IR modification with state keeping to support rollback.
1212 /// @{
1213 /// Same as Instruction::setOperand.
1214 void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
1215 /// Same as Instruction::eraseFromParent.
1216 void eraseInstruction(Instruction *Inst, Value *NewVal = NULL);
1217 /// Same as Value::replaceAllUsesWith.
1218 void replaceAllUsesWith(Instruction *Inst, Value *New);
1219 /// Same as Value::mutateType.
1220 void mutateType(Instruction *Inst, Type *NewTy);
1221 /// Same as IRBuilder::createTrunc.
1222 Instruction *createTrunc(Instruction *Opnd, Type *Ty);
1223 /// Same as IRBuilder::createSExt.
1224 Instruction *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
1225 /// Same as Instruction::moveBefore.
1226 void moveBefore(Instruction *Inst, Instruction *Before);
1227 /// @}
1228
1229 ~TypePromotionTransaction();
1230
1231private:
1232 /// The ordered list of actions made so far.
1233 SmallVector<TypePromotionAction *, 16> Actions;
1234 typedef SmallVectorImpl<TypePromotionAction *>::iterator CommitPt;
1235};
1236
1237void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
1238 Value *NewVal) {
1239 Actions.push_back(
1240 new TypePromotionTransaction::OperandSetter(Inst, Idx, NewVal));
1241}
1242
1243void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
1244 Value *NewVal) {
1245 Actions.push_back(
1246 new TypePromotionTransaction::InstructionRemover(Inst, NewVal));
1247}
1248
1249void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
1250 Value *New) {
1251 Actions.push_back(new TypePromotionTransaction::UsesReplacer(Inst, New));
1252}
1253
1254void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
1255 Actions.push_back(new TypePromotionTransaction::TypeMutator(Inst, NewTy));
1256}
1257
1258Instruction *TypePromotionTransaction::createTrunc(Instruction *Opnd,
1259 Type *Ty) {
1260 TruncBuilder *TB = new TruncBuilder(Opnd, Ty);
1261 Actions.push_back(TB);
1262 return TB->getBuiltInstruction();
1263}
1264
1265Instruction *TypePromotionTransaction::createSExt(Instruction *Inst,
1266 Value *Opnd, Type *Ty) {
1267 SExtBuilder *SB = new SExtBuilder(Inst, Opnd, Ty);
1268 Actions.push_back(SB);
1269 return SB->getBuiltInstruction();
1270}
1271
1272void TypePromotionTransaction::moveBefore(Instruction *Inst,
1273 Instruction *Before) {
1274 Actions.push_back(
1275 new TypePromotionTransaction::InstructionMoveBefore(Inst, Before));
1276}
1277
1278TypePromotionTransaction::ConstRestorationPt
1279TypePromotionTransaction::getRestorationPoint() const {
1280 return Actions.rbegin() != Actions.rend() ? *Actions.rbegin() : NULL;
1281}
1282
1283void TypePromotionTransaction::commit() {
1284 for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt;
1285 ++It) {
1286 (*It)->commit();
1287 delete *It;
1288 }
1289 Actions.clear();
1290}
1291
1292void TypePromotionTransaction::rollback(
1293 TypePromotionTransaction::ConstRestorationPt Point) {
1294 while (!Actions.empty() && Point != (*Actions.rbegin())) {
1295 TypePromotionAction *Curr = Actions.pop_back_val();
1296 Curr->undo();
1297 delete Curr;
1298 }
1299}
1300
1301TypePromotionTransaction::~TypePromotionTransaction() {
1302 for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt; ++It)
1303 delete *It;
1304 Actions.clear();
1305}
Chandler Carruthc8925912013-01-05 02:09:22 +00001306
1307/// \brief A helper class for matching addressing modes.
1308///
1309/// This encapsulates the logic for matching the target-legal addressing modes.
1310class AddressingModeMatcher {
1311 SmallVectorImpl<Instruction*> &AddrModeInsts;
1312 const TargetLowering &TLI;
1313
1314 /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
1315 /// the memory instruction that we're computing this address for.
1316 Type *AccessTy;
1317 Instruction *MemoryInst;
Stephen Lin837bba12013-07-15 17:55:02 +00001318
Chandler Carruthc8925912013-01-05 02:09:22 +00001319 /// AddrMode - This is the addressing mode that we're building up. This is
1320 /// part of the return value of this addressing mode matching stuff.
1321 ExtAddrMode &AddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00001322
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001323 /// The truncate instruction inserted by other CodeGenPrepare optimizations.
1324 const SetOfInstrs &InsertedTruncs;
1325 /// A map from the instructions to their type before promotion.
1326 InstrToOrigTy &PromotedInsts;
1327 /// The ongoing transaction where every action should be registered.
1328 TypePromotionTransaction &TPT;
1329
Chandler Carruthc8925912013-01-05 02:09:22 +00001330 /// IgnoreProfitability - This is set to true when we should not do
1331 /// profitability checks. When true, IsProfitableToFoldIntoAddressingMode
1332 /// always returns true.
1333 bool IgnoreProfitability;
Stephen Lin837bba12013-07-15 17:55:02 +00001334
Chandler Carruthc8925912013-01-05 02:09:22 +00001335 AddressingModeMatcher(SmallVectorImpl<Instruction*> &AMI,
1336 const TargetLowering &T, Type *AT,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001337 Instruction *MI, ExtAddrMode &AM,
1338 const SetOfInstrs &InsertedTruncs,
1339 InstrToOrigTy &PromotedInsts,
1340 TypePromotionTransaction &TPT)
1341 : AddrModeInsts(AMI), TLI(T), AccessTy(AT), MemoryInst(MI), AddrMode(AM),
1342 InsertedTruncs(InsertedTruncs), PromotedInsts(PromotedInsts), TPT(TPT) {
Chandler Carruthc8925912013-01-05 02:09:22 +00001343 IgnoreProfitability = false;
1344 }
1345public:
Stephen Lin837bba12013-07-15 17:55:02 +00001346
Chandler Carruthc8925912013-01-05 02:09:22 +00001347 /// Match - Find the maximal addressing mode that a load/store of V can fold,
1348 /// give an access type of AccessTy. This returns a list of involved
1349 /// instructions in AddrModeInsts.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001350 /// \p InsertedTruncs The truncate instruction inserted by other
1351 /// CodeGenPrepare
1352 /// optimizations.
1353 /// \p PromotedInsts maps the instructions to their type before promotion.
1354 /// \p The ongoing transaction where every action should be registered.
Chandler Carruthc8925912013-01-05 02:09:22 +00001355 static ExtAddrMode Match(Value *V, Type *AccessTy,
1356 Instruction *MemoryInst,
1357 SmallVectorImpl<Instruction*> &AddrModeInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001358 const TargetLowering &TLI,
1359 const SetOfInstrs &InsertedTruncs,
1360 InstrToOrigTy &PromotedInsts,
1361 TypePromotionTransaction &TPT) {
Chandler Carruthc8925912013-01-05 02:09:22 +00001362 ExtAddrMode Result;
1363
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001364 bool Success = AddressingModeMatcher(AddrModeInsts, TLI, AccessTy,
1365 MemoryInst, Result, InsertedTruncs,
1366 PromotedInsts, TPT).MatchAddr(V, 0);
Chandler Carruthc8925912013-01-05 02:09:22 +00001367 (void)Success; assert(Success && "Couldn't select *anything*?");
1368 return Result;
1369 }
1370private:
1371 bool MatchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
1372 bool MatchAddr(Value *V, unsigned Depth);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001373 bool MatchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth,
1374 bool *MovedAway = NULL);
Chandler Carruthc8925912013-01-05 02:09:22 +00001375 bool IsProfitableToFoldIntoAddressingMode(Instruction *I,
1376 ExtAddrMode &AMBefore,
1377 ExtAddrMode &AMAfter);
1378 bool ValueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
Quentin Colombet867c5502014-02-14 22:23:22 +00001379 bool IsPromotionProfitable(unsigned MatchedSize, unsigned SizeWithPromotion,
1380 Value *PromotedOperand) const;
Chandler Carruthc8925912013-01-05 02:09:22 +00001381};
1382
1383/// MatchScaledValue - Try adding ScaleReg*Scale to the current addressing mode.
1384/// Return true and update AddrMode if this addr mode is legal for the target,
1385/// false if not.
1386bool AddressingModeMatcher::MatchScaledValue(Value *ScaleReg, int64_t Scale,
1387 unsigned Depth) {
1388 // If Scale is 1, then this is the same as adding ScaleReg to the addressing
1389 // mode. Just process that directly.
1390 if (Scale == 1)
1391 return MatchAddr(ScaleReg, Depth);
Stephen Lin837bba12013-07-15 17:55:02 +00001392
Chandler Carruthc8925912013-01-05 02:09:22 +00001393 // If the scale is 0, it takes nothing to add this.
1394 if (Scale == 0)
1395 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00001396
Chandler Carruthc8925912013-01-05 02:09:22 +00001397 // If we already have a scale of this value, we can add to it, otherwise, we
1398 // need an available scale field.
1399 if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
1400 return false;
1401
1402 ExtAddrMode TestAddrMode = AddrMode;
1403
1404 // Add scale to turn X*4+X*3 -> X*7. This could also do things like
1405 // [A+B + A*7] -> [B+A*8].
1406 TestAddrMode.Scale += Scale;
1407 TestAddrMode.ScaledReg = ScaleReg;
1408
1409 // If the new address isn't legal, bail out.
1410 if (!TLI.isLegalAddressingMode(TestAddrMode, AccessTy))
1411 return false;
1412
1413 // It was legal, so commit it.
1414 AddrMode = TestAddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00001415
Chandler Carruthc8925912013-01-05 02:09:22 +00001416 // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
1417 // to see if ScaleReg is actually X+C. If so, we can turn this into adding
1418 // X*Scale + C*Scale to addr mode.
1419 ConstantInt *CI = 0; Value *AddLHS = 0;
1420 if (isa<Instruction>(ScaleReg) && // not a constant expr.
1421 match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
1422 TestAddrMode.ScaledReg = AddLHS;
1423 TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00001424
Chandler Carruthc8925912013-01-05 02:09:22 +00001425 // If this addressing mode is legal, commit it and remember that we folded
1426 // this instruction.
1427 if (TLI.isLegalAddressingMode(TestAddrMode, AccessTy)) {
1428 AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
1429 AddrMode = TestAddrMode;
1430 return true;
1431 }
1432 }
1433
1434 // Otherwise, not (x+c)*scale, just return what we have.
1435 return true;
1436}
1437
1438/// MightBeFoldableInst - This is a little filter, which returns true if an
1439/// addressing computation involving I might be folded into a load/store
1440/// accessing it. This doesn't need to be perfect, but needs to accept at least
1441/// the set of instructions that MatchOperationAddr can.
1442static bool MightBeFoldableInst(Instruction *I) {
1443 switch (I->getOpcode()) {
1444 case Instruction::BitCast:
1445 // Don't touch identity bitcasts.
1446 if (I->getType() == I->getOperand(0)->getType())
1447 return false;
1448 return I->getType()->isPointerTy() || I->getType()->isIntegerTy();
1449 case Instruction::PtrToInt:
1450 // PtrToInt is always a noop, as we know that the int type is pointer sized.
1451 return true;
1452 case Instruction::IntToPtr:
1453 // We know the input is intptr_t, so this is foldable.
1454 return true;
1455 case Instruction::Add:
1456 return true;
1457 case Instruction::Mul:
1458 case Instruction::Shl:
1459 // Can only handle X*C and X << C.
1460 return isa<ConstantInt>(I->getOperand(1));
1461 case Instruction::GetElementPtr:
1462 return true;
1463 default:
1464 return false;
1465 }
1466}
1467
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001468/// \brief Hepler class to perform type promotion.
1469class TypePromotionHelper {
1470 /// \brief Utility function to check whether or not a sign extension of
1471 /// \p Inst with \p ConsideredSExtType can be moved through \p Inst by either
1472 /// using the operands of \p Inst or promoting \p Inst.
1473 /// In other words, check if:
1474 /// sext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredSExtType.
1475 /// #1 Promotion applies:
1476 /// ConsideredSExtType Inst (sext opnd1 to ConsideredSExtType, ...).
1477 /// #2 Operand reuses:
1478 /// sext opnd1 to ConsideredSExtType.
1479 /// \p PromotedInsts maps the instructions to their type before promotion.
1480 static bool canGetThrough(const Instruction *Inst, Type *ConsideredSExtType,
1481 const InstrToOrigTy &PromotedInsts);
1482
1483 /// \brief Utility function to determine if \p OpIdx should be promoted when
1484 /// promoting \p Inst.
1485 static bool shouldSExtOperand(const Instruction *Inst, int OpIdx) {
1486 if (isa<SelectInst>(Inst) && OpIdx == 0)
1487 return false;
1488 return true;
1489 }
1490
1491 /// \brief Utility function to promote the operand of \p SExt when this
1492 /// operand is a promotable trunc or sext.
1493 /// \p PromotedInsts maps the instructions to their type before promotion.
1494 /// \p CreatedInsts[out] contains how many non-free instructions have been
1495 /// created to promote the operand of SExt.
1496 /// Should never be called directly.
1497 /// \return The promoted value which is used instead of SExt.
1498 static Value *promoteOperandForTruncAndSExt(Instruction *SExt,
1499 TypePromotionTransaction &TPT,
1500 InstrToOrigTy &PromotedInsts,
1501 unsigned &CreatedInsts);
1502
1503 /// \brief Utility function to promote the operand of \p SExt when this
1504 /// operand is promotable and is not a supported trunc or sext.
1505 /// \p PromotedInsts maps the instructions to their type before promotion.
1506 /// \p CreatedInsts[out] contains how many non-free instructions have been
1507 /// created to promote the operand of SExt.
1508 /// Should never be called directly.
1509 /// \return The promoted value which is used instead of SExt.
1510 static Value *promoteOperandForOther(Instruction *SExt,
1511 TypePromotionTransaction &TPT,
1512 InstrToOrigTy &PromotedInsts,
1513 unsigned &CreatedInsts);
1514
1515public:
1516 /// Type for the utility function that promotes the operand of SExt.
1517 typedef Value *(*Action)(Instruction *SExt, TypePromotionTransaction &TPT,
1518 InstrToOrigTy &PromotedInsts,
1519 unsigned &CreatedInsts);
1520 /// \brief Given a sign extend instruction \p SExt, return the approriate
1521 /// action to promote the operand of \p SExt instead of using SExt.
1522 /// \return NULL if no promotable action is possible with the current
1523 /// sign extension.
1524 /// \p InsertedTruncs keeps track of all the truncate instructions inserted by
1525 /// the others CodeGenPrepare optimizations. This information is important
1526 /// because we do not want to promote these instructions as CodeGenPrepare
1527 /// will reinsert them later. Thus creating an infinite loop: create/remove.
1528 /// \p PromotedInsts maps the instructions to their type before promotion.
1529 static Action getAction(Instruction *SExt, const SetOfInstrs &InsertedTruncs,
1530 const TargetLowering &TLI,
1531 const InstrToOrigTy &PromotedInsts);
1532};
1533
1534bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
1535 Type *ConsideredSExtType,
1536 const InstrToOrigTy &PromotedInsts) {
1537 // We can always get through sext.
1538 if (isa<SExtInst>(Inst))
1539 return true;
1540
1541 // We can get through binary operator, if it is legal. In other words, the
1542 // binary operator must have a nuw or nsw flag.
1543 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
1544 if (BinOp && isa<OverflowingBinaryOperator>(BinOp) &&
1545 (BinOp->hasNoUnsignedWrap() || BinOp->hasNoSignedWrap()))
1546 return true;
1547
1548 // Check if we can do the following simplification.
1549 // sext(trunc(sext)) --> sext
1550 if (!isa<TruncInst>(Inst))
1551 return false;
1552
1553 Value *OpndVal = Inst->getOperand(0);
1554 // Check if we can use this operand in the sext.
1555 // If the type is larger than the result type of the sign extension,
1556 // we cannot.
1557 if (OpndVal->getType()->getIntegerBitWidth() >
1558 ConsideredSExtType->getIntegerBitWidth())
1559 return false;
1560
1561 // If the operand of the truncate is not an instruction, we will not have
1562 // any information on the dropped bits.
1563 // (Actually we could for constant but it is not worth the extra logic).
1564 Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
1565 if (!Opnd)
1566 return false;
1567
1568 // Check if the source of the type is narrow enough.
1569 // I.e., check that trunc just drops sign extended bits.
1570 // #1 get the type of the operand.
1571 const Type *OpndType;
1572 InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
1573 if (It != PromotedInsts.end())
1574 OpndType = It->second;
1575 else if (isa<SExtInst>(Opnd))
1576 OpndType = cast<Instruction>(Opnd)->getOperand(0)->getType();
1577 else
1578 return false;
1579
1580 // #2 check that the truncate just drop sign extended bits.
1581 if (Inst->getType()->getIntegerBitWidth() >= OpndType->getIntegerBitWidth())
1582 return true;
1583
1584 return false;
1585}
1586
1587TypePromotionHelper::Action TypePromotionHelper::getAction(
1588 Instruction *SExt, const SetOfInstrs &InsertedTruncs,
1589 const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
1590 Instruction *SExtOpnd = dyn_cast<Instruction>(SExt->getOperand(0));
1591 Type *SExtTy = SExt->getType();
1592 // If the operand of the sign extension is not an instruction, we cannot
1593 // get through.
1594 // If it, check we can get through.
1595 if (!SExtOpnd || !canGetThrough(SExtOpnd, SExtTy, PromotedInsts))
1596 return NULL;
1597
1598 // Do not promote if the operand has been added by codegenprepare.
1599 // Otherwise, it means we are undoing an optimization that is likely to be
1600 // redone, thus causing potential infinite loop.
1601 if (isa<TruncInst>(SExtOpnd) && InsertedTruncs.count(SExtOpnd))
1602 return NULL;
1603
1604 // SExt or Trunc instructions.
1605 // Return the related handler.
1606 if (isa<SExtInst>(SExtOpnd) || isa<TruncInst>(SExtOpnd))
1607 return promoteOperandForTruncAndSExt;
1608
1609 // Regular instruction.
1610 // Abort early if we will have to insert non-free instructions.
1611 if (!SExtOpnd->hasOneUse() &&
1612 !TLI.isTruncateFree(SExtTy, SExtOpnd->getType()))
1613 return NULL;
1614 return promoteOperandForOther;
1615}
1616
1617Value *TypePromotionHelper::promoteOperandForTruncAndSExt(
1618 llvm::Instruction *SExt, TypePromotionTransaction &TPT,
1619 InstrToOrigTy &PromotedInsts, unsigned &CreatedInsts) {
1620 // By construction, the operand of SExt is an instruction. Otherwise we cannot
1621 // get through it and this method should not be called.
1622 Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
1623 // Replace sext(trunc(opnd)) or sext(sext(opnd))
1624 // => sext(opnd).
1625 TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
1626 CreatedInsts = 0;
1627
1628 // Remove dead code.
1629 if (SExtOpnd->use_empty())
1630 TPT.eraseInstruction(SExtOpnd);
1631
1632 // Check if the sext is still needed.
1633 if (SExt->getType() != SExt->getOperand(0)->getType())
1634 return SExt;
1635
1636 // At this point we have: sext ty opnd to ty.
1637 // Reassign the uses of SExt to the opnd and remove SExt.
1638 Value *NextVal = SExt->getOperand(0);
1639 TPT.eraseInstruction(SExt, NextVal);
1640 return NextVal;
1641}
1642
1643Value *
1644TypePromotionHelper::promoteOperandForOther(Instruction *SExt,
1645 TypePromotionTransaction &TPT,
1646 InstrToOrigTy &PromotedInsts,
1647 unsigned &CreatedInsts) {
1648 // By construction, the operand of SExt is an instruction. Otherwise we cannot
1649 // get through it and this method should not be called.
1650 Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
1651 CreatedInsts = 0;
1652 if (!SExtOpnd->hasOneUse()) {
1653 // SExtOpnd will be promoted.
1654 // All its uses, but SExt, will need to use a truncated value of the
1655 // promoted version.
1656 // Create the truncate now.
1657 Instruction *Trunc = TPT.createTrunc(SExt, SExtOpnd->getType());
1658 Trunc->removeFromParent();
1659 // Insert it just after the definition.
1660 Trunc->insertAfter(SExtOpnd);
1661
1662 TPT.replaceAllUsesWith(SExtOpnd, Trunc);
1663 // Restore the operand of SExt (which has been replace by the previous call
1664 // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
1665 TPT.setOperand(SExt, 0, SExtOpnd);
1666 }
1667
1668 // Get through the Instruction:
1669 // 1. Update its type.
1670 // 2. Replace the uses of SExt by Inst.
1671 // 3. Sign extend each operand that needs to be sign extended.
1672
1673 // Remember the original type of the instruction before promotion.
1674 // This is useful to know that the high bits are sign extended bits.
1675 PromotedInsts.insert(
1676 std::pair<Instruction *, Type *>(SExtOpnd, SExtOpnd->getType()));
1677 // Step #1.
1678 TPT.mutateType(SExtOpnd, SExt->getType());
1679 // Step #2.
1680 TPT.replaceAllUsesWith(SExt, SExtOpnd);
1681 // Step #3.
1682 Instruction *SExtForOpnd = SExt;
1683
1684 DEBUG(dbgs() << "Propagate SExt to operands\n");
1685 for (int OpIdx = 0, EndOpIdx = SExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
1686 ++OpIdx) {
1687 DEBUG(dbgs() << "Operand:\n" << *(SExtOpnd->getOperand(OpIdx)) << '\n');
1688 if (SExtOpnd->getOperand(OpIdx)->getType() == SExt->getType() ||
1689 !shouldSExtOperand(SExtOpnd, OpIdx)) {
1690 DEBUG(dbgs() << "No need to propagate\n");
1691 continue;
1692 }
1693 // Check if we can statically sign extend the operand.
1694 Value *Opnd = SExtOpnd->getOperand(OpIdx);
1695 if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
1696 DEBUG(dbgs() << "Statically sign extend\n");
1697 TPT.setOperand(
1698 SExtOpnd, OpIdx,
1699 ConstantInt::getSigned(SExt->getType(), Cst->getSExtValue()));
1700 continue;
1701 }
1702 // UndefValue are typed, so we have to statically sign extend them.
1703 if (isa<UndefValue>(Opnd)) {
1704 DEBUG(dbgs() << "Statically sign extend\n");
1705 TPT.setOperand(SExtOpnd, OpIdx, UndefValue::get(SExt->getType()));
1706 continue;
1707 }
1708
1709 // Otherwise we have to explicity sign extend the operand.
1710 // Check if SExt was reused to sign extend an operand.
1711 if (!SExtForOpnd) {
1712 // If yes, create a new one.
1713 DEBUG(dbgs() << "More operands to sext\n");
1714 SExtForOpnd = TPT.createSExt(SExt, Opnd, SExt->getType());
1715 ++CreatedInsts;
1716 }
1717
1718 TPT.setOperand(SExtForOpnd, 0, Opnd);
1719
1720 // Move the sign extension before the insertion point.
1721 TPT.moveBefore(SExtForOpnd, SExtOpnd);
1722 TPT.setOperand(SExtOpnd, OpIdx, SExtForOpnd);
1723 // If more sext are required, new instructions will have to be created.
1724 SExtForOpnd = NULL;
1725 }
1726 if (SExtForOpnd == SExt) {
1727 DEBUG(dbgs() << "Sign extension is useless now\n");
1728 TPT.eraseInstruction(SExt);
1729 }
1730 return SExtOpnd;
1731}
1732
Quentin Colombet867c5502014-02-14 22:23:22 +00001733/// IsPromotionProfitable - Check whether or not promoting an instruction
1734/// to a wider type was profitable.
1735/// \p MatchedSize gives the number of instructions that have been matched
1736/// in the addressing mode after the promotion was applied.
1737/// \p SizeWithPromotion gives the number of created instructions for
1738/// the promotion plus the number of instructions that have been
1739/// matched in the addressing mode before the promotion.
1740/// \p PromotedOperand is the value that has been promoted.
1741/// \return True if the promotion is profitable, false otherwise.
1742bool
1743AddressingModeMatcher::IsPromotionProfitable(unsigned MatchedSize,
1744 unsigned SizeWithPromotion,
1745 Value *PromotedOperand) const {
1746 // We folded less instructions than what we created to promote the operand.
1747 // This is not profitable.
1748 if (MatchedSize < SizeWithPromotion)
1749 return false;
1750 if (MatchedSize > SizeWithPromotion)
1751 return true;
1752 // The promotion is neutral but it may help folding the sign extension in
1753 // loads for instance.
1754 // Check that we did not create an illegal instruction.
1755 Instruction *PromotedInst = dyn_cast<Instruction>(PromotedOperand);
1756 if (!PromotedInst)
1757 return false;
1758 return TLI.isOperationLegalOrCustom(PromotedInst->getOpcode(),
1759 EVT::getEVT(PromotedInst->getType()));
1760}
1761
Chandler Carruthc8925912013-01-05 02:09:22 +00001762/// MatchOperationAddr - Given an instruction or constant expr, see if we can
1763/// fold the operation into the addressing mode. If so, update the addressing
1764/// mode and return true, otherwise return false without modifying AddrMode.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001765/// If \p MovedAway is not NULL, it contains the information of whether or
1766/// not AddrInst has to be folded into the addressing mode on success.
1767/// If \p MovedAway == true, \p AddrInst will not be part of the addressing
1768/// because it has been moved away.
1769/// Thus AddrInst must not be added in the matched instructions.
1770/// This state can happen when AddrInst is a sext, since it may be moved away.
1771/// Therefore, AddrInst may not be valid when MovedAway is true and it must
1772/// not be referenced anymore.
Chandler Carruthc8925912013-01-05 02:09:22 +00001773bool AddressingModeMatcher::MatchOperationAddr(User *AddrInst, unsigned Opcode,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001774 unsigned Depth,
1775 bool *MovedAway) {
Chandler Carruthc8925912013-01-05 02:09:22 +00001776 // Avoid exponential behavior on extremely deep expression trees.
1777 if (Depth >= 5) return false;
Stephen Lin837bba12013-07-15 17:55:02 +00001778
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001779 // By default, all matched instructions stay in place.
1780 if (MovedAway)
1781 *MovedAway = false;
1782
Chandler Carruthc8925912013-01-05 02:09:22 +00001783 switch (Opcode) {
1784 case Instruction::PtrToInt:
1785 // PtrToInt is always a noop, as we know that the int type is pointer sized.
1786 return MatchAddr(AddrInst->getOperand(0), Depth);
1787 case Instruction::IntToPtr:
1788 // This inttoptr is a no-op if the integer type is pointer sized.
1789 if (TLI.getValueType(AddrInst->getOperand(0)->getType()) ==
Matt Arsenault37d42ec2013-09-06 00:18:43 +00001790 TLI.getPointerTy(AddrInst->getType()->getPointerAddressSpace()))
Chandler Carruthc8925912013-01-05 02:09:22 +00001791 return MatchAddr(AddrInst->getOperand(0), Depth);
1792 return false;
1793 case Instruction::BitCast:
1794 // BitCast is always a noop, and we can handle it as long as it is
1795 // int->int or pointer->pointer (we don't want int<->fp or something).
1796 if ((AddrInst->getOperand(0)->getType()->isPointerTy() ||
1797 AddrInst->getOperand(0)->getType()->isIntegerTy()) &&
1798 // Don't touch identity bitcasts. These were probably put here by LSR,
1799 // and we don't want to mess around with them. Assume it knows what it
1800 // is doing.
1801 AddrInst->getOperand(0)->getType() != AddrInst->getType())
1802 return MatchAddr(AddrInst->getOperand(0), Depth);
1803 return false;
1804 case Instruction::Add: {
1805 // Check to see if we can merge in the RHS then the LHS. If so, we win.
1806 ExtAddrMode BackupAddrMode = AddrMode;
1807 unsigned OldSize = AddrModeInsts.size();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001808 // Start a transaction at this point.
1809 // The LHS may match but not the RHS.
1810 // Therefore, we need a higher level restoration point to undo partially
1811 // matched operation.
1812 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
1813 TPT.getRestorationPoint();
1814
Chandler Carruthc8925912013-01-05 02:09:22 +00001815 if (MatchAddr(AddrInst->getOperand(1), Depth+1) &&
1816 MatchAddr(AddrInst->getOperand(0), Depth+1))
1817 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00001818
Chandler Carruthc8925912013-01-05 02:09:22 +00001819 // Restore the old addr mode info.
1820 AddrMode = BackupAddrMode;
1821 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001822 TPT.rollback(LastKnownGood);
Stephen Lin837bba12013-07-15 17:55:02 +00001823
Chandler Carruthc8925912013-01-05 02:09:22 +00001824 // Otherwise this was over-aggressive. Try merging in the LHS then the RHS.
1825 if (MatchAddr(AddrInst->getOperand(0), Depth+1) &&
1826 MatchAddr(AddrInst->getOperand(1), Depth+1))
1827 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00001828
Chandler Carruthc8925912013-01-05 02:09:22 +00001829 // Otherwise we definitely can't merge the ADD in.
1830 AddrMode = BackupAddrMode;
1831 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001832 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00001833 break;
1834 }
1835 //case Instruction::Or:
1836 // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
1837 //break;
1838 case Instruction::Mul:
1839 case Instruction::Shl: {
1840 // Can only handle X*C and X << C.
1841 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
1842 if (!RHS) return false;
1843 int64_t Scale = RHS->getSExtValue();
1844 if (Opcode == Instruction::Shl)
1845 Scale = 1LL << Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00001846
Chandler Carruthc8925912013-01-05 02:09:22 +00001847 return MatchScaledValue(AddrInst->getOperand(0), Scale, Depth);
1848 }
1849 case Instruction::GetElementPtr: {
1850 // Scan the GEP. We check it if it contains constant offsets and at most
1851 // one variable offset.
1852 int VariableOperand = -1;
1853 unsigned VariableScale = 0;
Stephen Lin837bba12013-07-15 17:55:02 +00001854
Chandler Carruthc8925912013-01-05 02:09:22 +00001855 int64_t ConstantOffset = 0;
1856 const DataLayout *TD = TLI.getDataLayout();
1857 gep_type_iterator GTI = gep_type_begin(AddrInst);
1858 for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
1859 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
1860 const StructLayout *SL = TD->getStructLayout(STy);
1861 unsigned Idx =
1862 cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
1863 ConstantOffset += SL->getElementOffset(Idx);
1864 } else {
1865 uint64_t TypeSize = TD->getTypeAllocSize(GTI.getIndexedType());
1866 if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
1867 ConstantOffset += CI->getSExtValue()*TypeSize;
1868 } else if (TypeSize) { // Scales of zero don't do anything.
1869 // We only allow one variable index at the moment.
1870 if (VariableOperand != -1)
1871 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00001872
Chandler Carruthc8925912013-01-05 02:09:22 +00001873 // Remember the variable index.
1874 VariableOperand = i;
1875 VariableScale = TypeSize;
1876 }
1877 }
1878 }
Stephen Lin837bba12013-07-15 17:55:02 +00001879
Chandler Carruthc8925912013-01-05 02:09:22 +00001880 // A common case is for the GEP to only do a constant offset. In this case,
1881 // just add it to the disp field and check validity.
1882 if (VariableOperand == -1) {
1883 AddrMode.BaseOffs += ConstantOffset;
1884 if (ConstantOffset == 0 || TLI.isLegalAddressingMode(AddrMode, AccessTy)){
1885 // Check to see if we can fold the base pointer in too.
1886 if (MatchAddr(AddrInst->getOperand(0), Depth+1))
1887 return true;
1888 }
1889 AddrMode.BaseOffs -= ConstantOffset;
1890 return false;
1891 }
1892
1893 // Save the valid addressing mode in case we can't match.
1894 ExtAddrMode BackupAddrMode = AddrMode;
1895 unsigned OldSize = AddrModeInsts.size();
1896
1897 // See if the scale and offset amount is valid for this target.
1898 AddrMode.BaseOffs += ConstantOffset;
1899
1900 // Match the base operand of the GEP.
1901 if (!MatchAddr(AddrInst->getOperand(0), Depth+1)) {
1902 // If it couldn't be matched, just stuff the value in a register.
1903 if (AddrMode.HasBaseReg) {
1904 AddrMode = BackupAddrMode;
1905 AddrModeInsts.resize(OldSize);
1906 return false;
1907 }
1908 AddrMode.HasBaseReg = true;
1909 AddrMode.BaseReg = AddrInst->getOperand(0);
1910 }
1911
1912 // Match the remaining variable portion of the GEP.
1913 if (!MatchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
1914 Depth)) {
1915 // If it couldn't be matched, try stuffing the base into a register
1916 // instead of matching it, and retrying the match of the scale.
1917 AddrMode = BackupAddrMode;
1918 AddrModeInsts.resize(OldSize);
1919 if (AddrMode.HasBaseReg)
1920 return false;
1921 AddrMode.HasBaseReg = true;
1922 AddrMode.BaseReg = AddrInst->getOperand(0);
1923 AddrMode.BaseOffs += ConstantOffset;
1924 if (!MatchScaledValue(AddrInst->getOperand(VariableOperand),
1925 VariableScale, Depth)) {
1926 // If even that didn't work, bail.
1927 AddrMode = BackupAddrMode;
1928 AddrModeInsts.resize(OldSize);
1929 return false;
1930 }
1931 }
1932
1933 return true;
1934 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001935 case Instruction::SExt: {
1936 // Try to move this sext out of the way of the addressing mode.
1937 Instruction *SExt = cast<Instruction>(AddrInst);
1938 // Ask for a method for doing so.
1939 TypePromotionHelper::Action TPH = TypePromotionHelper::getAction(
1940 SExt, InsertedTruncs, TLI, PromotedInsts);
1941 if (!TPH)
1942 return false;
1943
1944 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
1945 TPT.getRestorationPoint();
1946 unsigned CreatedInsts = 0;
1947 Value *PromotedOperand = TPH(SExt, TPT, PromotedInsts, CreatedInsts);
1948 // SExt has been moved away.
1949 // Thus either it will be rematched later in the recursive calls or it is
1950 // gone. Anyway, we must not fold it into the addressing mode at this point.
1951 // E.g.,
1952 // op = add opnd, 1
1953 // idx = sext op
1954 // addr = gep base, idx
1955 // is now:
1956 // promotedOpnd = sext opnd <- no match here
1957 // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls)
1958 // addr = gep base, op <- match
1959 if (MovedAway)
1960 *MovedAway = true;
1961
1962 assert(PromotedOperand &&
1963 "TypePromotionHelper should have filtered out those cases");
1964
1965 ExtAddrMode BackupAddrMode = AddrMode;
1966 unsigned OldSize = AddrModeInsts.size();
1967
1968 if (!MatchAddr(PromotedOperand, Depth) ||
Quentin Colombet867c5502014-02-14 22:23:22 +00001969 !IsPromotionProfitable(AddrModeInsts.size(), OldSize + CreatedInsts,
1970 PromotedOperand)) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001971 AddrMode = BackupAddrMode;
1972 AddrModeInsts.resize(OldSize);
1973 DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
1974 TPT.rollback(LastKnownGood);
1975 return false;
1976 }
1977 return true;
1978 }
Chandler Carruthc8925912013-01-05 02:09:22 +00001979 }
1980 return false;
1981}
1982
1983/// MatchAddr - If we can, try to add the value of 'Addr' into the current
1984/// addressing mode. If Addr can't be added to AddrMode this returns false and
1985/// leaves AddrMode unmodified. This assumes that Addr is either a pointer type
1986/// or intptr_t for the target.
1987///
1988bool AddressingModeMatcher::MatchAddr(Value *Addr, unsigned Depth) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001989 // Start a transaction at this point that we will rollback if the matching
1990 // fails.
1991 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
1992 TPT.getRestorationPoint();
Chandler Carruthc8925912013-01-05 02:09:22 +00001993 if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
1994 // Fold in immediates if legal for the target.
1995 AddrMode.BaseOffs += CI->getSExtValue();
1996 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
1997 return true;
1998 AddrMode.BaseOffs -= CI->getSExtValue();
1999 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
2000 // If this is a global variable, try to fold it into the addressing mode.
2001 if (AddrMode.BaseGV == 0) {
2002 AddrMode.BaseGV = GV;
2003 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2004 return true;
2005 AddrMode.BaseGV = 0;
2006 }
2007 } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
2008 ExtAddrMode BackupAddrMode = AddrMode;
2009 unsigned OldSize = AddrModeInsts.size();
2010
2011 // Check to see if it is possible to fold this operation.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002012 bool MovedAway = false;
2013 if (MatchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
2014 // This instruction may have been move away. If so, there is nothing
2015 // to check here.
2016 if (MovedAway)
2017 return true;
Chandler Carruthc8925912013-01-05 02:09:22 +00002018 // Okay, it's possible to fold this. Check to see if it is actually
2019 // *profitable* to do so. We use a simple cost model to avoid increasing
2020 // register pressure too much.
2021 if (I->hasOneUse() ||
2022 IsProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
2023 AddrModeInsts.push_back(I);
2024 return true;
2025 }
Stephen Lin837bba12013-07-15 17:55:02 +00002026
Chandler Carruthc8925912013-01-05 02:09:22 +00002027 // It isn't profitable to do this, roll back.
2028 //cerr << "NOT FOLDING: " << *I;
2029 AddrMode = BackupAddrMode;
2030 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002031 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00002032 }
2033 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
2034 if (MatchOperationAddr(CE, CE->getOpcode(), Depth))
2035 return true;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002036 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00002037 } else if (isa<ConstantPointerNull>(Addr)) {
2038 // Null pointer gets folded without affecting the addressing mode.
2039 return true;
2040 }
2041
2042 // Worse case, the target should support [reg] addressing modes. :)
2043 if (!AddrMode.HasBaseReg) {
2044 AddrMode.HasBaseReg = true;
2045 AddrMode.BaseReg = Addr;
2046 // Still check for legality in case the target supports [imm] but not [i+r].
2047 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2048 return true;
2049 AddrMode.HasBaseReg = false;
2050 AddrMode.BaseReg = 0;
2051 }
2052
2053 // If the base register is already taken, see if we can do [r+r].
2054 if (AddrMode.Scale == 0) {
2055 AddrMode.Scale = 1;
2056 AddrMode.ScaledReg = Addr;
2057 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2058 return true;
2059 AddrMode.Scale = 0;
2060 AddrMode.ScaledReg = 0;
2061 }
2062 // Couldn't match.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002063 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00002064 return false;
2065}
2066
2067/// IsOperandAMemoryOperand - Check to see if all uses of OpVal by the specified
2068/// inline asm call are due to memory operands. If so, return true, otherwise
2069/// return false.
2070static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
2071 const TargetLowering &TLI) {
2072 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(ImmutableCallSite(CI));
2073 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
2074 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Stephen Lin837bba12013-07-15 17:55:02 +00002075
Chandler Carruthc8925912013-01-05 02:09:22 +00002076 // Compute the constraint code and ConstraintType to use.
2077 TLI.ComputeConstraintToUse(OpInfo, SDValue());
2078
2079 // If this asm operand is our Value*, and if it isn't an indirect memory
2080 // operand, we can't fold it!
2081 if (OpInfo.CallOperandVal == OpVal &&
2082 (OpInfo.ConstraintType != TargetLowering::C_Memory ||
2083 !OpInfo.isIndirect))
2084 return false;
2085 }
2086
2087 return true;
2088}
2089
2090/// FindAllMemoryUses - Recursively walk all the uses of I until we find a
2091/// memory use. If we find an obviously non-foldable instruction, return true.
2092/// Add the ultimately found memory instructions to MemoryUses.
2093static bool FindAllMemoryUses(Instruction *I,
2094 SmallVectorImpl<std::pair<Instruction*,unsigned> > &MemoryUses,
2095 SmallPtrSet<Instruction*, 16> &ConsideredInsts,
2096 const TargetLowering &TLI) {
2097 // If we already considered this instruction, we're done.
2098 if (!ConsideredInsts.insert(I))
2099 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00002100
Chandler Carruthc8925912013-01-05 02:09:22 +00002101 // If this is an obviously unfoldable instruction, bail out.
2102 if (!MightBeFoldableInst(I))
2103 return true;
2104
2105 // Loop over all the uses, recursively processing them.
2106 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
2107 UI != E; ++UI) {
2108 User *U = *UI;
2109
2110 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
2111 MemoryUses.push_back(std::make_pair(LI, UI.getOperandNo()));
2112 continue;
2113 }
Stephen Lin837bba12013-07-15 17:55:02 +00002114
Chandler Carruthc8925912013-01-05 02:09:22 +00002115 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
2116 unsigned opNo = UI.getOperandNo();
2117 if (opNo == 0) return true; // Storing addr, not into addr.
2118 MemoryUses.push_back(std::make_pair(SI, opNo));
2119 continue;
2120 }
Stephen Lin837bba12013-07-15 17:55:02 +00002121
Chandler Carruthc8925912013-01-05 02:09:22 +00002122 if (CallInst *CI = dyn_cast<CallInst>(U)) {
2123 InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
2124 if (!IA) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002125
Chandler Carruthc8925912013-01-05 02:09:22 +00002126 // If this is a memory operand, we're cool, otherwise bail out.
2127 if (!IsOperandAMemoryOperand(CI, IA, I, TLI))
2128 return true;
2129 continue;
2130 }
Stephen Lin837bba12013-07-15 17:55:02 +00002131
Chandler Carruthc8925912013-01-05 02:09:22 +00002132 if (FindAllMemoryUses(cast<Instruction>(U), MemoryUses, ConsideredInsts,
2133 TLI))
2134 return true;
2135 }
2136
2137 return false;
2138}
2139
2140/// ValueAlreadyLiveAtInst - Retrn true if Val is already known to be live at
2141/// the use site that we're folding it into. If so, there is no cost to
2142/// include it in the addressing mode. KnownLive1 and KnownLive2 are two values
2143/// that we know are live at the instruction already.
2144bool AddressingModeMatcher::ValueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
2145 Value *KnownLive2) {
2146 // If Val is either of the known-live values, we know it is live!
2147 if (Val == 0 || Val == KnownLive1 || Val == KnownLive2)
2148 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002149
Chandler Carruthc8925912013-01-05 02:09:22 +00002150 // All values other than instructions and arguments (e.g. constants) are live.
2151 if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002152
Chandler Carruthc8925912013-01-05 02:09:22 +00002153 // If Val is a constant sized alloca in the entry block, it is live, this is
2154 // true because it is just a reference to the stack/frame pointer, which is
2155 // live for the whole function.
2156 if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
2157 if (AI->isStaticAlloca())
2158 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002159
Chandler Carruthc8925912013-01-05 02:09:22 +00002160 // Check to see if this value is already used in the memory instruction's
2161 // block. If so, it's already live into the block at the very least, so we
2162 // can reasonably fold it.
2163 return Val->isUsedInBasicBlock(MemoryInst->getParent());
2164}
2165
2166/// IsProfitableToFoldIntoAddressingMode - It is possible for the addressing
2167/// mode of the machine to fold the specified instruction into a load or store
2168/// that ultimately uses it. However, the specified instruction has multiple
2169/// uses. Given this, it may actually increase register pressure to fold it
2170/// into the load. For example, consider this code:
2171///
2172/// X = ...
2173/// Y = X+1
2174/// use(Y) -> nonload/store
2175/// Z = Y+1
2176/// load Z
2177///
2178/// In this case, Y has multiple uses, and can be folded into the load of Z
2179/// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to
2180/// be live at the use(Y) line. If we don't fold Y into load Z, we use one
2181/// fewer register. Since Y can't be folded into "use(Y)" we don't increase the
2182/// number of computations either.
2183///
2184/// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If
2185/// X was live across 'load Z' for other reasons, we actually *would* want to
2186/// fold the addressing mode in the Z case. This would make Y die earlier.
2187bool AddressingModeMatcher::
2188IsProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
2189 ExtAddrMode &AMAfter) {
2190 if (IgnoreProfitability) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002191
Chandler Carruthc8925912013-01-05 02:09:22 +00002192 // AMBefore is the addressing mode before this instruction was folded into it,
2193 // and AMAfter is the addressing mode after the instruction was folded. Get
2194 // the set of registers referenced by AMAfter and subtract out those
2195 // referenced by AMBefore: this is the set of values which folding in this
2196 // address extends the lifetime of.
2197 //
2198 // Note that there are only two potential values being referenced here,
2199 // BaseReg and ScaleReg (global addresses are always available, as are any
2200 // folded immediates).
2201 Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
Stephen Lin837bba12013-07-15 17:55:02 +00002202
Chandler Carruthc8925912013-01-05 02:09:22 +00002203 // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
2204 // lifetime wasn't extended by adding this instruction.
2205 if (ValueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
2206 BaseReg = 0;
2207 if (ValueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
2208 ScaledReg = 0;
2209
2210 // If folding this instruction (and it's subexprs) didn't extend any live
2211 // ranges, we're ok with it.
2212 if (BaseReg == 0 && ScaledReg == 0)
2213 return true;
2214
2215 // If all uses of this instruction are ultimately load/store/inlineasm's,
2216 // check to see if their addressing modes will include this instruction. If
2217 // so, we can fold it into all uses, so it doesn't matter if it has multiple
2218 // uses.
2219 SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
2220 SmallPtrSet<Instruction*, 16> ConsideredInsts;
2221 if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TLI))
2222 return false; // Has a non-memory, non-foldable use!
Stephen Lin837bba12013-07-15 17:55:02 +00002223
Chandler Carruthc8925912013-01-05 02:09:22 +00002224 // Now that we know that all uses of this instruction are part of a chain of
2225 // computation involving only operations that could theoretically be folded
2226 // into a memory use, loop over each of these uses and see if they could
2227 // *actually* fold the instruction.
2228 SmallVector<Instruction*, 32> MatchedAddrModeInsts;
2229 for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
2230 Instruction *User = MemoryUses[i].first;
2231 unsigned OpNo = MemoryUses[i].second;
Stephen Lin837bba12013-07-15 17:55:02 +00002232
Chandler Carruthc8925912013-01-05 02:09:22 +00002233 // Get the access type of this use. If the use isn't a pointer, we don't
2234 // know what it accesses.
2235 Value *Address = User->getOperand(OpNo);
2236 if (!Address->getType()->isPointerTy())
2237 return false;
Matt Arsenault8227b9f2013-09-06 00:37:24 +00002238 Type *AddressAccessTy = Address->getType()->getPointerElementType();
Stephen Lin837bba12013-07-15 17:55:02 +00002239
Chandler Carruthc8925912013-01-05 02:09:22 +00002240 // Do a match against the root of this address, ignoring profitability. This
2241 // will tell us if the addressing mode for the memory operation will
2242 // *actually* cover the shared instruction.
2243 ExtAddrMode Result;
Quentin Colombet5a69dda2014-02-11 01:59:02 +00002244 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2245 TPT.getRestorationPoint();
Chandler Carruthc8925912013-01-05 02:09:22 +00002246 AddressingModeMatcher Matcher(MatchedAddrModeInsts, TLI, AddressAccessTy,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002247 MemoryInst, Result, InsertedTruncs,
2248 PromotedInsts, TPT);
Chandler Carruthc8925912013-01-05 02:09:22 +00002249 Matcher.IgnoreProfitability = true;
2250 bool Success = Matcher.MatchAddr(Address, 0);
2251 (void)Success; assert(Success && "Couldn't select *anything*?");
2252
Quentin Colombet5a69dda2014-02-11 01:59:02 +00002253 // The match was to check the profitability, the changes made are not
2254 // part of the original matcher. Therefore, they should be dropped
2255 // otherwise the original matcher will not present the right state.
2256 TPT.rollback(LastKnownGood);
2257
Chandler Carruthc8925912013-01-05 02:09:22 +00002258 // If the match didn't cover I, then it won't be shared by it.
2259 if (std::find(MatchedAddrModeInsts.begin(), MatchedAddrModeInsts.end(),
2260 I) == MatchedAddrModeInsts.end())
2261 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00002262
Chandler Carruthc8925912013-01-05 02:09:22 +00002263 MatchedAddrModeInsts.clear();
2264 }
Stephen Lin837bba12013-07-15 17:55:02 +00002265
Chandler Carruthc8925912013-01-05 02:09:22 +00002266 return true;
2267}
2268
2269} // end anonymous namespace
2270
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002271/// IsNonLocalValue - Return true if the specified values are defined in a
2272/// different basic block than BB.
2273static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
2274 if (Instruction *I = dyn_cast<Instruction>(V))
2275 return I->getParent() != BB;
2276 return false;
2277}
2278
Bob Wilson53bdae32009-12-03 21:47:07 +00002279/// OptimizeMemoryInst - Load and Store Instructions often have
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002280/// addressing modes that can do significant amounts of computation. As such,
2281/// instruction selection will try to get the load or store to do as much
2282/// computation as possible for the program. The problem is that isel can only
2283/// see within a single block. As such, we sink as much legal addressing mode
2284/// stuff into the block as possible.
Chris Lattner728f9022008-11-25 07:09:13 +00002285///
2286/// This method is used to optimize both load/store and inline asms with memory
2287/// operands.
Chris Lattner6d71b7f2008-11-26 03:20:37 +00002288bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
Chris Lattner229907c2011-07-18 04:54:35 +00002289 Type *AccessTy) {
Owen Anderson8ba5f392010-11-27 08:15:55 +00002290 Value *Repl = Addr;
Nadav Rotem465834c2012-07-24 10:51:42 +00002291
2292 // Try to collapse single-value PHI nodes. This is necessary to undo
Owen Andersondfb8c3b2010-11-19 22:15:03 +00002293 // unprofitable PRE transformations.
Cameron Zwarich43cecb12011-01-03 06:33:01 +00002294 SmallVector<Value*, 8> worklist;
2295 SmallPtrSet<Value*, 16> Visited;
Owen Anderson8ba5f392010-11-27 08:15:55 +00002296 worklist.push_back(Addr);
Nadav Rotem465834c2012-07-24 10:51:42 +00002297
Owen Anderson8ba5f392010-11-27 08:15:55 +00002298 // Use a worklist to iteratively look through PHI nodes, and ensure that
2299 // the addressing mode obtained from the non-PHI roots of the graph
2300 // are equivalent.
2301 Value *Consensus = 0;
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00002302 unsigned NumUsesConsensus = 0;
Cameron Zwarich13c885d2011-03-05 08:12:26 +00002303 bool IsNumUsesConsensusValid = false;
Owen Anderson8ba5f392010-11-27 08:15:55 +00002304 SmallVector<Instruction*, 16> AddrModeInsts;
2305 ExtAddrMode AddrMode;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002306 TypePromotionTransaction TPT;
2307 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2308 TPT.getRestorationPoint();
Owen Anderson8ba5f392010-11-27 08:15:55 +00002309 while (!worklist.empty()) {
2310 Value *V = worklist.back();
2311 worklist.pop_back();
Nadav Rotem465834c2012-07-24 10:51:42 +00002312
Owen Anderson8ba5f392010-11-27 08:15:55 +00002313 // Break use-def graph loops.
Nick Lewyckya3e7ffd2011-09-29 23:40:12 +00002314 if (!Visited.insert(V)) {
Owen Anderson8ba5f392010-11-27 08:15:55 +00002315 Consensus = 0;
2316 break;
Owen Andersondfb8c3b2010-11-19 22:15:03 +00002317 }
Nadav Rotem465834c2012-07-24 10:51:42 +00002318
Owen Anderson8ba5f392010-11-27 08:15:55 +00002319 // For a PHI node, push all of its incoming values.
2320 if (PHINode *P = dyn_cast<PHINode>(V)) {
2321 for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i)
2322 worklist.push_back(P->getIncomingValue(i));
2323 continue;
2324 }
Nadav Rotem465834c2012-07-24 10:51:42 +00002325
Owen Anderson8ba5f392010-11-27 08:15:55 +00002326 // For non-PHIs, determine the addressing mode being computed.
2327 SmallVector<Instruction*, 16> NewAddrModeInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002328 ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
2329 V, AccessTy, MemoryInst, NewAddrModeInsts, *TLI, InsertedTruncsSet,
2330 PromotedInsts, TPT);
Cameron Zwarich13c885d2011-03-05 08:12:26 +00002331
2332 // This check is broken into two cases with very similar code to avoid using
2333 // getNumUses() as much as possible. Some values have a lot of uses, so
2334 // calling getNumUses() unconditionally caused a significant compile-time
2335 // regression.
2336 if (!Consensus) {
2337 Consensus = V;
2338 AddrMode = NewAddrMode;
2339 AddrModeInsts = NewAddrModeInsts;
2340 continue;
2341 } else if (NewAddrMode == AddrMode) {
2342 if (!IsNumUsesConsensusValid) {
2343 NumUsesConsensus = Consensus->getNumUses();
2344 IsNumUsesConsensusValid = true;
2345 }
2346
2347 // Ensure that the obtained addressing mode is equivalent to that obtained
2348 // for all other roots of the PHI traversal. Also, when choosing one
2349 // such root as representative, select the one with the most uses in order
2350 // to keep the cost modeling heuristics in AddressingModeMatcher
2351 // applicable.
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00002352 unsigned NumUses = V->getNumUses();
2353 if (NumUses > NumUsesConsensus) {
Owen Anderson8ba5f392010-11-27 08:15:55 +00002354 Consensus = V;
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00002355 NumUsesConsensus = NumUses;
Owen Anderson8ba5f392010-11-27 08:15:55 +00002356 AddrModeInsts = NewAddrModeInsts;
2357 }
2358 continue;
2359 }
Nadav Rotem465834c2012-07-24 10:51:42 +00002360
Owen Anderson8ba5f392010-11-27 08:15:55 +00002361 Consensus = 0;
2362 break;
Owen Andersondfb8c3b2010-11-19 22:15:03 +00002363 }
Nadav Rotem465834c2012-07-24 10:51:42 +00002364
Owen Anderson8ba5f392010-11-27 08:15:55 +00002365 // If the addressing mode couldn't be determined, or if multiple different
2366 // ones were determined, bail out now.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002367 if (!Consensus) {
2368 TPT.rollback(LastKnownGood);
2369 return false;
2370 }
2371 TPT.commit();
Nadav Rotem465834c2012-07-24 10:51:42 +00002372
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002373 // Check to see if any of the instructions supersumed by this addr mode are
2374 // non-local to I's BB.
2375 bool AnyNonLocal = false;
2376 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
Chris Lattner6d71b7f2008-11-26 03:20:37 +00002377 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002378 AnyNonLocal = true;
2379 break;
2380 }
2381 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00002382
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002383 // If all the instructions matched are already in this BB, don't do anything.
2384 if (!AnyNonLocal) {
David Greene74e2d492010-01-05 01:27:11 +00002385 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002386 return false;
2387 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00002388
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002389 // Insert this computation right after this user. Since our caller is
2390 // scanning from the top of the BB to the bottom, reuse of the expr are
2391 // guaranteed to happen later.
Devang Patelc10e52a2011-09-06 18:49:53 +00002392 IRBuilder<> Builder(MemoryInst);
Eric Christopherc1ea1492008-09-24 05:32:41 +00002393
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002394 // Now that we determined the addressing expression we want to use and know
2395 // that we have to sink it into this block. Check to see if we have already
2396 // done this for some other load/store instr in this block. If so, reuse the
2397 // computation.
2398 Value *&SunkAddr = SunkAddrs[Addr];
2399 if (SunkAddr) {
David Greene74e2d492010-01-05 01:27:11 +00002400 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
Dan Gohman29f2baf2009-07-25 01:13:51 +00002401 << *MemoryInst);
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002402 if (SunkAddr->getType() != Addr->getType())
Benjamin Kramer547b6c52011-09-27 20:39:19 +00002403 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002404 } else {
David Greene74e2d492010-01-05 01:27:11 +00002405 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Dan Gohman29f2baf2009-07-25 01:13:51 +00002406 << *MemoryInst);
Matt Arsenault37d42ec2013-09-06 00:18:43 +00002407 Type *IntPtrTy = TLI->getDataLayout()->getIntPtrType(Addr->getType());
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002408 Value *Result = 0;
Dan Gohmanca194452010-01-19 22:45:06 +00002409
2410 // Start with the base register. Do this first so that subsequent address
2411 // matching finds it last, which will prevent it from trying to match it
2412 // as the scaled value in case it happens to be a mul. That would be
2413 // problematic if we've sunk a different mul for the scale, because then
2414 // we'd end up sinking both muls.
2415 if (AddrMode.BaseReg) {
2416 Value *V = AddrMode.BaseReg;
Duncan Sands19d0b472010-02-16 11:11:14 +00002417 if (V->getType()->isPointerTy())
Devang Patelc10e52a2011-09-06 18:49:53 +00002418 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00002419 if (V->getType() != IntPtrTy)
Devang Patelc10e52a2011-09-06 18:49:53 +00002420 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00002421 Result = V;
2422 }
2423
2424 // Add the scale value.
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002425 if (AddrMode.Scale) {
2426 Value *V = AddrMode.ScaledReg;
2427 if (V->getType() == IntPtrTy) {
2428 // done.
Duncan Sands19d0b472010-02-16 11:11:14 +00002429 } else if (V->getType()->isPointerTy()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00002430 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002431 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
2432 cast<IntegerType>(V->getType())->getBitWidth()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00002433 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002434 } else {
Devang Patelc10e52a2011-09-06 18:49:53 +00002435 V = Builder.CreateSExt(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002436 }
2437 if (AddrMode.Scale != 1)
Devang Patelc10e52a2011-09-06 18:49:53 +00002438 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
2439 "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002440 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00002441 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002442 else
2443 Result = V;
2444 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00002445
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002446 // Add in the BaseGV if present.
2447 if (AddrMode.BaseGV) {
Devang Patelc10e52a2011-09-06 18:49:53 +00002448 Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002449 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00002450 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002451 else
2452 Result = V;
2453 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00002454
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002455 // Add in the Base Offset if present.
2456 if (AddrMode.BaseOffs) {
Owen Andersonedb4a702009-07-24 23:12:02 +00002457 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002458 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00002459 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002460 else
2461 Result = V;
2462 }
2463
2464 if (Result == 0)
Owen Anderson5a1acd92009-07-31 20:28:14 +00002465 SunkAddr = Constant::getNullValue(Addr->getType());
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002466 else
Devang Patelc10e52a2011-09-06 18:49:53 +00002467 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002468 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00002469
Owen Andersondfb8c3b2010-11-19 22:15:03 +00002470 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
Eric Christopherc1ea1492008-09-24 05:32:41 +00002471
Chris Lattneraf1bcce2011-04-09 07:05:44 +00002472 // If we have no uses, recursively delete the value and all dead instructions
2473 // using it.
Owen Andersondfb8c3b2010-11-19 22:15:03 +00002474 if (Repl->use_empty()) {
Chris Lattneraf1bcce2011-04-09 07:05:44 +00002475 // This can cause recursive deletion, which can invalidate our iterator.
2476 // Use a WeakVH to hold onto it in case this happens.
2477 WeakVH IterHandle(CurInstIterator);
2478 BasicBlock *BB = CurInstIterator->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +00002479
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00002480 RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
Chris Lattneraf1bcce2011-04-09 07:05:44 +00002481
2482 if (IterHandle != CurInstIterator) {
2483 // If the iterator instruction was recursively deleted, start over at the
2484 // start of the block.
2485 CurInstIterator = BB->begin();
2486 SunkAddrs.clear();
Nadav Rotem465834c2012-07-24 10:51:42 +00002487 }
Dale Johannesenb67a6e662010-03-31 20:37:15 +00002488 }
Cameron Zwarichced753f2011-01-05 17:27:27 +00002489 ++NumMemoryInsts;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002490 return true;
2491}
2492
Evan Cheng1da25002008-02-26 02:42:37 +00002493/// OptimizeInlineAsmInst - If there are any memory operands, use
Chris Lattner728f9022008-11-25 07:09:13 +00002494/// OptimizeMemoryInst to sink their address computing into the block when
Evan Cheng1da25002008-02-26 02:42:37 +00002495/// possible / profitable.
Chris Lattner7a277142011-01-15 07:14:54 +00002496bool CodeGenPrepare::OptimizeInlineAsmInst(CallInst *CS) {
Evan Cheng1da25002008-02-26 02:42:37 +00002497 bool MadeChange = false;
Evan Cheng1da25002008-02-26 02:42:37 +00002498
Nadav Rotem465834c2012-07-24 10:51:42 +00002499 TargetLowering::AsmOperandInfoVector
Chris Lattner7a277142011-01-15 07:14:54 +00002500 TargetConstraints = TLI->ParseConstraints(CS);
Dale Johannesenf95f59a2010-09-16 18:30:55 +00002501 unsigned ArgNo = 0;
John Thompson1094c802010-09-13 18:15:37 +00002502 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
2503 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Nadav Rotem465834c2012-07-24 10:51:42 +00002504
Evan Cheng1da25002008-02-26 02:42:37 +00002505 // Compute the constraint code and ConstraintType to use.
Dale Johannesence97d552010-06-25 21:55:36 +00002506 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Evan Cheng1da25002008-02-26 02:42:37 +00002507
Eli Friedman666bbe32008-02-26 18:37:49 +00002508 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
2509 OpInfo.isIndirect) {
Chris Lattner7a277142011-01-15 07:14:54 +00002510 Value *OpVal = CS->getArgOperand(ArgNo++);
Chris Lattneree588de2011-01-15 07:29:01 +00002511 MadeChange |= OptimizeMemoryInst(CS, OpVal, OpVal->getType());
Dale Johannesenf95f59a2010-09-16 18:30:55 +00002512 } else if (OpInfo.Type == InlineAsm::isInput)
2513 ArgNo++;
Evan Cheng1da25002008-02-26 02:42:37 +00002514 }
2515
2516 return MadeChange;
2517}
2518
Dan Gohman99429a02009-10-16 20:59:35 +00002519/// MoveExtToFormExtLoad - Move a zext or sext fed by a load into the same
2520/// basic block as the load, unless conditions are unfavorable. This allows
2521/// SelectionDAG to fold the extend into the load.
2522///
2523bool CodeGenPrepare::MoveExtToFormExtLoad(Instruction *I) {
2524 // Look for a load being extended.
2525 LoadInst *LI = dyn_cast<LoadInst>(I->getOperand(0));
2526 if (!LI) return false;
2527
2528 // If they're already in the same block, there's nothing to do.
2529 if (LI->getParent() == I->getParent())
2530 return false;
2531
2532 // If the load has other users and the truncate is not free, this probably
2533 // isn't worthwhile.
2534 if (!LI->hasOneUse() &&
Bob Wilsonb6832a42010-09-22 18:44:56 +00002535 TLI && (TLI->isTypeLegal(TLI->getValueType(LI->getType())) ||
2536 !TLI->isTypeLegal(TLI->getValueType(I->getType()))) &&
Bob Wilson4ddcb6a2010-09-21 21:54:27 +00002537 !TLI->isTruncateFree(I->getType(), LI->getType()))
Dan Gohman99429a02009-10-16 20:59:35 +00002538 return false;
2539
2540 // Check whether the target supports casts folded into loads.
2541 unsigned LType;
2542 if (isa<ZExtInst>(I))
2543 LType = ISD::ZEXTLOAD;
2544 else {
2545 assert(isa<SExtInst>(I) && "Unexpected ext type!");
2546 LType = ISD::SEXTLOAD;
2547 }
Patrik Hagglunde98b7a02012-12-11 11:14:33 +00002548 if (TLI && !TLI->isLoadExtLegal(LType, TLI->getValueType(LI->getType())))
Dan Gohman99429a02009-10-16 20:59:35 +00002549 return false;
2550
2551 // Move the extend into the same block as the load, so that SelectionDAG
2552 // can fold it.
2553 I->removeFromParent();
2554 I->insertAfter(LI);
Cameron Zwarichced753f2011-01-05 17:27:27 +00002555 ++NumExtsMoved;
Dan Gohman99429a02009-10-16 20:59:35 +00002556 return true;
2557}
2558
Evan Chengd3d80172007-12-05 23:58:20 +00002559bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
2560 BasicBlock *DefBB = I->getParent();
2561
Bob Wilsonff714f92010-09-21 21:44:14 +00002562 // If the result of a {s|z}ext and its source are both live out, rewrite all
Evan Chengd3d80172007-12-05 23:58:20 +00002563 // other uses of the source with result of extension.
2564 Value *Src = I->getOperand(0);
2565 if (Src->hasOneUse())
2566 return false;
2567
Evan Cheng2011df42007-12-13 07:50:36 +00002568 // Only do this xform if truncating is free.
Gabor Greifaa261722008-02-26 19:13:21 +00002569 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
Evan Cheng37c36ed2007-12-13 03:32:53 +00002570 return false;
2571
Evan Cheng7bc89422007-12-12 00:51:06 +00002572 // Only safe to perform the optimization if the source is also defined in
Evan Cheng63d33cf2007-12-12 02:53:41 +00002573 // this block.
2574 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
Evan Cheng7bc89422007-12-12 00:51:06 +00002575 return false;
2576
Evan Chengd3d80172007-12-05 23:58:20 +00002577 bool DefIsLiveOut = false;
Eric Christopherc1ea1492008-09-24 05:32:41 +00002578 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
Evan Chengd3d80172007-12-05 23:58:20 +00002579 UI != E; ++UI) {
2580 Instruction *User = cast<Instruction>(*UI);
2581
2582 // Figure out which BB this ext is used in.
2583 BasicBlock *UserBB = User->getParent();
2584 if (UserBB == DefBB) continue;
2585 DefIsLiveOut = true;
2586 break;
2587 }
2588 if (!DefIsLiveOut)
2589 return false;
2590
Jim Grosbach0f38c1e2013-04-15 17:40:48 +00002591 // Make sure none of the uses are PHI nodes.
Eric Christopherc1ea1492008-09-24 05:32:41 +00002592 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
Evan Cheng63d33cf2007-12-12 02:53:41 +00002593 UI != E; ++UI) {
2594 Instruction *User = cast<Instruction>(*UI);
Evan Cheng37c36ed2007-12-13 03:32:53 +00002595 BasicBlock *UserBB = User->getParent();
2596 if (UserBB == DefBB) continue;
2597 // Be conservative. We don't want this xform to end up introducing
2598 // reloads just before load / store instructions.
2599 if (isa<PHINode>(User) || isa<LoadInst>(User) || isa<StoreInst>(User))
Evan Cheng63d33cf2007-12-12 02:53:41 +00002600 return false;
2601 }
2602
Evan Chengd3d80172007-12-05 23:58:20 +00002603 // InsertedTruncs - Only insert one trunc in each block once.
2604 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
2605
2606 bool MadeChange = false;
Eric Christopherc1ea1492008-09-24 05:32:41 +00002607 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
Evan Chengd3d80172007-12-05 23:58:20 +00002608 UI != E; ++UI) {
2609 Use &TheUse = UI.getUse();
2610 Instruction *User = cast<Instruction>(*UI);
2611
2612 // Figure out which BB this ext is used in.
2613 BasicBlock *UserBB = User->getParent();
2614 if (UserBB == DefBB) continue;
2615
2616 // Both src and def are live in this block. Rewrite the use.
2617 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
2618
2619 if (!InsertedTrunc) {
Bill Wendling8ddfc092011-08-16 20:45:24 +00002620 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Evan Chengd3d80172007-12-05 23:58:20 +00002621 InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002622 InsertedTruncsSet.insert(InsertedTrunc);
Evan Chengd3d80172007-12-05 23:58:20 +00002623 }
2624
2625 // Replace a use of the {s|z}ext source with a use of the result.
2626 TheUse = InsertedTrunc;
Cameron Zwarichced753f2011-01-05 17:27:27 +00002627 ++NumExtUses;
Evan Chengd3d80172007-12-05 23:58:20 +00002628 MadeChange = true;
2629 }
2630
2631 return MadeChange;
2632}
2633
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00002634/// isFormingBranchFromSelectProfitable - Returns true if a SelectInst should be
2635/// turned into an explicit branch.
2636static bool isFormingBranchFromSelectProfitable(SelectInst *SI) {
2637 // FIXME: This should use the same heuristics as IfConversion to determine
2638 // whether a select is better represented as a branch. This requires that
2639 // branch probability metadata is preserved for the select, which is not the
2640 // case currently.
2641
2642 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
2643
2644 // If the branch is predicted right, an out of order CPU can avoid blocking on
2645 // the compare. Emit cmovs on compares with a memory operand as branches to
2646 // avoid stalls on the load from memory. If the compare has more than one use
2647 // there's probably another cmov or setcc around so it's not worth emitting a
2648 // branch.
2649 if (!Cmp)
2650 return false;
2651
2652 Value *CmpOp0 = Cmp->getOperand(0);
2653 Value *CmpOp1 = Cmp->getOperand(1);
2654
2655 // We check that the memory operand has one use to avoid uses of the loaded
2656 // value directly after the compare, making branches unprofitable.
2657 return Cmp->hasOneUse() &&
2658 ((isa<LoadInst>(CmpOp0) && CmpOp0->hasOneUse()) ||
2659 (isa<LoadInst>(CmpOp1) && CmpOp1->hasOneUse()));
2660}
2661
2662
Nadav Rotem9d832022012-09-02 12:10:19 +00002663/// If we have a SelectInst that will likely profit from branch prediction,
2664/// turn it into a branch.
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00002665bool CodeGenPrepare::OptimizeSelectInst(SelectInst *SI) {
Nadav Rotem9d832022012-09-02 12:10:19 +00002666 bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
2667
2668 // Can we convert the 'select' to CF ?
2669 if (DisableSelectToBranch || OptSize || !TLI || VectorCond)
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00002670 return false;
2671
Nadav Rotem9d832022012-09-02 12:10:19 +00002672 TargetLowering::SelectSupportKind SelectKind;
2673 if (VectorCond)
2674 SelectKind = TargetLowering::VectorMaskSelect;
2675 else if (SI->getType()->isVectorTy())
2676 SelectKind = TargetLowering::ScalarCondVectorVal;
2677 else
2678 SelectKind = TargetLowering::ScalarValSelect;
2679
2680 // Do we have efficient codegen support for this kind of 'selects' ?
2681 if (TLI->isSelectSupported(SelectKind)) {
2682 // We have efficient codegen support for the select instruction.
2683 // Check if it is profitable to keep this 'select'.
2684 if (!TLI->isPredictableSelectExpensive() ||
2685 !isFormingBranchFromSelectProfitable(SI))
2686 return false;
2687 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00002688
2689 ModifiedDT = true;
2690
2691 // First, we split the block containing the select into 2 blocks.
2692 BasicBlock *StartBlock = SI->getParent();
2693 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(SI));
2694 BasicBlock *NextBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
2695
2696 // Create a new block serving as the landing pad for the branch.
2697 BasicBlock *SmallBlock = BasicBlock::Create(SI->getContext(), "select.mid",
2698 NextBlock->getParent(), NextBlock);
2699
2700 // Move the unconditional branch from the block with the select in it into our
2701 // landing pad block.
2702 StartBlock->getTerminator()->eraseFromParent();
2703 BranchInst::Create(NextBlock, SmallBlock);
2704
2705 // Insert the real conditional branch based on the original condition.
2706 BranchInst::Create(NextBlock, SmallBlock, SI->getCondition(), SI);
2707
2708 // The select itself is replaced with a PHI Node.
2709 PHINode *PN = PHINode::Create(SI->getType(), 2, "", NextBlock->begin());
2710 PN->takeName(SI);
2711 PN->addIncoming(SI->getTrueValue(), StartBlock);
2712 PN->addIncoming(SI->getFalseValue(), SmallBlock);
2713 SI->replaceAllUsesWith(PN);
2714 SI->eraseFromParent();
2715
2716 // Instruct OptimizeBlock to skip to the next block.
2717 CurInstIterator = StartBlock->end();
2718 ++NumSelectsExpanded;
2719 return true;
2720}
2721
Cameron Zwarich14ac8652011-01-06 02:37:26 +00002722bool CodeGenPrepare::OptimizeInst(Instruction *I) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00002723 if (PHINode *P = dyn_cast<PHINode>(I)) {
2724 // It is possible for very late stage optimizations (such as SimplifyCFG)
2725 // to introduce PHI nodes too late to be cleaned up. If we detect such a
2726 // trivial PHI, go ahead and zap it here.
Benjamin Kramer30d249a2013-09-24 16:37:40 +00002727 if (Value *V = SimplifyInstruction(P, TLI ? TLI->getDataLayout() : 0,
2728 TLInfo, DT)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00002729 P->replaceAllUsesWith(V);
2730 P->eraseFromParent();
2731 ++NumPHIsElim;
Chris Lattneree588de2011-01-15 07:29:01 +00002732 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00002733 }
Chris Lattneree588de2011-01-15 07:29:01 +00002734 return false;
2735 }
Nadav Rotem465834c2012-07-24 10:51:42 +00002736
Chris Lattneree588de2011-01-15 07:29:01 +00002737 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00002738 // If the source of the cast is a constant, then this should have
2739 // already been constant folded. The only reason NOT to constant fold
2740 // it is if something (e.g. LSR) was careful to place the constant
2741 // evaluation in a block other than then one that uses it (e.g. to hoist
2742 // the address of globals out of a loop). If this is the case, we don't
2743 // want to forward-subst the cast.
2744 if (isa<Constant>(CI->getOperand(0)))
2745 return false;
2746
Chris Lattneree588de2011-01-15 07:29:01 +00002747 if (TLI && OptimizeNoopCopyExpression(CI, *TLI))
2748 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00002749
Chris Lattneree588de2011-01-15 07:29:01 +00002750 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
2751 bool MadeChange = MoveExtToFormExtLoad(I);
2752 return MadeChange | OptimizeExtUses(I);
Cameron Zwarich14ac8652011-01-06 02:37:26 +00002753 }
Chris Lattneree588de2011-01-15 07:29:01 +00002754 return false;
2755 }
Nadav Rotem465834c2012-07-24 10:51:42 +00002756
Chris Lattneree588de2011-01-15 07:29:01 +00002757 if (CmpInst *CI = dyn_cast<CmpInst>(I))
Hal Finkeldecb0242014-01-02 21:13:43 +00002758 if (!TLI || !TLI->hasMultipleConditionRegisters())
2759 return OptimizeCmpExpression(CI);
Nadav Rotem465834c2012-07-24 10:51:42 +00002760
Chris Lattneree588de2011-01-15 07:29:01 +00002761 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00002762 if (TLI)
Hans Wennborgf3254832012-10-30 11:23:25 +00002763 return OptimizeMemoryInst(I, I->getOperand(0), LI->getType());
2764 return false;
Chris Lattneree588de2011-01-15 07:29:01 +00002765 }
Nadav Rotem465834c2012-07-24 10:51:42 +00002766
Chris Lattneree588de2011-01-15 07:29:01 +00002767 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00002768 if (TLI)
Chris Lattneree588de2011-01-15 07:29:01 +00002769 return OptimizeMemoryInst(I, SI->getOperand(1),
2770 SI->getOperand(0)->getType());
2771 return false;
2772 }
Nadav Rotem465834c2012-07-24 10:51:42 +00002773
Chris Lattneree588de2011-01-15 07:29:01 +00002774 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00002775 if (GEPI->hasAllZeroIndices()) {
2776 /// The GEP operand must be a pointer, so must its result -> BitCast
2777 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
2778 GEPI->getName(), GEPI);
2779 GEPI->replaceAllUsesWith(NC);
2780 GEPI->eraseFromParent();
2781 ++NumGEPsElim;
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00002782 OptimizeInst(NC);
Chris Lattneree588de2011-01-15 07:29:01 +00002783 return true;
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00002784 }
Chris Lattneree588de2011-01-15 07:29:01 +00002785 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00002786 }
Nadav Rotem465834c2012-07-24 10:51:42 +00002787
Chris Lattneree588de2011-01-15 07:29:01 +00002788 if (CallInst *CI = dyn_cast<CallInst>(I))
2789 return OptimizeCallInst(CI);
Cameron Zwarich14ac8652011-01-06 02:37:26 +00002790
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00002791 if (SelectInst *SI = dyn_cast<SelectInst>(I))
2792 return OptimizeSelectInst(SI);
2793
Chris Lattneree588de2011-01-15 07:29:01 +00002794 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00002795}
2796
Chris Lattnerf2836d12007-03-31 04:06:36 +00002797// In this pass we look for GEP and cast instructions that are used
2798// across basic blocks and rewrite them to improve basic-block-at-a-time
2799// selection.
2800bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
Cameron Zwarichce3b9302011-01-06 00:42:50 +00002801 SunkAddrs.clear();
Cameron Zwarich5dd2aa22011-03-02 03:31:46 +00002802 bool MadeChange = false;
Eric Christopherc1ea1492008-09-24 05:32:41 +00002803
Chris Lattner7a277142011-01-15 07:14:54 +00002804 CurInstIterator = BB.begin();
Hans Wennborg02fbc712012-09-19 07:48:16 +00002805 while (CurInstIterator != BB.end())
Chris Lattner1b93be52011-01-15 07:25:29 +00002806 MadeChange |= OptimizeInst(CurInstIterator++);
Eric Christopherc1ea1492008-09-24 05:32:41 +00002807
Benjamin Kramer455fa352012-11-23 19:17:06 +00002808 MadeChange |= DupRetToEnableTailCallOpts(&BB);
2809
Chris Lattnerf2836d12007-03-31 04:06:36 +00002810 return MadeChange;
2811}
Devang Patel53771ba2011-08-18 00:50:51 +00002812
2813// llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotem465834c2012-07-24 10:51:42 +00002814// handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patel53771ba2011-08-18 00:50:51 +00002815// find a node corresponding to the value.
2816bool CodeGenPrepare::PlaceDbgValues(Function &F) {
2817 bool MadeChange = false;
2818 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
2819 Instruction *PrevNonDbgInst = NULL;
2820 for (BasicBlock::iterator BI = I->begin(), BE = I->end(); BI != BE;) {
2821 Instruction *Insn = BI; ++BI;
2822 DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
2823 if (!DVI) {
2824 PrevNonDbgInst = Insn;
2825 continue;
2826 }
2827
2828 Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
2829 if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
2830 DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
2831 DVI->removeFromParent();
2832 if (isa<PHINode>(VI))
2833 DVI->insertBefore(VI->getParent()->getFirstInsertionPt());
2834 else
2835 DVI->insertAfter(VI);
2836 MadeChange = true;
2837 ++NumDbgValueMoved;
2838 }
2839 }
2840 }
2841 return MadeChange;
2842}