blob: 72d6ac5636251a6c0692115e6e933bf6df41936c [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"
Quentin Colombeta3490842014-02-22 00:07:45 +000017#include "llvm/CodeGen/Passes.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"
Chandler Carruthed0881b2012-12-03 16:50:05 +000021#include "llvm/Analysis/InstructionSimplify.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000022#include "llvm/IR/CallSite.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"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000028#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000029#include "llvm/IR/IRBuilder.h"
30#include "llvm/IR/InlineAsm.h"
31#include "llvm/IR/Instructions.h"
32#include "llvm/IR/IntrinsicInst.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000033#include "llvm/IR/PatternMatch.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +000034#include "llvm/IR/ValueHandle.h"
Chandler Carrutha4ea2692014-03-04 11:26:31 +000035#include "llvm/IR/ValueMap.h"
Chris Lattnerf2836d12007-03-31 04:06:36 +000036#include "llvm/Pass.h"
Evan Cheng8b637b12010-08-17 01:34:49 +000037#include "llvm/Support/CommandLine.h"
Evan Chengd3d80172007-12-05 23:58:20 +000038#include "llvm/Support/Debug.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");
Tim Northovercea0abb2014-03-29 08:22:29 +000063STATISTIC(NumAndCmpsMoved, "Number of and/cmp's pushed into branches");
Jakob Stoklund Oleseneb12f492010-09-30 20:51:52 +000064
Cameron Zwarich338d3622011-03-11 21:52:04 +000065static cl::opt<bool> DisableBranchOpts(
66 "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
67 cl::desc("Disable branch optimizations in CodeGenPrepare"));
68
Benjamin Kramer3d38c172012-05-06 14:25:16 +000069static cl::opt<bool> DisableSelectToBranch(
70 "disable-cgp-select2branch", cl::Hidden, cl::init(false),
71 cl::desc("Disable select to branch conversion."));
Benjamin Kramer047d7ca2012-05-05 12:49:22 +000072
Tim Northovercea0abb2014-03-29 08:22:29 +000073static cl::opt<bool> EnableAndCmpSinking(
74 "enable-andcmp-sinking", cl::Hidden, cl::init(true),
75 cl::desc("Enable sinkinig and/cmp into branches."));
76
Eric Christopherc1ea1492008-09-24 05:32:41 +000077namespace {
Quentin Colombet3a4bf042014-02-06 21:44:56 +000078typedef SmallPtrSet<Instruction *, 16> SetOfInstrs;
79typedef DenseMap<Instruction *, Type *> InstrToOrigTy;
80
Chris Lattner2dd09db2009-09-02 06:11:42 +000081 class CodeGenPrepare : public FunctionPass {
Chris Lattnerf2836d12007-03-31 04:06:36 +000082 /// TLI - Keep a pointer of a TargetLowering to consult for determining
83 /// transformation profitability.
Bill Wendling7a639ea2013-06-19 21:07:11 +000084 const TargetMachine *TM;
Chris Lattnerf2836d12007-03-31 04:06:36 +000085 const TargetLowering *TLI;
Chad Rosierc24b86f2011-12-01 03:08:23 +000086 const TargetLibraryInfo *TLInfo;
Cameron Zwarich84986b22011-01-08 17:01:52 +000087 DominatorTree *DT;
Nadav Rotem465834c2012-07-24 10:51:42 +000088
Chris Lattner7a277142011-01-15 07:14:54 +000089 /// CurInstIterator - As we scan instructions optimizing them, this is the
90 /// next instruction to optimize. Xforms that can invalidate this should
91 /// update it.
92 BasicBlock::iterator CurInstIterator;
Evan Cheng3b3de7c2008-12-19 18:03:11 +000093
Evan Cheng0663f232011-03-21 01:19:09 +000094 /// Keeps track of non-local addresses that have been sunk into a block.
95 /// This allows us to avoid inserting duplicate code for blocks with
96 /// multiple load/stores of the same address.
Nick Lewycky5fb19632013-05-08 09:00:10 +000097 ValueMap<Value*, Value*> SunkAddrs;
Cameron Zwarichce3b9302011-01-06 00:42:50 +000098
Quentin Colombet3a4bf042014-02-06 21:44:56 +000099 /// Keeps track of all truncates inserted for the current function.
100 SetOfInstrs InsertedTruncsSet;
101 /// Keeps track of the type of the related instruction before their
102 /// promotion for the current function.
103 InstrToOrigTy PromotedInsts;
104
Devang Patel8f606d72011-03-24 15:35:25 +0000105 /// ModifiedDT - If CFG is modified in anyway, dominator tree may need to
Evan Cheng0663f232011-03-21 01:19:09 +0000106 /// be updated.
Devang Patel8f606d72011-03-24 15:35:25 +0000107 bool ModifiedDT;
Evan Cheng0663f232011-03-21 01:19:09 +0000108
Benjamin Kramer047d7ca2012-05-05 12:49:22 +0000109 /// OptSize - True if optimizing for size.
110 bool OptSize;
111
Chris Lattnerf2836d12007-03-31 04:06:36 +0000112 public:
Nick Lewyckye7da2d62007-05-06 13:37:16 +0000113 static char ID; // Pass identification, replacement for typeid
Bill Wendling7a639ea2013-06-19 21:07:11 +0000114 explicit CodeGenPrepare(const TargetMachine *TM = 0)
115 : FunctionPass(ID), TM(TM), TLI(0) {
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000116 initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
117 }
Craig Topper4584cd52014-03-07 09:26:03 +0000118 bool runOnFunction(Function &F) override;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000119
Craig Topper4584cd52014-03-07 09:26:03 +0000120 const char *getPassName() const override { return "CodeGen Prepare"; }
Evan Cheng99cafb12012-12-21 01:48:14 +0000121
Craig Topper4584cd52014-03-07 09:26:03 +0000122 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruth73523022014-01-13 13:07:17 +0000123 AU.addPreserved<DominatorTreeWrapperPass>();
Chad Rosierc24b86f2011-12-01 03:08:23 +0000124 AU.addRequired<TargetLibraryInfo>();
Andreas Neustifterf8cb7582009-09-16 09:26:52 +0000125 }
126
Chris Lattnerf2836d12007-03-31 04:06:36 +0000127 private:
Nadav Rotem70409992012-08-14 05:19:07 +0000128 bool EliminateFallThrough(Function &F);
Chris Lattnerc3748562007-04-02 01:35:34 +0000129 bool EliminateMostlyEmptyBlocks(Function &F);
130 bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
131 void EliminateMostlyEmptyBlock(BasicBlock *BB);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000132 bool OptimizeBlock(BasicBlock &BB);
Cameron Zwarich14ac8652011-01-06 02:37:26 +0000133 bool OptimizeInst(Instruction *I);
Chris Lattner229907c2011-07-18 04:54:35 +0000134 bool OptimizeMemoryInst(Instruction *I, Value *Addr, Type *AccessTy);
Chris Lattner7a277142011-01-15 07:14:54 +0000135 bool OptimizeInlineAsmInst(CallInst *CS);
Eric Christopher4b7948e2010-03-11 02:41:03 +0000136 bool OptimizeCallInst(CallInst *CI);
Dan Gohman99429a02009-10-16 20:59:35 +0000137 bool MoveExtToFormExtLoad(Instruction *I);
Evan Chengd3d80172007-12-05 23:58:20 +0000138 bool OptimizeExtUses(Instruction *I);
Benjamin Kramer047d7ca2012-05-05 12:49:22 +0000139 bool OptimizeSelectInst(SelectInst *SI);
Tim Northoveraeb8e062014-02-19 10:02:43 +0000140 bool OptimizeShuffleVectorInst(ShuffleVectorInst *SI);
Benjamin Kramer455fa352012-11-23 19:17:06 +0000141 bool DupRetToEnableTailCallOpts(BasicBlock *BB);
Devang Patel53771ba2011-08-18 00:50:51 +0000142 bool PlaceDbgValues(Function &F);
Tim Northovercea0abb2014-03-29 08:22:29 +0000143 bool sinkAndCmp(Function &F);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000144 };
145}
Devang Patel09f162c2007-05-01 21:15:47 +0000146
Devang Patel8c78a0b2007-05-03 01:11:54 +0000147char CodeGenPrepare::ID = 0;
Quentin Colombetdc0b2ea2014-01-16 21:44:34 +0000148static void *initializeCodeGenPreparePassOnce(PassRegistry &Registry) {
149 initializeTargetLibraryInfoPass(Registry);
150 PassInfo *PI = new PassInfo(
151 "Optimize for code generation", "codegenprepare", &CodeGenPrepare::ID,
152 PassInfo::NormalCtor_t(callDefaultCtor<CodeGenPrepare>), false, false,
153 PassInfo::TargetMachineCtor_t(callTargetMachineCtor<CodeGenPrepare>));
154 Registry.registerPass(*PI, true);
155 return PI;
156}
157
158void llvm::initializeCodeGenPreparePass(PassRegistry &Registry) {
159 CALL_ONCE_INITIALIZATION(initializeCodeGenPreparePassOnce)
160}
Chris Lattnerf2836d12007-03-31 04:06:36 +0000161
Bill Wendling7a639ea2013-06-19 21:07:11 +0000162FunctionPass *llvm::createCodeGenPreparePass(const TargetMachine *TM) {
163 return new CodeGenPrepare(TM);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000164}
165
Chris Lattnerf2836d12007-03-31 04:06:36 +0000166bool CodeGenPrepare::runOnFunction(Function &F) {
Chris Lattnerf2836d12007-03-31 04:06:36 +0000167 bool EverMadeChange = false;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000168 // Clear per function information.
169 InsertedTruncsSet.clear();
170 PromotedInsts.clear();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000171
Devang Patel8f606d72011-03-24 15:35:25 +0000172 ModifiedDT = false;
Bill Wendling7a639ea2013-06-19 21:07:11 +0000173 if (TM) TLI = TM->getTargetLowering();
Chad Rosierc24b86f2011-12-01 03:08:23 +0000174 TLInfo = &getAnalysis<TargetLibraryInfo>();
Chandler Carruth73523022014-01-13 13:07:17 +0000175 DominatorTreeWrapperPass *DTWP =
176 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
177 DT = DTWP ? &DTWP->getDomTree() : 0;
Bill Wendling698e84f2012-12-30 10:32:01 +0000178 OptSize = F.getAttributes().hasAttribute(AttributeSet::FunctionIndex,
179 Attribute::OptimizeForSize);
Evan Cheng0663f232011-03-21 01:19:09 +0000180
Preston Gurdcdf540d2012-09-04 18:22:17 +0000181 /// This optimization identifies DIV instructions that can be
182 /// profitably bypassed and carried out with a shorter, faster divide.
Preston Gurd485296d2013-03-04 18:13:57 +0000183 if (!OptSize && TLI && TLI->isSlowDivBypassed()) {
Preston Gurd0d67f512012-10-04 21:33:40 +0000184 const DenseMap<unsigned int, unsigned int> &BypassWidths =
185 TLI->getBypassSlowDivWidths();
Evan Cheng71be12b2012-09-14 21:25:34 +0000186 for (Function::iterator I = F.begin(); I != F.end(); I++)
Preston Gurd0d67f512012-10-04 21:33:40 +0000187 EverMadeChange |= bypassSlowDivision(F, I, BypassWidths);
Preston Gurdcdf540d2012-09-04 18:22:17 +0000188 }
189
190 // Eliminate blocks that contain only PHI nodes and an
Chris Lattnerc3748562007-04-02 01:35:34 +0000191 // unconditional branch.
192 EverMadeChange |= EliminateMostlyEmptyBlocks(F);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000193
Devang Patel53771ba2011-08-18 00:50:51 +0000194 // llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotem465834c2012-07-24 10:51:42 +0000195 // handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patel53771ba2011-08-18 00:50:51 +0000196 // find a node corresponding to the value.
197 EverMadeChange |= PlaceDbgValues(F);
198
Tim Northovercea0abb2014-03-29 08:22:29 +0000199 // If there is a mask, compare against zero, and branch that can be combined
200 // into a single target instruction, push the mask and compare into branch
201 // users. Do this before OptimizeBlock -> OptimizeInst ->
202 // OptimizeCmpExpression, which perturbs the pattern being searched for.
203 if (!DisableBranchOpts)
204 EverMadeChange |= sinkAndCmp(F);
205
Chris Lattnerc3748562007-04-02 01:35:34 +0000206 bool MadeChange = true;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000207 while (MadeChange) {
208 MadeChange = false;
Hans Wennborg02fbc712012-09-19 07:48:16 +0000209 for (Function::iterator I = F.begin(); I != F.end(); ) {
Evan Cheng0663f232011-03-21 01:19:09 +0000210 BasicBlock *BB = I++;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000211 MadeChange |= OptimizeBlock(*BB);
Evan Cheng0663f232011-03-21 01:19:09 +0000212 }
Chris Lattnerf2836d12007-03-31 04:06:36 +0000213 EverMadeChange |= MadeChange;
214 }
Cameron Zwarichce3b9302011-01-06 00:42:50 +0000215
216 SunkAddrs.clear();
217
Cameron Zwarich338d3622011-03-11 21:52:04 +0000218 if (!DisableBranchOpts) {
219 MadeChange = false;
Bill Wendling97b93592012-03-04 10:46:01 +0000220 SmallPtrSet<BasicBlock*, 8> WorkList;
221 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
222 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
Frits van Bommelad964552011-05-22 16:24:18 +0000223 MadeChange |= ConstantFoldTerminator(BB, true);
Bill Wendling97b93592012-03-04 10:46:01 +0000224 if (!MadeChange) continue;
225
226 for (SmallVectorImpl<BasicBlock*>::iterator
227 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
228 if (pred_begin(*II) == pred_end(*II))
229 WorkList.insert(*II);
230 }
231
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000232 // Delete the dead blocks and any of their dead successors.
Bill Wendlingab417b62012-12-06 00:30:20 +0000233 MadeChange |= !WorkList.empty();
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000234 while (!WorkList.empty()) {
235 BasicBlock *BB = *WorkList.begin();
236 WorkList.erase(BB);
237 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
238
239 DeleteDeadBlock(BB);
Stephen Lin837bba12013-07-15 17:55:02 +0000240
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000241 for (SmallVectorImpl<BasicBlock*>::iterator
242 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
243 if (pred_begin(*II) == pred_end(*II))
244 WorkList.insert(*II);
245 }
Cameron Zwarich338d3622011-03-11 21:52:04 +0000246
Nadav Rotem70409992012-08-14 05:19:07 +0000247 // Merge pairs of basic blocks with unconditional branches, connected by
248 // a single edge.
249 if (EverMadeChange || MadeChange)
250 MadeChange |= EliminateFallThrough(F);
251
Evan Cheng0663f232011-03-21 01:19:09 +0000252 if (MadeChange)
Devang Patel8f606d72011-03-24 15:35:25 +0000253 ModifiedDT = true;
Cameron Zwarich338d3622011-03-11 21:52:04 +0000254 EverMadeChange |= MadeChange;
255 }
256
Devang Patel8f606d72011-03-24 15:35:25 +0000257 if (ModifiedDT && DT)
Chandler Carruth73523022014-01-13 13:07:17 +0000258 DT->recalculate(F);
Evan Cheng0663f232011-03-21 01:19:09 +0000259
Chris Lattnerf2836d12007-03-31 04:06:36 +0000260 return EverMadeChange;
261}
262
Nadav Rotem70409992012-08-14 05:19:07 +0000263/// EliminateFallThrough - Merge basic blocks which are connected
264/// by a single edge, where one of the basic blocks has a single successor
265/// pointing to the other basic block, which has a single predecessor.
266bool CodeGenPrepare::EliminateFallThrough(Function &F) {
267 bool Changed = false;
268 // Scan all of the blocks in the function, except for the entry block.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000269 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
Nadav Rotem70409992012-08-14 05:19:07 +0000270 BasicBlock *BB = I++;
271 // If the destination block has a single pred, then this is a trivial
272 // edge, just collapse it.
273 BasicBlock *SinglePred = BB->getSinglePredecessor();
274
Evan Cheng64a223a2012-09-28 23:58:57 +0000275 // Don't merge if BB's address is taken.
276 if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue;
Nadav Rotem70409992012-08-14 05:19:07 +0000277
278 BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
279 if (Term && !Term->isConditional()) {
280 Changed = true;
Michael Liao6e12d122012-08-21 05:55:22 +0000281 DEBUG(dbgs() << "To merge:\n"<< *SinglePred << "\n\n\n");
Nadav Rotem70409992012-08-14 05:19:07 +0000282 // Remember if SinglePred was the entry block of the function.
283 // If so, we will need to move BB back to the entry position.
284 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
285 MergeBasicBlockIntoOnlyPred(BB, this);
286
287 if (isEntry && BB != &BB->getParent()->getEntryBlock())
288 BB->moveBefore(&BB->getParent()->getEntryBlock());
289
290 // We have erased a block. Update the iterator.
291 I = BB;
Nadav Rotem70409992012-08-14 05:19:07 +0000292 }
293 }
294 return Changed;
295}
296
Dale Johannesen4026b042009-03-27 01:13:37 +0000297/// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes,
298/// debug info directives, and an unconditional branch. Passes before isel
299/// (e.g. LSR/loopsimplify) often split edges in ways that are non-optimal for
300/// isel. Start by eliminating these blocks so we can split them the way we
301/// want them.
Chris Lattnerc3748562007-04-02 01:35:34 +0000302bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
303 bool MadeChange = false;
304 // Note that this intentionally skips the entry block.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000305 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
Chris Lattnerc3748562007-04-02 01:35:34 +0000306 BasicBlock *BB = I++;
307
308 // If this block doesn't end with an uncond branch, ignore it.
309 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
310 if (!BI || !BI->isUnconditional())
311 continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000312
Dale Johannesen4026b042009-03-27 01:13:37 +0000313 // If the instruction before the branch (skipping debug info) isn't a phi
314 // node, then other stuff is happening here.
Chris Lattnerc3748562007-04-02 01:35:34 +0000315 BasicBlock::iterator BBI = BI;
316 if (BBI != BB->begin()) {
317 --BBI;
Dale Johannesen4026b042009-03-27 01:13:37 +0000318 while (isa<DbgInfoIntrinsic>(BBI)) {
319 if (BBI == BB->begin())
320 break;
321 --BBI;
322 }
323 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
324 continue;
Chris Lattnerc3748562007-04-02 01:35:34 +0000325 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000326
Chris Lattnerc3748562007-04-02 01:35:34 +0000327 // Do not break infinite loops.
328 BasicBlock *DestBB = BI->getSuccessor(0);
329 if (DestBB == BB)
330 continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000331
Chris Lattnerc3748562007-04-02 01:35:34 +0000332 if (!CanMergeBlocks(BB, DestBB))
333 continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000334
Chris Lattnerc3748562007-04-02 01:35:34 +0000335 EliminateMostlyEmptyBlock(BB);
336 MadeChange = true;
337 }
338 return MadeChange;
339}
340
341/// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
342/// single uncond branch between them, and BB contains no other non-phi
343/// instructions.
344bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
345 const BasicBlock *DestBB) const {
346 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
347 // the successor. If there are more complex condition (e.g. preheaders),
348 // don't mess around with them.
349 BasicBlock::const_iterator BBI = BB->begin();
350 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000351 for (const User *U : PN->users()) {
352 const Instruction *UI = cast<Instruction>(U);
353 if (UI->getParent() != DestBB || !isa<PHINode>(UI))
Chris Lattnerc3748562007-04-02 01:35:34 +0000354 return false;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000355 // If User is inside DestBB block and it is a PHINode then check
356 // incoming value. If incoming value is not from BB then this is
Devang Pateld3208522007-04-25 00:37:04 +0000357 // a complex condition (e.g. preheaders) we want to avoid here.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000358 if (UI->getParent() == DestBB) {
359 if (const PHINode *UPN = dyn_cast<PHINode>(UI))
Devang Pateld3208522007-04-25 00:37:04 +0000360 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
361 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
362 if (Insn && Insn->getParent() == BB &&
363 Insn->getParent() != UPN->getIncomingBlock(I))
364 return false;
365 }
366 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000367 }
368 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000369
Chris Lattnerc3748562007-04-02 01:35:34 +0000370 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
371 // and DestBB may have conflicting incoming values for the block. If so, we
372 // can't merge the block.
373 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
374 if (!DestBBPN) return true; // no conflict.
Eric Christopherc1ea1492008-09-24 05:32:41 +0000375
Chris Lattnerc3748562007-04-02 01:35:34 +0000376 // Collect the preds of BB.
Chris Lattner8201a9b2007-11-06 22:07:40 +0000377 SmallPtrSet<const BasicBlock*, 16> BBPreds;
Chris Lattnerc3748562007-04-02 01:35:34 +0000378 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
379 // It is faster to get preds from a PHI than with pred_iterator.
380 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
381 BBPreds.insert(BBPN->getIncomingBlock(i));
382 } else {
383 BBPreds.insert(pred_begin(BB), pred_end(BB));
384 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000385
Chris Lattnerc3748562007-04-02 01:35:34 +0000386 // Walk the preds of DestBB.
387 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
388 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
389 if (BBPreds.count(Pred)) { // Common predecessor?
390 BBI = DestBB->begin();
391 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
392 const Value *V1 = PN->getIncomingValueForBlock(Pred);
393 const Value *V2 = PN->getIncomingValueForBlock(BB);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000394
Chris Lattnerc3748562007-04-02 01:35:34 +0000395 // If V2 is a phi node in BB, look up what the mapped value will be.
396 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
397 if (V2PN->getParent() == BB)
398 V2 = V2PN->getIncomingValueForBlock(Pred);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000399
Chris Lattnerc3748562007-04-02 01:35:34 +0000400 // If there is a conflict, bail out.
401 if (V1 != V2) return false;
402 }
403 }
404 }
405
406 return true;
407}
408
409
410/// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
411/// an unconditional branch in it.
412void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
413 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
414 BasicBlock *DestBB = BI->getSuccessor(0);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000415
David Greene74e2d492010-01-05 01:27:11 +0000416 DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000417
Chris Lattnerc3748562007-04-02 01:35:34 +0000418 // If the destination block has a single pred, then this is a trivial edge,
419 // just collapse it.
Chris Lattner4059f432008-11-27 19:29:14 +0000420 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
Chris Lattner8a172da2008-11-28 19:54:49 +0000421 if (SinglePred != DestBB) {
422 // Remember if SinglePred was the entry block of the function. If so, we
423 // will need to move BB back to the entry position.
424 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Andreas Neustifterf8cb7582009-09-16 09:26:52 +0000425 MergeBasicBlockIntoOnlyPred(DestBB, this);
Chris Lattner4059f432008-11-27 19:29:14 +0000426
Chris Lattner8a172da2008-11-28 19:54:49 +0000427 if (isEntry && BB != &BB->getParent()->getEntryBlock())
428 BB->moveBefore(&BB->getParent()->getEntryBlock());
Nadav Rotem465834c2012-07-24 10:51:42 +0000429
David Greene74e2d492010-01-05 01:27:11 +0000430 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattner8a172da2008-11-28 19:54:49 +0000431 return;
432 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000433 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000434
Chris Lattnerc3748562007-04-02 01:35:34 +0000435 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
436 // to handle the new incoming edges it is about to have.
437 PHINode *PN;
438 for (BasicBlock::iterator BBI = DestBB->begin();
439 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
440 // Remove the incoming value for BB, and remember it.
441 Value *InVal = PN->removeIncomingValue(BB, false);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000442
Chris Lattnerc3748562007-04-02 01:35:34 +0000443 // Two options: either the InVal is a phi node defined in BB or it is some
444 // value that dominates BB.
445 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
446 if (InValPhi && InValPhi->getParent() == BB) {
447 // Add all of the input values of the input PHI as inputs of this phi.
448 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
449 PN->addIncoming(InValPhi->getIncomingValue(i),
450 InValPhi->getIncomingBlock(i));
451 } else {
452 // Otherwise, add one instance of the dominating value for each edge that
453 // we will be adding.
454 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
455 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
456 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
457 } else {
458 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
459 PN->addIncoming(InVal, *PI);
460 }
461 }
462 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000463
Chris Lattnerc3748562007-04-02 01:35:34 +0000464 // The PHIs are now updated, change everything that refers to BB to use
465 // DestBB and remove BB.
466 BB->replaceAllUsesWith(DestBB);
Devang Patel8f606d72011-03-24 15:35:25 +0000467 if (DT && !ModifiedDT) {
Cameron Zwarich84986b22011-01-08 17:01:52 +0000468 BasicBlock *BBIDom = DT->getNode(BB)->getIDom()->getBlock();
469 BasicBlock *DestBBIDom = DT->getNode(DestBB)->getIDom()->getBlock();
470 BasicBlock *NewIDom = DT->findNearestCommonDominator(BBIDom, DestBBIDom);
471 DT->changeImmediateDominator(DestBB, NewIDom);
472 DT->eraseNode(BB);
473 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000474 BB->eraseFromParent();
Cameron Zwarichced753f2011-01-05 17:27:27 +0000475 ++NumBlocksElim;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000476
David Greene74e2d492010-01-05 01:27:11 +0000477 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerc3748562007-04-02 01:35:34 +0000478}
479
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000480/// SinkCast - Sink the specified cast instruction into its user blocks
481static bool SinkCast(CastInst *CI) {
Chris Lattnerf2836d12007-03-31 04:06:36 +0000482 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000483
Chris Lattnerf2836d12007-03-31 04:06:36 +0000484 /// InsertedCasts - Only insert a cast in each block once.
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000485 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000486
Chris Lattnerf2836d12007-03-31 04:06:36 +0000487 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000488 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
Chris Lattnerf2836d12007-03-31 04:06:36 +0000489 UI != E; ) {
490 Use &TheUse = UI.getUse();
491 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000492
Chris Lattnerf2836d12007-03-31 04:06:36 +0000493 // Figure out which BB this cast is used in. For PHI's this is the
494 // appropriate predecessor block.
495 BasicBlock *UserBB = User->getParent();
496 if (PHINode *PN = dyn_cast<PHINode>(User)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000497 UserBB = PN->getIncomingBlock(TheUse);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000498 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000499
Chris Lattnerf2836d12007-03-31 04:06:36 +0000500 // Preincrement use iterator so we don't invalidate it.
501 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000502
Chris Lattnerf2836d12007-03-31 04:06:36 +0000503 // If this user is in the same block as the cast, don't change the cast.
504 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000505
Chris Lattnerf2836d12007-03-31 04:06:36 +0000506 // If we have already inserted a cast into this block, use it.
507 CastInst *&InsertedCast = InsertedCasts[UserBB];
508
509 if (!InsertedCast) {
Bill Wendling8ddfc092011-08-16 20:45:24 +0000510 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000511 InsertedCast =
512 CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
Chris Lattnerf2836d12007-03-31 04:06:36 +0000513 InsertPt);
514 MadeChange = true;
515 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000516
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000517 // Replace a use of the cast with a use of the new cast.
Chris Lattnerf2836d12007-03-31 04:06:36 +0000518 TheUse = InsertedCast;
Cameron Zwarichced753f2011-01-05 17:27:27 +0000519 ++NumCastUses;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000520 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000521
Chris Lattnerf2836d12007-03-31 04:06:36 +0000522 // If we removed all uses, nuke the cast.
Duncan Sandsafa84da42008-01-20 16:51:46 +0000523 if (CI->use_empty()) {
Chris Lattnerf2836d12007-03-31 04:06:36 +0000524 CI->eraseFromParent();
Duncan Sandsafa84da42008-01-20 16:51:46 +0000525 MadeChange = true;
526 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000527
Chris Lattnerf2836d12007-03-31 04:06:36 +0000528 return MadeChange;
529}
530
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000531/// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
532/// copy (e.g. it's casting from one pointer type to another, i32->i8 on PPC),
533/// sink it into user blocks to reduce the number of virtual
534/// registers that must be created and coalesced.
535///
536/// Return true if any changes are made.
537///
538static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
539 // If this is a noop copy,
540 EVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
541 EVT DstVT = TLI.getValueType(CI->getType());
542
543 // This is an fp<->int conversion?
544 if (SrcVT.isInteger() != DstVT.isInteger())
545 return false;
546
547 // If this is an extension, it will be a zero or sign extension, which
548 // isn't a noop.
549 if (SrcVT.bitsLT(DstVT)) return false;
550
551 // If these values will be promoted, find out what they will be promoted
552 // to. This helps us consider truncates on PPC as noop copies when they
553 // are.
554 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
555 TargetLowering::TypePromoteInteger)
556 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
557 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
558 TargetLowering::TypePromoteInteger)
559 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
560
561 // If, after promotion, these are the same types, this is a noop copy.
562 if (SrcVT != DstVT)
563 return false;
564
565 return SinkCast(CI);
566}
567
Eric Christopherc1ea1492008-09-24 05:32:41 +0000568/// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000569/// the number of virtual registers that must be created and coalesced. This is
Chris Lattner27406942007-08-02 16:53:43 +0000570/// a clear win except on targets with multiple condition code registers
571/// (PowerPC), where it might lose; some adjustment may be wanted there.
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000572///
573/// Return true if any changes are made.
Chris Lattner6416a6b2008-11-24 22:44:16 +0000574static bool OptimizeCmpExpression(CmpInst *CI) {
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000575 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000576
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000577 /// InsertedCmp - Only insert a cmp in each block once.
578 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000579
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000580 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000581 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000582 UI != E; ) {
583 Use &TheUse = UI.getUse();
584 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000585
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000586 // Preincrement use iterator so we don't invalidate it.
587 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000588
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000589 // Don't bother for PHI nodes.
590 if (isa<PHINode>(User))
591 continue;
592
593 // Figure out which BB this cmp is used in.
594 BasicBlock *UserBB = User->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000595
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000596 // If this user is in the same block as the cmp, don't change the cmp.
597 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000598
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000599 // If we have already inserted a cmp into this block, use it.
600 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
601
602 if (!InsertedCmp) {
Bill Wendling8ddfc092011-08-16 20:45:24 +0000603 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000604 InsertedCmp =
Dan Gohmanad1f0a12009-08-25 23:17:54 +0000605 CmpInst::Create(CI->getOpcode(),
Owen Anderson1e5f00e2009-07-09 23:48:35 +0000606 CI->getPredicate(), CI->getOperand(0),
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000607 CI->getOperand(1), "", InsertPt);
608 MadeChange = true;
609 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000610
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000611 // Replace a use of the cmp with a use of the new cmp.
612 TheUse = InsertedCmp;
Cameron Zwarichced753f2011-01-05 17:27:27 +0000613 ++NumCmpUses;
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000614 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000615
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000616 // If we removed all uses, nuke the cmp.
617 if (CI->use_empty())
618 CI->eraseFromParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000619
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000620 return MadeChange;
621}
622
Benjamin Kramer7b88a492010-03-12 09:27:41 +0000623namespace {
624class CodeGenPrepareFortifiedLibCalls : public SimplifyFortifiedLibCalls {
625protected:
Craig Topper4584cd52014-03-07 09:26:03 +0000626 void replaceCall(Value *With) override {
Benjamin Kramer7b88a492010-03-12 09:27:41 +0000627 CI->replaceAllUsesWith(With);
628 CI->eraseFromParent();
629 }
Craig Topper4584cd52014-03-07 09:26:03 +0000630 bool isFoldable(unsigned SizeCIOp, unsigned, bool) const override {
Gabor Greif6d673952010-07-16 09:38:02 +0000631 if (ConstantInt *SizeCI =
632 dyn_cast<ConstantInt>(CI->getArgOperand(SizeCIOp)))
633 return SizeCI->isAllOnesValue();
Benjamin Kramer7b88a492010-03-12 09:27:41 +0000634 return false;
635 }
636};
637} // end anonymous namespace
638
Eric Christopher4b7948e2010-03-11 02:41:03 +0000639bool CodeGenPrepare::OptimizeCallInst(CallInst *CI) {
Chris Lattner7a277142011-01-15 07:14:54 +0000640 BasicBlock *BB = CI->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +0000641
Chris Lattner7a277142011-01-15 07:14:54 +0000642 // Lower inline assembly if we can.
643 // If we found an inline asm expession, and if the target knows how to
644 // lower it to normal LLVM code, do so now.
645 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
646 if (TLI->ExpandInlineAsm(CI)) {
647 // Avoid invalidating the iterator.
648 CurInstIterator = BB->begin();
649 // Avoid processing instructions out of order, which could cause
650 // reuse before a value is defined.
651 SunkAddrs.clear();
652 return true;
653 }
654 // Sink address computing for memory operands into the block.
655 if (OptimizeInlineAsmInst(CI))
656 return true;
657 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000658
Eric Christopher4b7948e2010-03-11 02:41:03 +0000659 // Lower all uses of llvm.objectsize.*
660 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
661 if (II && II->getIntrinsicID() == Intrinsic::objectsize) {
Gabor Greif4a39b842010-06-24 00:44:01 +0000662 bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
Chris Lattner229907c2011-07-18 04:54:35 +0000663 Type *ReturnTy = CI->getType();
Nadav Rotem465834c2012-07-24 10:51:42 +0000664 Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
665
Chris Lattner1b93be52011-01-15 07:25:29 +0000666 // Substituting this can cause recursive simplifications, which can
667 // invalidate our iterator. Use a WeakVH to hold onto it in case this
668 // happens.
669 WeakVH IterHandle(CurInstIterator);
Nadav Rotem465834c2012-07-24 10:51:42 +0000670
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000671 replaceAndRecursivelySimplify(CI, RetVal, TLI ? TLI->getDataLayout() : 0,
Chandler Carruthcf1b5852012-03-24 21:11:24 +0000672 TLInfo, ModifiedDT ? 0 : DT);
Chris Lattner1b93be52011-01-15 07:25:29 +0000673
674 // If the iterator instruction was recursively deleted, start over at the
675 // start of the block.
Chris Lattner86d56c62011-01-18 20:53:04 +0000676 if (IterHandle != CurInstIterator) {
Chris Lattner1b93be52011-01-15 07:25:29 +0000677 CurInstIterator = BB->begin();
Chris Lattner86d56c62011-01-18 20:53:04 +0000678 SunkAddrs.clear();
679 }
Eric Christopher4b7948e2010-03-11 02:41:03 +0000680 return true;
681 }
682
Pete Cooper615fd892012-03-13 20:59:56 +0000683 if (II && TLI) {
684 SmallVector<Value*, 2> PtrOps;
685 Type *AccessTy;
686 if (TLI->GetAddrModeArguments(II, PtrOps, AccessTy))
687 while (!PtrOps.empty())
688 if (OptimizeMemoryInst(II, PtrOps.pop_back_val(), AccessTy))
689 return true;
690 }
691
Eric Christopher4b7948e2010-03-11 02:41:03 +0000692 // From here on out we're working with named functions.
693 if (CI->getCalledFunction() == 0) return false;
Devang Patel0da52502011-05-26 21:51:06 +0000694
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000695 // We'll need DataLayout from here on out.
696 const DataLayout *TD = TLI ? TLI->getDataLayout() : 0;
Eric Christopher4b7948e2010-03-11 02:41:03 +0000697 if (!TD) return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000698
Benjamin Kramer7b88a492010-03-12 09:27:41 +0000699 // Lower all default uses of _chk calls. This is very similar
700 // to what InstCombineCalls does, but here we are only lowering calls
Eric Christopher4b7948e2010-03-11 02:41:03 +0000701 // that have the default "don't know" as the objectsize. Anything else
702 // should be left alone.
Benjamin Kramer7b88a492010-03-12 09:27:41 +0000703 CodeGenPrepareFortifiedLibCalls Simplifier;
Nuno Lopes89702e92012-07-25 16:46:31 +0000704 return Simplifier.fold(CI, TD, TLInfo);
Eric Christopher4b7948e2010-03-11 02:41:03 +0000705}
Chris Lattner1b93be52011-01-15 07:25:29 +0000706
Evan Cheng0663f232011-03-21 01:19:09 +0000707/// DupRetToEnableTailCallOpts - Look for opportunities to duplicate return
708/// instructions to the predecessor to enable tail call optimizations. The
709/// case it is currently looking for is:
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +0000710/// @code
Evan Cheng0663f232011-03-21 01:19:09 +0000711/// bb0:
712/// %tmp0 = tail call i32 @f0()
713/// br label %return
714/// bb1:
715/// %tmp1 = tail call i32 @f1()
716/// br label %return
717/// bb2:
718/// %tmp2 = tail call i32 @f2()
719/// br label %return
720/// return:
721/// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
722/// ret i32 %retval
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +0000723/// @endcode
Evan Cheng0663f232011-03-21 01:19:09 +0000724///
725/// =>
726///
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +0000727/// @code
Evan Cheng0663f232011-03-21 01:19:09 +0000728/// bb0:
729/// %tmp0 = tail call i32 @f0()
730/// ret i32 %tmp0
731/// bb1:
732/// %tmp1 = tail call i32 @f1()
733/// ret i32 %tmp1
734/// bb2:
735/// %tmp2 = tail call i32 @f2()
736/// ret i32 %tmp2
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +0000737/// @endcode
Benjamin Kramer455fa352012-11-23 19:17:06 +0000738bool CodeGenPrepare::DupRetToEnableTailCallOpts(BasicBlock *BB) {
Cameron Zwarich47e71752011-03-24 04:51:51 +0000739 if (!TLI)
740 return false;
741
Benjamin Kramer455fa352012-11-23 19:17:06 +0000742 ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
743 if (!RI)
744 return false;
745
Evan Cheng249716e2012-07-27 21:21:26 +0000746 PHINode *PN = 0;
747 BitCastInst *BCI = 0;
Evan Cheng0663f232011-03-21 01:19:09 +0000748 Value *V = RI->getReturnValue();
Evan Cheng249716e2012-07-27 21:21:26 +0000749 if (V) {
750 BCI = dyn_cast<BitCastInst>(V);
751 if (BCI)
752 V = BCI->getOperand(0);
753
754 PN = dyn_cast<PHINode>(V);
755 if (!PN)
756 return false;
757 }
Evan Cheng0663f232011-03-21 01:19:09 +0000758
Cameron Zwarich4649f172011-03-24 04:52:10 +0000759 if (PN && PN->getParent() != BB)
Cameron Zwarich0e331c02011-03-24 04:52:07 +0000760 return false;
Evan Cheng0663f232011-03-21 01:19:09 +0000761
Cameron Zwarich0e331c02011-03-24 04:52:07 +0000762 // It's not safe to eliminate the sign / zero extension of the return value.
763 // See llvm::isInTailCallPosition().
764 const Function *F = BB->getParent();
Bill Wendling658d24d2013-01-18 21:53:16 +0000765 AttributeSet CallerAttrs = F->getAttributes();
766 if (CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::ZExt) ||
767 CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::SExt))
Cameron Zwarich0e331c02011-03-24 04:52:07 +0000768 return false;
Evan Cheng0663f232011-03-21 01:19:09 +0000769
Cameron Zwarich4649f172011-03-24 04:52:10 +0000770 // Make sure there are no instructions between the PHI and return, or that the
771 // return is the first instruction in the block.
772 if (PN) {
773 BasicBlock::iterator BI = BB->begin();
774 do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
Evan Cheng249716e2012-07-27 21:21:26 +0000775 if (&*BI == BCI)
776 // Also skip over the bitcast.
777 ++BI;
Cameron Zwarich4649f172011-03-24 04:52:10 +0000778 if (&*BI != RI)
779 return false;
780 } else {
Cameron Zwarich74157ab2011-03-24 16:34:59 +0000781 BasicBlock::iterator BI = BB->begin();
782 while (isa<DbgInfoIntrinsic>(BI)) ++BI;
783 if (&*BI != RI)
Cameron Zwarich4649f172011-03-24 04:52:10 +0000784 return false;
785 }
Evan Cheng0663f232011-03-21 01:19:09 +0000786
Cameron Zwarich0e331c02011-03-24 04:52:07 +0000787 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
788 /// call.
789 SmallVector<CallInst*, 4> TailCalls;
Cameron Zwarich4649f172011-03-24 04:52:10 +0000790 if (PN) {
791 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
792 CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
793 // Make sure the phi value is indeed produced by the tail call.
794 if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
795 TLI->mayBeEmittedAsTailCall(CI))
796 TailCalls.push_back(CI);
797 }
798 } else {
799 SmallPtrSet<BasicBlock*, 4> VisitedBBs;
800 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
801 if (!VisitedBBs.insert(*PI))
802 continue;
803
804 BasicBlock::InstListType &InstList = (*PI)->getInstList();
805 BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
806 BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
Cameron Zwarich74157ab2011-03-24 16:34:59 +0000807 do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
808 if (RI == RE)
Cameron Zwarich4649f172011-03-24 04:52:10 +0000809 continue;
Cameron Zwarich74157ab2011-03-24 16:34:59 +0000810
Cameron Zwarich4649f172011-03-24 04:52:10 +0000811 CallInst *CI = dyn_cast<CallInst>(&*RI);
Cameron Zwarich2edfe772011-03-24 15:54:11 +0000812 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI))
Cameron Zwarich4649f172011-03-24 04:52:10 +0000813 TailCalls.push_back(CI);
814 }
Evan Cheng0663f232011-03-21 01:19:09 +0000815 }
816
Cameron Zwarich0e331c02011-03-24 04:52:07 +0000817 bool Changed = false;
818 for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
819 CallInst *CI = TailCalls[i];
820 CallSite CS(CI);
821
822 // Conservatively require the attributes of the call to match those of the
823 // return. Ignore noalias because it doesn't affect the call sequence.
Bill Wendling658d24d2013-01-18 21:53:16 +0000824 AttributeSet CalleeAttrs = CS.getAttributes();
825 if (AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
Bill Wendling3d7b0b82012-12-19 07:18:57 +0000826 removeAttribute(Attribute::NoAlias) !=
Bill Wendling658d24d2013-01-18 21:53:16 +0000827 AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
Bill Wendling3d7b0b82012-12-19 07:18:57 +0000828 removeAttribute(Attribute::NoAlias))
Cameron Zwarich0e331c02011-03-24 04:52:07 +0000829 continue;
830
831 // Make sure the call instruction is followed by an unconditional branch to
832 // the return block.
833 BasicBlock *CallBB = CI->getParent();
834 BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
835 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
836 continue;
837
838 // Duplicate the return into CallBB.
839 (void)FoldReturnIntoUncondBranch(RI, BB, CallBB);
Devang Patel8f606d72011-03-24 15:35:25 +0000840 ModifiedDT = Changed = true;
Cameron Zwarich0e331c02011-03-24 04:52:07 +0000841 ++NumRetsDup;
842 }
843
844 // If we eliminated all predecessors of the block, delete the block now.
Evan Cheng64a223a2012-09-28 23:58:57 +0000845 if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
Cameron Zwarich0e331c02011-03-24 04:52:07 +0000846 BB->eraseFromParent();
847
848 return Changed;
Evan Cheng0663f232011-03-21 01:19:09 +0000849}
850
Chris Lattner728f9022008-11-25 07:09:13 +0000851//===----------------------------------------------------------------------===//
Chris Lattner728f9022008-11-25 07:09:13 +0000852// Memory Optimization
853//===----------------------------------------------------------------------===//
854
Chandler Carruthc8925912013-01-05 02:09:22 +0000855namespace {
856
857/// ExtAddrMode - This is an extended version of TargetLowering::AddrMode
858/// which holds actual Value*'s for register values.
Chandler Carruth95f83e02013-01-07 15:14:13 +0000859struct ExtAddrMode : public TargetLowering::AddrMode {
Chandler Carruthc8925912013-01-05 02:09:22 +0000860 Value *BaseReg;
861 Value *ScaledReg;
862 ExtAddrMode() : BaseReg(0), ScaledReg(0) {}
863 void print(raw_ostream &OS) const;
864 void dump() const;
Stephen Lin837bba12013-07-15 17:55:02 +0000865
Chandler Carruthc8925912013-01-05 02:09:22 +0000866 bool operator==(const ExtAddrMode& O) const {
867 return (BaseReg == O.BaseReg) && (ScaledReg == O.ScaledReg) &&
868 (BaseGV == O.BaseGV) && (BaseOffs == O.BaseOffs) &&
869 (HasBaseReg == O.HasBaseReg) && (Scale == O.Scale);
870 }
871};
872
Eli Friedmanc1f1f852013-09-10 23:09:24 +0000873#ifndef NDEBUG
874static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
875 AM.print(OS);
876 return OS;
877}
878#endif
879
Chandler Carruthc8925912013-01-05 02:09:22 +0000880void ExtAddrMode::print(raw_ostream &OS) const {
881 bool NeedPlus = false;
882 OS << "[";
883 if (BaseGV) {
884 OS << (NeedPlus ? " + " : "")
885 << "GV:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +0000886 BaseGV->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +0000887 NeedPlus = true;
888 }
889
890 if (BaseOffs)
891 OS << (NeedPlus ? " + " : "") << BaseOffs, NeedPlus = true;
892
893 if (BaseReg) {
894 OS << (NeedPlus ? " + " : "")
895 << "Base:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +0000896 BaseReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +0000897 NeedPlus = true;
898 }
899 if (Scale) {
900 OS << (NeedPlus ? " + " : "")
901 << Scale << "*";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +0000902 ScaledReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +0000903 }
904
905 OS << ']';
906}
907
908#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
909void ExtAddrMode::dump() const {
910 print(dbgs());
911 dbgs() << '\n';
912}
913#endif
914
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000915/// \brief This class provides transaction based operation on the IR.
916/// Every change made through this class is recorded in the internal state and
917/// can be undone (rollback) until commit is called.
918class TypePromotionTransaction {
919
920 /// \brief This represents the common interface of the individual transaction.
921 /// Each class implements the logic for doing one specific modification on
922 /// the IR via the TypePromotionTransaction.
923 class TypePromotionAction {
924 protected:
925 /// The Instruction modified.
926 Instruction *Inst;
927
928 public:
929 /// \brief Constructor of the action.
930 /// The constructor performs the related action on the IR.
931 TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
932
933 virtual ~TypePromotionAction() {}
934
935 /// \brief Undo the modification done by this action.
936 /// When this method is called, the IR must be in the same state as it was
937 /// before this action was applied.
938 /// \pre Undoing the action works if and only if the IR is in the exact same
939 /// state as it was directly after this action was applied.
940 virtual void undo() = 0;
941
942 /// \brief Advocate every change made by this action.
943 /// When the results on the IR of the action are to be kept, it is important
944 /// to call this function, otherwise hidden information may be kept forever.
945 virtual void commit() {
946 // Nothing to be done, this action is not doing anything.
947 }
948 };
949
950 /// \brief Utility to remember the position of an instruction.
951 class InsertionHandler {
952 /// Position of an instruction.
953 /// Either an instruction:
954 /// - Is the first in a basic block: BB is used.
955 /// - Has a previous instructon: PrevInst is used.
956 union {
957 Instruction *PrevInst;
958 BasicBlock *BB;
959 } Point;
960 /// Remember whether or not the instruction had a previous instruction.
961 bool HasPrevInstruction;
962
963 public:
964 /// \brief Record the position of \p Inst.
965 InsertionHandler(Instruction *Inst) {
966 BasicBlock::iterator It = Inst;
967 HasPrevInstruction = (It != (Inst->getParent()->begin()));
968 if (HasPrevInstruction)
969 Point.PrevInst = --It;
970 else
971 Point.BB = Inst->getParent();
972 }
973
974 /// \brief Insert \p Inst at the recorded position.
975 void insert(Instruction *Inst) {
976 if (HasPrevInstruction) {
977 if (Inst->getParent())
978 Inst->removeFromParent();
979 Inst->insertAfter(Point.PrevInst);
980 } else {
981 Instruction *Position = Point.BB->getFirstInsertionPt();
982 if (Inst->getParent())
983 Inst->moveBefore(Position);
984 else
985 Inst->insertBefore(Position);
986 }
987 }
988 };
989
990 /// \brief Move an instruction before another.
991 class InstructionMoveBefore : public TypePromotionAction {
992 /// Original position of the instruction.
993 InsertionHandler Position;
994
995 public:
996 /// \brief Move \p Inst before \p Before.
997 InstructionMoveBefore(Instruction *Inst, Instruction *Before)
998 : TypePromotionAction(Inst), Position(Inst) {
999 DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before << "\n");
1000 Inst->moveBefore(Before);
1001 }
1002
1003 /// \brief Move the instruction back to its original position.
Craig Topper4584cd52014-03-07 09:26:03 +00001004 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001005 DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n");
1006 Position.insert(Inst);
1007 }
1008 };
1009
1010 /// \brief Set the operand of an instruction with a new value.
1011 class OperandSetter : public TypePromotionAction {
1012 /// Original operand of the instruction.
1013 Value *Origin;
1014 /// Index of the modified instruction.
1015 unsigned Idx;
1016
1017 public:
1018 /// \brief Set \p Idx operand of \p Inst with \p NewVal.
1019 OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
1020 : TypePromotionAction(Inst), Idx(Idx) {
1021 DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"
1022 << "for:" << *Inst << "\n"
1023 << "with:" << *NewVal << "\n");
1024 Origin = Inst->getOperand(Idx);
1025 Inst->setOperand(Idx, NewVal);
1026 }
1027
1028 /// \brief Restore the original value of the instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00001029 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001030 DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"
1031 << "for: " << *Inst << "\n"
1032 << "with: " << *Origin << "\n");
1033 Inst->setOperand(Idx, Origin);
1034 }
1035 };
1036
1037 /// \brief Hide the operands of an instruction.
1038 /// Do as if this instruction was not using any of its operands.
1039 class OperandsHider : public TypePromotionAction {
1040 /// The list of original operands.
1041 SmallVector<Value *, 4> OriginalValues;
1042
1043 public:
1044 /// \brief Remove \p Inst from the uses of the operands of \p Inst.
1045 OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
1046 DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n");
1047 unsigned NumOpnds = Inst->getNumOperands();
1048 OriginalValues.reserve(NumOpnds);
1049 for (unsigned It = 0; It < NumOpnds; ++It) {
1050 // Save the current operand.
1051 Value *Val = Inst->getOperand(It);
1052 OriginalValues.push_back(Val);
1053 // Set a dummy one.
1054 // We could use OperandSetter here, but that would implied an overhead
1055 // that we are not willing to pay.
1056 Inst->setOperand(It, UndefValue::get(Val->getType()));
1057 }
1058 }
1059
1060 /// \brief Restore the original list of uses.
Craig Topper4584cd52014-03-07 09:26:03 +00001061 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001062 DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n");
1063 for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
1064 Inst->setOperand(It, OriginalValues[It]);
1065 }
1066 };
1067
1068 /// \brief Build a truncate instruction.
1069 class TruncBuilder : public TypePromotionAction {
1070 public:
1071 /// \brief Build a truncate instruction of \p Opnd producing a \p Ty
1072 /// result.
1073 /// trunc Opnd to Ty.
1074 TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
1075 IRBuilder<> Builder(Opnd);
1076 Inst = cast<Instruction>(Builder.CreateTrunc(Opnd, Ty, "promoted"));
1077 DEBUG(dbgs() << "Do: TruncBuilder: " << *Inst << "\n");
1078 }
1079
1080 /// \brief Get the built instruction.
1081 Instruction *getBuiltInstruction() { return Inst; }
1082
1083 /// \brief Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00001084 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001085 DEBUG(dbgs() << "Undo: TruncBuilder: " << *Inst << "\n");
1086 Inst->eraseFromParent();
1087 }
1088 };
1089
1090 /// \brief Build a sign extension instruction.
1091 class SExtBuilder : public TypePromotionAction {
1092 public:
1093 /// \brief Build a sign extension instruction of \p Opnd producing a \p Ty
1094 /// result.
1095 /// sext Opnd to Ty.
1096 SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
1097 : TypePromotionAction(Inst) {
1098 IRBuilder<> Builder(InsertPt);
1099 Inst = cast<Instruction>(Builder.CreateSExt(Opnd, Ty, "promoted"));
1100 DEBUG(dbgs() << "Do: SExtBuilder: " << *Inst << "\n");
1101 }
1102
1103 /// \brief Get the built instruction.
1104 Instruction *getBuiltInstruction() { return Inst; }
1105
1106 /// \brief Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00001107 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001108 DEBUG(dbgs() << "Undo: SExtBuilder: " << *Inst << "\n");
1109 Inst->eraseFromParent();
1110 }
1111 };
1112
1113 /// \brief Mutate an instruction to another type.
1114 class TypeMutator : public TypePromotionAction {
1115 /// Record the original type.
1116 Type *OrigTy;
1117
1118 public:
1119 /// \brief Mutate the type of \p Inst into \p NewTy.
1120 TypeMutator(Instruction *Inst, Type *NewTy)
1121 : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
1122 DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy
1123 << "\n");
1124 Inst->mutateType(NewTy);
1125 }
1126
1127 /// \brief Mutate the instruction back to its original type.
Craig Topper4584cd52014-03-07 09:26:03 +00001128 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001129 DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy
1130 << "\n");
1131 Inst->mutateType(OrigTy);
1132 }
1133 };
1134
1135 /// \brief Replace the uses of an instruction by another instruction.
1136 class UsesReplacer : public TypePromotionAction {
1137 /// Helper structure to keep track of the replaced uses.
1138 struct InstructionAndIdx {
1139 /// The instruction using the instruction.
1140 Instruction *Inst;
1141 /// The index where this instruction is used for Inst.
1142 unsigned Idx;
1143 InstructionAndIdx(Instruction *Inst, unsigned Idx)
1144 : Inst(Inst), Idx(Idx) {}
1145 };
1146
1147 /// Keep track of the original uses (pair Instruction, Index).
1148 SmallVector<InstructionAndIdx, 4> OriginalUses;
1149 typedef SmallVectorImpl<InstructionAndIdx>::iterator use_iterator;
1150
1151 public:
1152 /// \brief Replace all the use of \p Inst by \p New.
1153 UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) {
1154 DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New
1155 << "\n");
1156 // Record the original uses.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001157 for (Use &U : Inst->uses()) {
1158 Instruction *UserI = cast<Instruction>(U.getUser());
1159 OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo()));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001160 }
1161 // Now, we can replace the uses.
1162 Inst->replaceAllUsesWith(New);
1163 }
1164
1165 /// \brief Reassign the original uses of Inst to Inst.
Craig Topper4584cd52014-03-07 09:26:03 +00001166 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001167 DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n");
1168 for (use_iterator UseIt = OriginalUses.begin(),
1169 EndIt = OriginalUses.end();
1170 UseIt != EndIt; ++UseIt) {
1171 UseIt->Inst->setOperand(UseIt->Idx, Inst);
1172 }
1173 }
1174 };
1175
1176 /// \brief Remove an instruction from the IR.
1177 class InstructionRemover : public TypePromotionAction {
1178 /// Original position of the instruction.
1179 InsertionHandler Inserter;
1180 /// Helper structure to hide all the link to the instruction. In other
1181 /// words, this helps to do as if the instruction was removed.
1182 OperandsHider Hider;
1183 /// Keep track of the uses replaced, if any.
1184 UsesReplacer *Replacer;
1185
1186 public:
1187 /// \brief Remove all reference of \p Inst and optinally replace all its
1188 /// uses with New.
1189 /// \pre If !Inst->use_empty(), then New != NULL
1190 InstructionRemover(Instruction *Inst, Value *New = NULL)
1191 : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
1192 Replacer(NULL) {
1193 if (New)
1194 Replacer = new UsesReplacer(Inst, New);
1195 DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n");
1196 Inst->removeFromParent();
1197 }
1198
1199 ~InstructionRemover() { delete Replacer; }
1200
1201 /// \brief Really remove the instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00001202 void commit() override { delete Inst; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001203
1204 /// \brief Resurrect the instruction and reassign it to the proper uses if
1205 /// new value was provided when build this action.
Craig Topper4584cd52014-03-07 09:26:03 +00001206 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001207 DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n");
1208 Inserter.insert(Inst);
1209 if (Replacer)
1210 Replacer->undo();
1211 Hider.undo();
1212 }
1213 };
1214
1215public:
1216 /// Restoration point.
1217 /// The restoration point is a pointer to an action instead of an iterator
1218 /// because the iterator may be invalidated but not the pointer.
1219 typedef const TypePromotionAction *ConstRestorationPt;
1220 /// Advocate every changes made in that transaction.
1221 void commit();
1222 /// Undo all the changes made after the given point.
1223 void rollback(ConstRestorationPt Point);
1224 /// Get the current restoration point.
1225 ConstRestorationPt getRestorationPoint() const;
1226
1227 /// \name API for IR modification with state keeping to support rollback.
1228 /// @{
1229 /// Same as Instruction::setOperand.
1230 void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
1231 /// Same as Instruction::eraseFromParent.
1232 void eraseInstruction(Instruction *Inst, Value *NewVal = NULL);
1233 /// Same as Value::replaceAllUsesWith.
1234 void replaceAllUsesWith(Instruction *Inst, Value *New);
1235 /// Same as Value::mutateType.
1236 void mutateType(Instruction *Inst, Type *NewTy);
1237 /// Same as IRBuilder::createTrunc.
1238 Instruction *createTrunc(Instruction *Opnd, Type *Ty);
1239 /// Same as IRBuilder::createSExt.
1240 Instruction *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
1241 /// Same as Instruction::moveBefore.
1242 void moveBefore(Instruction *Inst, Instruction *Before);
1243 /// @}
1244
1245 ~TypePromotionTransaction();
1246
1247private:
1248 /// The ordered list of actions made so far.
1249 SmallVector<TypePromotionAction *, 16> Actions;
1250 typedef SmallVectorImpl<TypePromotionAction *>::iterator CommitPt;
1251};
1252
1253void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
1254 Value *NewVal) {
1255 Actions.push_back(
1256 new TypePromotionTransaction::OperandSetter(Inst, Idx, NewVal));
1257}
1258
1259void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
1260 Value *NewVal) {
1261 Actions.push_back(
1262 new TypePromotionTransaction::InstructionRemover(Inst, NewVal));
1263}
1264
1265void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
1266 Value *New) {
1267 Actions.push_back(new TypePromotionTransaction::UsesReplacer(Inst, New));
1268}
1269
1270void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
1271 Actions.push_back(new TypePromotionTransaction::TypeMutator(Inst, NewTy));
1272}
1273
1274Instruction *TypePromotionTransaction::createTrunc(Instruction *Opnd,
1275 Type *Ty) {
1276 TruncBuilder *TB = new TruncBuilder(Opnd, Ty);
1277 Actions.push_back(TB);
1278 return TB->getBuiltInstruction();
1279}
1280
1281Instruction *TypePromotionTransaction::createSExt(Instruction *Inst,
1282 Value *Opnd, Type *Ty) {
1283 SExtBuilder *SB = new SExtBuilder(Inst, Opnd, Ty);
1284 Actions.push_back(SB);
1285 return SB->getBuiltInstruction();
1286}
1287
1288void TypePromotionTransaction::moveBefore(Instruction *Inst,
1289 Instruction *Before) {
1290 Actions.push_back(
1291 new TypePromotionTransaction::InstructionMoveBefore(Inst, Before));
1292}
1293
1294TypePromotionTransaction::ConstRestorationPt
1295TypePromotionTransaction::getRestorationPoint() const {
1296 return Actions.rbegin() != Actions.rend() ? *Actions.rbegin() : NULL;
1297}
1298
1299void TypePromotionTransaction::commit() {
1300 for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt;
1301 ++It) {
1302 (*It)->commit();
1303 delete *It;
1304 }
1305 Actions.clear();
1306}
1307
1308void TypePromotionTransaction::rollback(
1309 TypePromotionTransaction::ConstRestorationPt Point) {
1310 while (!Actions.empty() && Point != (*Actions.rbegin())) {
1311 TypePromotionAction *Curr = Actions.pop_back_val();
1312 Curr->undo();
1313 delete Curr;
1314 }
1315}
1316
1317TypePromotionTransaction::~TypePromotionTransaction() {
1318 for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt; ++It)
1319 delete *It;
1320 Actions.clear();
1321}
Chandler Carruthc8925912013-01-05 02:09:22 +00001322
1323/// \brief A helper class for matching addressing modes.
1324///
1325/// This encapsulates the logic for matching the target-legal addressing modes.
1326class AddressingModeMatcher {
1327 SmallVectorImpl<Instruction*> &AddrModeInsts;
1328 const TargetLowering &TLI;
1329
1330 /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
1331 /// the memory instruction that we're computing this address for.
1332 Type *AccessTy;
1333 Instruction *MemoryInst;
Stephen Lin837bba12013-07-15 17:55:02 +00001334
Chandler Carruthc8925912013-01-05 02:09:22 +00001335 /// AddrMode - This is the addressing mode that we're building up. This is
1336 /// part of the return value of this addressing mode matching stuff.
1337 ExtAddrMode &AddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00001338
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001339 /// The truncate instruction inserted by other CodeGenPrepare optimizations.
1340 const SetOfInstrs &InsertedTruncs;
1341 /// A map from the instructions to their type before promotion.
1342 InstrToOrigTy &PromotedInsts;
1343 /// The ongoing transaction where every action should be registered.
1344 TypePromotionTransaction &TPT;
1345
Chandler Carruthc8925912013-01-05 02:09:22 +00001346 /// IgnoreProfitability - This is set to true when we should not do
1347 /// profitability checks. When true, IsProfitableToFoldIntoAddressingMode
1348 /// always returns true.
1349 bool IgnoreProfitability;
Stephen Lin837bba12013-07-15 17:55:02 +00001350
Chandler Carruthc8925912013-01-05 02:09:22 +00001351 AddressingModeMatcher(SmallVectorImpl<Instruction*> &AMI,
1352 const TargetLowering &T, Type *AT,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001353 Instruction *MI, ExtAddrMode &AM,
1354 const SetOfInstrs &InsertedTruncs,
1355 InstrToOrigTy &PromotedInsts,
1356 TypePromotionTransaction &TPT)
1357 : AddrModeInsts(AMI), TLI(T), AccessTy(AT), MemoryInst(MI), AddrMode(AM),
1358 InsertedTruncs(InsertedTruncs), PromotedInsts(PromotedInsts), TPT(TPT) {
Chandler Carruthc8925912013-01-05 02:09:22 +00001359 IgnoreProfitability = false;
1360 }
1361public:
Stephen Lin837bba12013-07-15 17:55:02 +00001362
Chandler Carruthc8925912013-01-05 02:09:22 +00001363 /// Match - Find the maximal addressing mode that a load/store of V can fold,
1364 /// give an access type of AccessTy. This returns a list of involved
1365 /// instructions in AddrModeInsts.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001366 /// \p InsertedTruncs The truncate instruction inserted by other
1367 /// CodeGenPrepare
1368 /// optimizations.
1369 /// \p PromotedInsts maps the instructions to their type before promotion.
1370 /// \p The ongoing transaction where every action should be registered.
Chandler Carruthc8925912013-01-05 02:09:22 +00001371 static ExtAddrMode Match(Value *V, Type *AccessTy,
1372 Instruction *MemoryInst,
1373 SmallVectorImpl<Instruction*> &AddrModeInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001374 const TargetLowering &TLI,
1375 const SetOfInstrs &InsertedTruncs,
1376 InstrToOrigTy &PromotedInsts,
1377 TypePromotionTransaction &TPT) {
Chandler Carruthc8925912013-01-05 02:09:22 +00001378 ExtAddrMode Result;
1379
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001380 bool Success = AddressingModeMatcher(AddrModeInsts, TLI, AccessTy,
1381 MemoryInst, Result, InsertedTruncs,
1382 PromotedInsts, TPT).MatchAddr(V, 0);
Chandler Carruthc8925912013-01-05 02:09:22 +00001383 (void)Success; assert(Success && "Couldn't select *anything*?");
1384 return Result;
1385 }
1386private:
1387 bool MatchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
1388 bool MatchAddr(Value *V, unsigned Depth);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001389 bool MatchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth,
1390 bool *MovedAway = NULL);
Chandler Carruthc8925912013-01-05 02:09:22 +00001391 bool IsProfitableToFoldIntoAddressingMode(Instruction *I,
1392 ExtAddrMode &AMBefore,
1393 ExtAddrMode &AMAfter);
1394 bool ValueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
Quentin Colombet867c5502014-02-14 22:23:22 +00001395 bool IsPromotionProfitable(unsigned MatchedSize, unsigned SizeWithPromotion,
1396 Value *PromotedOperand) const;
Chandler Carruthc8925912013-01-05 02:09:22 +00001397};
1398
1399/// MatchScaledValue - Try adding ScaleReg*Scale to the current addressing mode.
1400/// Return true and update AddrMode if this addr mode is legal for the target,
1401/// false if not.
1402bool AddressingModeMatcher::MatchScaledValue(Value *ScaleReg, int64_t Scale,
1403 unsigned Depth) {
1404 // If Scale is 1, then this is the same as adding ScaleReg to the addressing
1405 // mode. Just process that directly.
1406 if (Scale == 1)
1407 return MatchAddr(ScaleReg, Depth);
Stephen Lin837bba12013-07-15 17:55:02 +00001408
Chandler Carruthc8925912013-01-05 02:09:22 +00001409 // If the scale is 0, it takes nothing to add this.
1410 if (Scale == 0)
1411 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00001412
Chandler Carruthc8925912013-01-05 02:09:22 +00001413 // If we already have a scale of this value, we can add to it, otherwise, we
1414 // need an available scale field.
1415 if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
1416 return false;
1417
1418 ExtAddrMode TestAddrMode = AddrMode;
1419
1420 // Add scale to turn X*4+X*3 -> X*7. This could also do things like
1421 // [A+B + A*7] -> [B+A*8].
1422 TestAddrMode.Scale += Scale;
1423 TestAddrMode.ScaledReg = ScaleReg;
1424
1425 // If the new address isn't legal, bail out.
1426 if (!TLI.isLegalAddressingMode(TestAddrMode, AccessTy))
1427 return false;
1428
1429 // It was legal, so commit it.
1430 AddrMode = TestAddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00001431
Chandler Carruthc8925912013-01-05 02:09:22 +00001432 // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
1433 // to see if ScaleReg is actually X+C. If so, we can turn this into adding
1434 // X*Scale + C*Scale to addr mode.
1435 ConstantInt *CI = 0; Value *AddLHS = 0;
1436 if (isa<Instruction>(ScaleReg) && // not a constant expr.
1437 match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
1438 TestAddrMode.ScaledReg = AddLHS;
1439 TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00001440
Chandler Carruthc8925912013-01-05 02:09:22 +00001441 // If this addressing mode is legal, commit it and remember that we folded
1442 // this instruction.
1443 if (TLI.isLegalAddressingMode(TestAddrMode, AccessTy)) {
1444 AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
1445 AddrMode = TestAddrMode;
1446 return true;
1447 }
1448 }
1449
1450 // Otherwise, not (x+c)*scale, just return what we have.
1451 return true;
1452}
1453
1454/// MightBeFoldableInst - This is a little filter, which returns true if an
1455/// addressing computation involving I might be folded into a load/store
1456/// accessing it. This doesn't need to be perfect, but needs to accept at least
1457/// the set of instructions that MatchOperationAddr can.
1458static bool MightBeFoldableInst(Instruction *I) {
1459 switch (I->getOpcode()) {
1460 case Instruction::BitCast:
1461 // Don't touch identity bitcasts.
1462 if (I->getType() == I->getOperand(0)->getType())
1463 return false;
1464 return I->getType()->isPointerTy() || I->getType()->isIntegerTy();
1465 case Instruction::PtrToInt:
1466 // PtrToInt is always a noop, as we know that the int type is pointer sized.
1467 return true;
1468 case Instruction::IntToPtr:
1469 // We know the input is intptr_t, so this is foldable.
1470 return true;
1471 case Instruction::Add:
1472 return true;
1473 case Instruction::Mul:
1474 case Instruction::Shl:
1475 // Can only handle X*C and X << C.
1476 return isa<ConstantInt>(I->getOperand(1));
1477 case Instruction::GetElementPtr:
1478 return true;
1479 default:
1480 return false;
1481 }
1482}
1483
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001484/// \brief Hepler class to perform type promotion.
1485class TypePromotionHelper {
1486 /// \brief Utility function to check whether or not a sign extension of
1487 /// \p Inst with \p ConsideredSExtType can be moved through \p Inst by either
1488 /// using the operands of \p Inst or promoting \p Inst.
1489 /// In other words, check if:
1490 /// sext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredSExtType.
1491 /// #1 Promotion applies:
1492 /// ConsideredSExtType Inst (sext opnd1 to ConsideredSExtType, ...).
1493 /// #2 Operand reuses:
1494 /// sext opnd1 to ConsideredSExtType.
1495 /// \p PromotedInsts maps the instructions to their type before promotion.
1496 static bool canGetThrough(const Instruction *Inst, Type *ConsideredSExtType,
1497 const InstrToOrigTy &PromotedInsts);
1498
1499 /// \brief Utility function to determine if \p OpIdx should be promoted when
1500 /// promoting \p Inst.
1501 static bool shouldSExtOperand(const Instruction *Inst, int OpIdx) {
1502 if (isa<SelectInst>(Inst) && OpIdx == 0)
1503 return false;
1504 return true;
1505 }
1506
1507 /// \brief Utility function to promote the operand of \p SExt when this
1508 /// operand is a promotable trunc or sext.
1509 /// \p PromotedInsts maps the instructions to their type before promotion.
1510 /// \p CreatedInsts[out] contains how many non-free instructions have been
1511 /// created to promote the operand of SExt.
1512 /// Should never be called directly.
1513 /// \return The promoted value which is used instead of SExt.
1514 static Value *promoteOperandForTruncAndSExt(Instruction *SExt,
1515 TypePromotionTransaction &TPT,
1516 InstrToOrigTy &PromotedInsts,
1517 unsigned &CreatedInsts);
1518
1519 /// \brief Utility function to promote the operand of \p SExt when this
1520 /// operand is promotable and is not a supported trunc or sext.
1521 /// \p PromotedInsts maps the instructions to their type before promotion.
1522 /// \p CreatedInsts[out] contains how many non-free instructions have been
1523 /// created to promote the operand of SExt.
1524 /// Should never be called directly.
1525 /// \return The promoted value which is used instead of SExt.
1526 static Value *promoteOperandForOther(Instruction *SExt,
1527 TypePromotionTransaction &TPT,
1528 InstrToOrigTy &PromotedInsts,
1529 unsigned &CreatedInsts);
1530
1531public:
1532 /// Type for the utility function that promotes the operand of SExt.
1533 typedef Value *(*Action)(Instruction *SExt, TypePromotionTransaction &TPT,
1534 InstrToOrigTy &PromotedInsts,
1535 unsigned &CreatedInsts);
1536 /// \brief Given a sign extend instruction \p SExt, return the approriate
1537 /// action to promote the operand of \p SExt instead of using SExt.
1538 /// \return NULL if no promotable action is possible with the current
1539 /// sign extension.
1540 /// \p InsertedTruncs keeps track of all the truncate instructions inserted by
1541 /// the others CodeGenPrepare optimizations. This information is important
1542 /// because we do not want to promote these instructions as CodeGenPrepare
1543 /// will reinsert them later. Thus creating an infinite loop: create/remove.
1544 /// \p PromotedInsts maps the instructions to their type before promotion.
1545 static Action getAction(Instruction *SExt, const SetOfInstrs &InsertedTruncs,
1546 const TargetLowering &TLI,
1547 const InstrToOrigTy &PromotedInsts);
1548};
1549
1550bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
1551 Type *ConsideredSExtType,
1552 const InstrToOrigTy &PromotedInsts) {
1553 // We can always get through sext.
1554 if (isa<SExtInst>(Inst))
1555 return true;
1556
1557 // We can get through binary operator, if it is legal. In other words, the
1558 // binary operator must have a nuw or nsw flag.
1559 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
1560 if (BinOp && isa<OverflowingBinaryOperator>(BinOp) &&
1561 (BinOp->hasNoUnsignedWrap() || BinOp->hasNoSignedWrap()))
1562 return true;
1563
1564 // Check if we can do the following simplification.
1565 // sext(trunc(sext)) --> sext
1566 if (!isa<TruncInst>(Inst))
1567 return false;
1568
1569 Value *OpndVal = Inst->getOperand(0);
1570 // Check if we can use this operand in the sext.
1571 // If the type is larger than the result type of the sign extension,
1572 // we cannot.
1573 if (OpndVal->getType()->getIntegerBitWidth() >
1574 ConsideredSExtType->getIntegerBitWidth())
1575 return false;
1576
1577 // If the operand of the truncate is not an instruction, we will not have
1578 // any information on the dropped bits.
1579 // (Actually we could for constant but it is not worth the extra logic).
1580 Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
1581 if (!Opnd)
1582 return false;
1583
1584 // Check if the source of the type is narrow enough.
1585 // I.e., check that trunc just drops sign extended bits.
1586 // #1 get the type of the operand.
1587 const Type *OpndType;
1588 InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
1589 if (It != PromotedInsts.end())
1590 OpndType = It->second;
1591 else if (isa<SExtInst>(Opnd))
1592 OpndType = cast<Instruction>(Opnd)->getOperand(0)->getType();
1593 else
1594 return false;
1595
1596 // #2 check that the truncate just drop sign extended bits.
1597 if (Inst->getType()->getIntegerBitWidth() >= OpndType->getIntegerBitWidth())
1598 return true;
1599
1600 return false;
1601}
1602
1603TypePromotionHelper::Action TypePromotionHelper::getAction(
1604 Instruction *SExt, const SetOfInstrs &InsertedTruncs,
1605 const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
1606 Instruction *SExtOpnd = dyn_cast<Instruction>(SExt->getOperand(0));
1607 Type *SExtTy = SExt->getType();
1608 // If the operand of the sign extension is not an instruction, we cannot
1609 // get through.
1610 // If it, check we can get through.
1611 if (!SExtOpnd || !canGetThrough(SExtOpnd, SExtTy, PromotedInsts))
1612 return NULL;
1613
1614 // Do not promote if the operand has been added by codegenprepare.
1615 // Otherwise, it means we are undoing an optimization that is likely to be
1616 // redone, thus causing potential infinite loop.
1617 if (isa<TruncInst>(SExtOpnd) && InsertedTruncs.count(SExtOpnd))
1618 return NULL;
1619
1620 // SExt or Trunc instructions.
1621 // Return the related handler.
1622 if (isa<SExtInst>(SExtOpnd) || isa<TruncInst>(SExtOpnd))
1623 return promoteOperandForTruncAndSExt;
1624
1625 // Regular instruction.
1626 // Abort early if we will have to insert non-free instructions.
1627 if (!SExtOpnd->hasOneUse() &&
1628 !TLI.isTruncateFree(SExtTy, SExtOpnd->getType()))
1629 return NULL;
1630 return promoteOperandForOther;
1631}
1632
1633Value *TypePromotionHelper::promoteOperandForTruncAndSExt(
1634 llvm::Instruction *SExt, TypePromotionTransaction &TPT,
1635 InstrToOrigTy &PromotedInsts, unsigned &CreatedInsts) {
1636 // By construction, the operand of SExt is an instruction. Otherwise we cannot
1637 // get through it and this method should not be called.
1638 Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
1639 // Replace sext(trunc(opnd)) or sext(sext(opnd))
1640 // => sext(opnd).
1641 TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
1642 CreatedInsts = 0;
1643
1644 // Remove dead code.
1645 if (SExtOpnd->use_empty())
1646 TPT.eraseInstruction(SExtOpnd);
1647
1648 // Check if the sext is still needed.
1649 if (SExt->getType() != SExt->getOperand(0)->getType())
1650 return SExt;
1651
1652 // At this point we have: sext ty opnd to ty.
1653 // Reassign the uses of SExt to the opnd and remove SExt.
1654 Value *NextVal = SExt->getOperand(0);
1655 TPT.eraseInstruction(SExt, NextVal);
1656 return NextVal;
1657}
1658
1659Value *
1660TypePromotionHelper::promoteOperandForOther(Instruction *SExt,
1661 TypePromotionTransaction &TPT,
1662 InstrToOrigTy &PromotedInsts,
1663 unsigned &CreatedInsts) {
1664 // By construction, the operand of SExt is an instruction. Otherwise we cannot
1665 // get through it and this method should not be called.
1666 Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
1667 CreatedInsts = 0;
1668 if (!SExtOpnd->hasOneUse()) {
1669 // SExtOpnd will be promoted.
1670 // All its uses, but SExt, will need to use a truncated value of the
1671 // promoted version.
1672 // Create the truncate now.
1673 Instruction *Trunc = TPT.createTrunc(SExt, SExtOpnd->getType());
1674 Trunc->removeFromParent();
1675 // Insert it just after the definition.
1676 Trunc->insertAfter(SExtOpnd);
1677
1678 TPT.replaceAllUsesWith(SExtOpnd, Trunc);
1679 // Restore the operand of SExt (which has been replace by the previous call
1680 // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
1681 TPT.setOperand(SExt, 0, SExtOpnd);
1682 }
1683
1684 // Get through the Instruction:
1685 // 1. Update its type.
1686 // 2. Replace the uses of SExt by Inst.
1687 // 3. Sign extend each operand that needs to be sign extended.
1688
1689 // Remember the original type of the instruction before promotion.
1690 // This is useful to know that the high bits are sign extended bits.
1691 PromotedInsts.insert(
1692 std::pair<Instruction *, Type *>(SExtOpnd, SExtOpnd->getType()));
1693 // Step #1.
1694 TPT.mutateType(SExtOpnd, SExt->getType());
1695 // Step #2.
1696 TPT.replaceAllUsesWith(SExt, SExtOpnd);
1697 // Step #3.
1698 Instruction *SExtForOpnd = SExt;
1699
1700 DEBUG(dbgs() << "Propagate SExt to operands\n");
1701 for (int OpIdx = 0, EndOpIdx = SExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
1702 ++OpIdx) {
1703 DEBUG(dbgs() << "Operand:\n" << *(SExtOpnd->getOperand(OpIdx)) << '\n');
1704 if (SExtOpnd->getOperand(OpIdx)->getType() == SExt->getType() ||
1705 !shouldSExtOperand(SExtOpnd, OpIdx)) {
1706 DEBUG(dbgs() << "No need to propagate\n");
1707 continue;
1708 }
1709 // Check if we can statically sign extend the operand.
1710 Value *Opnd = SExtOpnd->getOperand(OpIdx);
1711 if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
1712 DEBUG(dbgs() << "Statically sign extend\n");
1713 TPT.setOperand(
1714 SExtOpnd, OpIdx,
1715 ConstantInt::getSigned(SExt->getType(), Cst->getSExtValue()));
1716 continue;
1717 }
1718 // UndefValue are typed, so we have to statically sign extend them.
1719 if (isa<UndefValue>(Opnd)) {
1720 DEBUG(dbgs() << "Statically sign extend\n");
1721 TPT.setOperand(SExtOpnd, OpIdx, UndefValue::get(SExt->getType()));
1722 continue;
1723 }
1724
1725 // Otherwise we have to explicity sign extend the operand.
1726 // Check if SExt was reused to sign extend an operand.
1727 if (!SExtForOpnd) {
1728 // If yes, create a new one.
1729 DEBUG(dbgs() << "More operands to sext\n");
1730 SExtForOpnd = TPT.createSExt(SExt, Opnd, SExt->getType());
1731 ++CreatedInsts;
1732 }
1733
1734 TPT.setOperand(SExtForOpnd, 0, Opnd);
1735
1736 // Move the sign extension before the insertion point.
1737 TPT.moveBefore(SExtForOpnd, SExtOpnd);
1738 TPT.setOperand(SExtOpnd, OpIdx, SExtForOpnd);
1739 // If more sext are required, new instructions will have to be created.
1740 SExtForOpnd = NULL;
1741 }
1742 if (SExtForOpnd == SExt) {
1743 DEBUG(dbgs() << "Sign extension is useless now\n");
1744 TPT.eraseInstruction(SExt);
1745 }
1746 return SExtOpnd;
1747}
1748
Quentin Colombet867c5502014-02-14 22:23:22 +00001749/// IsPromotionProfitable - Check whether or not promoting an instruction
1750/// to a wider type was profitable.
1751/// \p MatchedSize gives the number of instructions that have been matched
1752/// in the addressing mode after the promotion was applied.
1753/// \p SizeWithPromotion gives the number of created instructions for
1754/// the promotion plus the number of instructions that have been
1755/// matched in the addressing mode before the promotion.
1756/// \p PromotedOperand is the value that has been promoted.
1757/// \return True if the promotion is profitable, false otherwise.
1758bool
1759AddressingModeMatcher::IsPromotionProfitable(unsigned MatchedSize,
1760 unsigned SizeWithPromotion,
1761 Value *PromotedOperand) const {
1762 // We folded less instructions than what we created to promote the operand.
1763 // This is not profitable.
1764 if (MatchedSize < SizeWithPromotion)
1765 return false;
1766 if (MatchedSize > SizeWithPromotion)
1767 return true;
1768 // The promotion is neutral but it may help folding the sign extension in
1769 // loads for instance.
1770 // Check that we did not create an illegal instruction.
1771 Instruction *PromotedInst = dyn_cast<Instruction>(PromotedOperand);
1772 if (!PromotedInst)
1773 return false;
Quentin Colombet1627a412014-02-22 01:06:41 +00001774 int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode());
1775 // If the ISDOpcode is undefined, it was undefined before the promotion.
1776 if (!ISDOpcode)
1777 return true;
1778 // Otherwise, check if the promoted instruction is legal or not.
1779 return TLI.isOperationLegalOrCustom(ISDOpcode,
Quentin Colombet867c5502014-02-14 22:23:22 +00001780 EVT::getEVT(PromotedInst->getType()));
1781}
1782
Chandler Carruthc8925912013-01-05 02:09:22 +00001783/// MatchOperationAddr - Given an instruction or constant expr, see if we can
1784/// fold the operation into the addressing mode. If so, update the addressing
1785/// mode and return true, otherwise return false without modifying AddrMode.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001786/// If \p MovedAway is not NULL, it contains the information of whether or
1787/// not AddrInst has to be folded into the addressing mode on success.
1788/// If \p MovedAway == true, \p AddrInst will not be part of the addressing
1789/// because it has been moved away.
1790/// Thus AddrInst must not be added in the matched instructions.
1791/// This state can happen when AddrInst is a sext, since it may be moved away.
1792/// Therefore, AddrInst may not be valid when MovedAway is true and it must
1793/// not be referenced anymore.
Chandler Carruthc8925912013-01-05 02:09:22 +00001794bool AddressingModeMatcher::MatchOperationAddr(User *AddrInst, unsigned Opcode,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001795 unsigned Depth,
1796 bool *MovedAway) {
Chandler Carruthc8925912013-01-05 02:09:22 +00001797 // Avoid exponential behavior on extremely deep expression trees.
1798 if (Depth >= 5) return false;
Stephen Lin837bba12013-07-15 17:55:02 +00001799
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001800 // By default, all matched instructions stay in place.
1801 if (MovedAway)
1802 *MovedAway = false;
1803
Chandler Carruthc8925912013-01-05 02:09:22 +00001804 switch (Opcode) {
1805 case Instruction::PtrToInt:
1806 // PtrToInt is always a noop, as we know that the int type is pointer sized.
1807 return MatchAddr(AddrInst->getOperand(0), Depth);
1808 case Instruction::IntToPtr:
1809 // This inttoptr is a no-op if the integer type is pointer sized.
1810 if (TLI.getValueType(AddrInst->getOperand(0)->getType()) ==
Matt Arsenault37d42ec2013-09-06 00:18:43 +00001811 TLI.getPointerTy(AddrInst->getType()->getPointerAddressSpace()))
Chandler Carruthc8925912013-01-05 02:09:22 +00001812 return MatchAddr(AddrInst->getOperand(0), Depth);
1813 return false;
1814 case Instruction::BitCast:
1815 // BitCast is always a noop, and we can handle it as long as it is
1816 // int->int or pointer->pointer (we don't want int<->fp or something).
1817 if ((AddrInst->getOperand(0)->getType()->isPointerTy() ||
1818 AddrInst->getOperand(0)->getType()->isIntegerTy()) &&
1819 // Don't touch identity bitcasts. These were probably put here by LSR,
1820 // and we don't want to mess around with them. Assume it knows what it
1821 // is doing.
1822 AddrInst->getOperand(0)->getType() != AddrInst->getType())
1823 return MatchAddr(AddrInst->getOperand(0), Depth);
1824 return false;
1825 case Instruction::Add: {
1826 // Check to see if we can merge in the RHS then the LHS. If so, we win.
1827 ExtAddrMode BackupAddrMode = AddrMode;
1828 unsigned OldSize = AddrModeInsts.size();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001829 // Start a transaction at this point.
1830 // The LHS may match but not the RHS.
1831 // Therefore, we need a higher level restoration point to undo partially
1832 // matched operation.
1833 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
1834 TPT.getRestorationPoint();
1835
Chandler Carruthc8925912013-01-05 02:09:22 +00001836 if (MatchAddr(AddrInst->getOperand(1), Depth+1) &&
1837 MatchAddr(AddrInst->getOperand(0), Depth+1))
1838 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00001839
Chandler Carruthc8925912013-01-05 02:09:22 +00001840 // Restore the old addr mode info.
1841 AddrMode = BackupAddrMode;
1842 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001843 TPT.rollback(LastKnownGood);
Stephen Lin837bba12013-07-15 17:55:02 +00001844
Chandler Carruthc8925912013-01-05 02:09:22 +00001845 // Otherwise this was over-aggressive. Try merging in the LHS then the RHS.
1846 if (MatchAddr(AddrInst->getOperand(0), Depth+1) &&
1847 MatchAddr(AddrInst->getOperand(1), Depth+1))
1848 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00001849
Chandler Carruthc8925912013-01-05 02:09:22 +00001850 // Otherwise we definitely can't merge the ADD in.
1851 AddrMode = BackupAddrMode;
1852 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001853 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00001854 break;
1855 }
1856 //case Instruction::Or:
1857 // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
1858 //break;
1859 case Instruction::Mul:
1860 case Instruction::Shl: {
1861 // Can only handle X*C and X << C.
1862 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
1863 if (!RHS) return false;
1864 int64_t Scale = RHS->getSExtValue();
1865 if (Opcode == Instruction::Shl)
1866 Scale = 1LL << Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00001867
Chandler Carruthc8925912013-01-05 02:09:22 +00001868 return MatchScaledValue(AddrInst->getOperand(0), Scale, Depth);
1869 }
1870 case Instruction::GetElementPtr: {
1871 // Scan the GEP. We check it if it contains constant offsets and at most
1872 // one variable offset.
1873 int VariableOperand = -1;
1874 unsigned VariableScale = 0;
Stephen Lin837bba12013-07-15 17:55:02 +00001875
Chandler Carruthc8925912013-01-05 02:09:22 +00001876 int64_t ConstantOffset = 0;
1877 const DataLayout *TD = TLI.getDataLayout();
1878 gep_type_iterator GTI = gep_type_begin(AddrInst);
1879 for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
1880 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
1881 const StructLayout *SL = TD->getStructLayout(STy);
1882 unsigned Idx =
1883 cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
1884 ConstantOffset += SL->getElementOffset(Idx);
1885 } else {
1886 uint64_t TypeSize = TD->getTypeAllocSize(GTI.getIndexedType());
1887 if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
1888 ConstantOffset += CI->getSExtValue()*TypeSize;
1889 } else if (TypeSize) { // Scales of zero don't do anything.
1890 // We only allow one variable index at the moment.
1891 if (VariableOperand != -1)
1892 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00001893
Chandler Carruthc8925912013-01-05 02:09:22 +00001894 // Remember the variable index.
1895 VariableOperand = i;
1896 VariableScale = TypeSize;
1897 }
1898 }
1899 }
Stephen Lin837bba12013-07-15 17:55:02 +00001900
Chandler Carruthc8925912013-01-05 02:09:22 +00001901 // A common case is for the GEP to only do a constant offset. In this case,
1902 // just add it to the disp field and check validity.
1903 if (VariableOperand == -1) {
1904 AddrMode.BaseOffs += ConstantOffset;
1905 if (ConstantOffset == 0 || TLI.isLegalAddressingMode(AddrMode, AccessTy)){
1906 // Check to see if we can fold the base pointer in too.
1907 if (MatchAddr(AddrInst->getOperand(0), Depth+1))
1908 return true;
1909 }
1910 AddrMode.BaseOffs -= ConstantOffset;
1911 return false;
1912 }
1913
1914 // Save the valid addressing mode in case we can't match.
1915 ExtAddrMode BackupAddrMode = AddrMode;
1916 unsigned OldSize = AddrModeInsts.size();
1917
1918 // See if the scale and offset amount is valid for this target.
1919 AddrMode.BaseOffs += ConstantOffset;
1920
1921 // Match the base operand of the GEP.
1922 if (!MatchAddr(AddrInst->getOperand(0), Depth+1)) {
1923 // If it couldn't be matched, just stuff the value in a register.
1924 if (AddrMode.HasBaseReg) {
1925 AddrMode = BackupAddrMode;
1926 AddrModeInsts.resize(OldSize);
1927 return false;
1928 }
1929 AddrMode.HasBaseReg = true;
1930 AddrMode.BaseReg = AddrInst->getOperand(0);
1931 }
1932
1933 // Match the remaining variable portion of the GEP.
1934 if (!MatchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
1935 Depth)) {
1936 // If it couldn't be matched, try stuffing the base into a register
1937 // instead of matching it, and retrying the match of the scale.
1938 AddrMode = BackupAddrMode;
1939 AddrModeInsts.resize(OldSize);
1940 if (AddrMode.HasBaseReg)
1941 return false;
1942 AddrMode.HasBaseReg = true;
1943 AddrMode.BaseReg = AddrInst->getOperand(0);
1944 AddrMode.BaseOffs += ConstantOffset;
1945 if (!MatchScaledValue(AddrInst->getOperand(VariableOperand),
1946 VariableScale, Depth)) {
1947 // If even that didn't work, bail.
1948 AddrMode = BackupAddrMode;
1949 AddrModeInsts.resize(OldSize);
1950 return false;
1951 }
1952 }
1953
1954 return true;
1955 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001956 case Instruction::SExt: {
1957 // Try to move this sext out of the way of the addressing mode.
1958 Instruction *SExt = cast<Instruction>(AddrInst);
1959 // Ask for a method for doing so.
1960 TypePromotionHelper::Action TPH = TypePromotionHelper::getAction(
1961 SExt, InsertedTruncs, TLI, PromotedInsts);
1962 if (!TPH)
1963 return false;
1964
1965 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
1966 TPT.getRestorationPoint();
1967 unsigned CreatedInsts = 0;
1968 Value *PromotedOperand = TPH(SExt, TPT, PromotedInsts, CreatedInsts);
1969 // SExt has been moved away.
1970 // Thus either it will be rematched later in the recursive calls or it is
1971 // gone. Anyway, we must not fold it into the addressing mode at this point.
1972 // E.g.,
1973 // op = add opnd, 1
1974 // idx = sext op
1975 // addr = gep base, idx
1976 // is now:
1977 // promotedOpnd = sext opnd <- no match here
1978 // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls)
1979 // addr = gep base, op <- match
1980 if (MovedAway)
1981 *MovedAway = true;
1982
1983 assert(PromotedOperand &&
1984 "TypePromotionHelper should have filtered out those cases");
1985
1986 ExtAddrMode BackupAddrMode = AddrMode;
1987 unsigned OldSize = AddrModeInsts.size();
1988
1989 if (!MatchAddr(PromotedOperand, Depth) ||
Quentin Colombet867c5502014-02-14 22:23:22 +00001990 !IsPromotionProfitable(AddrModeInsts.size(), OldSize + CreatedInsts,
1991 PromotedOperand)) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001992 AddrMode = BackupAddrMode;
1993 AddrModeInsts.resize(OldSize);
1994 DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
1995 TPT.rollback(LastKnownGood);
1996 return false;
1997 }
1998 return true;
1999 }
Chandler Carruthc8925912013-01-05 02:09:22 +00002000 }
2001 return false;
2002}
2003
2004/// MatchAddr - If we can, try to add the value of 'Addr' into the current
2005/// addressing mode. If Addr can't be added to AddrMode this returns false and
2006/// leaves AddrMode unmodified. This assumes that Addr is either a pointer type
2007/// or intptr_t for the target.
2008///
2009bool AddressingModeMatcher::MatchAddr(Value *Addr, unsigned Depth) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002010 // Start a transaction at this point that we will rollback if the matching
2011 // fails.
2012 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2013 TPT.getRestorationPoint();
Chandler Carruthc8925912013-01-05 02:09:22 +00002014 if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
2015 // Fold in immediates if legal for the target.
2016 AddrMode.BaseOffs += CI->getSExtValue();
2017 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2018 return true;
2019 AddrMode.BaseOffs -= CI->getSExtValue();
2020 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
2021 // If this is a global variable, try to fold it into the addressing mode.
2022 if (AddrMode.BaseGV == 0) {
2023 AddrMode.BaseGV = GV;
2024 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2025 return true;
2026 AddrMode.BaseGV = 0;
2027 }
2028 } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
2029 ExtAddrMode BackupAddrMode = AddrMode;
2030 unsigned OldSize = AddrModeInsts.size();
2031
2032 // Check to see if it is possible to fold this operation.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002033 bool MovedAway = false;
2034 if (MatchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
2035 // This instruction may have been move away. If so, there is nothing
2036 // to check here.
2037 if (MovedAway)
2038 return true;
Chandler Carruthc8925912013-01-05 02:09:22 +00002039 // Okay, it's possible to fold this. Check to see if it is actually
2040 // *profitable* to do so. We use a simple cost model to avoid increasing
2041 // register pressure too much.
2042 if (I->hasOneUse() ||
2043 IsProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
2044 AddrModeInsts.push_back(I);
2045 return true;
2046 }
Stephen Lin837bba12013-07-15 17:55:02 +00002047
Chandler Carruthc8925912013-01-05 02:09:22 +00002048 // It isn't profitable to do this, roll back.
2049 //cerr << "NOT FOLDING: " << *I;
2050 AddrMode = BackupAddrMode;
2051 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002052 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00002053 }
2054 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
2055 if (MatchOperationAddr(CE, CE->getOpcode(), Depth))
2056 return true;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002057 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00002058 } else if (isa<ConstantPointerNull>(Addr)) {
2059 // Null pointer gets folded without affecting the addressing mode.
2060 return true;
2061 }
2062
2063 // Worse case, the target should support [reg] addressing modes. :)
2064 if (!AddrMode.HasBaseReg) {
2065 AddrMode.HasBaseReg = true;
2066 AddrMode.BaseReg = Addr;
2067 // Still check for legality in case the target supports [imm] but not [i+r].
2068 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2069 return true;
2070 AddrMode.HasBaseReg = false;
2071 AddrMode.BaseReg = 0;
2072 }
2073
2074 // If the base register is already taken, see if we can do [r+r].
2075 if (AddrMode.Scale == 0) {
2076 AddrMode.Scale = 1;
2077 AddrMode.ScaledReg = Addr;
2078 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2079 return true;
2080 AddrMode.Scale = 0;
2081 AddrMode.ScaledReg = 0;
2082 }
2083 // Couldn't match.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002084 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00002085 return false;
2086}
2087
2088/// IsOperandAMemoryOperand - Check to see if all uses of OpVal by the specified
2089/// inline asm call are due to memory operands. If so, return true, otherwise
2090/// return false.
2091static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
2092 const TargetLowering &TLI) {
2093 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(ImmutableCallSite(CI));
2094 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
2095 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Stephen Lin837bba12013-07-15 17:55:02 +00002096
Chandler Carruthc8925912013-01-05 02:09:22 +00002097 // Compute the constraint code and ConstraintType to use.
2098 TLI.ComputeConstraintToUse(OpInfo, SDValue());
2099
2100 // If this asm operand is our Value*, and if it isn't an indirect memory
2101 // operand, we can't fold it!
2102 if (OpInfo.CallOperandVal == OpVal &&
2103 (OpInfo.ConstraintType != TargetLowering::C_Memory ||
2104 !OpInfo.isIndirect))
2105 return false;
2106 }
2107
2108 return true;
2109}
2110
2111/// FindAllMemoryUses - Recursively walk all the uses of I until we find a
2112/// memory use. If we find an obviously non-foldable instruction, return true.
2113/// Add the ultimately found memory instructions to MemoryUses.
2114static bool FindAllMemoryUses(Instruction *I,
2115 SmallVectorImpl<std::pair<Instruction*,unsigned> > &MemoryUses,
2116 SmallPtrSet<Instruction*, 16> &ConsideredInsts,
2117 const TargetLowering &TLI) {
2118 // If we already considered this instruction, we're done.
2119 if (!ConsideredInsts.insert(I))
2120 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00002121
Chandler Carruthc8925912013-01-05 02:09:22 +00002122 // If this is an obviously unfoldable instruction, bail out.
2123 if (!MightBeFoldableInst(I))
2124 return true;
2125
2126 // Loop over all the uses, recursively processing them.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002127 for (Use &U : I->uses()) {
2128 Instruction *UserI = cast<Instruction>(U.getUser());
Chandler Carruthc8925912013-01-05 02:09:22 +00002129
Chandler Carruthcdf47882014-03-09 03:16:01 +00002130 if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
2131 MemoryUses.push_back(std::make_pair(LI, U.getOperandNo()));
Chandler Carruthc8925912013-01-05 02:09:22 +00002132 continue;
2133 }
Stephen Lin837bba12013-07-15 17:55:02 +00002134
Chandler Carruthcdf47882014-03-09 03:16:01 +00002135 if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
2136 unsigned opNo = U.getOperandNo();
Chandler Carruthc8925912013-01-05 02:09:22 +00002137 if (opNo == 0) return true; // Storing addr, not into addr.
2138 MemoryUses.push_back(std::make_pair(SI, opNo));
2139 continue;
2140 }
Stephen Lin837bba12013-07-15 17:55:02 +00002141
Chandler Carruthcdf47882014-03-09 03:16:01 +00002142 if (CallInst *CI = dyn_cast<CallInst>(UserI)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002143 InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
2144 if (!IA) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002145
Chandler Carruthc8925912013-01-05 02:09:22 +00002146 // If this is a memory operand, we're cool, otherwise bail out.
2147 if (!IsOperandAMemoryOperand(CI, IA, I, TLI))
2148 return true;
2149 continue;
2150 }
Stephen Lin837bba12013-07-15 17:55:02 +00002151
Chandler Carruthcdf47882014-03-09 03:16:01 +00002152 if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TLI))
Chandler Carruthc8925912013-01-05 02:09:22 +00002153 return true;
2154 }
2155
2156 return false;
2157}
2158
2159/// ValueAlreadyLiveAtInst - Retrn true if Val is already known to be live at
2160/// the use site that we're folding it into. If so, there is no cost to
2161/// include it in the addressing mode. KnownLive1 and KnownLive2 are two values
2162/// that we know are live at the instruction already.
2163bool AddressingModeMatcher::ValueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
2164 Value *KnownLive2) {
2165 // If Val is either of the known-live values, we know it is live!
2166 if (Val == 0 || Val == KnownLive1 || Val == KnownLive2)
2167 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002168
Chandler Carruthc8925912013-01-05 02:09:22 +00002169 // All values other than instructions and arguments (e.g. constants) are live.
2170 if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002171
Chandler Carruthc8925912013-01-05 02:09:22 +00002172 // If Val is a constant sized alloca in the entry block, it is live, this is
2173 // true because it is just a reference to the stack/frame pointer, which is
2174 // live for the whole function.
2175 if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
2176 if (AI->isStaticAlloca())
2177 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002178
Chandler Carruthc8925912013-01-05 02:09:22 +00002179 // Check to see if this value is already used in the memory instruction's
2180 // block. If so, it's already live into the block at the very least, so we
2181 // can reasonably fold it.
2182 return Val->isUsedInBasicBlock(MemoryInst->getParent());
2183}
2184
2185/// IsProfitableToFoldIntoAddressingMode - It is possible for the addressing
2186/// mode of the machine to fold the specified instruction into a load or store
2187/// that ultimately uses it. However, the specified instruction has multiple
2188/// uses. Given this, it may actually increase register pressure to fold it
2189/// into the load. For example, consider this code:
2190///
2191/// X = ...
2192/// Y = X+1
2193/// use(Y) -> nonload/store
2194/// Z = Y+1
2195/// load Z
2196///
2197/// In this case, Y has multiple uses, and can be folded into the load of Z
2198/// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to
2199/// be live at the use(Y) line. If we don't fold Y into load Z, we use one
2200/// fewer register. Since Y can't be folded into "use(Y)" we don't increase the
2201/// number of computations either.
2202///
2203/// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If
2204/// X was live across 'load Z' for other reasons, we actually *would* want to
2205/// fold the addressing mode in the Z case. This would make Y die earlier.
2206bool AddressingModeMatcher::
2207IsProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
2208 ExtAddrMode &AMAfter) {
2209 if (IgnoreProfitability) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002210
Chandler Carruthc8925912013-01-05 02:09:22 +00002211 // AMBefore is the addressing mode before this instruction was folded into it,
2212 // and AMAfter is the addressing mode after the instruction was folded. Get
2213 // the set of registers referenced by AMAfter and subtract out those
2214 // referenced by AMBefore: this is the set of values which folding in this
2215 // address extends the lifetime of.
2216 //
2217 // Note that there are only two potential values being referenced here,
2218 // BaseReg and ScaleReg (global addresses are always available, as are any
2219 // folded immediates).
2220 Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
Stephen Lin837bba12013-07-15 17:55:02 +00002221
Chandler Carruthc8925912013-01-05 02:09:22 +00002222 // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
2223 // lifetime wasn't extended by adding this instruction.
2224 if (ValueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
2225 BaseReg = 0;
2226 if (ValueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
2227 ScaledReg = 0;
2228
2229 // If folding this instruction (and it's subexprs) didn't extend any live
2230 // ranges, we're ok with it.
2231 if (BaseReg == 0 && ScaledReg == 0)
2232 return true;
2233
2234 // If all uses of this instruction are ultimately load/store/inlineasm's,
2235 // check to see if their addressing modes will include this instruction. If
2236 // so, we can fold it into all uses, so it doesn't matter if it has multiple
2237 // uses.
2238 SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
2239 SmallPtrSet<Instruction*, 16> ConsideredInsts;
2240 if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TLI))
2241 return false; // Has a non-memory, non-foldable use!
Stephen Lin837bba12013-07-15 17:55:02 +00002242
Chandler Carruthc8925912013-01-05 02:09:22 +00002243 // Now that we know that all uses of this instruction are part of a chain of
2244 // computation involving only operations that could theoretically be folded
2245 // into a memory use, loop over each of these uses and see if they could
2246 // *actually* fold the instruction.
2247 SmallVector<Instruction*, 32> MatchedAddrModeInsts;
2248 for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
2249 Instruction *User = MemoryUses[i].first;
2250 unsigned OpNo = MemoryUses[i].second;
Stephen Lin837bba12013-07-15 17:55:02 +00002251
Chandler Carruthc8925912013-01-05 02:09:22 +00002252 // Get the access type of this use. If the use isn't a pointer, we don't
2253 // know what it accesses.
2254 Value *Address = User->getOperand(OpNo);
2255 if (!Address->getType()->isPointerTy())
2256 return false;
Matt Arsenault8227b9f2013-09-06 00:37:24 +00002257 Type *AddressAccessTy = Address->getType()->getPointerElementType();
Stephen Lin837bba12013-07-15 17:55:02 +00002258
Chandler Carruthc8925912013-01-05 02:09:22 +00002259 // Do a match against the root of this address, ignoring profitability. This
2260 // will tell us if the addressing mode for the memory operation will
2261 // *actually* cover the shared instruction.
2262 ExtAddrMode Result;
Quentin Colombet5a69dda2014-02-11 01:59:02 +00002263 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2264 TPT.getRestorationPoint();
Chandler Carruthc8925912013-01-05 02:09:22 +00002265 AddressingModeMatcher Matcher(MatchedAddrModeInsts, TLI, AddressAccessTy,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002266 MemoryInst, Result, InsertedTruncs,
2267 PromotedInsts, TPT);
Chandler Carruthc8925912013-01-05 02:09:22 +00002268 Matcher.IgnoreProfitability = true;
2269 bool Success = Matcher.MatchAddr(Address, 0);
2270 (void)Success; assert(Success && "Couldn't select *anything*?");
2271
Quentin Colombet5a69dda2014-02-11 01:59:02 +00002272 // The match was to check the profitability, the changes made are not
2273 // part of the original matcher. Therefore, they should be dropped
2274 // otherwise the original matcher will not present the right state.
2275 TPT.rollback(LastKnownGood);
2276
Chandler Carruthc8925912013-01-05 02:09:22 +00002277 // If the match didn't cover I, then it won't be shared by it.
2278 if (std::find(MatchedAddrModeInsts.begin(), MatchedAddrModeInsts.end(),
2279 I) == MatchedAddrModeInsts.end())
2280 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00002281
Chandler Carruthc8925912013-01-05 02:09:22 +00002282 MatchedAddrModeInsts.clear();
2283 }
Stephen Lin837bba12013-07-15 17:55:02 +00002284
Chandler Carruthc8925912013-01-05 02:09:22 +00002285 return true;
2286}
2287
2288} // end anonymous namespace
2289
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002290/// IsNonLocalValue - Return true if the specified values are defined in a
2291/// different basic block than BB.
2292static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
2293 if (Instruction *I = dyn_cast<Instruction>(V))
2294 return I->getParent() != BB;
2295 return false;
2296}
2297
Bob Wilson53bdae32009-12-03 21:47:07 +00002298/// OptimizeMemoryInst - Load and Store Instructions often have
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002299/// addressing modes that can do significant amounts of computation. As such,
2300/// instruction selection will try to get the load or store to do as much
2301/// computation as possible for the program. The problem is that isel can only
2302/// see within a single block. As such, we sink as much legal addressing mode
2303/// stuff into the block as possible.
Chris Lattner728f9022008-11-25 07:09:13 +00002304///
2305/// This method is used to optimize both load/store and inline asms with memory
2306/// operands.
Chris Lattner6d71b7f2008-11-26 03:20:37 +00002307bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
Chris Lattner229907c2011-07-18 04:54:35 +00002308 Type *AccessTy) {
Owen Anderson8ba5f392010-11-27 08:15:55 +00002309 Value *Repl = Addr;
Nadav Rotem465834c2012-07-24 10:51:42 +00002310
2311 // Try to collapse single-value PHI nodes. This is necessary to undo
Owen Andersondfb8c3b2010-11-19 22:15:03 +00002312 // unprofitable PRE transformations.
Cameron Zwarich43cecb12011-01-03 06:33:01 +00002313 SmallVector<Value*, 8> worklist;
2314 SmallPtrSet<Value*, 16> Visited;
Owen Anderson8ba5f392010-11-27 08:15:55 +00002315 worklist.push_back(Addr);
Nadav Rotem465834c2012-07-24 10:51:42 +00002316
Owen Anderson8ba5f392010-11-27 08:15:55 +00002317 // Use a worklist to iteratively look through PHI nodes, and ensure that
2318 // the addressing mode obtained from the non-PHI roots of the graph
2319 // are equivalent.
2320 Value *Consensus = 0;
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00002321 unsigned NumUsesConsensus = 0;
Cameron Zwarich13c885d2011-03-05 08:12:26 +00002322 bool IsNumUsesConsensusValid = false;
Owen Anderson8ba5f392010-11-27 08:15:55 +00002323 SmallVector<Instruction*, 16> AddrModeInsts;
2324 ExtAddrMode AddrMode;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002325 TypePromotionTransaction TPT;
2326 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2327 TPT.getRestorationPoint();
Owen Anderson8ba5f392010-11-27 08:15:55 +00002328 while (!worklist.empty()) {
2329 Value *V = worklist.back();
2330 worklist.pop_back();
Nadav Rotem465834c2012-07-24 10:51:42 +00002331
Owen Anderson8ba5f392010-11-27 08:15:55 +00002332 // Break use-def graph loops.
Nick Lewyckya3e7ffd2011-09-29 23:40:12 +00002333 if (!Visited.insert(V)) {
Owen Anderson8ba5f392010-11-27 08:15:55 +00002334 Consensus = 0;
2335 break;
Owen Andersondfb8c3b2010-11-19 22:15:03 +00002336 }
Nadav Rotem465834c2012-07-24 10:51:42 +00002337
Owen Anderson8ba5f392010-11-27 08:15:55 +00002338 // For a PHI node, push all of its incoming values.
2339 if (PHINode *P = dyn_cast<PHINode>(V)) {
2340 for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i)
2341 worklist.push_back(P->getIncomingValue(i));
2342 continue;
2343 }
Nadav Rotem465834c2012-07-24 10:51:42 +00002344
Owen Anderson8ba5f392010-11-27 08:15:55 +00002345 // For non-PHIs, determine the addressing mode being computed.
2346 SmallVector<Instruction*, 16> NewAddrModeInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002347 ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
2348 V, AccessTy, MemoryInst, NewAddrModeInsts, *TLI, InsertedTruncsSet,
2349 PromotedInsts, TPT);
Cameron Zwarich13c885d2011-03-05 08:12:26 +00002350
2351 // This check is broken into two cases with very similar code to avoid using
2352 // getNumUses() as much as possible. Some values have a lot of uses, so
2353 // calling getNumUses() unconditionally caused a significant compile-time
2354 // regression.
2355 if (!Consensus) {
2356 Consensus = V;
2357 AddrMode = NewAddrMode;
2358 AddrModeInsts = NewAddrModeInsts;
2359 continue;
2360 } else if (NewAddrMode == AddrMode) {
2361 if (!IsNumUsesConsensusValid) {
2362 NumUsesConsensus = Consensus->getNumUses();
2363 IsNumUsesConsensusValid = true;
2364 }
2365
2366 // Ensure that the obtained addressing mode is equivalent to that obtained
2367 // for all other roots of the PHI traversal. Also, when choosing one
2368 // such root as representative, select the one with the most uses in order
2369 // to keep the cost modeling heuristics in AddressingModeMatcher
2370 // applicable.
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00002371 unsigned NumUses = V->getNumUses();
2372 if (NumUses > NumUsesConsensus) {
Owen Anderson8ba5f392010-11-27 08:15:55 +00002373 Consensus = V;
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00002374 NumUsesConsensus = NumUses;
Owen Anderson8ba5f392010-11-27 08:15:55 +00002375 AddrModeInsts = NewAddrModeInsts;
2376 }
2377 continue;
2378 }
Nadav Rotem465834c2012-07-24 10:51:42 +00002379
Owen Anderson8ba5f392010-11-27 08:15:55 +00002380 Consensus = 0;
2381 break;
Owen Andersondfb8c3b2010-11-19 22:15:03 +00002382 }
Nadav Rotem465834c2012-07-24 10:51:42 +00002383
Owen Anderson8ba5f392010-11-27 08:15:55 +00002384 // If the addressing mode couldn't be determined, or if multiple different
2385 // ones were determined, bail out now.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002386 if (!Consensus) {
2387 TPT.rollback(LastKnownGood);
2388 return false;
2389 }
2390 TPT.commit();
Nadav Rotem465834c2012-07-24 10:51:42 +00002391
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002392 // Check to see if any of the instructions supersumed by this addr mode are
2393 // non-local to I's BB.
2394 bool AnyNonLocal = false;
2395 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
Chris Lattner6d71b7f2008-11-26 03:20:37 +00002396 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002397 AnyNonLocal = true;
2398 break;
2399 }
2400 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00002401
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002402 // If all the instructions matched are already in this BB, don't do anything.
2403 if (!AnyNonLocal) {
David Greene74e2d492010-01-05 01:27:11 +00002404 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002405 return false;
2406 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00002407
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002408 // Insert this computation right after this user. Since our caller is
2409 // scanning from the top of the BB to the bottom, reuse of the expr are
2410 // guaranteed to happen later.
Devang Patelc10e52a2011-09-06 18:49:53 +00002411 IRBuilder<> Builder(MemoryInst);
Eric Christopherc1ea1492008-09-24 05:32:41 +00002412
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002413 // Now that we determined the addressing expression we want to use and know
2414 // that we have to sink it into this block. Check to see if we have already
2415 // done this for some other load/store instr in this block. If so, reuse the
2416 // computation.
2417 Value *&SunkAddr = SunkAddrs[Addr];
2418 if (SunkAddr) {
David Greene74e2d492010-01-05 01:27:11 +00002419 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
Dan Gohman29f2baf2009-07-25 01:13:51 +00002420 << *MemoryInst);
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002421 if (SunkAddr->getType() != Addr->getType())
Benjamin Kramer547b6c52011-09-27 20:39:19 +00002422 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002423 } else {
David Greene74e2d492010-01-05 01:27:11 +00002424 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Dan Gohman29f2baf2009-07-25 01:13:51 +00002425 << *MemoryInst);
Matt Arsenault37d42ec2013-09-06 00:18:43 +00002426 Type *IntPtrTy = TLI->getDataLayout()->getIntPtrType(Addr->getType());
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002427 Value *Result = 0;
Dan Gohmanca194452010-01-19 22:45:06 +00002428
2429 // Start with the base register. Do this first so that subsequent address
2430 // matching finds it last, which will prevent it from trying to match it
2431 // as the scaled value in case it happens to be a mul. That would be
2432 // problematic if we've sunk a different mul for the scale, because then
2433 // we'd end up sinking both muls.
2434 if (AddrMode.BaseReg) {
2435 Value *V = AddrMode.BaseReg;
Duncan Sands19d0b472010-02-16 11:11:14 +00002436 if (V->getType()->isPointerTy())
Devang Patelc10e52a2011-09-06 18:49:53 +00002437 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00002438 if (V->getType() != IntPtrTy)
Devang Patelc10e52a2011-09-06 18:49:53 +00002439 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00002440 Result = V;
2441 }
2442
2443 // Add the scale value.
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002444 if (AddrMode.Scale) {
2445 Value *V = AddrMode.ScaledReg;
2446 if (V->getType() == IntPtrTy) {
2447 // done.
Duncan Sands19d0b472010-02-16 11:11:14 +00002448 } else if (V->getType()->isPointerTy()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00002449 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002450 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
2451 cast<IntegerType>(V->getType())->getBitWidth()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00002452 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002453 } else {
Jim Grosbached2cd392014-03-26 17:27:01 +00002454 // It is only safe to sign extend the BaseReg if we know that the math
2455 // required to create it did not overflow before we extend it. Since
2456 // the original IR value was tossed in favor of a constant back when
2457 // the AddrMode was created we need to bail out gracefully if widths
2458 // do not match instead of extending it.
2459 if (Result != AddrMode.BaseReg)
2460 cast<Instruction>(Result)->eraseFromParent();
2461 return false;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002462 }
2463 if (AddrMode.Scale != 1)
Devang Patelc10e52a2011-09-06 18:49:53 +00002464 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
2465 "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002466 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00002467 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002468 else
2469 Result = V;
2470 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00002471
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002472 // Add in the BaseGV if present.
2473 if (AddrMode.BaseGV) {
Devang Patelc10e52a2011-09-06 18:49:53 +00002474 Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002475 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00002476 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002477 else
2478 Result = V;
2479 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00002480
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002481 // Add in the Base Offset if present.
2482 if (AddrMode.BaseOffs) {
Owen Andersonedb4a702009-07-24 23:12:02 +00002483 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002484 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00002485 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002486 else
2487 Result = V;
2488 }
2489
2490 if (Result == 0)
Owen Anderson5a1acd92009-07-31 20:28:14 +00002491 SunkAddr = Constant::getNullValue(Addr->getType());
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002492 else
Devang Patelc10e52a2011-09-06 18:49:53 +00002493 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002494 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00002495
Owen Andersondfb8c3b2010-11-19 22:15:03 +00002496 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
Eric Christopherc1ea1492008-09-24 05:32:41 +00002497
Chris Lattneraf1bcce2011-04-09 07:05:44 +00002498 // If we have no uses, recursively delete the value and all dead instructions
2499 // using it.
Owen Andersondfb8c3b2010-11-19 22:15:03 +00002500 if (Repl->use_empty()) {
Chris Lattneraf1bcce2011-04-09 07:05:44 +00002501 // This can cause recursive deletion, which can invalidate our iterator.
2502 // Use a WeakVH to hold onto it in case this happens.
2503 WeakVH IterHandle(CurInstIterator);
2504 BasicBlock *BB = CurInstIterator->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +00002505
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00002506 RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
Chris Lattneraf1bcce2011-04-09 07:05:44 +00002507
2508 if (IterHandle != CurInstIterator) {
2509 // If the iterator instruction was recursively deleted, start over at the
2510 // start of the block.
2511 CurInstIterator = BB->begin();
2512 SunkAddrs.clear();
Nadav Rotem465834c2012-07-24 10:51:42 +00002513 }
Dale Johannesenb67a6e662010-03-31 20:37:15 +00002514 }
Cameron Zwarichced753f2011-01-05 17:27:27 +00002515 ++NumMemoryInsts;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002516 return true;
2517}
2518
Evan Cheng1da25002008-02-26 02:42:37 +00002519/// OptimizeInlineAsmInst - If there are any memory operands, use
Chris Lattner728f9022008-11-25 07:09:13 +00002520/// OptimizeMemoryInst to sink their address computing into the block when
Evan Cheng1da25002008-02-26 02:42:37 +00002521/// possible / profitable.
Chris Lattner7a277142011-01-15 07:14:54 +00002522bool CodeGenPrepare::OptimizeInlineAsmInst(CallInst *CS) {
Evan Cheng1da25002008-02-26 02:42:37 +00002523 bool MadeChange = false;
Evan Cheng1da25002008-02-26 02:42:37 +00002524
Nadav Rotem465834c2012-07-24 10:51:42 +00002525 TargetLowering::AsmOperandInfoVector
Chris Lattner7a277142011-01-15 07:14:54 +00002526 TargetConstraints = TLI->ParseConstraints(CS);
Dale Johannesenf95f59a2010-09-16 18:30:55 +00002527 unsigned ArgNo = 0;
John Thompson1094c802010-09-13 18:15:37 +00002528 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
2529 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Nadav Rotem465834c2012-07-24 10:51:42 +00002530
Evan Cheng1da25002008-02-26 02:42:37 +00002531 // Compute the constraint code and ConstraintType to use.
Dale Johannesence97d552010-06-25 21:55:36 +00002532 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Evan Cheng1da25002008-02-26 02:42:37 +00002533
Eli Friedman666bbe32008-02-26 18:37:49 +00002534 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
2535 OpInfo.isIndirect) {
Chris Lattner7a277142011-01-15 07:14:54 +00002536 Value *OpVal = CS->getArgOperand(ArgNo++);
Chris Lattneree588de2011-01-15 07:29:01 +00002537 MadeChange |= OptimizeMemoryInst(CS, OpVal, OpVal->getType());
Dale Johannesenf95f59a2010-09-16 18:30:55 +00002538 } else if (OpInfo.Type == InlineAsm::isInput)
2539 ArgNo++;
Evan Cheng1da25002008-02-26 02:42:37 +00002540 }
2541
2542 return MadeChange;
2543}
2544
Dan Gohman99429a02009-10-16 20:59:35 +00002545/// MoveExtToFormExtLoad - Move a zext or sext fed by a load into the same
2546/// basic block as the load, unless conditions are unfavorable. This allows
2547/// SelectionDAG to fold the extend into the load.
2548///
2549bool CodeGenPrepare::MoveExtToFormExtLoad(Instruction *I) {
2550 // Look for a load being extended.
2551 LoadInst *LI = dyn_cast<LoadInst>(I->getOperand(0));
2552 if (!LI) return false;
2553
2554 // If they're already in the same block, there's nothing to do.
2555 if (LI->getParent() == I->getParent())
2556 return false;
2557
2558 // If the load has other users and the truncate is not free, this probably
2559 // isn't worthwhile.
2560 if (!LI->hasOneUse() &&
Bob Wilsonb6832a42010-09-22 18:44:56 +00002561 TLI && (TLI->isTypeLegal(TLI->getValueType(LI->getType())) ||
2562 !TLI->isTypeLegal(TLI->getValueType(I->getType()))) &&
Bob Wilson4ddcb6a2010-09-21 21:54:27 +00002563 !TLI->isTruncateFree(I->getType(), LI->getType()))
Dan Gohman99429a02009-10-16 20:59:35 +00002564 return false;
2565
2566 // Check whether the target supports casts folded into loads.
2567 unsigned LType;
2568 if (isa<ZExtInst>(I))
2569 LType = ISD::ZEXTLOAD;
2570 else {
2571 assert(isa<SExtInst>(I) && "Unexpected ext type!");
2572 LType = ISD::SEXTLOAD;
2573 }
Patrik Hagglunde98b7a02012-12-11 11:14:33 +00002574 if (TLI && !TLI->isLoadExtLegal(LType, TLI->getValueType(LI->getType())))
Dan Gohman99429a02009-10-16 20:59:35 +00002575 return false;
2576
2577 // Move the extend into the same block as the load, so that SelectionDAG
2578 // can fold it.
2579 I->removeFromParent();
2580 I->insertAfter(LI);
Cameron Zwarichced753f2011-01-05 17:27:27 +00002581 ++NumExtsMoved;
Dan Gohman99429a02009-10-16 20:59:35 +00002582 return true;
2583}
2584
Evan Chengd3d80172007-12-05 23:58:20 +00002585bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
2586 BasicBlock *DefBB = I->getParent();
2587
Bob Wilsonff714f92010-09-21 21:44:14 +00002588 // If the result of a {s|z}ext and its source are both live out, rewrite all
Evan Chengd3d80172007-12-05 23:58:20 +00002589 // other uses of the source with result of extension.
2590 Value *Src = I->getOperand(0);
2591 if (Src->hasOneUse())
2592 return false;
2593
Evan Cheng2011df42007-12-13 07:50:36 +00002594 // Only do this xform if truncating is free.
Gabor Greifaa261722008-02-26 19:13:21 +00002595 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
Evan Cheng37c36ed2007-12-13 03:32:53 +00002596 return false;
2597
Evan Cheng7bc89422007-12-12 00:51:06 +00002598 // Only safe to perform the optimization if the source is also defined in
Evan Cheng63d33cf2007-12-12 02:53:41 +00002599 // this block.
2600 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
Evan Cheng7bc89422007-12-12 00:51:06 +00002601 return false;
2602
Evan Chengd3d80172007-12-05 23:58:20 +00002603 bool DefIsLiveOut = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00002604 for (User *U : I->users()) {
2605 Instruction *UI = cast<Instruction>(U);
Evan Chengd3d80172007-12-05 23:58:20 +00002606
2607 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002608 BasicBlock *UserBB = UI->getParent();
Evan Chengd3d80172007-12-05 23:58:20 +00002609 if (UserBB == DefBB) continue;
2610 DefIsLiveOut = true;
2611 break;
2612 }
2613 if (!DefIsLiveOut)
2614 return false;
2615
Jim Grosbach0f38c1e2013-04-15 17:40:48 +00002616 // Make sure none of the uses are PHI nodes.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002617 for (User *U : Src->users()) {
2618 Instruction *UI = cast<Instruction>(U);
2619 BasicBlock *UserBB = UI->getParent();
Evan Cheng37c36ed2007-12-13 03:32:53 +00002620 if (UserBB == DefBB) continue;
2621 // Be conservative. We don't want this xform to end up introducing
2622 // reloads just before load / store instructions.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002623 if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI))
Evan Cheng63d33cf2007-12-12 02:53:41 +00002624 return false;
2625 }
2626
Evan Chengd3d80172007-12-05 23:58:20 +00002627 // InsertedTruncs - Only insert one trunc in each block once.
2628 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
2629
2630 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00002631 for (Use &U : Src->uses()) {
2632 Instruction *User = cast<Instruction>(U.getUser());
Evan Chengd3d80172007-12-05 23:58:20 +00002633
2634 // Figure out which BB this ext is used in.
2635 BasicBlock *UserBB = User->getParent();
2636 if (UserBB == DefBB) continue;
2637
2638 // Both src and def are live in this block. Rewrite the use.
2639 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
2640
2641 if (!InsertedTrunc) {
Bill Wendling8ddfc092011-08-16 20:45:24 +00002642 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Evan Chengd3d80172007-12-05 23:58:20 +00002643 InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002644 InsertedTruncsSet.insert(InsertedTrunc);
Evan Chengd3d80172007-12-05 23:58:20 +00002645 }
2646
2647 // Replace a use of the {s|z}ext source with a use of the result.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002648 U = InsertedTrunc;
Cameron Zwarichced753f2011-01-05 17:27:27 +00002649 ++NumExtUses;
Evan Chengd3d80172007-12-05 23:58:20 +00002650 MadeChange = true;
2651 }
2652
2653 return MadeChange;
2654}
2655
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00002656/// isFormingBranchFromSelectProfitable - Returns true if a SelectInst should be
2657/// turned into an explicit branch.
2658static bool isFormingBranchFromSelectProfitable(SelectInst *SI) {
2659 // FIXME: This should use the same heuristics as IfConversion to determine
2660 // whether a select is better represented as a branch. This requires that
2661 // branch probability metadata is preserved for the select, which is not the
2662 // case currently.
2663
2664 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
2665
2666 // If the branch is predicted right, an out of order CPU can avoid blocking on
2667 // the compare. Emit cmovs on compares with a memory operand as branches to
2668 // avoid stalls on the load from memory. If the compare has more than one use
2669 // there's probably another cmov or setcc around so it's not worth emitting a
2670 // branch.
2671 if (!Cmp)
2672 return false;
2673
2674 Value *CmpOp0 = Cmp->getOperand(0);
2675 Value *CmpOp1 = Cmp->getOperand(1);
2676
2677 // We check that the memory operand has one use to avoid uses of the loaded
2678 // value directly after the compare, making branches unprofitable.
2679 return Cmp->hasOneUse() &&
2680 ((isa<LoadInst>(CmpOp0) && CmpOp0->hasOneUse()) ||
2681 (isa<LoadInst>(CmpOp1) && CmpOp1->hasOneUse()));
2682}
2683
2684
Nadav Rotem9d832022012-09-02 12:10:19 +00002685/// If we have a SelectInst that will likely profit from branch prediction,
2686/// turn it into a branch.
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00002687bool CodeGenPrepare::OptimizeSelectInst(SelectInst *SI) {
Nadav Rotem9d832022012-09-02 12:10:19 +00002688 bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
2689
2690 // Can we convert the 'select' to CF ?
2691 if (DisableSelectToBranch || OptSize || !TLI || VectorCond)
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00002692 return false;
2693
Nadav Rotem9d832022012-09-02 12:10:19 +00002694 TargetLowering::SelectSupportKind SelectKind;
2695 if (VectorCond)
2696 SelectKind = TargetLowering::VectorMaskSelect;
2697 else if (SI->getType()->isVectorTy())
2698 SelectKind = TargetLowering::ScalarCondVectorVal;
2699 else
2700 SelectKind = TargetLowering::ScalarValSelect;
2701
2702 // Do we have efficient codegen support for this kind of 'selects' ?
2703 if (TLI->isSelectSupported(SelectKind)) {
2704 // We have efficient codegen support for the select instruction.
2705 // Check if it is profitable to keep this 'select'.
2706 if (!TLI->isPredictableSelectExpensive() ||
2707 !isFormingBranchFromSelectProfitable(SI))
2708 return false;
2709 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00002710
2711 ModifiedDT = true;
2712
2713 // First, we split the block containing the select into 2 blocks.
2714 BasicBlock *StartBlock = SI->getParent();
2715 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(SI));
2716 BasicBlock *NextBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
2717
2718 // Create a new block serving as the landing pad for the branch.
2719 BasicBlock *SmallBlock = BasicBlock::Create(SI->getContext(), "select.mid",
2720 NextBlock->getParent(), NextBlock);
2721
2722 // Move the unconditional branch from the block with the select in it into our
2723 // landing pad block.
2724 StartBlock->getTerminator()->eraseFromParent();
2725 BranchInst::Create(NextBlock, SmallBlock);
2726
2727 // Insert the real conditional branch based on the original condition.
2728 BranchInst::Create(NextBlock, SmallBlock, SI->getCondition(), SI);
2729
2730 // The select itself is replaced with a PHI Node.
2731 PHINode *PN = PHINode::Create(SI->getType(), 2, "", NextBlock->begin());
2732 PN->takeName(SI);
2733 PN->addIncoming(SI->getTrueValue(), StartBlock);
2734 PN->addIncoming(SI->getFalseValue(), SmallBlock);
2735 SI->replaceAllUsesWith(PN);
2736 SI->eraseFromParent();
2737
2738 // Instruct OptimizeBlock to skip to the next block.
2739 CurInstIterator = StartBlock->end();
2740 ++NumSelectsExpanded;
2741 return true;
2742}
2743
Benjamin Kramer573ff362014-03-01 17:24:40 +00002744static bool isBroadcastShuffle(ShuffleVectorInst *SVI) {
Tim Northoveraeb8e062014-02-19 10:02:43 +00002745 SmallVector<int, 16> Mask(SVI->getShuffleMask());
2746 int SplatElem = -1;
2747 for (unsigned i = 0; i < Mask.size(); ++i) {
2748 if (SplatElem != -1 && Mask[i] != -1 && Mask[i] != SplatElem)
2749 return false;
2750 SplatElem = Mask[i];
2751 }
2752
2753 return true;
2754}
2755
2756/// Some targets have expensive vector shifts if the lanes aren't all the same
2757/// (e.g. x86 only introduced "vpsllvd" and friends with AVX2). In these cases
2758/// it's often worth sinking a shufflevector splat down to its use so that
2759/// codegen can spot all lanes are identical.
2760bool CodeGenPrepare::OptimizeShuffleVectorInst(ShuffleVectorInst *SVI) {
2761 BasicBlock *DefBB = SVI->getParent();
2762
2763 // Only do this xform if variable vector shifts are particularly expensive.
2764 if (!TLI || !TLI->isVectorShiftByScalarCheap(SVI->getType()))
2765 return false;
2766
2767 // We only expect better codegen by sinking a shuffle if we can recognise a
2768 // constant splat.
2769 if (!isBroadcastShuffle(SVI))
2770 return false;
2771
2772 // InsertedShuffles - Only insert a shuffle in each block once.
2773 DenseMap<BasicBlock*, Instruction*> InsertedShuffles;
2774
2775 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00002776 for (User *U : SVI->users()) {
2777 Instruction *UI = cast<Instruction>(U);
Tim Northoveraeb8e062014-02-19 10:02:43 +00002778
2779 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002780 BasicBlock *UserBB = UI->getParent();
Tim Northoveraeb8e062014-02-19 10:02:43 +00002781 if (UserBB == DefBB) continue;
2782
2783 // For now only apply this when the splat is used by a shift instruction.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002784 if (!UI->isShift()) continue;
Tim Northoveraeb8e062014-02-19 10:02:43 +00002785
2786 // Everything checks out, sink the shuffle if the user's block doesn't
2787 // already have a copy.
2788 Instruction *&InsertedShuffle = InsertedShuffles[UserBB];
2789
2790 if (!InsertedShuffle) {
2791 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
2792 InsertedShuffle = new ShuffleVectorInst(SVI->getOperand(0),
2793 SVI->getOperand(1),
2794 SVI->getOperand(2), "", InsertPt);
2795 }
2796
Chandler Carruthcdf47882014-03-09 03:16:01 +00002797 UI->replaceUsesOfWith(SVI, InsertedShuffle);
Tim Northoveraeb8e062014-02-19 10:02:43 +00002798 MadeChange = true;
2799 }
2800
2801 // If we removed all uses, nuke the shuffle.
2802 if (SVI->use_empty()) {
2803 SVI->eraseFromParent();
2804 MadeChange = true;
2805 }
2806
2807 return MadeChange;
2808}
2809
Cameron Zwarich14ac8652011-01-06 02:37:26 +00002810bool CodeGenPrepare::OptimizeInst(Instruction *I) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00002811 if (PHINode *P = dyn_cast<PHINode>(I)) {
2812 // It is possible for very late stage optimizations (such as SimplifyCFG)
2813 // to introduce PHI nodes too late to be cleaned up. If we detect such a
2814 // trivial PHI, go ahead and zap it here.
Benjamin Kramer30d249a2013-09-24 16:37:40 +00002815 if (Value *V = SimplifyInstruction(P, TLI ? TLI->getDataLayout() : 0,
2816 TLInfo, DT)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00002817 P->replaceAllUsesWith(V);
2818 P->eraseFromParent();
2819 ++NumPHIsElim;
Chris Lattneree588de2011-01-15 07:29:01 +00002820 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00002821 }
Chris Lattneree588de2011-01-15 07:29:01 +00002822 return false;
2823 }
Nadav Rotem465834c2012-07-24 10:51:42 +00002824
Chris Lattneree588de2011-01-15 07:29:01 +00002825 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00002826 // If the source of the cast is a constant, then this should have
2827 // already been constant folded. The only reason NOT to constant fold
2828 // it is if something (e.g. LSR) was careful to place the constant
2829 // evaluation in a block other than then one that uses it (e.g. to hoist
2830 // the address of globals out of a loop). If this is the case, we don't
2831 // want to forward-subst the cast.
2832 if (isa<Constant>(CI->getOperand(0)))
2833 return false;
2834
Chris Lattneree588de2011-01-15 07:29:01 +00002835 if (TLI && OptimizeNoopCopyExpression(CI, *TLI))
2836 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00002837
Chris Lattneree588de2011-01-15 07:29:01 +00002838 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +00002839 /// Sink a zext or sext into its user blocks if the target type doesn't
2840 /// fit in one register
2841 if (TLI && TLI->getTypeAction(CI->getContext(),
2842 TLI->getValueType(CI->getType())) ==
2843 TargetLowering::TypeExpandInteger) {
2844 return SinkCast(CI);
2845 } else {
2846 bool MadeChange = MoveExtToFormExtLoad(I);
2847 return MadeChange | OptimizeExtUses(I);
2848 }
Cameron Zwarich14ac8652011-01-06 02:37:26 +00002849 }
Chris Lattneree588de2011-01-15 07:29:01 +00002850 return false;
2851 }
Nadav Rotem465834c2012-07-24 10:51:42 +00002852
Chris Lattneree588de2011-01-15 07:29:01 +00002853 if (CmpInst *CI = dyn_cast<CmpInst>(I))
Hal Finkeldecb0242014-01-02 21:13:43 +00002854 if (!TLI || !TLI->hasMultipleConditionRegisters())
2855 return OptimizeCmpExpression(CI);
Nadav Rotem465834c2012-07-24 10:51:42 +00002856
Chris Lattneree588de2011-01-15 07:29:01 +00002857 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00002858 if (TLI)
Hans Wennborgf3254832012-10-30 11:23:25 +00002859 return OptimizeMemoryInst(I, I->getOperand(0), LI->getType());
2860 return false;
Chris Lattneree588de2011-01-15 07:29:01 +00002861 }
Nadav Rotem465834c2012-07-24 10:51:42 +00002862
Chris Lattneree588de2011-01-15 07:29:01 +00002863 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00002864 if (TLI)
Chris Lattneree588de2011-01-15 07:29:01 +00002865 return OptimizeMemoryInst(I, SI->getOperand(1),
2866 SI->getOperand(0)->getType());
2867 return false;
2868 }
Nadav Rotem465834c2012-07-24 10:51:42 +00002869
Chris Lattneree588de2011-01-15 07:29:01 +00002870 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00002871 if (GEPI->hasAllZeroIndices()) {
2872 /// The GEP operand must be a pointer, so must its result -> BitCast
2873 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
2874 GEPI->getName(), GEPI);
2875 GEPI->replaceAllUsesWith(NC);
2876 GEPI->eraseFromParent();
2877 ++NumGEPsElim;
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00002878 OptimizeInst(NC);
Chris Lattneree588de2011-01-15 07:29:01 +00002879 return true;
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00002880 }
Chris Lattneree588de2011-01-15 07:29:01 +00002881 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00002882 }
Nadav Rotem465834c2012-07-24 10:51:42 +00002883
Chris Lattneree588de2011-01-15 07:29:01 +00002884 if (CallInst *CI = dyn_cast<CallInst>(I))
2885 return OptimizeCallInst(CI);
Cameron Zwarich14ac8652011-01-06 02:37:26 +00002886
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00002887 if (SelectInst *SI = dyn_cast<SelectInst>(I))
2888 return OptimizeSelectInst(SI);
2889
Tim Northoveraeb8e062014-02-19 10:02:43 +00002890 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I))
2891 return OptimizeShuffleVectorInst(SVI);
2892
Chris Lattneree588de2011-01-15 07:29:01 +00002893 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00002894}
2895
Chris Lattnerf2836d12007-03-31 04:06:36 +00002896// In this pass we look for GEP and cast instructions that are used
2897// across basic blocks and rewrite them to improve basic-block-at-a-time
2898// selection.
2899bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
Cameron Zwarichce3b9302011-01-06 00:42:50 +00002900 SunkAddrs.clear();
Cameron Zwarich5dd2aa22011-03-02 03:31:46 +00002901 bool MadeChange = false;
Eric Christopherc1ea1492008-09-24 05:32:41 +00002902
Chris Lattner7a277142011-01-15 07:14:54 +00002903 CurInstIterator = BB.begin();
Hans Wennborg02fbc712012-09-19 07:48:16 +00002904 while (CurInstIterator != BB.end())
Chris Lattner1b93be52011-01-15 07:25:29 +00002905 MadeChange |= OptimizeInst(CurInstIterator++);
Eric Christopherc1ea1492008-09-24 05:32:41 +00002906
Benjamin Kramer455fa352012-11-23 19:17:06 +00002907 MadeChange |= DupRetToEnableTailCallOpts(&BB);
2908
Chris Lattnerf2836d12007-03-31 04:06:36 +00002909 return MadeChange;
2910}
Devang Patel53771ba2011-08-18 00:50:51 +00002911
2912// llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotem465834c2012-07-24 10:51:42 +00002913// handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patel53771ba2011-08-18 00:50:51 +00002914// find a node corresponding to the value.
2915bool CodeGenPrepare::PlaceDbgValues(Function &F) {
2916 bool MadeChange = false;
2917 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
2918 Instruction *PrevNonDbgInst = NULL;
2919 for (BasicBlock::iterator BI = I->begin(), BE = I->end(); BI != BE;) {
2920 Instruction *Insn = BI; ++BI;
2921 DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
2922 if (!DVI) {
2923 PrevNonDbgInst = Insn;
2924 continue;
2925 }
2926
2927 Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
2928 if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
2929 DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
2930 DVI->removeFromParent();
2931 if (isa<PHINode>(VI))
2932 DVI->insertBefore(VI->getParent()->getFirstInsertionPt());
2933 else
2934 DVI->insertAfter(VI);
2935 MadeChange = true;
2936 ++NumDbgValueMoved;
2937 }
2938 }
2939 }
2940 return MadeChange;
2941}
Tim Northovercea0abb2014-03-29 08:22:29 +00002942
2943// If there is a sequence that branches based on comparing a single bit
2944// against zero that can be combined into a single instruction, and the
2945// target supports folding these into a single instruction, sink the
2946// mask and compare into the branch uses. Do this before OptimizeBlock ->
2947// OptimizeInst -> OptimizeCmpExpression, which perturbs the pattern being
2948// searched for.
2949bool CodeGenPrepare::sinkAndCmp(Function &F) {
2950 if (!EnableAndCmpSinking)
2951 return false;
2952 if (!TLI || !TLI->isMaskAndBranchFoldingLegal())
2953 return false;
2954 bool MadeChange = false;
2955 for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
2956 BasicBlock *BB = I++;
2957
2958 // Does this BB end with the following?
2959 // %andVal = and %val, #single-bit-set
2960 // %icmpVal = icmp %andResult, 0
2961 // br i1 %cmpVal label %dest1, label %dest2"
2962 BranchInst *Brcc = dyn_cast<BranchInst>(BB->getTerminator());
2963 if (!Brcc || !Brcc->isConditional())
2964 continue;
2965 ICmpInst *Cmp = dyn_cast<ICmpInst>(Brcc->getOperand(0));
2966 if (!Cmp || Cmp->getParent() != BB)
2967 continue;
2968 ConstantInt *Zero = dyn_cast<ConstantInt>(Cmp->getOperand(1));
2969 if (!Zero || !Zero->isZero())
2970 continue;
2971 Instruction *And = dyn_cast<Instruction>(Cmp->getOperand(0));
2972 if (!And || And->getOpcode() != Instruction::And || And->getParent() != BB)
2973 continue;
2974 ConstantInt* Mask = dyn_cast<ConstantInt>(And->getOperand(1));
2975 if (!Mask || !Mask->getUniqueInteger().isPowerOf2())
2976 continue;
2977 DEBUG(dbgs() << "found and; icmp ?,0; brcc\n"); DEBUG(BB->dump());
2978
2979 // Push the "and; icmp" for any users that are conditional branches.
2980 // Since there can only be one branch use per BB, we don't need to keep
2981 // track of which BBs we insert into.
2982 for (Value::use_iterator UI = Cmp->use_begin(), E = Cmp->use_end();
2983 UI != E; ) {
2984 Use &TheUse = *UI;
2985 // Find brcc use.
2986 BranchInst *BrccUser = dyn_cast<BranchInst>(*UI);
2987 ++UI;
2988 if (!BrccUser || !BrccUser->isConditional())
2989 continue;
2990 BasicBlock *UserBB = BrccUser->getParent();
2991 if (UserBB == BB) continue;
2992 DEBUG(dbgs() << "found Brcc use\n");
2993
2994 // Sink the "and; icmp" to use.
2995 MadeChange = true;
2996 BinaryOperator *NewAnd =
2997 BinaryOperator::CreateAnd(And->getOperand(0), And->getOperand(1), "",
2998 BrccUser);
2999 CmpInst *NewCmp =
3000 CmpInst::Create(Cmp->getOpcode(), Cmp->getPredicate(), NewAnd, Zero,
3001 "", BrccUser);
3002 TheUse = NewCmp;
3003 ++NumAndCmpsMoved;
3004 DEBUG(BrccUser->getParent()->dump());
3005 }
3006 }
3007 return MadeChange;
3008}