blob: 91d702a56608e5958a16565fbbdf48b2990e36fc [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"
Hal Finkelc3998302014-04-12 00:59:48 +000042#include "llvm/Target/TargetSubtargetInfo.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000043#include "llvm/Transforms/Utils/BasicBlockUtils.h"
44#include "llvm/Transforms/Utils/BuildLibCalls.h"
Preston Gurdcdf540d2012-09-04 18:22:17 +000045#include "llvm/Transforms/Utils/BypassSlowDivision.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000046#include "llvm/Transforms/Utils/Local.h"
Chris Lattnerf2836d12007-03-31 04:06:36 +000047using namespace llvm;
Chris Lattnerd616ef52008-11-25 04:42:10 +000048using namespace llvm::PatternMatch;
Chris Lattnerf2836d12007-03-31 04:06:36 +000049
Cameron Zwarichced753f2011-01-05 17:27:27 +000050STATISTIC(NumBlocksElim, "Number of blocks eliminated");
Evan Cheng0663f232011-03-21 01:19:09 +000051STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated");
52STATISTIC(NumGEPsElim, "Number of GEPs converted to casts");
Cameron Zwarichced753f2011-01-05 17:27:27 +000053STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "
54 "sunken Cmps");
55STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
56 "of sunken Casts");
57STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "
58 "computations were sunk");
Evan Cheng0663f232011-03-21 01:19:09 +000059STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads");
60STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized");
61STATISTIC(NumRetsDup, "Number of return instructions duplicated");
Devang Patel53771ba2011-08-18 00:50:51 +000062STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved");
Benjamin Kramer047d7ca2012-05-05 12:49:22 +000063STATISTIC(NumSelectsExpanded, "Number of selects turned into branches");
Tim Northovercea0abb2014-03-29 08:22:29 +000064STATISTIC(NumAndCmpsMoved, "Number of and/cmp's pushed into branches");
Jakob Stoklund Oleseneb12f492010-09-30 20:51:52 +000065
Cameron Zwarich338d3622011-03-11 21:52:04 +000066static cl::opt<bool> DisableBranchOpts(
67 "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
68 cl::desc("Disable branch optimizations in CodeGenPrepare"));
69
Benjamin Kramer3d38c172012-05-06 14:25:16 +000070static cl::opt<bool> DisableSelectToBranch(
71 "disable-cgp-select2branch", cl::Hidden, cl::init(false),
72 cl::desc("Disable select to branch conversion."));
Benjamin Kramer047d7ca2012-05-05 12:49:22 +000073
Hal Finkelc3998302014-04-12 00:59:48 +000074static cl::opt<bool> AddrSinkUsingGEPs(
75 "addr-sink-using-gep", cl::Hidden, cl::init(false),
76 cl::desc("Address sinking in CGP using GEPs."));
77
Tim Northovercea0abb2014-03-29 08:22:29 +000078static cl::opt<bool> EnableAndCmpSinking(
79 "enable-andcmp-sinking", cl::Hidden, cl::init(true),
80 cl::desc("Enable sinkinig and/cmp into branches."));
81
Eric Christopherc1ea1492008-09-24 05:32:41 +000082namespace {
Quentin Colombet3a4bf042014-02-06 21:44:56 +000083typedef SmallPtrSet<Instruction *, 16> SetOfInstrs;
84typedef DenseMap<Instruction *, Type *> InstrToOrigTy;
85
Chris Lattner2dd09db2009-09-02 06:11:42 +000086 class CodeGenPrepare : public FunctionPass {
Chris Lattnerf2836d12007-03-31 04:06:36 +000087 /// TLI - Keep a pointer of a TargetLowering to consult for determining
88 /// transformation profitability.
Bill Wendling7a639ea2013-06-19 21:07:11 +000089 const TargetMachine *TM;
Chris Lattnerf2836d12007-03-31 04:06:36 +000090 const TargetLowering *TLI;
Chad Rosierc24b86f2011-12-01 03:08:23 +000091 const TargetLibraryInfo *TLInfo;
Cameron Zwarich84986b22011-01-08 17:01:52 +000092 DominatorTree *DT;
Nadav Rotem465834c2012-07-24 10:51:42 +000093
Chris Lattner7a277142011-01-15 07:14:54 +000094 /// CurInstIterator - As we scan instructions optimizing them, this is the
95 /// next instruction to optimize. Xforms that can invalidate this should
96 /// update it.
97 BasicBlock::iterator CurInstIterator;
Evan Cheng3b3de7c2008-12-19 18:03:11 +000098
Evan Cheng0663f232011-03-21 01:19:09 +000099 /// Keeps track of non-local addresses that have been sunk into a block.
100 /// This allows us to avoid inserting duplicate code for blocks with
101 /// multiple load/stores of the same address.
Nick Lewycky5fb19632013-05-08 09:00:10 +0000102 ValueMap<Value*, Value*> SunkAddrs;
Cameron Zwarichce3b9302011-01-06 00:42:50 +0000103
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000104 /// Keeps track of all truncates inserted for the current function.
105 SetOfInstrs InsertedTruncsSet;
106 /// Keeps track of the type of the related instruction before their
107 /// promotion for the current function.
108 InstrToOrigTy PromotedInsts;
109
Devang Patel8f606d72011-03-24 15:35:25 +0000110 /// ModifiedDT - If CFG is modified in anyway, dominator tree may need to
Evan Cheng0663f232011-03-21 01:19:09 +0000111 /// be updated.
Devang Patel8f606d72011-03-24 15:35:25 +0000112 bool ModifiedDT;
Evan Cheng0663f232011-03-21 01:19:09 +0000113
Benjamin Kramer047d7ca2012-05-05 12:49:22 +0000114 /// OptSize - True if optimizing for size.
115 bool OptSize;
116
Chris Lattnerf2836d12007-03-31 04:06:36 +0000117 public:
Nick Lewyckye7da2d62007-05-06 13:37:16 +0000118 static char ID; // Pass identification, replacement for typeid
Bill Wendling7a639ea2013-06-19 21:07:11 +0000119 explicit CodeGenPrepare(const TargetMachine *TM = 0)
120 : FunctionPass(ID), TM(TM), TLI(0) {
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000121 initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
122 }
Craig Topper4584cd52014-03-07 09:26:03 +0000123 bool runOnFunction(Function &F) override;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000124
Craig Topper4584cd52014-03-07 09:26:03 +0000125 const char *getPassName() const override { return "CodeGen Prepare"; }
Evan Cheng99cafb12012-12-21 01:48:14 +0000126
Craig Topper4584cd52014-03-07 09:26:03 +0000127 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruth73523022014-01-13 13:07:17 +0000128 AU.addPreserved<DominatorTreeWrapperPass>();
Chad Rosierc24b86f2011-12-01 03:08:23 +0000129 AU.addRequired<TargetLibraryInfo>();
Andreas Neustifterf8cb7582009-09-16 09:26:52 +0000130 }
131
Chris Lattnerf2836d12007-03-31 04:06:36 +0000132 private:
Nadav Rotem70409992012-08-14 05:19:07 +0000133 bool EliminateFallThrough(Function &F);
Chris Lattnerc3748562007-04-02 01:35:34 +0000134 bool EliminateMostlyEmptyBlocks(Function &F);
135 bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
136 void EliminateMostlyEmptyBlock(BasicBlock *BB);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000137 bool OptimizeBlock(BasicBlock &BB);
Cameron Zwarich14ac8652011-01-06 02:37:26 +0000138 bool OptimizeInst(Instruction *I);
Chris Lattner229907c2011-07-18 04:54:35 +0000139 bool OptimizeMemoryInst(Instruction *I, Value *Addr, Type *AccessTy);
Chris Lattner7a277142011-01-15 07:14:54 +0000140 bool OptimizeInlineAsmInst(CallInst *CS);
Eric Christopher4b7948e2010-03-11 02:41:03 +0000141 bool OptimizeCallInst(CallInst *CI);
Dan Gohman99429a02009-10-16 20:59:35 +0000142 bool MoveExtToFormExtLoad(Instruction *I);
Evan Chengd3d80172007-12-05 23:58:20 +0000143 bool OptimizeExtUses(Instruction *I);
Benjamin Kramer047d7ca2012-05-05 12:49:22 +0000144 bool OptimizeSelectInst(SelectInst *SI);
Tim Northoveraeb8e062014-02-19 10:02:43 +0000145 bool OptimizeShuffleVectorInst(ShuffleVectorInst *SI);
Benjamin Kramer455fa352012-11-23 19:17:06 +0000146 bool DupRetToEnableTailCallOpts(BasicBlock *BB);
Devang Patel53771ba2011-08-18 00:50:51 +0000147 bool PlaceDbgValues(Function &F);
Tim Northovercea0abb2014-03-29 08:22:29 +0000148 bool sinkAndCmp(Function &F);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000149 };
150}
Devang Patel09f162c2007-05-01 21:15:47 +0000151
Devang Patel8c78a0b2007-05-03 01:11:54 +0000152char CodeGenPrepare::ID = 0;
Quentin Colombetdc0b2ea2014-01-16 21:44:34 +0000153static void *initializeCodeGenPreparePassOnce(PassRegistry &Registry) {
154 initializeTargetLibraryInfoPass(Registry);
155 PassInfo *PI = new PassInfo(
156 "Optimize for code generation", "codegenprepare", &CodeGenPrepare::ID,
157 PassInfo::NormalCtor_t(callDefaultCtor<CodeGenPrepare>), false, false,
158 PassInfo::TargetMachineCtor_t(callTargetMachineCtor<CodeGenPrepare>));
159 Registry.registerPass(*PI, true);
160 return PI;
161}
162
163void llvm::initializeCodeGenPreparePass(PassRegistry &Registry) {
164 CALL_ONCE_INITIALIZATION(initializeCodeGenPreparePassOnce)
165}
Chris Lattnerf2836d12007-03-31 04:06:36 +0000166
Bill Wendling7a639ea2013-06-19 21:07:11 +0000167FunctionPass *llvm::createCodeGenPreparePass(const TargetMachine *TM) {
168 return new CodeGenPrepare(TM);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000169}
170
Chris Lattnerf2836d12007-03-31 04:06:36 +0000171bool CodeGenPrepare::runOnFunction(Function &F) {
Paul Robinson7c99ec52014-03-31 17:43:35 +0000172 if (skipOptnoneFunction(F))
173 return false;
174
Chris Lattnerf2836d12007-03-31 04:06:36 +0000175 bool EverMadeChange = false;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000176 // Clear per function information.
177 InsertedTruncsSet.clear();
178 PromotedInsts.clear();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000179
Devang Patel8f606d72011-03-24 15:35:25 +0000180 ModifiedDT = false;
Bill Wendling7a639ea2013-06-19 21:07:11 +0000181 if (TM) TLI = TM->getTargetLowering();
Chad Rosierc24b86f2011-12-01 03:08:23 +0000182 TLInfo = &getAnalysis<TargetLibraryInfo>();
Chandler Carruth73523022014-01-13 13:07:17 +0000183 DominatorTreeWrapperPass *DTWP =
184 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
185 DT = DTWP ? &DTWP->getDomTree() : 0;
Bill Wendling698e84f2012-12-30 10:32:01 +0000186 OptSize = F.getAttributes().hasAttribute(AttributeSet::FunctionIndex,
187 Attribute::OptimizeForSize);
Evan Cheng0663f232011-03-21 01:19:09 +0000188
Preston Gurdcdf540d2012-09-04 18:22:17 +0000189 /// This optimization identifies DIV instructions that can be
190 /// profitably bypassed and carried out with a shorter, faster divide.
Preston Gurd485296d2013-03-04 18:13:57 +0000191 if (!OptSize && TLI && TLI->isSlowDivBypassed()) {
Preston Gurd0d67f512012-10-04 21:33:40 +0000192 const DenseMap<unsigned int, unsigned int> &BypassWidths =
193 TLI->getBypassSlowDivWidths();
Evan Cheng71be12b2012-09-14 21:25:34 +0000194 for (Function::iterator I = F.begin(); I != F.end(); I++)
Preston Gurd0d67f512012-10-04 21:33:40 +0000195 EverMadeChange |= bypassSlowDivision(F, I, BypassWidths);
Preston Gurdcdf540d2012-09-04 18:22:17 +0000196 }
197
198 // Eliminate blocks that contain only PHI nodes and an
Chris Lattnerc3748562007-04-02 01:35:34 +0000199 // unconditional branch.
200 EverMadeChange |= EliminateMostlyEmptyBlocks(F);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000201
Devang Patel53771ba2011-08-18 00:50:51 +0000202 // llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotem465834c2012-07-24 10:51:42 +0000203 // handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patel53771ba2011-08-18 00:50:51 +0000204 // find a node corresponding to the value.
205 EverMadeChange |= PlaceDbgValues(F);
206
Tim Northovercea0abb2014-03-29 08:22:29 +0000207 // If there is a mask, compare against zero, and branch that can be combined
208 // into a single target instruction, push the mask and compare into branch
209 // users. Do this before OptimizeBlock -> OptimizeInst ->
210 // OptimizeCmpExpression, which perturbs the pattern being searched for.
211 if (!DisableBranchOpts)
212 EverMadeChange |= sinkAndCmp(F);
213
Chris Lattnerc3748562007-04-02 01:35:34 +0000214 bool MadeChange = true;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000215 while (MadeChange) {
216 MadeChange = false;
Hans Wennborg02fbc712012-09-19 07:48:16 +0000217 for (Function::iterator I = F.begin(); I != F.end(); ) {
Evan Cheng0663f232011-03-21 01:19:09 +0000218 BasicBlock *BB = I++;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000219 MadeChange |= OptimizeBlock(*BB);
Evan Cheng0663f232011-03-21 01:19:09 +0000220 }
Chris Lattnerf2836d12007-03-31 04:06:36 +0000221 EverMadeChange |= MadeChange;
222 }
Cameron Zwarichce3b9302011-01-06 00:42:50 +0000223
224 SunkAddrs.clear();
225
Cameron Zwarich338d3622011-03-11 21:52:04 +0000226 if (!DisableBranchOpts) {
227 MadeChange = false;
Bill Wendling97b93592012-03-04 10:46:01 +0000228 SmallPtrSet<BasicBlock*, 8> WorkList;
229 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
230 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
Frits van Bommelad964552011-05-22 16:24:18 +0000231 MadeChange |= ConstantFoldTerminator(BB, true);
Bill Wendling97b93592012-03-04 10:46:01 +0000232 if (!MadeChange) continue;
233
234 for (SmallVectorImpl<BasicBlock*>::iterator
235 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
236 if (pred_begin(*II) == pred_end(*II))
237 WorkList.insert(*II);
238 }
239
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000240 // Delete the dead blocks and any of their dead successors.
Bill Wendlingab417b62012-12-06 00:30:20 +0000241 MadeChange |= !WorkList.empty();
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000242 while (!WorkList.empty()) {
243 BasicBlock *BB = *WorkList.begin();
244 WorkList.erase(BB);
245 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
246
247 DeleteDeadBlock(BB);
Stephen Lin837bba12013-07-15 17:55:02 +0000248
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000249 for (SmallVectorImpl<BasicBlock*>::iterator
250 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
251 if (pred_begin(*II) == pred_end(*II))
252 WorkList.insert(*II);
253 }
Cameron Zwarich338d3622011-03-11 21:52:04 +0000254
Nadav Rotem70409992012-08-14 05:19:07 +0000255 // Merge pairs of basic blocks with unconditional branches, connected by
256 // a single edge.
257 if (EverMadeChange || MadeChange)
258 MadeChange |= EliminateFallThrough(F);
259
Evan Cheng0663f232011-03-21 01:19:09 +0000260 if (MadeChange)
Devang Patel8f606d72011-03-24 15:35:25 +0000261 ModifiedDT = true;
Cameron Zwarich338d3622011-03-11 21:52:04 +0000262 EverMadeChange |= MadeChange;
263 }
264
Devang Patel8f606d72011-03-24 15:35:25 +0000265 if (ModifiedDT && DT)
Chandler Carruth73523022014-01-13 13:07:17 +0000266 DT->recalculate(F);
Evan Cheng0663f232011-03-21 01:19:09 +0000267
Chris Lattnerf2836d12007-03-31 04:06:36 +0000268 return EverMadeChange;
269}
270
Nadav Rotem70409992012-08-14 05:19:07 +0000271/// EliminateFallThrough - Merge basic blocks which are connected
272/// by a single edge, where one of the basic blocks has a single successor
273/// pointing to the other basic block, which has a single predecessor.
274bool CodeGenPrepare::EliminateFallThrough(Function &F) {
275 bool Changed = false;
276 // Scan all of the blocks in the function, except for the entry block.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000277 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
Nadav Rotem70409992012-08-14 05:19:07 +0000278 BasicBlock *BB = I++;
279 // If the destination block has a single pred, then this is a trivial
280 // edge, just collapse it.
281 BasicBlock *SinglePred = BB->getSinglePredecessor();
282
Evan Cheng64a223a2012-09-28 23:58:57 +0000283 // Don't merge if BB's address is taken.
284 if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue;
Nadav Rotem70409992012-08-14 05:19:07 +0000285
286 BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
287 if (Term && !Term->isConditional()) {
288 Changed = true;
Michael Liao6e12d122012-08-21 05:55:22 +0000289 DEBUG(dbgs() << "To merge:\n"<< *SinglePred << "\n\n\n");
Nadav Rotem70409992012-08-14 05:19:07 +0000290 // Remember if SinglePred was the entry block of the function.
291 // If so, we will need to move BB back to the entry position.
292 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
293 MergeBasicBlockIntoOnlyPred(BB, this);
294
295 if (isEntry && BB != &BB->getParent()->getEntryBlock())
296 BB->moveBefore(&BB->getParent()->getEntryBlock());
297
298 // We have erased a block. Update the iterator.
299 I = BB;
Nadav Rotem70409992012-08-14 05:19:07 +0000300 }
301 }
302 return Changed;
303}
304
Dale Johannesen4026b042009-03-27 01:13:37 +0000305/// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes,
306/// debug info directives, and an unconditional branch. Passes before isel
307/// (e.g. LSR/loopsimplify) often split edges in ways that are non-optimal for
308/// isel. Start by eliminating these blocks so we can split them the way we
309/// want them.
Chris Lattnerc3748562007-04-02 01:35:34 +0000310bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
311 bool MadeChange = false;
312 // Note that this intentionally skips the entry block.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000313 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
Chris Lattnerc3748562007-04-02 01:35:34 +0000314 BasicBlock *BB = I++;
315
316 // If this block doesn't end with an uncond branch, ignore it.
317 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
318 if (!BI || !BI->isUnconditional())
319 continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000320
Dale Johannesen4026b042009-03-27 01:13:37 +0000321 // If the instruction before the branch (skipping debug info) isn't a phi
322 // node, then other stuff is happening here.
Chris Lattnerc3748562007-04-02 01:35:34 +0000323 BasicBlock::iterator BBI = BI;
324 if (BBI != BB->begin()) {
325 --BBI;
Dale Johannesen4026b042009-03-27 01:13:37 +0000326 while (isa<DbgInfoIntrinsic>(BBI)) {
327 if (BBI == BB->begin())
328 break;
329 --BBI;
330 }
331 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
332 continue;
Chris Lattnerc3748562007-04-02 01:35:34 +0000333 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000334
Chris Lattnerc3748562007-04-02 01:35:34 +0000335 // Do not break infinite loops.
336 BasicBlock *DestBB = BI->getSuccessor(0);
337 if (DestBB == BB)
338 continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000339
Chris Lattnerc3748562007-04-02 01:35:34 +0000340 if (!CanMergeBlocks(BB, DestBB))
341 continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000342
Chris Lattnerc3748562007-04-02 01:35:34 +0000343 EliminateMostlyEmptyBlock(BB);
344 MadeChange = true;
345 }
346 return MadeChange;
347}
348
349/// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
350/// single uncond branch between them, and BB contains no other non-phi
351/// instructions.
352bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
353 const BasicBlock *DestBB) const {
354 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
355 // the successor. If there are more complex condition (e.g. preheaders),
356 // don't mess around with them.
357 BasicBlock::const_iterator BBI = BB->begin();
358 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000359 for (const User *U : PN->users()) {
360 const Instruction *UI = cast<Instruction>(U);
361 if (UI->getParent() != DestBB || !isa<PHINode>(UI))
Chris Lattnerc3748562007-04-02 01:35:34 +0000362 return false;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000363 // If User is inside DestBB block and it is a PHINode then check
364 // incoming value. If incoming value is not from BB then this is
Devang Pateld3208522007-04-25 00:37:04 +0000365 // a complex condition (e.g. preheaders) we want to avoid here.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000366 if (UI->getParent() == DestBB) {
367 if (const PHINode *UPN = dyn_cast<PHINode>(UI))
Devang Pateld3208522007-04-25 00:37:04 +0000368 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
369 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
370 if (Insn && Insn->getParent() == BB &&
371 Insn->getParent() != UPN->getIncomingBlock(I))
372 return false;
373 }
374 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000375 }
376 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000377
Chris Lattnerc3748562007-04-02 01:35:34 +0000378 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
379 // and DestBB may have conflicting incoming values for the block. If so, we
380 // can't merge the block.
381 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
382 if (!DestBBPN) return true; // no conflict.
Eric Christopherc1ea1492008-09-24 05:32:41 +0000383
Chris Lattnerc3748562007-04-02 01:35:34 +0000384 // Collect the preds of BB.
Chris Lattner8201a9b2007-11-06 22:07:40 +0000385 SmallPtrSet<const BasicBlock*, 16> BBPreds;
Chris Lattnerc3748562007-04-02 01:35:34 +0000386 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
387 // It is faster to get preds from a PHI than with pred_iterator.
388 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
389 BBPreds.insert(BBPN->getIncomingBlock(i));
390 } else {
391 BBPreds.insert(pred_begin(BB), pred_end(BB));
392 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000393
Chris Lattnerc3748562007-04-02 01:35:34 +0000394 // Walk the preds of DestBB.
395 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
396 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
397 if (BBPreds.count(Pred)) { // Common predecessor?
398 BBI = DestBB->begin();
399 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
400 const Value *V1 = PN->getIncomingValueForBlock(Pred);
401 const Value *V2 = PN->getIncomingValueForBlock(BB);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000402
Chris Lattnerc3748562007-04-02 01:35:34 +0000403 // If V2 is a phi node in BB, look up what the mapped value will be.
404 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
405 if (V2PN->getParent() == BB)
406 V2 = V2PN->getIncomingValueForBlock(Pred);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000407
Chris Lattnerc3748562007-04-02 01:35:34 +0000408 // If there is a conflict, bail out.
409 if (V1 != V2) return false;
410 }
411 }
412 }
413
414 return true;
415}
416
417
418/// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
419/// an unconditional branch in it.
420void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
421 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
422 BasicBlock *DestBB = BI->getSuccessor(0);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000423
David Greene74e2d492010-01-05 01:27:11 +0000424 DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000425
Chris Lattnerc3748562007-04-02 01:35:34 +0000426 // If the destination block has a single pred, then this is a trivial edge,
427 // just collapse it.
Chris Lattner4059f432008-11-27 19:29:14 +0000428 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
Chris Lattner8a172da2008-11-28 19:54:49 +0000429 if (SinglePred != DestBB) {
430 // Remember if SinglePred was the entry block of the function. If so, we
431 // will need to move BB back to the entry position.
432 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Andreas Neustifterf8cb7582009-09-16 09:26:52 +0000433 MergeBasicBlockIntoOnlyPred(DestBB, this);
Chris Lattner4059f432008-11-27 19:29:14 +0000434
Chris Lattner8a172da2008-11-28 19:54:49 +0000435 if (isEntry && BB != &BB->getParent()->getEntryBlock())
436 BB->moveBefore(&BB->getParent()->getEntryBlock());
Nadav Rotem465834c2012-07-24 10:51:42 +0000437
David Greene74e2d492010-01-05 01:27:11 +0000438 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattner8a172da2008-11-28 19:54:49 +0000439 return;
440 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000441 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000442
Chris Lattnerc3748562007-04-02 01:35:34 +0000443 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
444 // to handle the new incoming edges it is about to have.
445 PHINode *PN;
446 for (BasicBlock::iterator BBI = DestBB->begin();
447 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
448 // Remove the incoming value for BB, and remember it.
449 Value *InVal = PN->removeIncomingValue(BB, false);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000450
Chris Lattnerc3748562007-04-02 01:35:34 +0000451 // Two options: either the InVal is a phi node defined in BB or it is some
452 // value that dominates BB.
453 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
454 if (InValPhi && InValPhi->getParent() == BB) {
455 // Add all of the input values of the input PHI as inputs of this phi.
456 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
457 PN->addIncoming(InValPhi->getIncomingValue(i),
458 InValPhi->getIncomingBlock(i));
459 } else {
460 // Otherwise, add one instance of the dominating value for each edge that
461 // we will be adding.
462 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
463 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
464 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
465 } else {
466 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
467 PN->addIncoming(InVal, *PI);
468 }
469 }
470 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000471
Chris Lattnerc3748562007-04-02 01:35:34 +0000472 // The PHIs are now updated, change everything that refers to BB to use
473 // DestBB and remove BB.
474 BB->replaceAllUsesWith(DestBB);
Devang Patel8f606d72011-03-24 15:35:25 +0000475 if (DT && !ModifiedDT) {
Cameron Zwarich84986b22011-01-08 17:01:52 +0000476 BasicBlock *BBIDom = DT->getNode(BB)->getIDom()->getBlock();
477 BasicBlock *DestBBIDom = DT->getNode(DestBB)->getIDom()->getBlock();
478 BasicBlock *NewIDom = DT->findNearestCommonDominator(BBIDom, DestBBIDom);
479 DT->changeImmediateDominator(DestBB, NewIDom);
480 DT->eraseNode(BB);
481 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000482 BB->eraseFromParent();
Cameron Zwarichced753f2011-01-05 17:27:27 +0000483 ++NumBlocksElim;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000484
David Greene74e2d492010-01-05 01:27:11 +0000485 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerc3748562007-04-02 01:35:34 +0000486}
487
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000488/// SinkCast - Sink the specified cast instruction into its user blocks
489static bool SinkCast(CastInst *CI) {
Chris Lattnerf2836d12007-03-31 04:06:36 +0000490 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000491
Chris Lattnerf2836d12007-03-31 04:06:36 +0000492 /// InsertedCasts - Only insert a cast in each block once.
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000493 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000494
Chris Lattnerf2836d12007-03-31 04:06:36 +0000495 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000496 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
Chris Lattnerf2836d12007-03-31 04:06:36 +0000497 UI != E; ) {
498 Use &TheUse = UI.getUse();
499 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000500
Chris Lattnerf2836d12007-03-31 04:06:36 +0000501 // Figure out which BB this cast is used in. For PHI's this is the
502 // appropriate predecessor block.
503 BasicBlock *UserBB = User->getParent();
504 if (PHINode *PN = dyn_cast<PHINode>(User)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000505 UserBB = PN->getIncomingBlock(TheUse);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000506 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000507
Chris Lattnerf2836d12007-03-31 04:06:36 +0000508 // Preincrement use iterator so we don't invalidate it.
509 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000510
Chris Lattnerf2836d12007-03-31 04:06:36 +0000511 // If this user is in the same block as the cast, don't change the cast.
512 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000513
Chris Lattnerf2836d12007-03-31 04:06:36 +0000514 // If we have already inserted a cast into this block, use it.
515 CastInst *&InsertedCast = InsertedCasts[UserBB];
516
517 if (!InsertedCast) {
Bill Wendling8ddfc092011-08-16 20:45:24 +0000518 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000519 InsertedCast =
520 CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
Chris Lattnerf2836d12007-03-31 04:06:36 +0000521 InsertPt);
522 MadeChange = true;
523 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000524
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000525 // Replace a use of the cast with a use of the new cast.
Chris Lattnerf2836d12007-03-31 04:06:36 +0000526 TheUse = InsertedCast;
Cameron Zwarichced753f2011-01-05 17:27:27 +0000527 ++NumCastUses;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000528 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000529
Chris Lattnerf2836d12007-03-31 04:06:36 +0000530 // If we removed all uses, nuke the cast.
Duncan Sandsafa84da42008-01-20 16:51:46 +0000531 if (CI->use_empty()) {
Chris Lattnerf2836d12007-03-31 04:06:36 +0000532 CI->eraseFromParent();
Duncan Sandsafa84da42008-01-20 16:51:46 +0000533 MadeChange = true;
534 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000535
Chris Lattnerf2836d12007-03-31 04:06:36 +0000536 return MadeChange;
537}
538
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000539/// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
540/// copy (e.g. it's casting from one pointer type to another, i32->i8 on PPC),
541/// sink it into user blocks to reduce the number of virtual
542/// registers that must be created and coalesced.
543///
544/// Return true if any changes are made.
545///
546static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
547 // If this is a noop copy,
548 EVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
549 EVT DstVT = TLI.getValueType(CI->getType());
550
551 // This is an fp<->int conversion?
552 if (SrcVT.isInteger() != DstVT.isInteger())
553 return false;
554
555 // If this is an extension, it will be a zero or sign extension, which
556 // isn't a noop.
557 if (SrcVT.bitsLT(DstVT)) return false;
558
559 // If these values will be promoted, find out what they will be promoted
560 // to. This helps us consider truncates on PPC as noop copies when they
561 // are.
562 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
563 TargetLowering::TypePromoteInteger)
564 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
565 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
566 TargetLowering::TypePromoteInteger)
567 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
568
569 // If, after promotion, these are the same types, this is a noop copy.
570 if (SrcVT != DstVT)
571 return false;
572
573 return SinkCast(CI);
574}
575
Eric Christopherc1ea1492008-09-24 05:32:41 +0000576/// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000577/// the number of virtual registers that must be created and coalesced. This is
Chris Lattner27406942007-08-02 16:53:43 +0000578/// a clear win except on targets with multiple condition code registers
579/// (PowerPC), where it might lose; some adjustment may be wanted there.
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000580///
581/// Return true if any changes are made.
Chris Lattner6416a6b2008-11-24 22:44:16 +0000582static bool OptimizeCmpExpression(CmpInst *CI) {
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000583 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000584
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000585 /// InsertedCmp - Only insert a cmp in each block once.
586 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000587
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000588 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000589 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000590 UI != E; ) {
591 Use &TheUse = UI.getUse();
592 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000593
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000594 // Preincrement use iterator so we don't invalidate it.
595 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000596
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000597 // Don't bother for PHI nodes.
598 if (isa<PHINode>(User))
599 continue;
600
601 // Figure out which BB this cmp is used in.
602 BasicBlock *UserBB = User->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000603
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000604 // If this user is in the same block as the cmp, don't change the cmp.
605 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000606
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000607 // If we have already inserted a cmp into this block, use it.
608 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
609
610 if (!InsertedCmp) {
Bill Wendling8ddfc092011-08-16 20:45:24 +0000611 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000612 InsertedCmp =
Dan Gohmanad1f0a12009-08-25 23:17:54 +0000613 CmpInst::Create(CI->getOpcode(),
Owen Anderson1e5f00e2009-07-09 23:48:35 +0000614 CI->getPredicate(), CI->getOperand(0),
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000615 CI->getOperand(1), "", InsertPt);
616 MadeChange = true;
617 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000618
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000619 // Replace a use of the cmp with a use of the new cmp.
620 TheUse = InsertedCmp;
Cameron Zwarichced753f2011-01-05 17:27:27 +0000621 ++NumCmpUses;
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000622 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000623
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000624 // If we removed all uses, nuke the cmp.
625 if (CI->use_empty())
626 CI->eraseFromParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000627
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000628 return MadeChange;
629}
630
Benjamin Kramer7b88a492010-03-12 09:27:41 +0000631namespace {
632class CodeGenPrepareFortifiedLibCalls : public SimplifyFortifiedLibCalls {
633protected:
Craig Topper4584cd52014-03-07 09:26:03 +0000634 void replaceCall(Value *With) override {
Benjamin Kramer7b88a492010-03-12 09:27:41 +0000635 CI->replaceAllUsesWith(With);
636 CI->eraseFromParent();
637 }
Craig Topper4584cd52014-03-07 09:26:03 +0000638 bool isFoldable(unsigned SizeCIOp, unsigned, bool) const override {
Gabor Greif6d673952010-07-16 09:38:02 +0000639 if (ConstantInt *SizeCI =
640 dyn_cast<ConstantInt>(CI->getArgOperand(SizeCIOp)))
641 return SizeCI->isAllOnesValue();
Benjamin Kramer7b88a492010-03-12 09:27:41 +0000642 return false;
643 }
644};
645} // end anonymous namespace
646
Eric Christopher4b7948e2010-03-11 02:41:03 +0000647bool CodeGenPrepare::OptimizeCallInst(CallInst *CI) {
Chris Lattner7a277142011-01-15 07:14:54 +0000648 BasicBlock *BB = CI->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +0000649
Chris Lattner7a277142011-01-15 07:14:54 +0000650 // Lower inline assembly if we can.
651 // If we found an inline asm expession, and if the target knows how to
652 // lower it to normal LLVM code, do so now.
653 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
654 if (TLI->ExpandInlineAsm(CI)) {
655 // Avoid invalidating the iterator.
656 CurInstIterator = BB->begin();
657 // Avoid processing instructions out of order, which could cause
658 // reuse before a value is defined.
659 SunkAddrs.clear();
660 return true;
661 }
662 // Sink address computing for memory operands into the block.
663 if (OptimizeInlineAsmInst(CI))
664 return true;
665 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000666
Eric Christopher4b7948e2010-03-11 02:41:03 +0000667 // Lower all uses of llvm.objectsize.*
668 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
669 if (II && II->getIntrinsicID() == Intrinsic::objectsize) {
Gabor Greif4a39b842010-06-24 00:44:01 +0000670 bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
Chris Lattner229907c2011-07-18 04:54:35 +0000671 Type *ReturnTy = CI->getType();
Nadav Rotem465834c2012-07-24 10:51:42 +0000672 Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
673
Chris Lattner1b93be52011-01-15 07:25:29 +0000674 // Substituting this can cause recursive simplifications, which can
675 // invalidate our iterator. Use a WeakVH to hold onto it in case this
676 // happens.
677 WeakVH IterHandle(CurInstIterator);
Nadav Rotem465834c2012-07-24 10:51:42 +0000678
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000679 replaceAndRecursivelySimplify(CI, RetVal, TLI ? TLI->getDataLayout() : 0,
Chandler Carruthcf1b5852012-03-24 21:11:24 +0000680 TLInfo, ModifiedDT ? 0 : DT);
Chris Lattner1b93be52011-01-15 07:25:29 +0000681
682 // If the iterator instruction was recursively deleted, start over at the
683 // start of the block.
Chris Lattner86d56c62011-01-18 20:53:04 +0000684 if (IterHandle != CurInstIterator) {
Chris Lattner1b93be52011-01-15 07:25:29 +0000685 CurInstIterator = BB->begin();
Chris Lattner86d56c62011-01-18 20:53:04 +0000686 SunkAddrs.clear();
687 }
Eric Christopher4b7948e2010-03-11 02:41:03 +0000688 return true;
689 }
690
Pete Cooper615fd892012-03-13 20:59:56 +0000691 if (II && TLI) {
692 SmallVector<Value*, 2> PtrOps;
693 Type *AccessTy;
694 if (TLI->GetAddrModeArguments(II, PtrOps, AccessTy))
695 while (!PtrOps.empty())
696 if (OptimizeMemoryInst(II, PtrOps.pop_back_val(), AccessTy))
697 return true;
698 }
699
Eric Christopher4b7948e2010-03-11 02:41:03 +0000700 // From here on out we're working with named functions.
701 if (CI->getCalledFunction() == 0) return false;
Devang Patel0da52502011-05-26 21:51:06 +0000702
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000703 // We'll need DataLayout from here on out.
704 const DataLayout *TD = TLI ? TLI->getDataLayout() : 0;
Eric Christopher4b7948e2010-03-11 02:41:03 +0000705 if (!TD) return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000706
Benjamin Kramer7b88a492010-03-12 09:27:41 +0000707 // Lower all default uses of _chk calls. This is very similar
708 // to what InstCombineCalls does, but here we are only lowering calls
Eric Christopher4b7948e2010-03-11 02:41:03 +0000709 // that have the default "don't know" as the objectsize. Anything else
710 // should be left alone.
Benjamin Kramer7b88a492010-03-12 09:27:41 +0000711 CodeGenPrepareFortifiedLibCalls Simplifier;
Nuno Lopes89702e92012-07-25 16:46:31 +0000712 return Simplifier.fold(CI, TD, TLInfo);
Eric Christopher4b7948e2010-03-11 02:41:03 +0000713}
Chris Lattner1b93be52011-01-15 07:25:29 +0000714
Evan Cheng0663f232011-03-21 01:19:09 +0000715/// DupRetToEnableTailCallOpts - Look for opportunities to duplicate return
716/// instructions to the predecessor to enable tail call optimizations. The
717/// case it is currently looking for is:
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +0000718/// @code
Evan Cheng0663f232011-03-21 01:19:09 +0000719/// bb0:
720/// %tmp0 = tail call i32 @f0()
721/// br label %return
722/// bb1:
723/// %tmp1 = tail call i32 @f1()
724/// br label %return
725/// bb2:
726/// %tmp2 = tail call i32 @f2()
727/// br label %return
728/// return:
729/// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
730/// ret i32 %retval
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +0000731/// @endcode
Evan Cheng0663f232011-03-21 01:19:09 +0000732///
733/// =>
734///
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +0000735/// @code
Evan Cheng0663f232011-03-21 01:19:09 +0000736/// bb0:
737/// %tmp0 = tail call i32 @f0()
738/// ret i32 %tmp0
739/// bb1:
740/// %tmp1 = tail call i32 @f1()
741/// ret i32 %tmp1
742/// bb2:
743/// %tmp2 = tail call i32 @f2()
744/// ret i32 %tmp2
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +0000745/// @endcode
Benjamin Kramer455fa352012-11-23 19:17:06 +0000746bool CodeGenPrepare::DupRetToEnableTailCallOpts(BasicBlock *BB) {
Cameron Zwarich47e71752011-03-24 04:51:51 +0000747 if (!TLI)
748 return false;
749
Benjamin Kramer455fa352012-11-23 19:17:06 +0000750 ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
751 if (!RI)
752 return false;
753
Evan Cheng249716e2012-07-27 21:21:26 +0000754 PHINode *PN = 0;
755 BitCastInst *BCI = 0;
Evan Cheng0663f232011-03-21 01:19:09 +0000756 Value *V = RI->getReturnValue();
Evan Cheng249716e2012-07-27 21:21:26 +0000757 if (V) {
758 BCI = dyn_cast<BitCastInst>(V);
759 if (BCI)
760 V = BCI->getOperand(0);
761
762 PN = dyn_cast<PHINode>(V);
763 if (!PN)
764 return false;
765 }
Evan Cheng0663f232011-03-21 01:19:09 +0000766
Cameron Zwarich4649f172011-03-24 04:52:10 +0000767 if (PN && PN->getParent() != BB)
Cameron Zwarich0e331c02011-03-24 04:52:07 +0000768 return false;
Evan Cheng0663f232011-03-21 01:19:09 +0000769
Cameron Zwarich0e331c02011-03-24 04:52:07 +0000770 // It's not safe to eliminate the sign / zero extension of the return value.
771 // See llvm::isInTailCallPosition().
772 const Function *F = BB->getParent();
Bill Wendling658d24d2013-01-18 21:53:16 +0000773 AttributeSet CallerAttrs = F->getAttributes();
774 if (CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::ZExt) ||
775 CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::SExt))
Cameron Zwarich0e331c02011-03-24 04:52:07 +0000776 return false;
Evan Cheng0663f232011-03-21 01:19:09 +0000777
Cameron Zwarich4649f172011-03-24 04:52:10 +0000778 // Make sure there are no instructions between the PHI and return, or that the
779 // return is the first instruction in the block.
780 if (PN) {
781 BasicBlock::iterator BI = BB->begin();
782 do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
Evan Cheng249716e2012-07-27 21:21:26 +0000783 if (&*BI == BCI)
784 // Also skip over the bitcast.
785 ++BI;
Cameron Zwarich4649f172011-03-24 04:52:10 +0000786 if (&*BI != RI)
787 return false;
788 } else {
Cameron Zwarich74157ab2011-03-24 16:34:59 +0000789 BasicBlock::iterator BI = BB->begin();
790 while (isa<DbgInfoIntrinsic>(BI)) ++BI;
791 if (&*BI != RI)
Cameron Zwarich4649f172011-03-24 04:52:10 +0000792 return false;
793 }
Evan Cheng0663f232011-03-21 01:19:09 +0000794
Cameron Zwarich0e331c02011-03-24 04:52:07 +0000795 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
796 /// call.
797 SmallVector<CallInst*, 4> TailCalls;
Cameron Zwarich4649f172011-03-24 04:52:10 +0000798 if (PN) {
799 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
800 CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
801 // Make sure the phi value is indeed produced by the tail call.
802 if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
803 TLI->mayBeEmittedAsTailCall(CI))
804 TailCalls.push_back(CI);
805 }
806 } else {
807 SmallPtrSet<BasicBlock*, 4> VisitedBBs;
808 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
809 if (!VisitedBBs.insert(*PI))
810 continue;
811
812 BasicBlock::InstListType &InstList = (*PI)->getInstList();
813 BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
814 BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
Cameron Zwarich74157ab2011-03-24 16:34:59 +0000815 do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
816 if (RI == RE)
Cameron Zwarich4649f172011-03-24 04:52:10 +0000817 continue;
Cameron Zwarich74157ab2011-03-24 16:34:59 +0000818
Cameron Zwarich4649f172011-03-24 04:52:10 +0000819 CallInst *CI = dyn_cast<CallInst>(&*RI);
Cameron Zwarich2edfe772011-03-24 15:54:11 +0000820 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI))
Cameron Zwarich4649f172011-03-24 04:52:10 +0000821 TailCalls.push_back(CI);
822 }
Evan Cheng0663f232011-03-21 01:19:09 +0000823 }
824
Cameron Zwarich0e331c02011-03-24 04:52:07 +0000825 bool Changed = false;
826 for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
827 CallInst *CI = TailCalls[i];
828 CallSite CS(CI);
829
830 // Conservatively require the attributes of the call to match those of the
831 // return. Ignore noalias because it doesn't affect the call sequence.
Bill Wendling658d24d2013-01-18 21:53:16 +0000832 AttributeSet CalleeAttrs = CS.getAttributes();
833 if (AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
Bill Wendling3d7b0b82012-12-19 07:18:57 +0000834 removeAttribute(Attribute::NoAlias) !=
Bill Wendling658d24d2013-01-18 21:53:16 +0000835 AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
Bill Wendling3d7b0b82012-12-19 07:18:57 +0000836 removeAttribute(Attribute::NoAlias))
Cameron Zwarich0e331c02011-03-24 04:52:07 +0000837 continue;
838
839 // Make sure the call instruction is followed by an unconditional branch to
840 // the return block.
841 BasicBlock *CallBB = CI->getParent();
842 BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
843 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
844 continue;
845
846 // Duplicate the return into CallBB.
847 (void)FoldReturnIntoUncondBranch(RI, BB, CallBB);
Devang Patel8f606d72011-03-24 15:35:25 +0000848 ModifiedDT = Changed = true;
Cameron Zwarich0e331c02011-03-24 04:52:07 +0000849 ++NumRetsDup;
850 }
851
852 // If we eliminated all predecessors of the block, delete the block now.
Evan Cheng64a223a2012-09-28 23:58:57 +0000853 if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
Cameron Zwarich0e331c02011-03-24 04:52:07 +0000854 BB->eraseFromParent();
855
856 return Changed;
Evan Cheng0663f232011-03-21 01:19:09 +0000857}
858
Chris Lattner728f9022008-11-25 07:09:13 +0000859//===----------------------------------------------------------------------===//
Chris Lattner728f9022008-11-25 07:09:13 +0000860// Memory Optimization
861//===----------------------------------------------------------------------===//
862
Chandler Carruthc8925912013-01-05 02:09:22 +0000863namespace {
864
865/// ExtAddrMode - This is an extended version of TargetLowering::AddrMode
866/// which holds actual Value*'s for register values.
Chandler Carruth95f83e02013-01-07 15:14:13 +0000867struct ExtAddrMode : public TargetLowering::AddrMode {
Chandler Carruthc8925912013-01-05 02:09:22 +0000868 Value *BaseReg;
869 Value *ScaledReg;
870 ExtAddrMode() : BaseReg(0), ScaledReg(0) {}
871 void print(raw_ostream &OS) const;
872 void dump() const;
Stephen Lin837bba12013-07-15 17:55:02 +0000873
Chandler Carruthc8925912013-01-05 02:09:22 +0000874 bool operator==(const ExtAddrMode& O) const {
875 return (BaseReg == O.BaseReg) && (ScaledReg == O.ScaledReg) &&
876 (BaseGV == O.BaseGV) && (BaseOffs == O.BaseOffs) &&
877 (HasBaseReg == O.HasBaseReg) && (Scale == O.Scale);
878 }
879};
880
Eli Friedmanc1f1f852013-09-10 23:09:24 +0000881#ifndef NDEBUG
882static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
883 AM.print(OS);
884 return OS;
885}
886#endif
887
Chandler Carruthc8925912013-01-05 02:09:22 +0000888void ExtAddrMode::print(raw_ostream &OS) const {
889 bool NeedPlus = false;
890 OS << "[";
891 if (BaseGV) {
892 OS << (NeedPlus ? " + " : "")
893 << "GV:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +0000894 BaseGV->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +0000895 NeedPlus = true;
896 }
897
898 if (BaseOffs)
899 OS << (NeedPlus ? " + " : "") << BaseOffs, NeedPlus = true;
900
901 if (BaseReg) {
902 OS << (NeedPlus ? " + " : "")
903 << "Base:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +0000904 BaseReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +0000905 NeedPlus = true;
906 }
907 if (Scale) {
908 OS << (NeedPlus ? " + " : "")
909 << Scale << "*";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +0000910 ScaledReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +0000911 }
912
913 OS << ']';
914}
915
916#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
917void ExtAddrMode::dump() const {
918 print(dbgs());
919 dbgs() << '\n';
920}
921#endif
922
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000923/// \brief This class provides transaction based operation on the IR.
924/// Every change made through this class is recorded in the internal state and
925/// can be undone (rollback) until commit is called.
926class TypePromotionTransaction {
927
928 /// \brief This represents the common interface of the individual transaction.
929 /// Each class implements the logic for doing one specific modification on
930 /// the IR via the TypePromotionTransaction.
931 class TypePromotionAction {
932 protected:
933 /// The Instruction modified.
934 Instruction *Inst;
935
936 public:
937 /// \brief Constructor of the action.
938 /// The constructor performs the related action on the IR.
939 TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
940
941 virtual ~TypePromotionAction() {}
942
943 /// \brief Undo the modification done by this action.
944 /// When this method is called, the IR must be in the same state as it was
945 /// before this action was applied.
946 /// \pre Undoing the action works if and only if the IR is in the exact same
947 /// state as it was directly after this action was applied.
948 virtual void undo() = 0;
949
950 /// \brief Advocate every change made by this action.
951 /// When the results on the IR of the action are to be kept, it is important
952 /// to call this function, otherwise hidden information may be kept forever.
953 virtual void commit() {
954 // Nothing to be done, this action is not doing anything.
955 }
956 };
957
958 /// \brief Utility to remember the position of an instruction.
959 class InsertionHandler {
960 /// Position of an instruction.
961 /// Either an instruction:
962 /// - Is the first in a basic block: BB is used.
963 /// - Has a previous instructon: PrevInst is used.
964 union {
965 Instruction *PrevInst;
966 BasicBlock *BB;
967 } Point;
968 /// Remember whether or not the instruction had a previous instruction.
969 bool HasPrevInstruction;
970
971 public:
972 /// \brief Record the position of \p Inst.
973 InsertionHandler(Instruction *Inst) {
974 BasicBlock::iterator It = Inst;
975 HasPrevInstruction = (It != (Inst->getParent()->begin()));
976 if (HasPrevInstruction)
977 Point.PrevInst = --It;
978 else
979 Point.BB = Inst->getParent();
980 }
981
982 /// \brief Insert \p Inst at the recorded position.
983 void insert(Instruction *Inst) {
984 if (HasPrevInstruction) {
985 if (Inst->getParent())
986 Inst->removeFromParent();
987 Inst->insertAfter(Point.PrevInst);
988 } else {
989 Instruction *Position = Point.BB->getFirstInsertionPt();
990 if (Inst->getParent())
991 Inst->moveBefore(Position);
992 else
993 Inst->insertBefore(Position);
994 }
995 }
996 };
997
998 /// \brief Move an instruction before another.
999 class InstructionMoveBefore : public TypePromotionAction {
1000 /// Original position of the instruction.
1001 InsertionHandler Position;
1002
1003 public:
1004 /// \brief Move \p Inst before \p Before.
1005 InstructionMoveBefore(Instruction *Inst, Instruction *Before)
1006 : TypePromotionAction(Inst), Position(Inst) {
1007 DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before << "\n");
1008 Inst->moveBefore(Before);
1009 }
1010
1011 /// \brief Move the instruction back to its original position.
Craig Topper4584cd52014-03-07 09:26:03 +00001012 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001013 DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n");
1014 Position.insert(Inst);
1015 }
1016 };
1017
1018 /// \brief Set the operand of an instruction with a new value.
1019 class OperandSetter : public TypePromotionAction {
1020 /// Original operand of the instruction.
1021 Value *Origin;
1022 /// Index of the modified instruction.
1023 unsigned Idx;
1024
1025 public:
1026 /// \brief Set \p Idx operand of \p Inst with \p NewVal.
1027 OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
1028 : TypePromotionAction(Inst), Idx(Idx) {
1029 DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"
1030 << "for:" << *Inst << "\n"
1031 << "with:" << *NewVal << "\n");
1032 Origin = Inst->getOperand(Idx);
1033 Inst->setOperand(Idx, NewVal);
1034 }
1035
1036 /// \brief Restore the original value of the instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00001037 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001038 DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"
1039 << "for: " << *Inst << "\n"
1040 << "with: " << *Origin << "\n");
1041 Inst->setOperand(Idx, Origin);
1042 }
1043 };
1044
1045 /// \brief Hide the operands of an instruction.
1046 /// Do as if this instruction was not using any of its operands.
1047 class OperandsHider : public TypePromotionAction {
1048 /// The list of original operands.
1049 SmallVector<Value *, 4> OriginalValues;
1050
1051 public:
1052 /// \brief Remove \p Inst from the uses of the operands of \p Inst.
1053 OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
1054 DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n");
1055 unsigned NumOpnds = Inst->getNumOperands();
1056 OriginalValues.reserve(NumOpnds);
1057 for (unsigned It = 0; It < NumOpnds; ++It) {
1058 // Save the current operand.
1059 Value *Val = Inst->getOperand(It);
1060 OriginalValues.push_back(Val);
1061 // Set a dummy one.
1062 // We could use OperandSetter here, but that would implied an overhead
1063 // that we are not willing to pay.
1064 Inst->setOperand(It, UndefValue::get(Val->getType()));
1065 }
1066 }
1067
1068 /// \brief Restore the original list of uses.
Craig Topper4584cd52014-03-07 09:26:03 +00001069 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001070 DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n");
1071 for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
1072 Inst->setOperand(It, OriginalValues[It]);
1073 }
1074 };
1075
1076 /// \brief Build a truncate instruction.
1077 class TruncBuilder : public TypePromotionAction {
1078 public:
1079 /// \brief Build a truncate instruction of \p Opnd producing a \p Ty
1080 /// result.
1081 /// trunc Opnd to Ty.
1082 TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
1083 IRBuilder<> Builder(Opnd);
1084 Inst = cast<Instruction>(Builder.CreateTrunc(Opnd, Ty, "promoted"));
1085 DEBUG(dbgs() << "Do: TruncBuilder: " << *Inst << "\n");
1086 }
1087
1088 /// \brief Get the built instruction.
1089 Instruction *getBuiltInstruction() { return Inst; }
1090
1091 /// \brief Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00001092 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001093 DEBUG(dbgs() << "Undo: TruncBuilder: " << *Inst << "\n");
1094 Inst->eraseFromParent();
1095 }
1096 };
1097
1098 /// \brief Build a sign extension instruction.
1099 class SExtBuilder : public TypePromotionAction {
1100 public:
1101 /// \brief Build a sign extension instruction of \p Opnd producing a \p Ty
1102 /// result.
1103 /// sext Opnd to Ty.
1104 SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
1105 : TypePromotionAction(Inst) {
1106 IRBuilder<> Builder(InsertPt);
1107 Inst = cast<Instruction>(Builder.CreateSExt(Opnd, Ty, "promoted"));
1108 DEBUG(dbgs() << "Do: SExtBuilder: " << *Inst << "\n");
1109 }
1110
1111 /// \brief Get the built instruction.
1112 Instruction *getBuiltInstruction() { return Inst; }
1113
1114 /// \brief Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00001115 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001116 DEBUG(dbgs() << "Undo: SExtBuilder: " << *Inst << "\n");
1117 Inst->eraseFromParent();
1118 }
1119 };
1120
1121 /// \brief Mutate an instruction to another type.
1122 class TypeMutator : public TypePromotionAction {
1123 /// Record the original type.
1124 Type *OrigTy;
1125
1126 public:
1127 /// \brief Mutate the type of \p Inst into \p NewTy.
1128 TypeMutator(Instruction *Inst, Type *NewTy)
1129 : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
1130 DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy
1131 << "\n");
1132 Inst->mutateType(NewTy);
1133 }
1134
1135 /// \brief Mutate the instruction back to its original type.
Craig Topper4584cd52014-03-07 09:26:03 +00001136 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001137 DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy
1138 << "\n");
1139 Inst->mutateType(OrigTy);
1140 }
1141 };
1142
1143 /// \brief Replace the uses of an instruction by another instruction.
1144 class UsesReplacer : public TypePromotionAction {
1145 /// Helper structure to keep track of the replaced uses.
1146 struct InstructionAndIdx {
1147 /// The instruction using the instruction.
1148 Instruction *Inst;
1149 /// The index where this instruction is used for Inst.
1150 unsigned Idx;
1151 InstructionAndIdx(Instruction *Inst, unsigned Idx)
1152 : Inst(Inst), Idx(Idx) {}
1153 };
1154
1155 /// Keep track of the original uses (pair Instruction, Index).
1156 SmallVector<InstructionAndIdx, 4> OriginalUses;
1157 typedef SmallVectorImpl<InstructionAndIdx>::iterator use_iterator;
1158
1159 public:
1160 /// \brief Replace all the use of \p Inst by \p New.
1161 UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) {
1162 DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New
1163 << "\n");
1164 // Record the original uses.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001165 for (Use &U : Inst->uses()) {
1166 Instruction *UserI = cast<Instruction>(U.getUser());
1167 OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo()));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001168 }
1169 // Now, we can replace the uses.
1170 Inst->replaceAllUsesWith(New);
1171 }
1172
1173 /// \brief Reassign the original uses of Inst to Inst.
Craig Topper4584cd52014-03-07 09:26:03 +00001174 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001175 DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n");
1176 for (use_iterator UseIt = OriginalUses.begin(),
1177 EndIt = OriginalUses.end();
1178 UseIt != EndIt; ++UseIt) {
1179 UseIt->Inst->setOperand(UseIt->Idx, Inst);
1180 }
1181 }
1182 };
1183
1184 /// \brief Remove an instruction from the IR.
1185 class InstructionRemover : public TypePromotionAction {
1186 /// Original position of the instruction.
1187 InsertionHandler Inserter;
1188 /// Helper structure to hide all the link to the instruction. In other
1189 /// words, this helps to do as if the instruction was removed.
1190 OperandsHider Hider;
1191 /// Keep track of the uses replaced, if any.
1192 UsesReplacer *Replacer;
1193
1194 public:
1195 /// \brief Remove all reference of \p Inst and optinally replace all its
1196 /// uses with New.
1197 /// \pre If !Inst->use_empty(), then New != NULL
1198 InstructionRemover(Instruction *Inst, Value *New = NULL)
1199 : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
1200 Replacer(NULL) {
1201 if (New)
1202 Replacer = new UsesReplacer(Inst, New);
1203 DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n");
1204 Inst->removeFromParent();
1205 }
1206
1207 ~InstructionRemover() { delete Replacer; }
1208
1209 /// \brief Really remove the instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00001210 void commit() override { delete Inst; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001211
1212 /// \brief Resurrect the instruction and reassign it to the proper uses if
1213 /// new value was provided when build this action.
Craig Topper4584cd52014-03-07 09:26:03 +00001214 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001215 DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n");
1216 Inserter.insert(Inst);
1217 if (Replacer)
1218 Replacer->undo();
1219 Hider.undo();
1220 }
1221 };
1222
1223public:
1224 /// Restoration point.
1225 /// The restoration point is a pointer to an action instead of an iterator
1226 /// because the iterator may be invalidated but not the pointer.
1227 typedef const TypePromotionAction *ConstRestorationPt;
1228 /// Advocate every changes made in that transaction.
1229 void commit();
1230 /// Undo all the changes made after the given point.
1231 void rollback(ConstRestorationPt Point);
1232 /// Get the current restoration point.
1233 ConstRestorationPt getRestorationPoint() const;
1234
1235 /// \name API for IR modification with state keeping to support rollback.
1236 /// @{
1237 /// Same as Instruction::setOperand.
1238 void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
1239 /// Same as Instruction::eraseFromParent.
1240 void eraseInstruction(Instruction *Inst, Value *NewVal = NULL);
1241 /// Same as Value::replaceAllUsesWith.
1242 void replaceAllUsesWith(Instruction *Inst, Value *New);
1243 /// Same as Value::mutateType.
1244 void mutateType(Instruction *Inst, Type *NewTy);
1245 /// Same as IRBuilder::createTrunc.
1246 Instruction *createTrunc(Instruction *Opnd, Type *Ty);
1247 /// Same as IRBuilder::createSExt.
1248 Instruction *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
1249 /// Same as Instruction::moveBefore.
1250 void moveBefore(Instruction *Inst, Instruction *Before);
1251 /// @}
1252
1253 ~TypePromotionTransaction();
1254
1255private:
1256 /// The ordered list of actions made so far.
1257 SmallVector<TypePromotionAction *, 16> Actions;
1258 typedef SmallVectorImpl<TypePromotionAction *>::iterator CommitPt;
1259};
1260
1261void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
1262 Value *NewVal) {
1263 Actions.push_back(
1264 new TypePromotionTransaction::OperandSetter(Inst, Idx, NewVal));
1265}
1266
1267void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
1268 Value *NewVal) {
1269 Actions.push_back(
1270 new TypePromotionTransaction::InstructionRemover(Inst, NewVal));
1271}
1272
1273void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
1274 Value *New) {
1275 Actions.push_back(new TypePromotionTransaction::UsesReplacer(Inst, New));
1276}
1277
1278void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
1279 Actions.push_back(new TypePromotionTransaction::TypeMutator(Inst, NewTy));
1280}
1281
1282Instruction *TypePromotionTransaction::createTrunc(Instruction *Opnd,
1283 Type *Ty) {
1284 TruncBuilder *TB = new TruncBuilder(Opnd, Ty);
1285 Actions.push_back(TB);
1286 return TB->getBuiltInstruction();
1287}
1288
1289Instruction *TypePromotionTransaction::createSExt(Instruction *Inst,
1290 Value *Opnd, Type *Ty) {
1291 SExtBuilder *SB = new SExtBuilder(Inst, Opnd, Ty);
1292 Actions.push_back(SB);
1293 return SB->getBuiltInstruction();
1294}
1295
1296void TypePromotionTransaction::moveBefore(Instruction *Inst,
1297 Instruction *Before) {
1298 Actions.push_back(
1299 new TypePromotionTransaction::InstructionMoveBefore(Inst, Before));
1300}
1301
1302TypePromotionTransaction::ConstRestorationPt
1303TypePromotionTransaction::getRestorationPoint() const {
1304 return Actions.rbegin() != Actions.rend() ? *Actions.rbegin() : NULL;
1305}
1306
1307void TypePromotionTransaction::commit() {
1308 for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt;
1309 ++It) {
1310 (*It)->commit();
1311 delete *It;
1312 }
1313 Actions.clear();
1314}
1315
1316void TypePromotionTransaction::rollback(
1317 TypePromotionTransaction::ConstRestorationPt Point) {
1318 while (!Actions.empty() && Point != (*Actions.rbegin())) {
1319 TypePromotionAction *Curr = Actions.pop_back_val();
1320 Curr->undo();
1321 delete Curr;
1322 }
1323}
1324
1325TypePromotionTransaction::~TypePromotionTransaction() {
1326 for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt; ++It)
1327 delete *It;
1328 Actions.clear();
1329}
Chandler Carruthc8925912013-01-05 02:09:22 +00001330
1331/// \brief A helper class for matching addressing modes.
1332///
1333/// This encapsulates the logic for matching the target-legal addressing modes.
1334class AddressingModeMatcher {
1335 SmallVectorImpl<Instruction*> &AddrModeInsts;
1336 const TargetLowering &TLI;
1337
1338 /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
1339 /// the memory instruction that we're computing this address for.
1340 Type *AccessTy;
1341 Instruction *MemoryInst;
Stephen Lin837bba12013-07-15 17:55:02 +00001342
Chandler Carruthc8925912013-01-05 02:09:22 +00001343 /// AddrMode - This is the addressing mode that we're building up. This is
1344 /// part of the return value of this addressing mode matching stuff.
1345 ExtAddrMode &AddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00001346
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001347 /// The truncate instruction inserted by other CodeGenPrepare optimizations.
1348 const SetOfInstrs &InsertedTruncs;
1349 /// A map from the instructions to their type before promotion.
1350 InstrToOrigTy &PromotedInsts;
1351 /// The ongoing transaction where every action should be registered.
1352 TypePromotionTransaction &TPT;
1353
Chandler Carruthc8925912013-01-05 02:09:22 +00001354 /// IgnoreProfitability - This is set to true when we should not do
1355 /// profitability checks. When true, IsProfitableToFoldIntoAddressingMode
1356 /// always returns true.
1357 bool IgnoreProfitability;
Stephen Lin837bba12013-07-15 17:55:02 +00001358
Chandler Carruthc8925912013-01-05 02:09:22 +00001359 AddressingModeMatcher(SmallVectorImpl<Instruction*> &AMI,
1360 const TargetLowering &T, Type *AT,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001361 Instruction *MI, ExtAddrMode &AM,
1362 const SetOfInstrs &InsertedTruncs,
1363 InstrToOrigTy &PromotedInsts,
1364 TypePromotionTransaction &TPT)
1365 : AddrModeInsts(AMI), TLI(T), AccessTy(AT), MemoryInst(MI), AddrMode(AM),
1366 InsertedTruncs(InsertedTruncs), PromotedInsts(PromotedInsts), TPT(TPT) {
Chandler Carruthc8925912013-01-05 02:09:22 +00001367 IgnoreProfitability = false;
1368 }
1369public:
Stephen Lin837bba12013-07-15 17:55:02 +00001370
Chandler Carruthc8925912013-01-05 02:09:22 +00001371 /// Match - Find the maximal addressing mode that a load/store of V can fold,
1372 /// give an access type of AccessTy. This returns a list of involved
1373 /// instructions in AddrModeInsts.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001374 /// \p InsertedTruncs The truncate instruction inserted by other
1375 /// CodeGenPrepare
1376 /// optimizations.
1377 /// \p PromotedInsts maps the instructions to their type before promotion.
1378 /// \p The ongoing transaction where every action should be registered.
Chandler Carruthc8925912013-01-05 02:09:22 +00001379 static ExtAddrMode Match(Value *V, Type *AccessTy,
1380 Instruction *MemoryInst,
1381 SmallVectorImpl<Instruction*> &AddrModeInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001382 const TargetLowering &TLI,
1383 const SetOfInstrs &InsertedTruncs,
1384 InstrToOrigTy &PromotedInsts,
1385 TypePromotionTransaction &TPT) {
Chandler Carruthc8925912013-01-05 02:09:22 +00001386 ExtAddrMode Result;
1387
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001388 bool Success = AddressingModeMatcher(AddrModeInsts, TLI, AccessTy,
1389 MemoryInst, Result, InsertedTruncs,
1390 PromotedInsts, TPT).MatchAddr(V, 0);
Chandler Carruthc8925912013-01-05 02:09:22 +00001391 (void)Success; assert(Success && "Couldn't select *anything*?");
1392 return Result;
1393 }
1394private:
1395 bool MatchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
1396 bool MatchAddr(Value *V, unsigned Depth);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001397 bool MatchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth,
1398 bool *MovedAway = NULL);
Chandler Carruthc8925912013-01-05 02:09:22 +00001399 bool IsProfitableToFoldIntoAddressingMode(Instruction *I,
1400 ExtAddrMode &AMBefore,
1401 ExtAddrMode &AMAfter);
1402 bool ValueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
Quentin Colombet867c5502014-02-14 22:23:22 +00001403 bool IsPromotionProfitable(unsigned MatchedSize, unsigned SizeWithPromotion,
1404 Value *PromotedOperand) const;
Chandler Carruthc8925912013-01-05 02:09:22 +00001405};
1406
1407/// MatchScaledValue - Try adding ScaleReg*Scale to the current addressing mode.
1408/// Return true and update AddrMode if this addr mode is legal for the target,
1409/// false if not.
1410bool AddressingModeMatcher::MatchScaledValue(Value *ScaleReg, int64_t Scale,
1411 unsigned Depth) {
1412 // If Scale is 1, then this is the same as adding ScaleReg to the addressing
1413 // mode. Just process that directly.
1414 if (Scale == 1)
1415 return MatchAddr(ScaleReg, Depth);
Stephen Lin837bba12013-07-15 17:55:02 +00001416
Chandler Carruthc8925912013-01-05 02:09:22 +00001417 // If the scale is 0, it takes nothing to add this.
1418 if (Scale == 0)
1419 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00001420
Chandler Carruthc8925912013-01-05 02:09:22 +00001421 // If we already have a scale of this value, we can add to it, otherwise, we
1422 // need an available scale field.
1423 if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
1424 return false;
1425
1426 ExtAddrMode TestAddrMode = AddrMode;
1427
1428 // Add scale to turn X*4+X*3 -> X*7. This could also do things like
1429 // [A+B + A*7] -> [B+A*8].
1430 TestAddrMode.Scale += Scale;
1431 TestAddrMode.ScaledReg = ScaleReg;
1432
1433 // If the new address isn't legal, bail out.
1434 if (!TLI.isLegalAddressingMode(TestAddrMode, AccessTy))
1435 return false;
1436
1437 // It was legal, so commit it.
1438 AddrMode = TestAddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00001439
Chandler Carruthc8925912013-01-05 02:09:22 +00001440 // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
1441 // to see if ScaleReg is actually X+C. If so, we can turn this into adding
1442 // X*Scale + C*Scale to addr mode.
1443 ConstantInt *CI = 0; Value *AddLHS = 0;
1444 if (isa<Instruction>(ScaleReg) && // not a constant expr.
1445 match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
1446 TestAddrMode.ScaledReg = AddLHS;
1447 TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00001448
Chandler Carruthc8925912013-01-05 02:09:22 +00001449 // If this addressing mode is legal, commit it and remember that we folded
1450 // this instruction.
1451 if (TLI.isLegalAddressingMode(TestAddrMode, AccessTy)) {
1452 AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
1453 AddrMode = TestAddrMode;
1454 return true;
1455 }
1456 }
1457
1458 // Otherwise, not (x+c)*scale, just return what we have.
1459 return true;
1460}
1461
1462/// MightBeFoldableInst - This is a little filter, which returns true if an
1463/// addressing computation involving I might be folded into a load/store
1464/// accessing it. This doesn't need to be perfect, but needs to accept at least
1465/// the set of instructions that MatchOperationAddr can.
1466static bool MightBeFoldableInst(Instruction *I) {
1467 switch (I->getOpcode()) {
1468 case Instruction::BitCast:
1469 // Don't touch identity bitcasts.
1470 if (I->getType() == I->getOperand(0)->getType())
1471 return false;
1472 return I->getType()->isPointerTy() || I->getType()->isIntegerTy();
1473 case Instruction::PtrToInt:
1474 // PtrToInt is always a noop, as we know that the int type is pointer sized.
1475 return true;
1476 case Instruction::IntToPtr:
1477 // We know the input is intptr_t, so this is foldable.
1478 return true;
1479 case Instruction::Add:
1480 return true;
1481 case Instruction::Mul:
1482 case Instruction::Shl:
1483 // Can only handle X*C and X << C.
1484 return isa<ConstantInt>(I->getOperand(1));
1485 case Instruction::GetElementPtr:
1486 return true;
1487 default:
1488 return false;
1489 }
1490}
1491
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001492/// \brief Hepler class to perform type promotion.
1493class TypePromotionHelper {
1494 /// \brief Utility function to check whether or not a sign extension of
1495 /// \p Inst with \p ConsideredSExtType can be moved through \p Inst by either
1496 /// using the operands of \p Inst or promoting \p Inst.
1497 /// In other words, check if:
1498 /// sext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredSExtType.
1499 /// #1 Promotion applies:
1500 /// ConsideredSExtType Inst (sext opnd1 to ConsideredSExtType, ...).
1501 /// #2 Operand reuses:
1502 /// sext opnd1 to ConsideredSExtType.
1503 /// \p PromotedInsts maps the instructions to their type before promotion.
1504 static bool canGetThrough(const Instruction *Inst, Type *ConsideredSExtType,
1505 const InstrToOrigTy &PromotedInsts);
1506
1507 /// \brief Utility function to determine if \p OpIdx should be promoted when
1508 /// promoting \p Inst.
1509 static bool shouldSExtOperand(const Instruction *Inst, int OpIdx) {
1510 if (isa<SelectInst>(Inst) && OpIdx == 0)
1511 return false;
1512 return true;
1513 }
1514
1515 /// \brief Utility function to promote the operand of \p SExt when this
1516 /// operand is a promotable trunc or sext.
1517 /// \p PromotedInsts maps the instructions to their type before promotion.
1518 /// \p CreatedInsts[out] contains how many non-free instructions have been
1519 /// created to promote the operand of SExt.
1520 /// Should never be called directly.
1521 /// \return The promoted value which is used instead of SExt.
1522 static Value *promoteOperandForTruncAndSExt(Instruction *SExt,
1523 TypePromotionTransaction &TPT,
1524 InstrToOrigTy &PromotedInsts,
1525 unsigned &CreatedInsts);
1526
1527 /// \brief Utility function to promote the operand of \p SExt when this
1528 /// operand is promotable and is not a supported trunc or sext.
1529 /// \p PromotedInsts maps the instructions to their type before promotion.
1530 /// \p CreatedInsts[out] contains how many non-free instructions have been
1531 /// created to promote the operand of SExt.
1532 /// Should never be called directly.
1533 /// \return The promoted value which is used instead of SExt.
1534 static Value *promoteOperandForOther(Instruction *SExt,
1535 TypePromotionTransaction &TPT,
1536 InstrToOrigTy &PromotedInsts,
1537 unsigned &CreatedInsts);
1538
1539public:
1540 /// Type for the utility function that promotes the operand of SExt.
1541 typedef Value *(*Action)(Instruction *SExt, TypePromotionTransaction &TPT,
1542 InstrToOrigTy &PromotedInsts,
1543 unsigned &CreatedInsts);
1544 /// \brief Given a sign extend instruction \p SExt, return the approriate
1545 /// action to promote the operand of \p SExt instead of using SExt.
1546 /// \return NULL if no promotable action is possible with the current
1547 /// sign extension.
1548 /// \p InsertedTruncs keeps track of all the truncate instructions inserted by
1549 /// the others CodeGenPrepare optimizations. This information is important
1550 /// because we do not want to promote these instructions as CodeGenPrepare
1551 /// will reinsert them later. Thus creating an infinite loop: create/remove.
1552 /// \p PromotedInsts maps the instructions to their type before promotion.
1553 static Action getAction(Instruction *SExt, const SetOfInstrs &InsertedTruncs,
1554 const TargetLowering &TLI,
1555 const InstrToOrigTy &PromotedInsts);
1556};
1557
1558bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
1559 Type *ConsideredSExtType,
1560 const InstrToOrigTy &PromotedInsts) {
1561 // We can always get through sext.
1562 if (isa<SExtInst>(Inst))
1563 return true;
1564
1565 // We can get through binary operator, if it is legal. In other words, the
1566 // binary operator must have a nuw or nsw flag.
1567 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
1568 if (BinOp && isa<OverflowingBinaryOperator>(BinOp) &&
1569 (BinOp->hasNoUnsignedWrap() || BinOp->hasNoSignedWrap()))
1570 return true;
1571
1572 // Check if we can do the following simplification.
1573 // sext(trunc(sext)) --> sext
1574 if (!isa<TruncInst>(Inst))
1575 return false;
1576
1577 Value *OpndVal = Inst->getOperand(0);
1578 // Check if we can use this operand in the sext.
1579 // If the type is larger than the result type of the sign extension,
1580 // we cannot.
1581 if (OpndVal->getType()->getIntegerBitWidth() >
1582 ConsideredSExtType->getIntegerBitWidth())
1583 return false;
1584
1585 // If the operand of the truncate is not an instruction, we will not have
1586 // any information on the dropped bits.
1587 // (Actually we could for constant but it is not worth the extra logic).
1588 Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
1589 if (!Opnd)
1590 return false;
1591
1592 // Check if the source of the type is narrow enough.
1593 // I.e., check that trunc just drops sign extended bits.
1594 // #1 get the type of the operand.
1595 const Type *OpndType;
1596 InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
1597 if (It != PromotedInsts.end())
1598 OpndType = It->second;
1599 else if (isa<SExtInst>(Opnd))
1600 OpndType = cast<Instruction>(Opnd)->getOperand(0)->getType();
1601 else
1602 return false;
1603
1604 // #2 check that the truncate just drop sign extended bits.
1605 if (Inst->getType()->getIntegerBitWidth() >= OpndType->getIntegerBitWidth())
1606 return true;
1607
1608 return false;
1609}
1610
1611TypePromotionHelper::Action TypePromotionHelper::getAction(
1612 Instruction *SExt, const SetOfInstrs &InsertedTruncs,
1613 const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
1614 Instruction *SExtOpnd = dyn_cast<Instruction>(SExt->getOperand(0));
1615 Type *SExtTy = SExt->getType();
1616 // If the operand of the sign extension is not an instruction, we cannot
1617 // get through.
1618 // If it, check we can get through.
1619 if (!SExtOpnd || !canGetThrough(SExtOpnd, SExtTy, PromotedInsts))
1620 return NULL;
1621
1622 // Do not promote if the operand has been added by codegenprepare.
1623 // Otherwise, it means we are undoing an optimization that is likely to be
1624 // redone, thus causing potential infinite loop.
1625 if (isa<TruncInst>(SExtOpnd) && InsertedTruncs.count(SExtOpnd))
1626 return NULL;
1627
1628 // SExt or Trunc instructions.
1629 // Return the related handler.
1630 if (isa<SExtInst>(SExtOpnd) || isa<TruncInst>(SExtOpnd))
1631 return promoteOperandForTruncAndSExt;
1632
1633 // Regular instruction.
1634 // Abort early if we will have to insert non-free instructions.
1635 if (!SExtOpnd->hasOneUse() &&
1636 !TLI.isTruncateFree(SExtTy, SExtOpnd->getType()))
1637 return NULL;
1638 return promoteOperandForOther;
1639}
1640
1641Value *TypePromotionHelper::promoteOperandForTruncAndSExt(
1642 llvm::Instruction *SExt, TypePromotionTransaction &TPT,
1643 InstrToOrigTy &PromotedInsts, unsigned &CreatedInsts) {
1644 // By construction, the operand of SExt is an instruction. Otherwise we cannot
1645 // get through it and this method should not be called.
1646 Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
1647 // Replace sext(trunc(opnd)) or sext(sext(opnd))
1648 // => sext(opnd).
1649 TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
1650 CreatedInsts = 0;
1651
1652 // Remove dead code.
1653 if (SExtOpnd->use_empty())
1654 TPT.eraseInstruction(SExtOpnd);
1655
1656 // Check if the sext is still needed.
1657 if (SExt->getType() != SExt->getOperand(0)->getType())
1658 return SExt;
1659
1660 // At this point we have: sext ty opnd to ty.
1661 // Reassign the uses of SExt to the opnd and remove SExt.
1662 Value *NextVal = SExt->getOperand(0);
1663 TPT.eraseInstruction(SExt, NextVal);
1664 return NextVal;
1665}
1666
1667Value *
1668TypePromotionHelper::promoteOperandForOther(Instruction *SExt,
1669 TypePromotionTransaction &TPT,
1670 InstrToOrigTy &PromotedInsts,
1671 unsigned &CreatedInsts) {
1672 // By construction, the operand of SExt is an instruction. Otherwise we cannot
1673 // get through it and this method should not be called.
1674 Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
1675 CreatedInsts = 0;
1676 if (!SExtOpnd->hasOneUse()) {
1677 // SExtOpnd will be promoted.
1678 // All its uses, but SExt, will need to use a truncated value of the
1679 // promoted version.
1680 // Create the truncate now.
1681 Instruction *Trunc = TPT.createTrunc(SExt, SExtOpnd->getType());
1682 Trunc->removeFromParent();
1683 // Insert it just after the definition.
1684 Trunc->insertAfter(SExtOpnd);
1685
1686 TPT.replaceAllUsesWith(SExtOpnd, Trunc);
1687 // Restore the operand of SExt (which has been replace by the previous call
1688 // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
1689 TPT.setOperand(SExt, 0, SExtOpnd);
1690 }
1691
1692 // Get through the Instruction:
1693 // 1. Update its type.
1694 // 2. Replace the uses of SExt by Inst.
1695 // 3. Sign extend each operand that needs to be sign extended.
1696
1697 // Remember the original type of the instruction before promotion.
1698 // This is useful to know that the high bits are sign extended bits.
1699 PromotedInsts.insert(
1700 std::pair<Instruction *, Type *>(SExtOpnd, SExtOpnd->getType()));
1701 // Step #1.
1702 TPT.mutateType(SExtOpnd, SExt->getType());
1703 // Step #2.
1704 TPT.replaceAllUsesWith(SExt, SExtOpnd);
1705 // Step #3.
1706 Instruction *SExtForOpnd = SExt;
1707
1708 DEBUG(dbgs() << "Propagate SExt to operands\n");
1709 for (int OpIdx = 0, EndOpIdx = SExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
1710 ++OpIdx) {
1711 DEBUG(dbgs() << "Operand:\n" << *(SExtOpnd->getOperand(OpIdx)) << '\n');
1712 if (SExtOpnd->getOperand(OpIdx)->getType() == SExt->getType() ||
1713 !shouldSExtOperand(SExtOpnd, OpIdx)) {
1714 DEBUG(dbgs() << "No need to propagate\n");
1715 continue;
1716 }
1717 // Check if we can statically sign extend the operand.
1718 Value *Opnd = SExtOpnd->getOperand(OpIdx);
1719 if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
1720 DEBUG(dbgs() << "Statically sign extend\n");
1721 TPT.setOperand(
1722 SExtOpnd, OpIdx,
1723 ConstantInt::getSigned(SExt->getType(), Cst->getSExtValue()));
1724 continue;
1725 }
1726 // UndefValue are typed, so we have to statically sign extend them.
1727 if (isa<UndefValue>(Opnd)) {
1728 DEBUG(dbgs() << "Statically sign extend\n");
1729 TPT.setOperand(SExtOpnd, OpIdx, UndefValue::get(SExt->getType()));
1730 continue;
1731 }
1732
1733 // Otherwise we have to explicity sign extend the operand.
1734 // Check if SExt was reused to sign extend an operand.
1735 if (!SExtForOpnd) {
1736 // If yes, create a new one.
1737 DEBUG(dbgs() << "More operands to sext\n");
1738 SExtForOpnd = TPT.createSExt(SExt, Opnd, SExt->getType());
1739 ++CreatedInsts;
1740 }
1741
1742 TPT.setOperand(SExtForOpnd, 0, Opnd);
1743
1744 // Move the sign extension before the insertion point.
1745 TPT.moveBefore(SExtForOpnd, SExtOpnd);
1746 TPT.setOperand(SExtOpnd, OpIdx, SExtForOpnd);
1747 // If more sext are required, new instructions will have to be created.
1748 SExtForOpnd = NULL;
1749 }
1750 if (SExtForOpnd == SExt) {
1751 DEBUG(dbgs() << "Sign extension is useless now\n");
1752 TPT.eraseInstruction(SExt);
1753 }
1754 return SExtOpnd;
1755}
1756
Quentin Colombet867c5502014-02-14 22:23:22 +00001757/// IsPromotionProfitable - Check whether or not promoting an instruction
1758/// to a wider type was profitable.
1759/// \p MatchedSize gives the number of instructions that have been matched
1760/// in the addressing mode after the promotion was applied.
1761/// \p SizeWithPromotion gives the number of created instructions for
1762/// the promotion plus the number of instructions that have been
1763/// matched in the addressing mode before the promotion.
1764/// \p PromotedOperand is the value that has been promoted.
1765/// \return True if the promotion is profitable, false otherwise.
1766bool
1767AddressingModeMatcher::IsPromotionProfitable(unsigned MatchedSize,
1768 unsigned SizeWithPromotion,
1769 Value *PromotedOperand) const {
1770 // We folded less instructions than what we created to promote the operand.
1771 // This is not profitable.
1772 if (MatchedSize < SizeWithPromotion)
1773 return false;
1774 if (MatchedSize > SizeWithPromotion)
1775 return true;
1776 // The promotion is neutral but it may help folding the sign extension in
1777 // loads for instance.
1778 // Check that we did not create an illegal instruction.
1779 Instruction *PromotedInst = dyn_cast<Instruction>(PromotedOperand);
1780 if (!PromotedInst)
1781 return false;
Quentin Colombet1627a412014-02-22 01:06:41 +00001782 int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode());
1783 // If the ISDOpcode is undefined, it was undefined before the promotion.
1784 if (!ISDOpcode)
1785 return true;
1786 // Otherwise, check if the promoted instruction is legal or not.
1787 return TLI.isOperationLegalOrCustom(ISDOpcode,
Quentin Colombet867c5502014-02-14 22:23:22 +00001788 EVT::getEVT(PromotedInst->getType()));
1789}
1790
Chandler Carruthc8925912013-01-05 02:09:22 +00001791/// MatchOperationAddr - Given an instruction or constant expr, see if we can
1792/// fold the operation into the addressing mode. If so, update the addressing
1793/// mode and return true, otherwise return false without modifying AddrMode.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001794/// If \p MovedAway is not NULL, it contains the information of whether or
1795/// not AddrInst has to be folded into the addressing mode on success.
1796/// If \p MovedAway == true, \p AddrInst will not be part of the addressing
1797/// because it has been moved away.
1798/// Thus AddrInst must not be added in the matched instructions.
1799/// This state can happen when AddrInst is a sext, since it may be moved away.
1800/// Therefore, AddrInst may not be valid when MovedAway is true and it must
1801/// not be referenced anymore.
Chandler Carruthc8925912013-01-05 02:09:22 +00001802bool AddressingModeMatcher::MatchOperationAddr(User *AddrInst, unsigned Opcode,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001803 unsigned Depth,
1804 bool *MovedAway) {
Chandler Carruthc8925912013-01-05 02:09:22 +00001805 // Avoid exponential behavior on extremely deep expression trees.
1806 if (Depth >= 5) return false;
Stephen Lin837bba12013-07-15 17:55:02 +00001807
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001808 // By default, all matched instructions stay in place.
1809 if (MovedAway)
1810 *MovedAway = false;
1811
Chandler Carruthc8925912013-01-05 02:09:22 +00001812 switch (Opcode) {
1813 case Instruction::PtrToInt:
1814 // PtrToInt is always a noop, as we know that the int type is pointer sized.
1815 return MatchAddr(AddrInst->getOperand(0), Depth);
1816 case Instruction::IntToPtr:
1817 // This inttoptr is a no-op if the integer type is pointer sized.
1818 if (TLI.getValueType(AddrInst->getOperand(0)->getType()) ==
Matt Arsenault37d42ec2013-09-06 00:18:43 +00001819 TLI.getPointerTy(AddrInst->getType()->getPointerAddressSpace()))
Chandler Carruthc8925912013-01-05 02:09:22 +00001820 return MatchAddr(AddrInst->getOperand(0), Depth);
1821 return false;
1822 case Instruction::BitCast:
1823 // BitCast is always a noop, and we can handle it as long as it is
1824 // int->int or pointer->pointer (we don't want int<->fp or something).
1825 if ((AddrInst->getOperand(0)->getType()->isPointerTy() ||
1826 AddrInst->getOperand(0)->getType()->isIntegerTy()) &&
1827 // Don't touch identity bitcasts. These were probably put here by LSR,
1828 // and we don't want to mess around with them. Assume it knows what it
1829 // is doing.
1830 AddrInst->getOperand(0)->getType() != AddrInst->getType())
1831 return MatchAddr(AddrInst->getOperand(0), Depth);
1832 return false;
1833 case Instruction::Add: {
1834 // Check to see if we can merge in the RHS then the LHS. If so, we win.
1835 ExtAddrMode BackupAddrMode = AddrMode;
1836 unsigned OldSize = AddrModeInsts.size();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001837 // Start a transaction at this point.
1838 // The LHS may match but not the RHS.
1839 // Therefore, we need a higher level restoration point to undo partially
1840 // matched operation.
1841 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
1842 TPT.getRestorationPoint();
1843
Chandler Carruthc8925912013-01-05 02:09:22 +00001844 if (MatchAddr(AddrInst->getOperand(1), Depth+1) &&
1845 MatchAddr(AddrInst->getOperand(0), Depth+1))
1846 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00001847
Chandler Carruthc8925912013-01-05 02:09:22 +00001848 // Restore the old addr mode info.
1849 AddrMode = BackupAddrMode;
1850 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001851 TPT.rollback(LastKnownGood);
Stephen Lin837bba12013-07-15 17:55:02 +00001852
Chandler Carruthc8925912013-01-05 02:09:22 +00001853 // Otherwise this was over-aggressive. Try merging in the LHS then the RHS.
1854 if (MatchAddr(AddrInst->getOperand(0), Depth+1) &&
1855 MatchAddr(AddrInst->getOperand(1), Depth+1))
1856 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00001857
Chandler Carruthc8925912013-01-05 02:09:22 +00001858 // Otherwise we definitely can't merge the ADD in.
1859 AddrMode = BackupAddrMode;
1860 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001861 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00001862 break;
1863 }
1864 //case Instruction::Or:
1865 // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
1866 //break;
1867 case Instruction::Mul:
1868 case Instruction::Shl: {
1869 // Can only handle X*C and X << C.
1870 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
1871 if (!RHS) return false;
1872 int64_t Scale = RHS->getSExtValue();
1873 if (Opcode == Instruction::Shl)
1874 Scale = 1LL << Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00001875
Chandler Carruthc8925912013-01-05 02:09:22 +00001876 return MatchScaledValue(AddrInst->getOperand(0), Scale, Depth);
1877 }
1878 case Instruction::GetElementPtr: {
1879 // Scan the GEP. We check it if it contains constant offsets and at most
1880 // one variable offset.
1881 int VariableOperand = -1;
1882 unsigned VariableScale = 0;
Stephen Lin837bba12013-07-15 17:55:02 +00001883
Chandler Carruthc8925912013-01-05 02:09:22 +00001884 int64_t ConstantOffset = 0;
1885 const DataLayout *TD = TLI.getDataLayout();
1886 gep_type_iterator GTI = gep_type_begin(AddrInst);
1887 for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
1888 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
1889 const StructLayout *SL = TD->getStructLayout(STy);
1890 unsigned Idx =
1891 cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
1892 ConstantOffset += SL->getElementOffset(Idx);
1893 } else {
1894 uint64_t TypeSize = TD->getTypeAllocSize(GTI.getIndexedType());
1895 if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
1896 ConstantOffset += CI->getSExtValue()*TypeSize;
1897 } else if (TypeSize) { // Scales of zero don't do anything.
1898 // We only allow one variable index at the moment.
1899 if (VariableOperand != -1)
1900 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00001901
Chandler Carruthc8925912013-01-05 02:09:22 +00001902 // Remember the variable index.
1903 VariableOperand = i;
1904 VariableScale = TypeSize;
1905 }
1906 }
1907 }
Stephen Lin837bba12013-07-15 17:55:02 +00001908
Chandler Carruthc8925912013-01-05 02:09:22 +00001909 // A common case is for the GEP to only do a constant offset. In this case,
1910 // just add it to the disp field and check validity.
1911 if (VariableOperand == -1) {
1912 AddrMode.BaseOffs += ConstantOffset;
1913 if (ConstantOffset == 0 || TLI.isLegalAddressingMode(AddrMode, AccessTy)){
1914 // Check to see if we can fold the base pointer in too.
1915 if (MatchAddr(AddrInst->getOperand(0), Depth+1))
1916 return true;
1917 }
1918 AddrMode.BaseOffs -= ConstantOffset;
1919 return false;
1920 }
1921
1922 // Save the valid addressing mode in case we can't match.
1923 ExtAddrMode BackupAddrMode = AddrMode;
1924 unsigned OldSize = AddrModeInsts.size();
1925
1926 // See if the scale and offset amount is valid for this target.
1927 AddrMode.BaseOffs += ConstantOffset;
1928
1929 // Match the base operand of the GEP.
1930 if (!MatchAddr(AddrInst->getOperand(0), Depth+1)) {
1931 // If it couldn't be matched, just stuff the value in a register.
1932 if (AddrMode.HasBaseReg) {
1933 AddrMode = BackupAddrMode;
1934 AddrModeInsts.resize(OldSize);
1935 return false;
1936 }
1937 AddrMode.HasBaseReg = true;
1938 AddrMode.BaseReg = AddrInst->getOperand(0);
1939 }
1940
1941 // Match the remaining variable portion of the GEP.
1942 if (!MatchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
1943 Depth)) {
1944 // If it couldn't be matched, try stuffing the base into a register
1945 // instead of matching it, and retrying the match of the scale.
1946 AddrMode = BackupAddrMode;
1947 AddrModeInsts.resize(OldSize);
1948 if (AddrMode.HasBaseReg)
1949 return false;
1950 AddrMode.HasBaseReg = true;
1951 AddrMode.BaseReg = AddrInst->getOperand(0);
1952 AddrMode.BaseOffs += ConstantOffset;
1953 if (!MatchScaledValue(AddrInst->getOperand(VariableOperand),
1954 VariableScale, Depth)) {
1955 // If even that didn't work, bail.
1956 AddrMode = BackupAddrMode;
1957 AddrModeInsts.resize(OldSize);
1958 return false;
1959 }
1960 }
1961
1962 return true;
1963 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001964 case Instruction::SExt: {
1965 // Try to move this sext out of the way of the addressing mode.
1966 Instruction *SExt = cast<Instruction>(AddrInst);
1967 // Ask for a method for doing so.
1968 TypePromotionHelper::Action TPH = TypePromotionHelper::getAction(
1969 SExt, InsertedTruncs, TLI, PromotedInsts);
1970 if (!TPH)
1971 return false;
1972
1973 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
1974 TPT.getRestorationPoint();
1975 unsigned CreatedInsts = 0;
1976 Value *PromotedOperand = TPH(SExt, TPT, PromotedInsts, CreatedInsts);
1977 // SExt has been moved away.
1978 // Thus either it will be rematched later in the recursive calls or it is
1979 // gone. Anyway, we must not fold it into the addressing mode at this point.
1980 // E.g.,
1981 // op = add opnd, 1
1982 // idx = sext op
1983 // addr = gep base, idx
1984 // is now:
1985 // promotedOpnd = sext opnd <- no match here
1986 // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls)
1987 // addr = gep base, op <- match
1988 if (MovedAway)
1989 *MovedAway = true;
1990
1991 assert(PromotedOperand &&
1992 "TypePromotionHelper should have filtered out those cases");
1993
1994 ExtAddrMode BackupAddrMode = AddrMode;
1995 unsigned OldSize = AddrModeInsts.size();
1996
1997 if (!MatchAddr(PromotedOperand, Depth) ||
Quentin Colombet867c5502014-02-14 22:23:22 +00001998 !IsPromotionProfitable(AddrModeInsts.size(), OldSize + CreatedInsts,
1999 PromotedOperand)) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002000 AddrMode = BackupAddrMode;
2001 AddrModeInsts.resize(OldSize);
2002 DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
2003 TPT.rollback(LastKnownGood);
2004 return false;
2005 }
2006 return true;
2007 }
Chandler Carruthc8925912013-01-05 02:09:22 +00002008 }
2009 return false;
2010}
2011
2012/// MatchAddr - If we can, try to add the value of 'Addr' into the current
2013/// addressing mode. If Addr can't be added to AddrMode this returns false and
2014/// leaves AddrMode unmodified. This assumes that Addr is either a pointer type
2015/// or intptr_t for the target.
2016///
2017bool AddressingModeMatcher::MatchAddr(Value *Addr, unsigned Depth) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002018 // Start a transaction at this point that we will rollback if the matching
2019 // fails.
2020 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2021 TPT.getRestorationPoint();
Chandler Carruthc8925912013-01-05 02:09:22 +00002022 if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
2023 // Fold in immediates if legal for the target.
2024 AddrMode.BaseOffs += CI->getSExtValue();
2025 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2026 return true;
2027 AddrMode.BaseOffs -= CI->getSExtValue();
2028 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
2029 // If this is a global variable, try to fold it into the addressing mode.
2030 if (AddrMode.BaseGV == 0) {
2031 AddrMode.BaseGV = GV;
2032 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2033 return true;
2034 AddrMode.BaseGV = 0;
2035 }
2036 } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
2037 ExtAddrMode BackupAddrMode = AddrMode;
2038 unsigned OldSize = AddrModeInsts.size();
2039
2040 // Check to see if it is possible to fold this operation.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002041 bool MovedAway = false;
2042 if (MatchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
2043 // This instruction may have been move away. If so, there is nothing
2044 // to check here.
2045 if (MovedAway)
2046 return true;
Chandler Carruthc8925912013-01-05 02:09:22 +00002047 // Okay, it's possible to fold this. Check to see if it is actually
2048 // *profitable* to do so. We use a simple cost model to avoid increasing
2049 // register pressure too much.
2050 if (I->hasOneUse() ||
2051 IsProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
2052 AddrModeInsts.push_back(I);
2053 return true;
2054 }
Stephen Lin837bba12013-07-15 17:55:02 +00002055
Chandler Carruthc8925912013-01-05 02:09:22 +00002056 // It isn't profitable to do this, roll back.
2057 //cerr << "NOT FOLDING: " << *I;
2058 AddrMode = BackupAddrMode;
2059 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002060 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00002061 }
2062 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
2063 if (MatchOperationAddr(CE, CE->getOpcode(), Depth))
2064 return true;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002065 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00002066 } else if (isa<ConstantPointerNull>(Addr)) {
2067 // Null pointer gets folded without affecting the addressing mode.
2068 return true;
2069 }
2070
2071 // Worse case, the target should support [reg] addressing modes. :)
2072 if (!AddrMode.HasBaseReg) {
2073 AddrMode.HasBaseReg = true;
2074 AddrMode.BaseReg = Addr;
2075 // Still check for legality in case the target supports [imm] but not [i+r].
2076 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2077 return true;
2078 AddrMode.HasBaseReg = false;
2079 AddrMode.BaseReg = 0;
2080 }
2081
2082 // If the base register is already taken, see if we can do [r+r].
2083 if (AddrMode.Scale == 0) {
2084 AddrMode.Scale = 1;
2085 AddrMode.ScaledReg = Addr;
2086 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2087 return true;
2088 AddrMode.Scale = 0;
2089 AddrMode.ScaledReg = 0;
2090 }
2091 // Couldn't match.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002092 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00002093 return false;
2094}
2095
2096/// IsOperandAMemoryOperand - Check to see if all uses of OpVal by the specified
2097/// inline asm call are due to memory operands. If so, return true, otherwise
2098/// return false.
2099static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
2100 const TargetLowering &TLI) {
2101 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(ImmutableCallSite(CI));
2102 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
2103 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Stephen Lin837bba12013-07-15 17:55:02 +00002104
Chandler Carruthc8925912013-01-05 02:09:22 +00002105 // Compute the constraint code and ConstraintType to use.
2106 TLI.ComputeConstraintToUse(OpInfo, SDValue());
2107
2108 // If this asm operand is our Value*, and if it isn't an indirect memory
2109 // operand, we can't fold it!
2110 if (OpInfo.CallOperandVal == OpVal &&
2111 (OpInfo.ConstraintType != TargetLowering::C_Memory ||
2112 !OpInfo.isIndirect))
2113 return false;
2114 }
2115
2116 return true;
2117}
2118
2119/// FindAllMemoryUses - Recursively walk all the uses of I until we find a
2120/// memory use. If we find an obviously non-foldable instruction, return true.
2121/// Add the ultimately found memory instructions to MemoryUses.
2122static bool FindAllMemoryUses(Instruction *I,
2123 SmallVectorImpl<std::pair<Instruction*,unsigned> > &MemoryUses,
2124 SmallPtrSet<Instruction*, 16> &ConsideredInsts,
2125 const TargetLowering &TLI) {
2126 // If we already considered this instruction, we're done.
2127 if (!ConsideredInsts.insert(I))
2128 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00002129
Chandler Carruthc8925912013-01-05 02:09:22 +00002130 // If this is an obviously unfoldable instruction, bail out.
2131 if (!MightBeFoldableInst(I))
2132 return true;
2133
2134 // Loop over all the uses, recursively processing them.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002135 for (Use &U : I->uses()) {
2136 Instruction *UserI = cast<Instruction>(U.getUser());
Chandler Carruthc8925912013-01-05 02:09:22 +00002137
Chandler Carruthcdf47882014-03-09 03:16:01 +00002138 if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
2139 MemoryUses.push_back(std::make_pair(LI, U.getOperandNo()));
Chandler Carruthc8925912013-01-05 02:09:22 +00002140 continue;
2141 }
Stephen Lin837bba12013-07-15 17:55:02 +00002142
Chandler Carruthcdf47882014-03-09 03:16:01 +00002143 if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
2144 unsigned opNo = U.getOperandNo();
Chandler Carruthc8925912013-01-05 02:09:22 +00002145 if (opNo == 0) return true; // Storing addr, not into addr.
2146 MemoryUses.push_back(std::make_pair(SI, opNo));
2147 continue;
2148 }
Stephen Lin837bba12013-07-15 17:55:02 +00002149
Chandler Carruthcdf47882014-03-09 03:16:01 +00002150 if (CallInst *CI = dyn_cast<CallInst>(UserI)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002151 InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
2152 if (!IA) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002153
Chandler Carruthc8925912013-01-05 02:09:22 +00002154 // If this is a memory operand, we're cool, otherwise bail out.
2155 if (!IsOperandAMemoryOperand(CI, IA, I, TLI))
2156 return true;
2157 continue;
2158 }
Stephen Lin837bba12013-07-15 17:55:02 +00002159
Chandler Carruthcdf47882014-03-09 03:16:01 +00002160 if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TLI))
Chandler Carruthc8925912013-01-05 02:09:22 +00002161 return true;
2162 }
2163
2164 return false;
2165}
2166
2167/// ValueAlreadyLiveAtInst - Retrn true if Val is already known to be live at
2168/// the use site that we're folding it into. If so, there is no cost to
2169/// include it in the addressing mode. KnownLive1 and KnownLive2 are two values
2170/// that we know are live at the instruction already.
2171bool AddressingModeMatcher::ValueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
2172 Value *KnownLive2) {
2173 // If Val is either of the known-live values, we know it is live!
2174 if (Val == 0 || Val == KnownLive1 || Val == KnownLive2)
2175 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002176
Chandler Carruthc8925912013-01-05 02:09:22 +00002177 // All values other than instructions and arguments (e.g. constants) are live.
2178 if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002179
Chandler Carruthc8925912013-01-05 02:09:22 +00002180 // If Val is a constant sized alloca in the entry block, it is live, this is
2181 // true because it is just a reference to the stack/frame pointer, which is
2182 // live for the whole function.
2183 if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
2184 if (AI->isStaticAlloca())
2185 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002186
Chandler Carruthc8925912013-01-05 02:09:22 +00002187 // Check to see if this value is already used in the memory instruction's
2188 // block. If so, it's already live into the block at the very least, so we
2189 // can reasonably fold it.
2190 return Val->isUsedInBasicBlock(MemoryInst->getParent());
2191}
2192
2193/// IsProfitableToFoldIntoAddressingMode - It is possible for the addressing
2194/// mode of the machine to fold the specified instruction into a load or store
2195/// that ultimately uses it. However, the specified instruction has multiple
2196/// uses. Given this, it may actually increase register pressure to fold it
2197/// into the load. For example, consider this code:
2198///
2199/// X = ...
2200/// Y = X+1
2201/// use(Y) -> nonload/store
2202/// Z = Y+1
2203/// load Z
2204///
2205/// In this case, Y has multiple uses, and can be folded into the load of Z
2206/// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to
2207/// be live at the use(Y) line. If we don't fold Y into load Z, we use one
2208/// fewer register. Since Y can't be folded into "use(Y)" we don't increase the
2209/// number of computations either.
2210///
2211/// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If
2212/// X was live across 'load Z' for other reasons, we actually *would* want to
2213/// fold the addressing mode in the Z case. This would make Y die earlier.
2214bool AddressingModeMatcher::
2215IsProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
2216 ExtAddrMode &AMAfter) {
2217 if (IgnoreProfitability) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002218
Chandler Carruthc8925912013-01-05 02:09:22 +00002219 // AMBefore is the addressing mode before this instruction was folded into it,
2220 // and AMAfter is the addressing mode after the instruction was folded. Get
2221 // the set of registers referenced by AMAfter and subtract out those
2222 // referenced by AMBefore: this is the set of values which folding in this
2223 // address extends the lifetime of.
2224 //
2225 // Note that there are only two potential values being referenced here,
2226 // BaseReg and ScaleReg (global addresses are always available, as are any
2227 // folded immediates).
2228 Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
Stephen Lin837bba12013-07-15 17:55:02 +00002229
Chandler Carruthc8925912013-01-05 02:09:22 +00002230 // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
2231 // lifetime wasn't extended by adding this instruction.
2232 if (ValueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
2233 BaseReg = 0;
2234 if (ValueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
2235 ScaledReg = 0;
2236
2237 // If folding this instruction (and it's subexprs) didn't extend any live
2238 // ranges, we're ok with it.
2239 if (BaseReg == 0 && ScaledReg == 0)
2240 return true;
2241
2242 // If all uses of this instruction are ultimately load/store/inlineasm's,
2243 // check to see if their addressing modes will include this instruction. If
2244 // so, we can fold it into all uses, so it doesn't matter if it has multiple
2245 // uses.
2246 SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
2247 SmallPtrSet<Instruction*, 16> ConsideredInsts;
2248 if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TLI))
2249 return false; // Has a non-memory, non-foldable use!
Stephen Lin837bba12013-07-15 17:55:02 +00002250
Chandler Carruthc8925912013-01-05 02:09:22 +00002251 // Now that we know that all uses of this instruction are part of a chain of
2252 // computation involving only operations that could theoretically be folded
2253 // into a memory use, loop over each of these uses and see if they could
2254 // *actually* fold the instruction.
2255 SmallVector<Instruction*, 32> MatchedAddrModeInsts;
2256 for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
2257 Instruction *User = MemoryUses[i].first;
2258 unsigned OpNo = MemoryUses[i].second;
Stephen Lin837bba12013-07-15 17:55:02 +00002259
Chandler Carruthc8925912013-01-05 02:09:22 +00002260 // Get the access type of this use. If the use isn't a pointer, we don't
2261 // know what it accesses.
2262 Value *Address = User->getOperand(OpNo);
2263 if (!Address->getType()->isPointerTy())
2264 return false;
Matt Arsenault8227b9f2013-09-06 00:37:24 +00002265 Type *AddressAccessTy = Address->getType()->getPointerElementType();
Stephen Lin837bba12013-07-15 17:55:02 +00002266
Chandler Carruthc8925912013-01-05 02:09:22 +00002267 // Do a match against the root of this address, ignoring profitability. This
2268 // will tell us if the addressing mode for the memory operation will
2269 // *actually* cover the shared instruction.
2270 ExtAddrMode Result;
Quentin Colombet5a69dda2014-02-11 01:59:02 +00002271 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2272 TPT.getRestorationPoint();
Chandler Carruthc8925912013-01-05 02:09:22 +00002273 AddressingModeMatcher Matcher(MatchedAddrModeInsts, TLI, AddressAccessTy,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002274 MemoryInst, Result, InsertedTruncs,
2275 PromotedInsts, TPT);
Chandler Carruthc8925912013-01-05 02:09:22 +00002276 Matcher.IgnoreProfitability = true;
2277 bool Success = Matcher.MatchAddr(Address, 0);
2278 (void)Success; assert(Success && "Couldn't select *anything*?");
2279
Quentin Colombet5a69dda2014-02-11 01:59:02 +00002280 // The match was to check the profitability, the changes made are not
2281 // part of the original matcher. Therefore, they should be dropped
2282 // otherwise the original matcher will not present the right state.
2283 TPT.rollback(LastKnownGood);
2284
Chandler Carruthc8925912013-01-05 02:09:22 +00002285 // If the match didn't cover I, then it won't be shared by it.
2286 if (std::find(MatchedAddrModeInsts.begin(), MatchedAddrModeInsts.end(),
2287 I) == MatchedAddrModeInsts.end())
2288 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00002289
Chandler Carruthc8925912013-01-05 02:09:22 +00002290 MatchedAddrModeInsts.clear();
2291 }
Stephen Lin837bba12013-07-15 17:55:02 +00002292
Chandler Carruthc8925912013-01-05 02:09:22 +00002293 return true;
2294}
2295
2296} // end anonymous namespace
2297
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002298/// IsNonLocalValue - Return true if the specified values are defined in a
2299/// different basic block than BB.
2300static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
2301 if (Instruction *I = dyn_cast<Instruction>(V))
2302 return I->getParent() != BB;
2303 return false;
2304}
2305
Bob Wilson53bdae32009-12-03 21:47:07 +00002306/// OptimizeMemoryInst - Load and Store Instructions often have
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002307/// addressing modes that can do significant amounts of computation. As such,
2308/// instruction selection will try to get the load or store to do as much
2309/// computation as possible for the program. The problem is that isel can only
2310/// see within a single block. As such, we sink as much legal addressing mode
2311/// stuff into the block as possible.
Chris Lattner728f9022008-11-25 07:09:13 +00002312///
2313/// This method is used to optimize both load/store and inline asms with memory
2314/// operands.
Chris Lattner6d71b7f2008-11-26 03:20:37 +00002315bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
Chris Lattner229907c2011-07-18 04:54:35 +00002316 Type *AccessTy) {
Owen Anderson8ba5f392010-11-27 08:15:55 +00002317 Value *Repl = Addr;
Nadav Rotem465834c2012-07-24 10:51:42 +00002318
2319 // Try to collapse single-value PHI nodes. This is necessary to undo
Owen Andersondfb8c3b2010-11-19 22:15:03 +00002320 // unprofitable PRE transformations.
Cameron Zwarich43cecb12011-01-03 06:33:01 +00002321 SmallVector<Value*, 8> worklist;
2322 SmallPtrSet<Value*, 16> Visited;
Owen Anderson8ba5f392010-11-27 08:15:55 +00002323 worklist.push_back(Addr);
Nadav Rotem465834c2012-07-24 10:51:42 +00002324
Owen Anderson8ba5f392010-11-27 08:15:55 +00002325 // Use a worklist to iteratively look through PHI nodes, and ensure that
2326 // the addressing mode obtained from the non-PHI roots of the graph
2327 // are equivalent.
2328 Value *Consensus = 0;
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00002329 unsigned NumUsesConsensus = 0;
Cameron Zwarich13c885d2011-03-05 08:12:26 +00002330 bool IsNumUsesConsensusValid = false;
Owen Anderson8ba5f392010-11-27 08:15:55 +00002331 SmallVector<Instruction*, 16> AddrModeInsts;
2332 ExtAddrMode AddrMode;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002333 TypePromotionTransaction TPT;
2334 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2335 TPT.getRestorationPoint();
Owen Anderson8ba5f392010-11-27 08:15:55 +00002336 while (!worklist.empty()) {
2337 Value *V = worklist.back();
2338 worklist.pop_back();
Nadav Rotem465834c2012-07-24 10:51:42 +00002339
Owen Anderson8ba5f392010-11-27 08:15:55 +00002340 // Break use-def graph loops.
Nick Lewyckya3e7ffd2011-09-29 23:40:12 +00002341 if (!Visited.insert(V)) {
Owen Anderson8ba5f392010-11-27 08:15:55 +00002342 Consensus = 0;
2343 break;
Owen Andersondfb8c3b2010-11-19 22:15:03 +00002344 }
Nadav Rotem465834c2012-07-24 10:51:42 +00002345
Owen Anderson8ba5f392010-11-27 08:15:55 +00002346 // For a PHI node, push all of its incoming values.
2347 if (PHINode *P = dyn_cast<PHINode>(V)) {
2348 for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i)
2349 worklist.push_back(P->getIncomingValue(i));
2350 continue;
2351 }
Nadav Rotem465834c2012-07-24 10:51:42 +00002352
Owen Anderson8ba5f392010-11-27 08:15:55 +00002353 // For non-PHIs, determine the addressing mode being computed.
2354 SmallVector<Instruction*, 16> NewAddrModeInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002355 ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
2356 V, AccessTy, MemoryInst, NewAddrModeInsts, *TLI, InsertedTruncsSet,
2357 PromotedInsts, TPT);
Cameron Zwarich13c885d2011-03-05 08:12:26 +00002358
2359 // This check is broken into two cases with very similar code to avoid using
2360 // getNumUses() as much as possible. Some values have a lot of uses, so
2361 // calling getNumUses() unconditionally caused a significant compile-time
2362 // regression.
2363 if (!Consensus) {
2364 Consensus = V;
2365 AddrMode = NewAddrMode;
2366 AddrModeInsts = NewAddrModeInsts;
2367 continue;
2368 } else if (NewAddrMode == AddrMode) {
2369 if (!IsNumUsesConsensusValid) {
2370 NumUsesConsensus = Consensus->getNumUses();
2371 IsNumUsesConsensusValid = true;
2372 }
2373
2374 // Ensure that the obtained addressing mode is equivalent to that obtained
2375 // for all other roots of the PHI traversal. Also, when choosing one
2376 // such root as representative, select the one with the most uses in order
2377 // to keep the cost modeling heuristics in AddressingModeMatcher
2378 // applicable.
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00002379 unsigned NumUses = V->getNumUses();
2380 if (NumUses > NumUsesConsensus) {
Owen Anderson8ba5f392010-11-27 08:15:55 +00002381 Consensus = V;
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00002382 NumUsesConsensus = NumUses;
Owen Anderson8ba5f392010-11-27 08:15:55 +00002383 AddrModeInsts = NewAddrModeInsts;
2384 }
2385 continue;
2386 }
Nadav Rotem465834c2012-07-24 10:51:42 +00002387
Owen Anderson8ba5f392010-11-27 08:15:55 +00002388 Consensus = 0;
2389 break;
Owen Andersondfb8c3b2010-11-19 22:15:03 +00002390 }
Nadav Rotem465834c2012-07-24 10:51:42 +00002391
Owen Anderson8ba5f392010-11-27 08:15:55 +00002392 // If the addressing mode couldn't be determined, or if multiple different
2393 // ones were determined, bail out now.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002394 if (!Consensus) {
2395 TPT.rollback(LastKnownGood);
2396 return false;
2397 }
2398 TPT.commit();
Nadav Rotem465834c2012-07-24 10:51:42 +00002399
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002400 // Check to see if any of the instructions supersumed by this addr mode are
2401 // non-local to I's BB.
2402 bool AnyNonLocal = false;
2403 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
Chris Lattner6d71b7f2008-11-26 03:20:37 +00002404 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002405 AnyNonLocal = true;
2406 break;
2407 }
2408 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00002409
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002410 // If all the instructions matched are already in this BB, don't do anything.
2411 if (!AnyNonLocal) {
David Greene74e2d492010-01-05 01:27:11 +00002412 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002413 return false;
2414 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00002415
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002416 // Insert this computation right after this user. Since our caller is
2417 // scanning from the top of the BB to the bottom, reuse of the expr are
2418 // guaranteed to happen later.
Devang Patelc10e52a2011-09-06 18:49:53 +00002419 IRBuilder<> Builder(MemoryInst);
Eric Christopherc1ea1492008-09-24 05:32:41 +00002420
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002421 // Now that we determined the addressing expression we want to use and know
2422 // that we have to sink it into this block. Check to see if we have already
2423 // done this for some other load/store instr in this block. If so, reuse the
2424 // computation.
2425 Value *&SunkAddr = SunkAddrs[Addr];
2426 if (SunkAddr) {
David Greene74e2d492010-01-05 01:27:11 +00002427 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
Dan Gohman29f2baf2009-07-25 01:13:51 +00002428 << *MemoryInst);
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002429 if (SunkAddr->getType() != Addr->getType())
Benjamin Kramer547b6c52011-09-27 20:39:19 +00002430 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
Hal Finkelc3998302014-04-12 00:59:48 +00002431 } else if (AddrSinkUsingGEPs || (!AddrSinkUsingGEPs.getNumOccurrences() &&
2432 TM && TM->getSubtarget<TargetSubtargetInfo>().useAA())) {
2433 // By default, we use the GEP-based method when AA is used later. This
2434 // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities.
2435 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
2436 << *MemoryInst);
2437 Type *IntPtrTy = TLI->getDataLayout()->getIntPtrType(Addr->getType());
2438 Value *ResultPtr = 0, *ResultIndex = 0;
2439
2440 // First, find the pointer.
2441 if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) {
2442 ResultPtr = AddrMode.BaseReg;
2443 AddrMode.BaseReg = 0;
2444 }
2445
2446 if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) {
2447 // We can't add more than one pointer together, nor can we scale a
2448 // pointer (both of which seem meaningless).
2449 if (ResultPtr || AddrMode.Scale != 1)
2450 return false;
2451
2452 ResultPtr = AddrMode.ScaledReg;
2453 AddrMode.Scale = 0;
2454 }
2455
2456 if (AddrMode.BaseGV) {
2457 if (ResultPtr)
2458 return false;
2459
2460 ResultPtr = AddrMode.BaseGV;
2461 }
2462
2463 // If the real base value actually came from an inttoptr, then the matcher
2464 // will look through it and provide only the integer value. In that case,
2465 // use it here.
2466 if (!ResultPtr && AddrMode.BaseReg) {
2467 ResultPtr =
2468 Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(), "sunkaddr");
2469 AddrMode.BaseReg = 0;
2470 } else if (!ResultPtr && AddrMode.Scale == 1) {
2471 ResultPtr =
2472 Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(), "sunkaddr");
2473 AddrMode.Scale = 0;
2474 }
2475
2476 if (!ResultPtr &&
2477 !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) {
2478 SunkAddr = Constant::getNullValue(Addr->getType());
2479 } else if (!ResultPtr) {
2480 return false;
2481 } else {
2482 Type *I8PtrTy =
2483 Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace());
2484
2485 // Start with the base register. Do this first so that subsequent address
2486 // matching finds it last, which will prevent it from trying to match it
2487 // as the scaled value in case it happens to be a mul. That would be
2488 // problematic if we've sunk a different mul for the scale, because then
2489 // we'd end up sinking both muls.
2490 if (AddrMode.BaseReg) {
2491 Value *V = AddrMode.BaseReg;
2492 if (V->getType() != IntPtrTy)
2493 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
2494
2495 ResultIndex = V;
2496 }
2497
2498 // Add the scale value.
2499 if (AddrMode.Scale) {
2500 Value *V = AddrMode.ScaledReg;
2501 if (V->getType() == IntPtrTy) {
2502 // done.
2503 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
2504 cast<IntegerType>(V->getType())->getBitWidth()) {
2505 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
2506 } else {
2507 // It is only safe to sign extend the BaseReg if we know that the math
2508 // required to create it did not overflow before we extend it. Since
2509 // the original IR value was tossed in favor of a constant back when
2510 // the AddrMode was created we need to bail out gracefully if widths
2511 // do not match instead of extending it.
2512 Instruction *I = dyn_cast_or_null<Instruction>(ResultIndex);
2513 if (I && (ResultIndex != AddrMode.BaseReg))
2514 I->eraseFromParent();
2515 return false;
2516 }
2517
2518 if (AddrMode.Scale != 1)
2519 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
2520 "sunkaddr");
2521 if (ResultIndex)
2522 ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr");
2523 else
2524 ResultIndex = V;
2525 }
2526
2527 // Add in the Base Offset if present.
2528 if (AddrMode.BaseOffs) {
2529 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
2530 if (ResultIndex) {
2531 // We need to add this separately from the scale above to help with
2532 // SDAG consecutive load/store merging.
2533 if (ResultPtr->getType() != I8PtrTy)
2534 ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
2535 ResultPtr = Builder.CreateGEP(ResultPtr, ResultIndex, "sunkaddr");
2536 }
2537
2538 ResultIndex = V;
2539 }
2540
2541 if (!ResultIndex) {
2542 SunkAddr = ResultPtr;
2543 } else {
2544 if (ResultPtr->getType() != I8PtrTy)
2545 ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
2546 SunkAddr = Builder.CreateGEP(ResultPtr, ResultIndex, "sunkaddr");
2547 }
2548
2549 if (SunkAddr->getType() != Addr->getType())
2550 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
2551 }
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002552 } else {
David Greene74e2d492010-01-05 01:27:11 +00002553 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Dan Gohman29f2baf2009-07-25 01:13:51 +00002554 << *MemoryInst);
Matt Arsenault37d42ec2013-09-06 00:18:43 +00002555 Type *IntPtrTy = TLI->getDataLayout()->getIntPtrType(Addr->getType());
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002556 Value *Result = 0;
Dan Gohmanca194452010-01-19 22:45:06 +00002557
2558 // Start with the base register. Do this first so that subsequent address
2559 // matching finds it last, which will prevent it from trying to match it
2560 // as the scaled value in case it happens to be a mul. That would be
2561 // problematic if we've sunk a different mul for the scale, because then
2562 // we'd end up sinking both muls.
2563 if (AddrMode.BaseReg) {
2564 Value *V = AddrMode.BaseReg;
Duncan Sands19d0b472010-02-16 11:11:14 +00002565 if (V->getType()->isPointerTy())
Devang Patelc10e52a2011-09-06 18:49:53 +00002566 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00002567 if (V->getType() != IntPtrTy)
Devang Patelc10e52a2011-09-06 18:49:53 +00002568 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00002569 Result = V;
2570 }
2571
2572 // Add the scale value.
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002573 if (AddrMode.Scale) {
2574 Value *V = AddrMode.ScaledReg;
2575 if (V->getType() == IntPtrTy) {
2576 // done.
Duncan Sands19d0b472010-02-16 11:11:14 +00002577 } else if (V->getType()->isPointerTy()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00002578 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002579 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
2580 cast<IntegerType>(V->getType())->getBitWidth()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00002581 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002582 } else {
Jim Grosbached2cd392014-03-26 17:27:01 +00002583 // It is only safe to sign extend the BaseReg if we know that the math
2584 // required to create it did not overflow before we extend it. Since
2585 // the original IR value was tossed in favor of a constant back when
2586 // the AddrMode was created we need to bail out gracefully if widths
2587 // do not match instead of extending it.
Jim Grosbach83b44e12014-04-10 00:27:45 +00002588 Instruction *I = dyn_cast<Instruction>(Result);
2589 if (I && (Result != AddrMode.BaseReg))
2590 I->eraseFromParent();
Jim Grosbached2cd392014-03-26 17:27:01 +00002591 return false;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002592 }
2593 if (AddrMode.Scale != 1)
Devang Patelc10e52a2011-09-06 18:49:53 +00002594 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
2595 "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002596 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00002597 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002598 else
2599 Result = V;
2600 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00002601
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002602 // Add in the BaseGV if present.
2603 if (AddrMode.BaseGV) {
Devang Patelc10e52a2011-09-06 18:49:53 +00002604 Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002605 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00002606 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002607 else
2608 Result = V;
2609 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00002610
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002611 // Add in the Base Offset if present.
2612 if (AddrMode.BaseOffs) {
Owen Andersonedb4a702009-07-24 23:12:02 +00002613 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002614 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00002615 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002616 else
2617 Result = V;
2618 }
2619
2620 if (Result == 0)
Owen Anderson5a1acd92009-07-31 20:28:14 +00002621 SunkAddr = Constant::getNullValue(Addr->getType());
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002622 else
Devang Patelc10e52a2011-09-06 18:49:53 +00002623 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002624 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00002625
Owen Andersondfb8c3b2010-11-19 22:15:03 +00002626 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
Eric Christopherc1ea1492008-09-24 05:32:41 +00002627
Chris Lattneraf1bcce2011-04-09 07:05:44 +00002628 // If we have no uses, recursively delete the value and all dead instructions
2629 // using it.
Owen Andersondfb8c3b2010-11-19 22:15:03 +00002630 if (Repl->use_empty()) {
Chris Lattneraf1bcce2011-04-09 07:05:44 +00002631 // This can cause recursive deletion, which can invalidate our iterator.
2632 // Use a WeakVH to hold onto it in case this happens.
2633 WeakVH IterHandle(CurInstIterator);
2634 BasicBlock *BB = CurInstIterator->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +00002635
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00002636 RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
Chris Lattneraf1bcce2011-04-09 07:05:44 +00002637
2638 if (IterHandle != CurInstIterator) {
2639 // If the iterator instruction was recursively deleted, start over at the
2640 // start of the block.
2641 CurInstIterator = BB->begin();
2642 SunkAddrs.clear();
Nadav Rotem465834c2012-07-24 10:51:42 +00002643 }
Dale Johannesenb67a6e662010-03-31 20:37:15 +00002644 }
Cameron Zwarichced753f2011-01-05 17:27:27 +00002645 ++NumMemoryInsts;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002646 return true;
2647}
2648
Evan Cheng1da25002008-02-26 02:42:37 +00002649/// OptimizeInlineAsmInst - If there are any memory operands, use
Chris Lattner728f9022008-11-25 07:09:13 +00002650/// OptimizeMemoryInst to sink their address computing into the block when
Evan Cheng1da25002008-02-26 02:42:37 +00002651/// possible / profitable.
Chris Lattner7a277142011-01-15 07:14:54 +00002652bool CodeGenPrepare::OptimizeInlineAsmInst(CallInst *CS) {
Evan Cheng1da25002008-02-26 02:42:37 +00002653 bool MadeChange = false;
Evan Cheng1da25002008-02-26 02:42:37 +00002654
Nadav Rotem465834c2012-07-24 10:51:42 +00002655 TargetLowering::AsmOperandInfoVector
Chris Lattner7a277142011-01-15 07:14:54 +00002656 TargetConstraints = TLI->ParseConstraints(CS);
Dale Johannesenf95f59a2010-09-16 18:30:55 +00002657 unsigned ArgNo = 0;
John Thompson1094c802010-09-13 18:15:37 +00002658 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
2659 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Nadav Rotem465834c2012-07-24 10:51:42 +00002660
Evan Cheng1da25002008-02-26 02:42:37 +00002661 // Compute the constraint code and ConstraintType to use.
Dale Johannesence97d552010-06-25 21:55:36 +00002662 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Evan Cheng1da25002008-02-26 02:42:37 +00002663
Eli Friedman666bbe32008-02-26 18:37:49 +00002664 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
2665 OpInfo.isIndirect) {
Chris Lattner7a277142011-01-15 07:14:54 +00002666 Value *OpVal = CS->getArgOperand(ArgNo++);
Chris Lattneree588de2011-01-15 07:29:01 +00002667 MadeChange |= OptimizeMemoryInst(CS, OpVal, OpVal->getType());
Dale Johannesenf95f59a2010-09-16 18:30:55 +00002668 } else if (OpInfo.Type == InlineAsm::isInput)
2669 ArgNo++;
Evan Cheng1da25002008-02-26 02:42:37 +00002670 }
2671
2672 return MadeChange;
2673}
2674
Dan Gohman99429a02009-10-16 20:59:35 +00002675/// MoveExtToFormExtLoad - Move a zext or sext fed by a load into the same
2676/// basic block as the load, unless conditions are unfavorable. This allows
2677/// SelectionDAG to fold the extend into the load.
2678///
2679bool CodeGenPrepare::MoveExtToFormExtLoad(Instruction *I) {
2680 // Look for a load being extended.
2681 LoadInst *LI = dyn_cast<LoadInst>(I->getOperand(0));
2682 if (!LI) return false;
2683
2684 // If they're already in the same block, there's nothing to do.
2685 if (LI->getParent() == I->getParent())
2686 return false;
2687
2688 // If the load has other users and the truncate is not free, this probably
2689 // isn't worthwhile.
2690 if (!LI->hasOneUse() &&
Bob Wilsonb6832a42010-09-22 18:44:56 +00002691 TLI && (TLI->isTypeLegal(TLI->getValueType(LI->getType())) ||
2692 !TLI->isTypeLegal(TLI->getValueType(I->getType()))) &&
Bob Wilson4ddcb6a2010-09-21 21:54:27 +00002693 !TLI->isTruncateFree(I->getType(), LI->getType()))
Dan Gohman99429a02009-10-16 20:59:35 +00002694 return false;
2695
2696 // Check whether the target supports casts folded into loads.
2697 unsigned LType;
2698 if (isa<ZExtInst>(I))
2699 LType = ISD::ZEXTLOAD;
2700 else {
2701 assert(isa<SExtInst>(I) && "Unexpected ext type!");
2702 LType = ISD::SEXTLOAD;
2703 }
Patrik Hagglunde98b7a02012-12-11 11:14:33 +00002704 if (TLI && !TLI->isLoadExtLegal(LType, TLI->getValueType(LI->getType())))
Dan Gohman99429a02009-10-16 20:59:35 +00002705 return false;
2706
2707 // Move the extend into the same block as the load, so that SelectionDAG
2708 // can fold it.
2709 I->removeFromParent();
2710 I->insertAfter(LI);
Cameron Zwarichced753f2011-01-05 17:27:27 +00002711 ++NumExtsMoved;
Dan Gohman99429a02009-10-16 20:59:35 +00002712 return true;
2713}
2714
Evan Chengd3d80172007-12-05 23:58:20 +00002715bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
2716 BasicBlock *DefBB = I->getParent();
2717
Bob Wilsonff714f92010-09-21 21:44:14 +00002718 // If the result of a {s|z}ext and its source are both live out, rewrite all
Evan Chengd3d80172007-12-05 23:58:20 +00002719 // other uses of the source with result of extension.
2720 Value *Src = I->getOperand(0);
2721 if (Src->hasOneUse())
2722 return false;
2723
Evan Cheng2011df42007-12-13 07:50:36 +00002724 // Only do this xform if truncating is free.
Gabor Greifaa261722008-02-26 19:13:21 +00002725 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
Evan Cheng37c36ed2007-12-13 03:32:53 +00002726 return false;
2727
Evan Cheng7bc89422007-12-12 00:51:06 +00002728 // Only safe to perform the optimization if the source is also defined in
Evan Cheng63d33cf2007-12-12 02:53:41 +00002729 // this block.
2730 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
Evan Cheng7bc89422007-12-12 00:51:06 +00002731 return false;
2732
Evan Chengd3d80172007-12-05 23:58:20 +00002733 bool DefIsLiveOut = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00002734 for (User *U : I->users()) {
2735 Instruction *UI = cast<Instruction>(U);
Evan Chengd3d80172007-12-05 23:58:20 +00002736
2737 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002738 BasicBlock *UserBB = UI->getParent();
Evan Chengd3d80172007-12-05 23:58:20 +00002739 if (UserBB == DefBB) continue;
2740 DefIsLiveOut = true;
2741 break;
2742 }
2743 if (!DefIsLiveOut)
2744 return false;
2745
Jim Grosbach0f38c1e2013-04-15 17:40:48 +00002746 // Make sure none of the uses are PHI nodes.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002747 for (User *U : Src->users()) {
2748 Instruction *UI = cast<Instruction>(U);
2749 BasicBlock *UserBB = UI->getParent();
Evan Cheng37c36ed2007-12-13 03:32:53 +00002750 if (UserBB == DefBB) continue;
2751 // Be conservative. We don't want this xform to end up introducing
2752 // reloads just before load / store instructions.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002753 if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI))
Evan Cheng63d33cf2007-12-12 02:53:41 +00002754 return false;
2755 }
2756
Evan Chengd3d80172007-12-05 23:58:20 +00002757 // InsertedTruncs - Only insert one trunc in each block once.
2758 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
2759
2760 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00002761 for (Use &U : Src->uses()) {
2762 Instruction *User = cast<Instruction>(U.getUser());
Evan Chengd3d80172007-12-05 23:58:20 +00002763
2764 // Figure out which BB this ext is used in.
2765 BasicBlock *UserBB = User->getParent();
2766 if (UserBB == DefBB) continue;
2767
2768 // Both src and def are live in this block. Rewrite the use.
2769 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
2770
2771 if (!InsertedTrunc) {
Bill Wendling8ddfc092011-08-16 20:45:24 +00002772 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Evan Chengd3d80172007-12-05 23:58:20 +00002773 InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002774 InsertedTruncsSet.insert(InsertedTrunc);
Evan Chengd3d80172007-12-05 23:58:20 +00002775 }
2776
2777 // Replace a use of the {s|z}ext source with a use of the result.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002778 U = InsertedTrunc;
Cameron Zwarichced753f2011-01-05 17:27:27 +00002779 ++NumExtUses;
Evan Chengd3d80172007-12-05 23:58:20 +00002780 MadeChange = true;
2781 }
2782
2783 return MadeChange;
2784}
2785
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00002786/// isFormingBranchFromSelectProfitable - Returns true if a SelectInst should be
2787/// turned into an explicit branch.
2788static bool isFormingBranchFromSelectProfitable(SelectInst *SI) {
2789 // FIXME: This should use the same heuristics as IfConversion to determine
2790 // whether a select is better represented as a branch. This requires that
2791 // branch probability metadata is preserved for the select, which is not the
2792 // case currently.
2793
2794 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
2795
2796 // If the branch is predicted right, an out of order CPU can avoid blocking on
2797 // the compare. Emit cmovs on compares with a memory operand as branches to
2798 // avoid stalls on the load from memory. If the compare has more than one use
2799 // there's probably another cmov or setcc around so it's not worth emitting a
2800 // branch.
2801 if (!Cmp)
2802 return false;
2803
2804 Value *CmpOp0 = Cmp->getOperand(0);
2805 Value *CmpOp1 = Cmp->getOperand(1);
2806
2807 // We check that the memory operand has one use to avoid uses of the loaded
2808 // value directly after the compare, making branches unprofitable.
2809 return Cmp->hasOneUse() &&
2810 ((isa<LoadInst>(CmpOp0) && CmpOp0->hasOneUse()) ||
2811 (isa<LoadInst>(CmpOp1) && CmpOp1->hasOneUse()));
2812}
2813
2814
Nadav Rotem9d832022012-09-02 12:10:19 +00002815/// If we have a SelectInst that will likely profit from branch prediction,
2816/// turn it into a branch.
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00002817bool CodeGenPrepare::OptimizeSelectInst(SelectInst *SI) {
Nadav Rotem9d832022012-09-02 12:10:19 +00002818 bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
2819
2820 // Can we convert the 'select' to CF ?
2821 if (DisableSelectToBranch || OptSize || !TLI || VectorCond)
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00002822 return false;
2823
Nadav Rotem9d832022012-09-02 12:10:19 +00002824 TargetLowering::SelectSupportKind SelectKind;
2825 if (VectorCond)
2826 SelectKind = TargetLowering::VectorMaskSelect;
2827 else if (SI->getType()->isVectorTy())
2828 SelectKind = TargetLowering::ScalarCondVectorVal;
2829 else
2830 SelectKind = TargetLowering::ScalarValSelect;
2831
2832 // Do we have efficient codegen support for this kind of 'selects' ?
2833 if (TLI->isSelectSupported(SelectKind)) {
2834 // We have efficient codegen support for the select instruction.
2835 // Check if it is profitable to keep this 'select'.
2836 if (!TLI->isPredictableSelectExpensive() ||
2837 !isFormingBranchFromSelectProfitable(SI))
2838 return false;
2839 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00002840
2841 ModifiedDT = true;
2842
2843 // First, we split the block containing the select into 2 blocks.
2844 BasicBlock *StartBlock = SI->getParent();
2845 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(SI));
2846 BasicBlock *NextBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
2847
2848 // Create a new block serving as the landing pad for the branch.
2849 BasicBlock *SmallBlock = BasicBlock::Create(SI->getContext(), "select.mid",
2850 NextBlock->getParent(), NextBlock);
2851
2852 // Move the unconditional branch from the block with the select in it into our
2853 // landing pad block.
2854 StartBlock->getTerminator()->eraseFromParent();
2855 BranchInst::Create(NextBlock, SmallBlock);
2856
2857 // Insert the real conditional branch based on the original condition.
2858 BranchInst::Create(NextBlock, SmallBlock, SI->getCondition(), SI);
2859
2860 // The select itself is replaced with a PHI Node.
2861 PHINode *PN = PHINode::Create(SI->getType(), 2, "", NextBlock->begin());
2862 PN->takeName(SI);
2863 PN->addIncoming(SI->getTrueValue(), StartBlock);
2864 PN->addIncoming(SI->getFalseValue(), SmallBlock);
2865 SI->replaceAllUsesWith(PN);
2866 SI->eraseFromParent();
2867
2868 // Instruct OptimizeBlock to skip to the next block.
2869 CurInstIterator = StartBlock->end();
2870 ++NumSelectsExpanded;
2871 return true;
2872}
2873
Benjamin Kramer573ff362014-03-01 17:24:40 +00002874static bool isBroadcastShuffle(ShuffleVectorInst *SVI) {
Tim Northoveraeb8e062014-02-19 10:02:43 +00002875 SmallVector<int, 16> Mask(SVI->getShuffleMask());
2876 int SplatElem = -1;
2877 for (unsigned i = 0; i < Mask.size(); ++i) {
2878 if (SplatElem != -1 && Mask[i] != -1 && Mask[i] != SplatElem)
2879 return false;
2880 SplatElem = Mask[i];
2881 }
2882
2883 return true;
2884}
2885
2886/// Some targets have expensive vector shifts if the lanes aren't all the same
2887/// (e.g. x86 only introduced "vpsllvd" and friends with AVX2). In these cases
2888/// it's often worth sinking a shufflevector splat down to its use so that
2889/// codegen can spot all lanes are identical.
2890bool CodeGenPrepare::OptimizeShuffleVectorInst(ShuffleVectorInst *SVI) {
2891 BasicBlock *DefBB = SVI->getParent();
2892
2893 // Only do this xform if variable vector shifts are particularly expensive.
2894 if (!TLI || !TLI->isVectorShiftByScalarCheap(SVI->getType()))
2895 return false;
2896
2897 // We only expect better codegen by sinking a shuffle if we can recognise a
2898 // constant splat.
2899 if (!isBroadcastShuffle(SVI))
2900 return false;
2901
2902 // InsertedShuffles - Only insert a shuffle in each block once.
2903 DenseMap<BasicBlock*, Instruction*> InsertedShuffles;
2904
2905 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00002906 for (User *U : SVI->users()) {
2907 Instruction *UI = cast<Instruction>(U);
Tim Northoveraeb8e062014-02-19 10:02:43 +00002908
2909 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002910 BasicBlock *UserBB = UI->getParent();
Tim Northoveraeb8e062014-02-19 10:02:43 +00002911 if (UserBB == DefBB) continue;
2912
2913 // For now only apply this when the splat is used by a shift instruction.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002914 if (!UI->isShift()) continue;
Tim Northoveraeb8e062014-02-19 10:02:43 +00002915
2916 // Everything checks out, sink the shuffle if the user's block doesn't
2917 // already have a copy.
2918 Instruction *&InsertedShuffle = InsertedShuffles[UserBB];
2919
2920 if (!InsertedShuffle) {
2921 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
2922 InsertedShuffle = new ShuffleVectorInst(SVI->getOperand(0),
2923 SVI->getOperand(1),
2924 SVI->getOperand(2), "", InsertPt);
2925 }
2926
Chandler Carruthcdf47882014-03-09 03:16:01 +00002927 UI->replaceUsesOfWith(SVI, InsertedShuffle);
Tim Northoveraeb8e062014-02-19 10:02:43 +00002928 MadeChange = true;
2929 }
2930
2931 // If we removed all uses, nuke the shuffle.
2932 if (SVI->use_empty()) {
2933 SVI->eraseFromParent();
2934 MadeChange = true;
2935 }
2936
2937 return MadeChange;
2938}
2939
Cameron Zwarich14ac8652011-01-06 02:37:26 +00002940bool CodeGenPrepare::OptimizeInst(Instruction *I) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00002941 if (PHINode *P = dyn_cast<PHINode>(I)) {
2942 // It is possible for very late stage optimizations (such as SimplifyCFG)
2943 // to introduce PHI nodes too late to be cleaned up. If we detect such a
2944 // trivial PHI, go ahead and zap it here.
Benjamin Kramer30d249a2013-09-24 16:37:40 +00002945 if (Value *V = SimplifyInstruction(P, TLI ? TLI->getDataLayout() : 0,
2946 TLInfo, DT)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00002947 P->replaceAllUsesWith(V);
2948 P->eraseFromParent();
2949 ++NumPHIsElim;
Chris Lattneree588de2011-01-15 07:29:01 +00002950 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00002951 }
Chris Lattneree588de2011-01-15 07:29:01 +00002952 return false;
2953 }
Nadav Rotem465834c2012-07-24 10:51:42 +00002954
Chris Lattneree588de2011-01-15 07:29:01 +00002955 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00002956 // If the source of the cast is a constant, then this should have
2957 // already been constant folded. The only reason NOT to constant fold
2958 // it is if something (e.g. LSR) was careful to place the constant
2959 // evaluation in a block other than then one that uses it (e.g. to hoist
2960 // the address of globals out of a loop). If this is the case, we don't
2961 // want to forward-subst the cast.
2962 if (isa<Constant>(CI->getOperand(0)))
2963 return false;
2964
Chris Lattneree588de2011-01-15 07:29:01 +00002965 if (TLI && OptimizeNoopCopyExpression(CI, *TLI))
2966 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00002967
Chris Lattneree588de2011-01-15 07:29:01 +00002968 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +00002969 /// Sink a zext or sext into its user blocks if the target type doesn't
2970 /// fit in one register
2971 if (TLI && TLI->getTypeAction(CI->getContext(),
2972 TLI->getValueType(CI->getType())) ==
2973 TargetLowering::TypeExpandInteger) {
2974 return SinkCast(CI);
2975 } else {
2976 bool MadeChange = MoveExtToFormExtLoad(I);
2977 return MadeChange | OptimizeExtUses(I);
2978 }
Cameron Zwarich14ac8652011-01-06 02:37:26 +00002979 }
Chris Lattneree588de2011-01-15 07:29:01 +00002980 return false;
2981 }
Nadav Rotem465834c2012-07-24 10:51:42 +00002982
Chris Lattneree588de2011-01-15 07:29:01 +00002983 if (CmpInst *CI = dyn_cast<CmpInst>(I))
Hal Finkeldecb0242014-01-02 21:13:43 +00002984 if (!TLI || !TLI->hasMultipleConditionRegisters())
2985 return OptimizeCmpExpression(CI);
Nadav Rotem465834c2012-07-24 10:51:42 +00002986
Chris Lattneree588de2011-01-15 07:29:01 +00002987 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00002988 if (TLI)
Hans Wennborgf3254832012-10-30 11:23:25 +00002989 return OptimizeMemoryInst(I, I->getOperand(0), LI->getType());
2990 return false;
Chris Lattneree588de2011-01-15 07:29:01 +00002991 }
Nadav Rotem465834c2012-07-24 10:51:42 +00002992
Chris Lattneree588de2011-01-15 07:29:01 +00002993 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00002994 if (TLI)
Chris Lattneree588de2011-01-15 07:29:01 +00002995 return OptimizeMemoryInst(I, SI->getOperand(1),
2996 SI->getOperand(0)->getType());
2997 return false;
2998 }
Nadav Rotem465834c2012-07-24 10:51:42 +00002999
Chris Lattneree588de2011-01-15 07:29:01 +00003000 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00003001 if (GEPI->hasAllZeroIndices()) {
3002 /// The GEP operand must be a pointer, so must its result -> BitCast
3003 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
3004 GEPI->getName(), GEPI);
3005 GEPI->replaceAllUsesWith(NC);
3006 GEPI->eraseFromParent();
3007 ++NumGEPsElim;
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00003008 OptimizeInst(NC);
Chris Lattneree588de2011-01-15 07:29:01 +00003009 return true;
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00003010 }
Chris Lattneree588de2011-01-15 07:29:01 +00003011 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00003012 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003013
Chris Lattneree588de2011-01-15 07:29:01 +00003014 if (CallInst *CI = dyn_cast<CallInst>(I))
3015 return OptimizeCallInst(CI);
Cameron Zwarich14ac8652011-01-06 02:37:26 +00003016
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00003017 if (SelectInst *SI = dyn_cast<SelectInst>(I))
3018 return OptimizeSelectInst(SI);
3019
Tim Northoveraeb8e062014-02-19 10:02:43 +00003020 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I))
3021 return OptimizeShuffleVectorInst(SVI);
3022
Chris Lattneree588de2011-01-15 07:29:01 +00003023 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00003024}
3025
Chris Lattnerf2836d12007-03-31 04:06:36 +00003026// In this pass we look for GEP and cast instructions that are used
3027// across basic blocks and rewrite them to improve basic-block-at-a-time
3028// selection.
3029bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
Cameron Zwarichce3b9302011-01-06 00:42:50 +00003030 SunkAddrs.clear();
Cameron Zwarich5dd2aa22011-03-02 03:31:46 +00003031 bool MadeChange = false;
Eric Christopherc1ea1492008-09-24 05:32:41 +00003032
Chris Lattner7a277142011-01-15 07:14:54 +00003033 CurInstIterator = BB.begin();
Hans Wennborg02fbc712012-09-19 07:48:16 +00003034 while (CurInstIterator != BB.end())
Chris Lattner1b93be52011-01-15 07:25:29 +00003035 MadeChange |= OptimizeInst(CurInstIterator++);
Eric Christopherc1ea1492008-09-24 05:32:41 +00003036
Benjamin Kramer455fa352012-11-23 19:17:06 +00003037 MadeChange |= DupRetToEnableTailCallOpts(&BB);
3038
Chris Lattnerf2836d12007-03-31 04:06:36 +00003039 return MadeChange;
3040}
Devang Patel53771ba2011-08-18 00:50:51 +00003041
3042// llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotem465834c2012-07-24 10:51:42 +00003043// handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patel53771ba2011-08-18 00:50:51 +00003044// find a node corresponding to the value.
3045bool CodeGenPrepare::PlaceDbgValues(Function &F) {
3046 bool MadeChange = false;
3047 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
3048 Instruction *PrevNonDbgInst = NULL;
3049 for (BasicBlock::iterator BI = I->begin(), BE = I->end(); BI != BE;) {
3050 Instruction *Insn = BI; ++BI;
3051 DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
3052 if (!DVI) {
3053 PrevNonDbgInst = Insn;
3054 continue;
3055 }
3056
3057 Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
3058 if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
3059 DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
3060 DVI->removeFromParent();
3061 if (isa<PHINode>(VI))
3062 DVI->insertBefore(VI->getParent()->getFirstInsertionPt());
3063 else
3064 DVI->insertAfter(VI);
3065 MadeChange = true;
3066 ++NumDbgValueMoved;
3067 }
3068 }
3069 }
3070 return MadeChange;
3071}
Tim Northovercea0abb2014-03-29 08:22:29 +00003072
3073// If there is a sequence that branches based on comparing a single bit
3074// against zero that can be combined into a single instruction, and the
3075// target supports folding these into a single instruction, sink the
3076// mask and compare into the branch uses. Do this before OptimizeBlock ->
3077// OptimizeInst -> OptimizeCmpExpression, which perturbs the pattern being
3078// searched for.
3079bool CodeGenPrepare::sinkAndCmp(Function &F) {
3080 if (!EnableAndCmpSinking)
3081 return false;
3082 if (!TLI || !TLI->isMaskAndBranchFoldingLegal())
3083 return false;
3084 bool MadeChange = false;
3085 for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
3086 BasicBlock *BB = I++;
3087
3088 // Does this BB end with the following?
3089 // %andVal = and %val, #single-bit-set
3090 // %icmpVal = icmp %andResult, 0
3091 // br i1 %cmpVal label %dest1, label %dest2"
3092 BranchInst *Brcc = dyn_cast<BranchInst>(BB->getTerminator());
3093 if (!Brcc || !Brcc->isConditional())
3094 continue;
3095 ICmpInst *Cmp = dyn_cast<ICmpInst>(Brcc->getOperand(0));
3096 if (!Cmp || Cmp->getParent() != BB)
3097 continue;
3098 ConstantInt *Zero = dyn_cast<ConstantInt>(Cmp->getOperand(1));
3099 if (!Zero || !Zero->isZero())
3100 continue;
3101 Instruction *And = dyn_cast<Instruction>(Cmp->getOperand(0));
3102 if (!And || And->getOpcode() != Instruction::And || And->getParent() != BB)
3103 continue;
3104 ConstantInt* Mask = dyn_cast<ConstantInt>(And->getOperand(1));
3105 if (!Mask || !Mask->getUniqueInteger().isPowerOf2())
3106 continue;
3107 DEBUG(dbgs() << "found and; icmp ?,0; brcc\n"); DEBUG(BB->dump());
3108
3109 // Push the "and; icmp" for any users that are conditional branches.
3110 // Since there can only be one branch use per BB, we don't need to keep
3111 // track of which BBs we insert into.
3112 for (Value::use_iterator UI = Cmp->use_begin(), E = Cmp->use_end();
3113 UI != E; ) {
3114 Use &TheUse = *UI;
3115 // Find brcc use.
3116 BranchInst *BrccUser = dyn_cast<BranchInst>(*UI);
3117 ++UI;
3118 if (!BrccUser || !BrccUser->isConditional())
3119 continue;
3120 BasicBlock *UserBB = BrccUser->getParent();
3121 if (UserBB == BB) continue;
3122 DEBUG(dbgs() << "found Brcc use\n");
3123
3124 // Sink the "and; icmp" to use.
3125 MadeChange = true;
3126 BinaryOperator *NewAnd =
3127 BinaryOperator::CreateAnd(And->getOperand(0), And->getOperand(1), "",
3128 BrccUser);
3129 CmpInst *NewCmp =
3130 CmpInst::Create(Cmp->getOpcode(), Cmp->getPredicate(), NewAnd, Zero,
3131 "", BrccUser);
3132 TheUse = NewCmp;
3133 ++NumAndCmpsMoved;
3134 DEBUG(BrccUser->getParent()->dump());
3135 }
3136 }
3137 return MadeChange;
3138}