blob: 009e153e0e8d0c100d87d48bae97a2318bbff100 [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
Craig Topperc0196b12014-04-14 00:51:57 +0000119 explicit CodeGenPrepare(const TargetMachine *TM = nullptr)
120 : FunctionPass(ID), TM(TM), TLI(nullptr) {
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>();
Craig Topperc0196b12014-04-14 00:51:57 +0000185 DT = DTWP ? &DTWP->getDomTree() : nullptr;
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
Craig Topperc0196b12014-04-14 00:51:57 +0000679 replaceAndRecursivelySimplify(CI, RetVal,
680 TLI ? TLI->getDataLayout() : nullptr,
681 TLInfo, ModifiedDT ? nullptr : DT);
Chris Lattner1b93be52011-01-15 07:25:29 +0000682
683 // If the iterator instruction was recursively deleted, start over at the
684 // start of the block.
Chris Lattner86d56c62011-01-18 20:53:04 +0000685 if (IterHandle != CurInstIterator) {
Chris Lattner1b93be52011-01-15 07:25:29 +0000686 CurInstIterator = BB->begin();
Chris Lattner86d56c62011-01-18 20:53:04 +0000687 SunkAddrs.clear();
688 }
Eric Christopher4b7948e2010-03-11 02:41:03 +0000689 return true;
690 }
Michael Zolotukhinf2ba9942014-04-21 12:01:33 +0000691 // Lower all uses of llvm.safe.[us]{div|rem}...
692 if (II &&
693 (II->getIntrinsicID() == Intrinsic::safe_sdiv ||
694 II->getIntrinsicID() == Intrinsic::safe_udiv ||
695 II->getIntrinsicID() == Intrinsic::safe_srem ||
696 II->getIntrinsicID() == Intrinsic::safe_urem)) {
697 // Given
698 // result_struct = type {iN, i1}
699 // %R = call result_struct llvm.safe.sdiv.iN(iN %x, iN %y)
700 // Expand it to actual IR, which produces result to the same variable %R.
701 // First element of the result %R.1 is the result of division, second
702 // element shows whether the division was correct or not.
703 // If %y is 0, %R.1 is 0, %R.2 is 1. (1)
704 // If %x is minSignedValue and %y is -1, %R.1 is %x, %R.2 is 1. (2)
705 // In other cases %R.1 is (sdiv %x, %y), %R.2 is 0. (3)
706 //
707 // Similar applies to srem, udiv, and urem builtins, except that in unsigned
708 // variants we don't check condition (2).
709
710 bool IsSigned;
711 BinaryOperator::BinaryOps Op;
712 switch (II->getIntrinsicID()) {
713 case Intrinsic::safe_sdiv:
714 IsSigned = true;
715 Op = Instruction::SDiv;
716 break;
717 case Intrinsic::safe_udiv:
718 IsSigned = false;
719 Op = Instruction::UDiv;
720 break;
721 case Intrinsic::safe_srem:
722 IsSigned = true;
723 Op = Instruction::SRem;
724 break;
725 case Intrinsic::safe_urem:
726 IsSigned = false;
727 Op = Instruction::URem;
728 break;
729 default:
730 llvm_unreachable("Only Div/Rem intrinsics are handled here.");
731 }
732
733 Value *LHS = II->getOperand(0), *RHS = II->getOperand(1);
734 bool DivWellDefined = TLI && TLI->isDivWellDefined();
735
736 bool ResultNeeded[2] = {false, false};
737 SmallVector<User*, 1> ResultsUsers[2];
738 bool BadCase = false;
739 for (User *U: II->users()) {
740 ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(U);
741 if (!EVI || EVI->getNumIndices() > 1 || EVI->getIndices()[0] > 1) {
742 BadCase = true;
743 break;
744 }
745 ResultNeeded[EVI->getIndices()[0]] = true;
746 ResultsUsers[EVI->getIndices()[0]].push_back(U);
747 }
748 // Behave conservatively, if there is an unusual user of the results.
749 if (BadCase)
750 ResultNeeded[0] = ResultNeeded[1] = true;
751
752 // Early exit if non of the results is ever used.
753 if (!ResultNeeded[0] && !ResultNeeded[1]) {
754 II->eraseFromParent();
755 return true;
756 }
757
758 // Early exit if the second result (flag) isn't used and target
759 // div-instruction computes exactly what we want to get as the first result
760 // and never traps.
761 if (ResultNeeded[0] && !ResultNeeded[1] && DivWellDefined) {
762 BinaryOperator *Div = BinaryOperator::Create(Op, LHS, RHS);
763 Div->insertAfter(II);
764 for (User *U: ResultsUsers[0]) {
765 Instruction *UserInst = dyn_cast<Instruction>(U);
766 assert(UserInst && "Unexpected null-instruction");
767 UserInst->replaceAllUsesWith(Div);
768 UserInst->eraseFromParent();
769 }
770 II->eraseFromParent();
771 CurInstIterator = Div;
772 ModifiedDT = true;
773 return true;
774 }
775
776 Value *MinusOne = Constant::getAllOnesValue(LHS->getType());
777 Value *Zero = Constant::getNullValue(LHS->getType());
778
779 // Split the original BB and create other basic blocks that will be used
780 // for checks.
781 BasicBlock *StartBB = II->getParent();
782 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(II));
783 BasicBlock *NextBB = StartBB->splitBasicBlock(SplitPt, "div.end");
784
785 BasicBlock *DivByZeroBB;
786 DivByZeroBB = BasicBlock::Create(II->getContext(), "div.divz",
787 NextBB->getParent(), NextBB);
788 BranchInst::Create(NextBB, DivByZeroBB);
789 BasicBlock *DivBB = BasicBlock::Create(II->getContext(), "div.div",
790 NextBB->getParent(), NextBB);
791 BranchInst::Create(NextBB, DivBB);
792
793 // For signed variants, check the condition (2):
794 // LHS == SignedMinValue, RHS == -1.
795 Value *CmpMinusOne;
796 Value *CmpMinValue;
797 BasicBlock *ChkDivMinBB;
798 BasicBlock *DivMinBB;
799 Value *MinValue;
800 if (IsSigned) {
801 APInt SignedMinValue =
802 APInt::getSignedMinValue(LHS->getType()->getPrimitiveSizeInBits());
803 MinValue = Constant::getIntegerValue(LHS->getType(), SignedMinValue);
804 ChkDivMinBB = BasicBlock::Create(II->getContext(), "div.chkdivmin",
805 NextBB->getParent(), NextBB);
806 BranchInst::Create(NextBB, ChkDivMinBB);
807 DivMinBB = BasicBlock::Create(II->getContext(), "div.divmin",
808 NextBB->getParent(), NextBB);
809 BranchInst::Create(NextBB, DivMinBB);
810 CmpMinusOne = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ,
811 RHS, MinusOne, "cmp.rhs.minus.one",
812 ChkDivMinBB->getTerminator());
813 CmpMinValue = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ,
814 LHS, MinValue, "cmp.lhs.signed.min",
815 ChkDivMinBB->getTerminator());
816 BinaryOperator *CmpSignedOvf = BinaryOperator::Create(Instruction::And,
817 CmpMinusOne,
818 CmpMinValue);
819 // Here we're interested in the case when both %x is TMin and %y is -1.
820 // In this case the result will overflow.
821 // If that's not the case, we can perform usual division. These blocks
822 // will be inserted after DivByZero, so the division will be safe.
823 CmpSignedOvf->insertBefore(ChkDivMinBB->getTerminator());
824 BranchInst::Create(DivMinBB, DivBB, CmpSignedOvf,
825 ChkDivMinBB->getTerminator());
826 ChkDivMinBB->getTerminator()->eraseFromParent();
827 }
828
829 // Check the condition (1):
830 // RHS == 0.
831 Value *CmpDivZero = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ,
832 RHS, Zero, "cmp.rhs.zero",
833 StartBB->getTerminator());
834
835 // If RHS != 0, we want to check condition (2) in signed case, or proceed
836 // to usual division in unsigned case.
837 BranchInst::Create(DivByZeroBB, IsSigned ? ChkDivMinBB : DivBB, CmpDivZero,
838 StartBB->getTerminator());
839 StartBB->getTerminator()->eraseFromParent();
840
841 // At the moment we have all the control flow created. We just need to
842 // insert DIV and PHI (if needed) to get the result value.
843 Instruction *DivRes, *FlagRes;
844 Instruction *InsPoint = nullptr;
845 if (ResultNeeded[0]) {
846 BinaryOperator *Div = BinaryOperator::Create(Op, LHS, RHS);
847 if (DivWellDefined) {
848 // The result value is the result of DIV operation placed right at the
849 // original place of the intrinsic.
850 Div->insertAfter(II);
851 DivRes = Div;
852 } else {
853 // The result is a PHI-node.
854 Div->insertBefore(DivBB->getTerminator());
855 PHINode *DivResPN =
856 PHINode::Create(LHS->getType(), IsSigned ? 3 : 2, "div.res.phi",
857 NextBB->begin());
858 DivResPN->addIncoming(Div, DivBB);
859 DivResPN->addIncoming(Zero, DivByZeroBB);
860 if (IsSigned)
861 DivResPN->addIncoming(MinValue, DivMinBB);
862 DivRes = DivResPN;
863 InsPoint = DivResPN;
864 }
865 }
866
867 // Prepare a value for the second result (flag) if it is needed.
868 if (ResultNeeded[1]) {
869 Type *FlagTy = II->getType()->getStructElementType(1);
870 PHINode *FlagResPN =
871 PHINode::Create(FlagTy, IsSigned ? 3 : 2, "div.flag.phi",
872 NextBB->begin());
873 FlagResPN->addIncoming(Constant::getNullValue(FlagTy), DivBB);
874 FlagResPN->addIncoming(Constant::getAllOnesValue(FlagTy), DivByZeroBB);
875 if (IsSigned)
876 FlagResPN->addIncoming(Constant::getAllOnesValue(FlagTy), DivMinBB);
877 FlagRes = FlagResPN;
878 if (!InsPoint)
879 InsPoint = FlagRes;
880 }
881
882 // If possible, propagate the results to the user. Otherwise, create alloca,
883 // and create a struct with the results on stack.
884 if (!BadCase) {
885 if (ResultNeeded[0]) {
886 for (User *U: ResultsUsers[0]) {
887 Instruction *UserInst = dyn_cast<Instruction>(U);
888 assert(UserInst && "Unexpected null-instruction");
889 UserInst->replaceAllUsesWith(DivRes);
890 UserInst->eraseFromParent();
891 }
892 }
893 if (ResultNeeded[1]) {
894 for (User *FlagU: ResultsUsers[1]) {
895 Instruction *FlagUInst = dyn_cast<Instruction>(FlagU);
896 FlagUInst->replaceAllUsesWith(FlagRes);
897 FlagUInst->eraseFromParent();
898 }
899 }
900 } else {
901 // Create alloca, store our new values to it, and then load the final
902 // result from it.
903 Constant *Idx0 = ConstantInt::get(Type::getInt32Ty(II->getContext()), 0);
904 Constant *Idx1 = ConstantInt::get(Type::getInt32Ty(II->getContext()), 1);
905 Value *Idxs_DivRes[2] = {Idx0, Idx0};
906 Value *Idxs_FlagRes[2] = {Idx0, Idx1};
907 Value *NewRes = new llvm::AllocaInst(II->getType(), 0, "div.res.ptr", II);
908 Instruction *ResDivAddr = GetElementPtrInst::Create(NewRes, Idxs_DivRes);
909 Instruction *ResFlagAddr =
910 GetElementPtrInst::Create(NewRes, Idxs_FlagRes);
911 ResDivAddr->insertAfter(InsPoint);
912 ResFlagAddr->insertAfter(ResDivAddr);
913 StoreInst *StoreResDiv = new StoreInst(DivRes, ResDivAddr);
914 StoreInst *StoreResFlag = new StoreInst(FlagRes, ResFlagAddr);
915 StoreResDiv->insertAfter(ResFlagAddr);
916 StoreResFlag->insertAfter(StoreResDiv);
917 LoadInst *LoadRes = new LoadInst(NewRes, "div.res");
918 LoadRes->insertAfter(StoreResFlag);
919 II->replaceAllUsesWith(LoadRes);
920 }
921
922 II->eraseFromParent();
923 CurInstIterator = StartBB->end();
924 ModifiedDT = true;
925 return true;
926 }
Eric Christopher4b7948e2010-03-11 02:41:03 +0000927
Pete Cooper615fd892012-03-13 20:59:56 +0000928 if (II && TLI) {
929 SmallVector<Value*, 2> PtrOps;
930 Type *AccessTy;
931 if (TLI->GetAddrModeArguments(II, PtrOps, AccessTy))
932 while (!PtrOps.empty())
933 if (OptimizeMemoryInst(II, PtrOps.pop_back_val(), AccessTy))
934 return true;
935 }
936
Eric Christopher4b7948e2010-03-11 02:41:03 +0000937 // From here on out we're working with named functions.
Craig Topperc0196b12014-04-14 00:51:57 +0000938 if (!CI->getCalledFunction()) return false;
Devang Patel0da52502011-05-26 21:51:06 +0000939
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000940 // We'll need DataLayout from here on out.
Craig Topperc0196b12014-04-14 00:51:57 +0000941 const DataLayout *TD = TLI ? TLI->getDataLayout() : nullptr;
Eric Christopher4b7948e2010-03-11 02:41:03 +0000942 if (!TD) return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000943
Benjamin Kramer7b88a492010-03-12 09:27:41 +0000944 // Lower all default uses of _chk calls. This is very similar
945 // to what InstCombineCalls does, but here we are only lowering calls
Eric Christopher4b7948e2010-03-11 02:41:03 +0000946 // that have the default "don't know" as the objectsize. Anything else
947 // should be left alone.
Benjamin Kramer7b88a492010-03-12 09:27:41 +0000948 CodeGenPrepareFortifiedLibCalls Simplifier;
Nuno Lopes89702e92012-07-25 16:46:31 +0000949 return Simplifier.fold(CI, TD, TLInfo);
Eric Christopher4b7948e2010-03-11 02:41:03 +0000950}
Chris Lattner1b93be52011-01-15 07:25:29 +0000951
Evan Cheng0663f232011-03-21 01:19:09 +0000952/// DupRetToEnableTailCallOpts - Look for opportunities to duplicate return
953/// instructions to the predecessor to enable tail call optimizations. The
954/// case it is currently looking for is:
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +0000955/// @code
Evan Cheng0663f232011-03-21 01:19:09 +0000956/// bb0:
957/// %tmp0 = tail call i32 @f0()
958/// br label %return
959/// bb1:
960/// %tmp1 = tail call i32 @f1()
961/// br label %return
962/// bb2:
963/// %tmp2 = tail call i32 @f2()
964/// br label %return
965/// return:
966/// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
967/// ret i32 %retval
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +0000968/// @endcode
Evan Cheng0663f232011-03-21 01:19:09 +0000969///
970/// =>
971///
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +0000972/// @code
Evan Cheng0663f232011-03-21 01:19:09 +0000973/// bb0:
974/// %tmp0 = tail call i32 @f0()
975/// ret i32 %tmp0
976/// bb1:
977/// %tmp1 = tail call i32 @f1()
978/// ret i32 %tmp1
979/// bb2:
980/// %tmp2 = tail call i32 @f2()
981/// ret i32 %tmp2
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +0000982/// @endcode
Benjamin Kramer455fa352012-11-23 19:17:06 +0000983bool CodeGenPrepare::DupRetToEnableTailCallOpts(BasicBlock *BB) {
Cameron Zwarich47e71752011-03-24 04:51:51 +0000984 if (!TLI)
985 return false;
986
Benjamin Kramer455fa352012-11-23 19:17:06 +0000987 ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
988 if (!RI)
989 return false;
990
Craig Topperc0196b12014-04-14 00:51:57 +0000991 PHINode *PN = nullptr;
992 BitCastInst *BCI = nullptr;
Evan Cheng0663f232011-03-21 01:19:09 +0000993 Value *V = RI->getReturnValue();
Evan Cheng249716e2012-07-27 21:21:26 +0000994 if (V) {
995 BCI = dyn_cast<BitCastInst>(V);
996 if (BCI)
997 V = BCI->getOperand(0);
998
999 PN = dyn_cast<PHINode>(V);
1000 if (!PN)
1001 return false;
1002 }
Evan Cheng0663f232011-03-21 01:19:09 +00001003
Cameron Zwarich4649f172011-03-24 04:52:10 +00001004 if (PN && PN->getParent() != BB)
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001005 return false;
Evan Cheng0663f232011-03-21 01:19:09 +00001006
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001007 // It's not safe to eliminate the sign / zero extension of the return value.
1008 // See llvm::isInTailCallPosition().
1009 const Function *F = BB->getParent();
Bill Wendling658d24d2013-01-18 21:53:16 +00001010 AttributeSet CallerAttrs = F->getAttributes();
1011 if (CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::ZExt) ||
1012 CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::SExt))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001013 return false;
Evan Cheng0663f232011-03-21 01:19:09 +00001014
Cameron Zwarich4649f172011-03-24 04:52:10 +00001015 // Make sure there are no instructions between the PHI and return, or that the
1016 // return is the first instruction in the block.
1017 if (PN) {
1018 BasicBlock::iterator BI = BB->begin();
1019 do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
Evan Cheng249716e2012-07-27 21:21:26 +00001020 if (&*BI == BCI)
1021 // Also skip over the bitcast.
1022 ++BI;
Cameron Zwarich4649f172011-03-24 04:52:10 +00001023 if (&*BI != RI)
1024 return false;
1025 } else {
Cameron Zwarich74157ab2011-03-24 16:34:59 +00001026 BasicBlock::iterator BI = BB->begin();
1027 while (isa<DbgInfoIntrinsic>(BI)) ++BI;
1028 if (&*BI != RI)
Cameron Zwarich4649f172011-03-24 04:52:10 +00001029 return false;
1030 }
Evan Cheng0663f232011-03-21 01:19:09 +00001031
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001032 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
1033 /// call.
1034 SmallVector<CallInst*, 4> TailCalls;
Cameron Zwarich4649f172011-03-24 04:52:10 +00001035 if (PN) {
1036 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
1037 CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
1038 // Make sure the phi value is indeed produced by the tail call.
1039 if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
1040 TLI->mayBeEmittedAsTailCall(CI))
1041 TailCalls.push_back(CI);
1042 }
1043 } else {
1044 SmallPtrSet<BasicBlock*, 4> VisitedBBs;
1045 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
1046 if (!VisitedBBs.insert(*PI))
1047 continue;
1048
1049 BasicBlock::InstListType &InstList = (*PI)->getInstList();
1050 BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
1051 BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
Cameron Zwarich74157ab2011-03-24 16:34:59 +00001052 do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
1053 if (RI == RE)
Cameron Zwarich4649f172011-03-24 04:52:10 +00001054 continue;
Cameron Zwarich74157ab2011-03-24 16:34:59 +00001055
Cameron Zwarich4649f172011-03-24 04:52:10 +00001056 CallInst *CI = dyn_cast<CallInst>(&*RI);
Cameron Zwarich2edfe772011-03-24 15:54:11 +00001057 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI))
Cameron Zwarich4649f172011-03-24 04:52:10 +00001058 TailCalls.push_back(CI);
1059 }
Evan Cheng0663f232011-03-21 01:19:09 +00001060 }
1061
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001062 bool Changed = false;
1063 for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
1064 CallInst *CI = TailCalls[i];
1065 CallSite CS(CI);
1066
1067 // Conservatively require the attributes of the call to match those of the
1068 // return. Ignore noalias because it doesn't affect the call sequence.
Bill Wendling658d24d2013-01-18 21:53:16 +00001069 AttributeSet CalleeAttrs = CS.getAttributes();
1070 if (AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001071 removeAttribute(Attribute::NoAlias) !=
Bill Wendling658d24d2013-01-18 21:53:16 +00001072 AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001073 removeAttribute(Attribute::NoAlias))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001074 continue;
1075
1076 // Make sure the call instruction is followed by an unconditional branch to
1077 // the return block.
1078 BasicBlock *CallBB = CI->getParent();
1079 BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
1080 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
1081 continue;
1082
1083 // Duplicate the return into CallBB.
1084 (void)FoldReturnIntoUncondBranch(RI, BB, CallBB);
Devang Patel8f606d72011-03-24 15:35:25 +00001085 ModifiedDT = Changed = true;
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001086 ++NumRetsDup;
1087 }
1088
1089 // If we eliminated all predecessors of the block, delete the block now.
Evan Cheng64a223a2012-09-28 23:58:57 +00001090 if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001091 BB->eraseFromParent();
1092
1093 return Changed;
Evan Cheng0663f232011-03-21 01:19:09 +00001094}
1095
Chris Lattner728f9022008-11-25 07:09:13 +00001096//===----------------------------------------------------------------------===//
Chris Lattner728f9022008-11-25 07:09:13 +00001097// Memory Optimization
1098//===----------------------------------------------------------------------===//
1099
Chandler Carruthc8925912013-01-05 02:09:22 +00001100namespace {
1101
1102/// ExtAddrMode - This is an extended version of TargetLowering::AddrMode
1103/// which holds actual Value*'s for register values.
Chandler Carruth95f83e02013-01-07 15:14:13 +00001104struct ExtAddrMode : public TargetLowering::AddrMode {
Chandler Carruthc8925912013-01-05 02:09:22 +00001105 Value *BaseReg;
1106 Value *ScaledReg;
Craig Topperc0196b12014-04-14 00:51:57 +00001107 ExtAddrMode() : BaseReg(nullptr), ScaledReg(nullptr) {}
Chandler Carruthc8925912013-01-05 02:09:22 +00001108 void print(raw_ostream &OS) const;
1109 void dump() const;
Stephen Lin837bba12013-07-15 17:55:02 +00001110
Chandler Carruthc8925912013-01-05 02:09:22 +00001111 bool operator==(const ExtAddrMode& O) const {
1112 return (BaseReg == O.BaseReg) && (ScaledReg == O.ScaledReg) &&
1113 (BaseGV == O.BaseGV) && (BaseOffs == O.BaseOffs) &&
1114 (HasBaseReg == O.HasBaseReg) && (Scale == O.Scale);
1115 }
1116};
1117
Eli Friedmanc1f1f852013-09-10 23:09:24 +00001118#ifndef NDEBUG
1119static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
1120 AM.print(OS);
1121 return OS;
1122}
1123#endif
1124
Chandler Carruthc8925912013-01-05 02:09:22 +00001125void ExtAddrMode::print(raw_ostream &OS) const {
1126 bool NeedPlus = false;
1127 OS << "[";
1128 if (BaseGV) {
1129 OS << (NeedPlus ? " + " : "")
1130 << "GV:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00001131 BaseGV->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00001132 NeedPlus = true;
1133 }
1134
1135 if (BaseOffs)
1136 OS << (NeedPlus ? " + " : "") << BaseOffs, NeedPlus = true;
1137
1138 if (BaseReg) {
1139 OS << (NeedPlus ? " + " : "")
1140 << "Base:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00001141 BaseReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00001142 NeedPlus = true;
1143 }
1144 if (Scale) {
1145 OS << (NeedPlus ? " + " : "")
1146 << Scale << "*";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00001147 ScaledReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00001148 }
1149
1150 OS << ']';
1151}
1152
1153#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1154void ExtAddrMode::dump() const {
1155 print(dbgs());
1156 dbgs() << '\n';
1157}
1158#endif
1159
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001160/// \brief This class provides transaction based operation on the IR.
1161/// Every change made through this class is recorded in the internal state and
1162/// can be undone (rollback) until commit is called.
1163class TypePromotionTransaction {
1164
1165 /// \brief This represents the common interface of the individual transaction.
1166 /// Each class implements the logic for doing one specific modification on
1167 /// the IR via the TypePromotionTransaction.
1168 class TypePromotionAction {
1169 protected:
1170 /// The Instruction modified.
1171 Instruction *Inst;
1172
1173 public:
1174 /// \brief Constructor of the action.
1175 /// The constructor performs the related action on the IR.
1176 TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
1177
1178 virtual ~TypePromotionAction() {}
1179
1180 /// \brief Undo the modification done by this action.
1181 /// When this method is called, the IR must be in the same state as it was
1182 /// before this action was applied.
1183 /// \pre Undoing the action works if and only if the IR is in the exact same
1184 /// state as it was directly after this action was applied.
1185 virtual void undo() = 0;
1186
1187 /// \brief Advocate every change made by this action.
1188 /// When the results on the IR of the action are to be kept, it is important
1189 /// to call this function, otherwise hidden information may be kept forever.
1190 virtual void commit() {
1191 // Nothing to be done, this action is not doing anything.
1192 }
1193 };
1194
1195 /// \brief Utility to remember the position of an instruction.
1196 class InsertionHandler {
1197 /// Position of an instruction.
1198 /// Either an instruction:
1199 /// - Is the first in a basic block: BB is used.
1200 /// - Has a previous instructon: PrevInst is used.
1201 union {
1202 Instruction *PrevInst;
1203 BasicBlock *BB;
1204 } Point;
1205 /// Remember whether or not the instruction had a previous instruction.
1206 bool HasPrevInstruction;
1207
1208 public:
1209 /// \brief Record the position of \p Inst.
1210 InsertionHandler(Instruction *Inst) {
1211 BasicBlock::iterator It = Inst;
1212 HasPrevInstruction = (It != (Inst->getParent()->begin()));
1213 if (HasPrevInstruction)
1214 Point.PrevInst = --It;
1215 else
1216 Point.BB = Inst->getParent();
1217 }
1218
1219 /// \brief Insert \p Inst at the recorded position.
1220 void insert(Instruction *Inst) {
1221 if (HasPrevInstruction) {
1222 if (Inst->getParent())
1223 Inst->removeFromParent();
1224 Inst->insertAfter(Point.PrevInst);
1225 } else {
1226 Instruction *Position = Point.BB->getFirstInsertionPt();
1227 if (Inst->getParent())
1228 Inst->moveBefore(Position);
1229 else
1230 Inst->insertBefore(Position);
1231 }
1232 }
1233 };
1234
1235 /// \brief Move an instruction before another.
1236 class InstructionMoveBefore : public TypePromotionAction {
1237 /// Original position of the instruction.
1238 InsertionHandler Position;
1239
1240 public:
1241 /// \brief Move \p Inst before \p Before.
1242 InstructionMoveBefore(Instruction *Inst, Instruction *Before)
1243 : TypePromotionAction(Inst), Position(Inst) {
1244 DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before << "\n");
1245 Inst->moveBefore(Before);
1246 }
1247
1248 /// \brief Move the instruction back to its original position.
Craig Topper4584cd52014-03-07 09:26:03 +00001249 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001250 DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n");
1251 Position.insert(Inst);
1252 }
1253 };
1254
1255 /// \brief Set the operand of an instruction with a new value.
1256 class OperandSetter : public TypePromotionAction {
1257 /// Original operand of the instruction.
1258 Value *Origin;
1259 /// Index of the modified instruction.
1260 unsigned Idx;
1261
1262 public:
1263 /// \brief Set \p Idx operand of \p Inst with \p NewVal.
1264 OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
1265 : TypePromotionAction(Inst), Idx(Idx) {
1266 DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"
1267 << "for:" << *Inst << "\n"
1268 << "with:" << *NewVal << "\n");
1269 Origin = Inst->getOperand(Idx);
1270 Inst->setOperand(Idx, NewVal);
1271 }
1272
1273 /// \brief Restore the original value of the instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00001274 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001275 DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"
1276 << "for: " << *Inst << "\n"
1277 << "with: " << *Origin << "\n");
1278 Inst->setOperand(Idx, Origin);
1279 }
1280 };
1281
1282 /// \brief Hide the operands of an instruction.
1283 /// Do as if this instruction was not using any of its operands.
1284 class OperandsHider : public TypePromotionAction {
1285 /// The list of original operands.
1286 SmallVector<Value *, 4> OriginalValues;
1287
1288 public:
1289 /// \brief Remove \p Inst from the uses of the operands of \p Inst.
1290 OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
1291 DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n");
1292 unsigned NumOpnds = Inst->getNumOperands();
1293 OriginalValues.reserve(NumOpnds);
1294 for (unsigned It = 0; It < NumOpnds; ++It) {
1295 // Save the current operand.
1296 Value *Val = Inst->getOperand(It);
1297 OriginalValues.push_back(Val);
1298 // Set a dummy one.
1299 // We could use OperandSetter here, but that would implied an overhead
1300 // that we are not willing to pay.
1301 Inst->setOperand(It, UndefValue::get(Val->getType()));
1302 }
1303 }
1304
1305 /// \brief Restore the original list of uses.
Craig Topper4584cd52014-03-07 09:26:03 +00001306 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001307 DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n");
1308 for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
1309 Inst->setOperand(It, OriginalValues[It]);
1310 }
1311 };
1312
1313 /// \brief Build a truncate instruction.
1314 class TruncBuilder : public TypePromotionAction {
1315 public:
1316 /// \brief Build a truncate instruction of \p Opnd producing a \p Ty
1317 /// result.
1318 /// trunc Opnd to Ty.
1319 TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
1320 IRBuilder<> Builder(Opnd);
1321 Inst = cast<Instruction>(Builder.CreateTrunc(Opnd, Ty, "promoted"));
1322 DEBUG(dbgs() << "Do: TruncBuilder: " << *Inst << "\n");
1323 }
1324
1325 /// \brief Get the built instruction.
1326 Instruction *getBuiltInstruction() { return Inst; }
1327
1328 /// \brief Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00001329 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001330 DEBUG(dbgs() << "Undo: TruncBuilder: " << *Inst << "\n");
1331 Inst->eraseFromParent();
1332 }
1333 };
1334
1335 /// \brief Build a sign extension instruction.
1336 class SExtBuilder : public TypePromotionAction {
1337 public:
1338 /// \brief Build a sign extension instruction of \p Opnd producing a \p Ty
1339 /// result.
1340 /// sext Opnd to Ty.
1341 SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
1342 : TypePromotionAction(Inst) {
1343 IRBuilder<> Builder(InsertPt);
1344 Inst = cast<Instruction>(Builder.CreateSExt(Opnd, Ty, "promoted"));
1345 DEBUG(dbgs() << "Do: SExtBuilder: " << *Inst << "\n");
1346 }
1347
1348 /// \brief Get the built instruction.
1349 Instruction *getBuiltInstruction() { return Inst; }
1350
1351 /// \brief Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00001352 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001353 DEBUG(dbgs() << "Undo: SExtBuilder: " << *Inst << "\n");
1354 Inst->eraseFromParent();
1355 }
1356 };
1357
1358 /// \brief Mutate an instruction to another type.
1359 class TypeMutator : public TypePromotionAction {
1360 /// Record the original type.
1361 Type *OrigTy;
1362
1363 public:
1364 /// \brief Mutate the type of \p Inst into \p NewTy.
1365 TypeMutator(Instruction *Inst, Type *NewTy)
1366 : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
1367 DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy
1368 << "\n");
1369 Inst->mutateType(NewTy);
1370 }
1371
1372 /// \brief Mutate the instruction back to its original type.
Craig Topper4584cd52014-03-07 09:26:03 +00001373 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001374 DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy
1375 << "\n");
1376 Inst->mutateType(OrigTy);
1377 }
1378 };
1379
1380 /// \brief Replace the uses of an instruction by another instruction.
1381 class UsesReplacer : public TypePromotionAction {
1382 /// Helper structure to keep track of the replaced uses.
1383 struct InstructionAndIdx {
1384 /// The instruction using the instruction.
1385 Instruction *Inst;
1386 /// The index where this instruction is used for Inst.
1387 unsigned Idx;
1388 InstructionAndIdx(Instruction *Inst, unsigned Idx)
1389 : Inst(Inst), Idx(Idx) {}
1390 };
1391
1392 /// Keep track of the original uses (pair Instruction, Index).
1393 SmallVector<InstructionAndIdx, 4> OriginalUses;
1394 typedef SmallVectorImpl<InstructionAndIdx>::iterator use_iterator;
1395
1396 public:
1397 /// \brief Replace all the use of \p Inst by \p New.
1398 UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) {
1399 DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New
1400 << "\n");
1401 // Record the original uses.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001402 for (Use &U : Inst->uses()) {
1403 Instruction *UserI = cast<Instruction>(U.getUser());
1404 OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo()));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001405 }
1406 // Now, we can replace the uses.
1407 Inst->replaceAllUsesWith(New);
1408 }
1409
1410 /// \brief Reassign the original uses of Inst to Inst.
Craig Topper4584cd52014-03-07 09:26:03 +00001411 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001412 DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n");
1413 for (use_iterator UseIt = OriginalUses.begin(),
1414 EndIt = OriginalUses.end();
1415 UseIt != EndIt; ++UseIt) {
1416 UseIt->Inst->setOperand(UseIt->Idx, Inst);
1417 }
1418 }
1419 };
1420
1421 /// \brief Remove an instruction from the IR.
1422 class InstructionRemover : public TypePromotionAction {
1423 /// Original position of the instruction.
1424 InsertionHandler Inserter;
1425 /// Helper structure to hide all the link to the instruction. In other
1426 /// words, this helps to do as if the instruction was removed.
1427 OperandsHider Hider;
1428 /// Keep track of the uses replaced, if any.
1429 UsesReplacer *Replacer;
1430
1431 public:
1432 /// \brief Remove all reference of \p Inst and optinally replace all its
1433 /// uses with New.
Craig Topperc0196b12014-04-14 00:51:57 +00001434 /// \pre If !Inst->use_empty(), then New != nullptr
1435 InstructionRemover(Instruction *Inst, Value *New = nullptr)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001436 : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
Craig Topperc0196b12014-04-14 00:51:57 +00001437 Replacer(nullptr) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001438 if (New)
1439 Replacer = new UsesReplacer(Inst, New);
1440 DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n");
1441 Inst->removeFromParent();
1442 }
1443
1444 ~InstructionRemover() { delete Replacer; }
1445
1446 /// \brief Really remove the instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00001447 void commit() override { delete Inst; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001448
1449 /// \brief Resurrect the instruction and reassign it to the proper uses if
1450 /// new value was provided when build this action.
Craig Topper4584cd52014-03-07 09:26:03 +00001451 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001452 DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n");
1453 Inserter.insert(Inst);
1454 if (Replacer)
1455 Replacer->undo();
1456 Hider.undo();
1457 }
1458 };
1459
1460public:
1461 /// Restoration point.
1462 /// The restoration point is a pointer to an action instead of an iterator
1463 /// because the iterator may be invalidated but not the pointer.
1464 typedef const TypePromotionAction *ConstRestorationPt;
1465 /// Advocate every changes made in that transaction.
1466 void commit();
1467 /// Undo all the changes made after the given point.
1468 void rollback(ConstRestorationPt Point);
1469 /// Get the current restoration point.
1470 ConstRestorationPt getRestorationPoint() const;
1471
1472 /// \name API for IR modification with state keeping to support rollback.
1473 /// @{
1474 /// Same as Instruction::setOperand.
1475 void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
1476 /// Same as Instruction::eraseFromParent.
Craig Topperc0196b12014-04-14 00:51:57 +00001477 void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001478 /// Same as Value::replaceAllUsesWith.
1479 void replaceAllUsesWith(Instruction *Inst, Value *New);
1480 /// Same as Value::mutateType.
1481 void mutateType(Instruction *Inst, Type *NewTy);
1482 /// Same as IRBuilder::createTrunc.
1483 Instruction *createTrunc(Instruction *Opnd, Type *Ty);
1484 /// Same as IRBuilder::createSExt.
1485 Instruction *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
1486 /// Same as Instruction::moveBefore.
1487 void moveBefore(Instruction *Inst, Instruction *Before);
1488 /// @}
1489
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001490private:
1491 /// The ordered list of actions made so far.
David Blaikie7620b312014-04-15 06:17:44 +00001492 SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions;
1493 typedef SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator CommitPt;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001494};
1495
1496void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
1497 Value *NewVal) {
1498 Actions.push_back(
David Blaikie7620b312014-04-15 06:17:44 +00001499 make_unique<TypePromotionTransaction::OperandSetter>(Inst, Idx, NewVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001500}
1501
1502void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
1503 Value *NewVal) {
1504 Actions.push_back(
David Blaikie7620b312014-04-15 06:17:44 +00001505 make_unique<TypePromotionTransaction::InstructionRemover>(Inst, NewVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001506}
1507
1508void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
1509 Value *New) {
David Blaikie7620b312014-04-15 06:17:44 +00001510 Actions.push_back(make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001511}
1512
1513void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
David Blaikie7620b312014-04-15 06:17:44 +00001514 Actions.push_back(make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001515}
1516
1517Instruction *TypePromotionTransaction::createTrunc(Instruction *Opnd,
1518 Type *Ty) {
David Blaikie7620b312014-04-15 06:17:44 +00001519 std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty));
1520 Instruction *I = Ptr->getBuiltInstruction();
1521 Actions.push_back(std::move(Ptr));
1522 return I;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001523}
1524
1525Instruction *TypePromotionTransaction::createSExt(Instruction *Inst,
1526 Value *Opnd, Type *Ty) {
David Blaikie7620b312014-04-15 06:17:44 +00001527 std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty));
1528 Instruction *I = Ptr->getBuiltInstruction();
1529 Actions.push_back(std::move(Ptr));
1530 return I;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001531}
1532
1533void TypePromotionTransaction::moveBefore(Instruction *Inst,
1534 Instruction *Before) {
1535 Actions.push_back(
David Blaikie7620b312014-04-15 06:17:44 +00001536 make_unique<TypePromotionTransaction::InstructionMoveBefore>(Inst, Before));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001537}
1538
1539TypePromotionTransaction::ConstRestorationPt
1540TypePromotionTransaction::getRestorationPoint() const {
David Blaikie7620b312014-04-15 06:17:44 +00001541 return !Actions.empty() ? Actions.back().get() : nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001542}
1543
1544void TypePromotionTransaction::commit() {
1545 for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt;
David Blaikie7620b312014-04-15 06:17:44 +00001546 ++It)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001547 (*It)->commit();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001548 Actions.clear();
1549}
1550
1551void TypePromotionTransaction::rollback(
1552 TypePromotionTransaction::ConstRestorationPt Point) {
David Blaikie7620b312014-04-15 06:17:44 +00001553 while (!Actions.empty() && Point != Actions.back().get()) {
1554 std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001555 Curr->undo();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001556 }
1557}
1558
Chandler Carruthc8925912013-01-05 02:09:22 +00001559/// \brief A helper class for matching addressing modes.
1560///
1561/// This encapsulates the logic for matching the target-legal addressing modes.
1562class AddressingModeMatcher {
1563 SmallVectorImpl<Instruction*> &AddrModeInsts;
1564 const TargetLowering &TLI;
1565
1566 /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
1567 /// the memory instruction that we're computing this address for.
1568 Type *AccessTy;
1569 Instruction *MemoryInst;
Stephen Lin837bba12013-07-15 17:55:02 +00001570
Chandler Carruthc8925912013-01-05 02:09:22 +00001571 /// AddrMode - This is the addressing mode that we're building up. This is
1572 /// part of the return value of this addressing mode matching stuff.
1573 ExtAddrMode &AddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00001574
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001575 /// The truncate instruction inserted by other CodeGenPrepare optimizations.
1576 const SetOfInstrs &InsertedTruncs;
1577 /// A map from the instructions to their type before promotion.
1578 InstrToOrigTy &PromotedInsts;
1579 /// The ongoing transaction where every action should be registered.
1580 TypePromotionTransaction &TPT;
1581
Chandler Carruthc8925912013-01-05 02:09:22 +00001582 /// IgnoreProfitability - This is set to true when we should not do
1583 /// profitability checks. When true, IsProfitableToFoldIntoAddressingMode
1584 /// always returns true.
1585 bool IgnoreProfitability;
Stephen Lin837bba12013-07-15 17:55:02 +00001586
Chandler Carruthc8925912013-01-05 02:09:22 +00001587 AddressingModeMatcher(SmallVectorImpl<Instruction*> &AMI,
1588 const TargetLowering &T, Type *AT,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001589 Instruction *MI, ExtAddrMode &AM,
1590 const SetOfInstrs &InsertedTruncs,
1591 InstrToOrigTy &PromotedInsts,
1592 TypePromotionTransaction &TPT)
1593 : AddrModeInsts(AMI), TLI(T), AccessTy(AT), MemoryInst(MI), AddrMode(AM),
1594 InsertedTruncs(InsertedTruncs), PromotedInsts(PromotedInsts), TPT(TPT) {
Chandler Carruthc8925912013-01-05 02:09:22 +00001595 IgnoreProfitability = false;
1596 }
1597public:
Stephen Lin837bba12013-07-15 17:55:02 +00001598
Chandler Carruthc8925912013-01-05 02:09:22 +00001599 /// Match - Find the maximal addressing mode that a load/store of V can fold,
1600 /// give an access type of AccessTy. This returns a list of involved
1601 /// instructions in AddrModeInsts.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001602 /// \p InsertedTruncs The truncate instruction inserted by other
1603 /// CodeGenPrepare
1604 /// optimizations.
1605 /// \p PromotedInsts maps the instructions to their type before promotion.
1606 /// \p The ongoing transaction where every action should be registered.
Chandler Carruthc8925912013-01-05 02:09:22 +00001607 static ExtAddrMode Match(Value *V, Type *AccessTy,
1608 Instruction *MemoryInst,
1609 SmallVectorImpl<Instruction*> &AddrModeInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001610 const TargetLowering &TLI,
1611 const SetOfInstrs &InsertedTruncs,
1612 InstrToOrigTy &PromotedInsts,
1613 TypePromotionTransaction &TPT) {
Chandler Carruthc8925912013-01-05 02:09:22 +00001614 ExtAddrMode Result;
1615
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001616 bool Success = AddressingModeMatcher(AddrModeInsts, TLI, AccessTy,
1617 MemoryInst, Result, InsertedTruncs,
1618 PromotedInsts, TPT).MatchAddr(V, 0);
Chandler Carruthc8925912013-01-05 02:09:22 +00001619 (void)Success; assert(Success && "Couldn't select *anything*?");
1620 return Result;
1621 }
1622private:
1623 bool MatchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
1624 bool MatchAddr(Value *V, unsigned Depth);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001625 bool MatchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth,
Craig Topperc0196b12014-04-14 00:51:57 +00001626 bool *MovedAway = nullptr);
Chandler Carruthc8925912013-01-05 02:09:22 +00001627 bool IsProfitableToFoldIntoAddressingMode(Instruction *I,
1628 ExtAddrMode &AMBefore,
1629 ExtAddrMode &AMAfter);
1630 bool ValueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
Quentin Colombet867c5502014-02-14 22:23:22 +00001631 bool IsPromotionProfitable(unsigned MatchedSize, unsigned SizeWithPromotion,
1632 Value *PromotedOperand) const;
Chandler Carruthc8925912013-01-05 02:09:22 +00001633};
1634
1635/// MatchScaledValue - Try adding ScaleReg*Scale to the current addressing mode.
1636/// Return true and update AddrMode if this addr mode is legal for the target,
1637/// false if not.
1638bool AddressingModeMatcher::MatchScaledValue(Value *ScaleReg, int64_t Scale,
1639 unsigned Depth) {
1640 // If Scale is 1, then this is the same as adding ScaleReg to the addressing
1641 // mode. Just process that directly.
1642 if (Scale == 1)
1643 return MatchAddr(ScaleReg, Depth);
Stephen Lin837bba12013-07-15 17:55:02 +00001644
Chandler Carruthc8925912013-01-05 02:09:22 +00001645 // If the scale is 0, it takes nothing to add this.
1646 if (Scale == 0)
1647 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00001648
Chandler Carruthc8925912013-01-05 02:09:22 +00001649 // If we already have a scale of this value, we can add to it, otherwise, we
1650 // need an available scale field.
1651 if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
1652 return false;
1653
1654 ExtAddrMode TestAddrMode = AddrMode;
1655
1656 // Add scale to turn X*4+X*3 -> X*7. This could also do things like
1657 // [A+B + A*7] -> [B+A*8].
1658 TestAddrMode.Scale += Scale;
1659 TestAddrMode.ScaledReg = ScaleReg;
1660
1661 // If the new address isn't legal, bail out.
1662 if (!TLI.isLegalAddressingMode(TestAddrMode, AccessTy))
1663 return false;
1664
1665 // It was legal, so commit it.
1666 AddrMode = TestAddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00001667
Chandler Carruthc8925912013-01-05 02:09:22 +00001668 // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
1669 // to see if ScaleReg is actually X+C. If so, we can turn this into adding
1670 // X*Scale + C*Scale to addr mode.
Craig Topperc0196b12014-04-14 00:51:57 +00001671 ConstantInt *CI = nullptr; Value *AddLHS = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00001672 if (isa<Instruction>(ScaleReg) && // not a constant expr.
1673 match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
1674 TestAddrMode.ScaledReg = AddLHS;
1675 TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00001676
Chandler Carruthc8925912013-01-05 02:09:22 +00001677 // If this addressing mode is legal, commit it and remember that we folded
1678 // this instruction.
1679 if (TLI.isLegalAddressingMode(TestAddrMode, AccessTy)) {
1680 AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
1681 AddrMode = TestAddrMode;
1682 return true;
1683 }
1684 }
1685
1686 // Otherwise, not (x+c)*scale, just return what we have.
1687 return true;
1688}
1689
1690/// MightBeFoldableInst - This is a little filter, which returns true if an
1691/// addressing computation involving I might be folded into a load/store
1692/// accessing it. This doesn't need to be perfect, but needs to accept at least
1693/// the set of instructions that MatchOperationAddr can.
1694static bool MightBeFoldableInst(Instruction *I) {
1695 switch (I->getOpcode()) {
1696 case Instruction::BitCast:
1697 // Don't touch identity bitcasts.
1698 if (I->getType() == I->getOperand(0)->getType())
1699 return false;
1700 return I->getType()->isPointerTy() || I->getType()->isIntegerTy();
1701 case Instruction::PtrToInt:
1702 // PtrToInt is always a noop, as we know that the int type is pointer sized.
1703 return true;
1704 case Instruction::IntToPtr:
1705 // We know the input is intptr_t, so this is foldable.
1706 return true;
1707 case Instruction::Add:
1708 return true;
1709 case Instruction::Mul:
1710 case Instruction::Shl:
1711 // Can only handle X*C and X << C.
1712 return isa<ConstantInt>(I->getOperand(1));
1713 case Instruction::GetElementPtr:
1714 return true;
1715 default:
1716 return false;
1717 }
1718}
1719
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001720/// \brief Hepler class to perform type promotion.
1721class TypePromotionHelper {
1722 /// \brief Utility function to check whether or not a sign extension of
1723 /// \p Inst with \p ConsideredSExtType can be moved through \p Inst by either
1724 /// using the operands of \p Inst or promoting \p Inst.
1725 /// In other words, check if:
1726 /// sext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredSExtType.
1727 /// #1 Promotion applies:
1728 /// ConsideredSExtType Inst (sext opnd1 to ConsideredSExtType, ...).
1729 /// #2 Operand reuses:
1730 /// sext opnd1 to ConsideredSExtType.
1731 /// \p PromotedInsts maps the instructions to their type before promotion.
1732 static bool canGetThrough(const Instruction *Inst, Type *ConsideredSExtType,
1733 const InstrToOrigTy &PromotedInsts);
1734
1735 /// \brief Utility function to determine if \p OpIdx should be promoted when
1736 /// promoting \p Inst.
1737 static bool shouldSExtOperand(const Instruction *Inst, int OpIdx) {
1738 if (isa<SelectInst>(Inst) && OpIdx == 0)
1739 return false;
1740 return true;
1741 }
1742
1743 /// \brief Utility function to promote the operand of \p SExt when this
1744 /// operand is a promotable trunc or sext.
1745 /// \p PromotedInsts maps the instructions to their type before promotion.
1746 /// \p CreatedInsts[out] contains how many non-free instructions have been
1747 /// created to promote the operand of SExt.
1748 /// Should never be called directly.
1749 /// \return The promoted value which is used instead of SExt.
1750 static Value *promoteOperandForTruncAndSExt(Instruction *SExt,
1751 TypePromotionTransaction &TPT,
1752 InstrToOrigTy &PromotedInsts,
1753 unsigned &CreatedInsts);
1754
1755 /// \brief Utility function to promote the operand of \p SExt when this
1756 /// operand is promotable and is not a supported trunc or sext.
1757 /// \p PromotedInsts maps the instructions to their type before promotion.
1758 /// \p CreatedInsts[out] contains how many non-free instructions have been
1759 /// created to promote the operand of SExt.
1760 /// Should never be called directly.
1761 /// \return The promoted value which is used instead of SExt.
1762 static Value *promoteOperandForOther(Instruction *SExt,
1763 TypePromotionTransaction &TPT,
1764 InstrToOrigTy &PromotedInsts,
1765 unsigned &CreatedInsts);
1766
1767public:
1768 /// Type for the utility function that promotes the operand of SExt.
1769 typedef Value *(*Action)(Instruction *SExt, TypePromotionTransaction &TPT,
1770 InstrToOrigTy &PromotedInsts,
1771 unsigned &CreatedInsts);
1772 /// \brief Given a sign extend instruction \p SExt, return the approriate
1773 /// action to promote the operand of \p SExt instead of using SExt.
1774 /// \return NULL if no promotable action is possible with the current
1775 /// sign extension.
1776 /// \p InsertedTruncs keeps track of all the truncate instructions inserted by
1777 /// the others CodeGenPrepare optimizations. This information is important
1778 /// because we do not want to promote these instructions as CodeGenPrepare
1779 /// will reinsert them later. Thus creating an infinite loop: create/remove.
1780 /// \p PromotedInsts maps the instructions to their type before promotion.
1781 static Action getAction(Instruction *SExt, const SetOfInstrs &InsertedTruncs,
1782 const TargetLowering &TLI,
1783 const InstrToOrigTy &PromotedInsts);
1784};
1785
1786bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
1787 Type *ConsideredSExtType,
1788 const InstrToOrigTy &PromotedInsts) {
1789 // We can always get through sext.
1790 if (isa<SExtInst>(Inst))
1791 return true;
1792
1793 // We can get through binary operator, if it is legal. In other words, the
1794 // binary operator must have a nuw or nsw flag.
1795 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
1796 if (BinOp && isa<OverflowingBinaryOperator>(BinOp) &&
1797 (BinOp->hasNoUnsignedWrap() || BinOp->hasNoSignedWrap()))
1798 return true;
1799
1800 // Check if we can do the following simplification.
1801 // sext(trunc(sext)) --> sext
1802 if (!isa<TruncInst>(Inst))
1803 return false;
1804
1805 Value *OpndVal = Inst->getOperand(0);
1806 // Check if we can use this operand in the sext.
1807 // If the type is larger than the result type of the sign extension,
1808 // we cannot.
1809 if (OpndVal->getType()->getIntegerBitWidth() >
1810 ConsideredSExtType->getIntegerBitWidth())
1811 return false;
1812
1813 // If the operand of the truncate is not an instruction, we will not have
1814 // any information on the dropped bits.
1815 // (Actually we could for constant but it is not worth the extra logic).
1816 Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
1817 if (!Opnd)
1818 return false;
1819
1820 // Check if the source of the type is narrow enough.
1821 // I.e., check that trunc just drops sign extended bits.
1822 // #1 get the type of the operand.
1823 const Type *OpndType;
1824 InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
1825 if (It != PromotedInsts.end())
1826 OpndType = It->second;
1827 else if (isa<SExtInst>(Opnd))
1828 OpndType = cast<Instruction>(Opnd)->getOperand(0)->getType();
1829 else
1830 return false;
1831
1832 // #2 check that the truncate just drop sign extended bits.
1833 if (Inst->getType()->getIntegerBitWidth() >= OpndType->getIntegerBitWidth())
1834 return true;
1835
1836 return false;
1837}
1838
1839TypePromotionHelper::Action TypePromotionHelper::getAction(
1840 Instruction *SExt, const SetOfInstrs &InsertedTruncs,
1841 const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
1842 Instruction *SExtOpnd = dyn_cast<Instruction>(SExt->getOperand(0));
1843 Type *SExtTy = SExt->getType();
1844 // If the operand of the sign extension is not an instruction, we cannot
1845 // get through.
1846 // If it, check we can get through.
1847 if (!SExtOpnd || !canGetThrough(SExtOpnd, SExtTy, PromotedInsts))
Craig Topperc0196b12014-04-14 00:51:57 +00001848 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001849
1850 // Do not promote if the operand has been added by codegenprepare.
1851 // Otherwise, it means we are undoing an optimization that is likely to be
1852 // redone, thus causing potential infinite loop.
1853 if (isa<TruncInst>(SExtOpnd) && InsertedTruncs.count(SExtOpnd))
Craig Topperc0196b12014-04-14 00:51:57 +00001854 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001855
1856 // SExt or Trunc instructions.
1857 // Return the related handler.
1858 if (isa<SExtInst>(SExtOpnd) || isa<TruncInst>(SExtOpnd))
1859 return promoteOperandForTruncAndSExt;
1860
1861 // Regular instruction.
1862 // Abort early if we will have to insert non-free instructions.
1863 if (!SExtOpnd->hasOneUse() &&
1864 !TLI.isTruncateFree(SExtTy, SExtOpnd->getType()))
Craig Topperc0196b12014-04-14 00:51:57 +00001865 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001866 return promoteOperandForOther;
1867}
1868
1869Value *TypePromotionHelper::promoteOperandForTruncAndSExt(
1870 llvm::Instruction *SExt, TypePromotionTransaction &TPT,
1871 InstrToOrigTy &PromotedInsts, unsigned &CreatedInsts) {
1872 // By construction, the operand of SExt is an instruction. Otherwise we cannot
1873 // get through it and this method should not be called.
1874 Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
1875 // Replace sext(trunc(opnd)) or sext(sext(opnd))
1876 // => sext(opnd).
1877 TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
1878 CreatedInsts = 0;
1879
1880 // Remove dead code.
1881 if (SExtOpnd->use_empty())
1882 TPT.eraseInstruction(SExtOpnd);
1883
1884 // Check if the sext is still needed.
1885 if (SExt->getType() != SExt->getOperand(0)->getType())
1886 return SExt;
1887
1888 // At this point we have: sext ty opnd to ty.
1889 // Reassign the uses of SExt to the opnd and remove SExt.
1890 Value *NextVal = SExt->getOperand(0);
1891 TPT.eraseInstruction(SExt, NextVal);
1892 return NextVal;
1893}
1894
1895Value *
1896TypePromotionHelper::promoteOperandForOther(Instruction *SExt,
1897 TypePromotionTransaction &TPT,
1898 InstrToOrigTy &PromotedInsts,
1899 unsigned &CreatedInsts) {
1900 // By construction, the operand of SExt is an instruction. Otherwise we cannot
1901 // get through it and this method should not be called.
1902 Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
1903 CreatedInsts = 0;
1904 if (!SExtOpnd->hasOneUse()) {
1905 // SExtOpnd will be promoted.
1906 // All its uses, but SExt, will need to use a truncated value of the
1907 // promoted version.
1908 // Create the truncate now.
1909 Instruction *Trunc = TPT.createTrunc(SExt, SExtOpnd->getType());
1910 Trunc->removeFromParent();
1911 // Insert it just after the definition.
1912 Trunc->insertAfter(SExtOpnd);
1913
1914 TPT.replaceAllUsesWith(SExtOpnd, Trunc);
1915 // Restore the operand of SExt (which has been replace by the previous call
1916 // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
1917 TPT.setOperand(SExt, 0, SExtOpnd);
1918 }
1919
1920 // Get through the Instruction:
1921 // 1. Update its type.
1922 // 2. Replace the uses of SExt by Inst.
1923 // 3. Sign extend each operand that needs to be sign extended.
1924
1925 // Remember the original type of the instruction before promotion.
1926 // This is useful to know that the high bits are sign extended bits.
1927 PromotedInsts.insert(
1928 std::pair<Instruction *, Type *>(SExtOpnd, SExtOpnd->getType()));
1929 // Step #1.
1930 TPT.mutateType(SExtOpnd, SExt->getType());
1931 // Step #2.
1932 TPT.replaceAllUsesWith(SExt, SExtOpnd);
1933 // Step #3.
1934 Instruction *SExtForOpnd = SExt;
1935
1936 DEBUG(dbgs() << "Propagate SExt to operands\n");
1937 for (int OpIdx = 0, EndOpIdx = SExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
1938 ++OpIdx) {
1939 DEBUG(dbgs() << "Operand:\n" << *(SExtOpnd->getOperand(OpIdx)) << '\n');
1940 if (SExtOpnd->getOperand(OpIdx)->getType() == SExt->getType() ||
1941 !shouldSExtOperand(SExtOpnd, OpIdx)) {
1942 DEBUG(dbgs() << "No need to propagate\n");
1943 continue;
1944 }
1945 // Check if we can statically sign extend the operand.
1946 Value *Opnd = SExtOpnd->getOperand(OpIdx);
1947 if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
1948 DEBUG(dbgs() << "Statically sign extend\n");
1949 TPT.setOperand(
1950 SExtOpnd, OpIdx,
1951 ConstantInt::getSigned(SExt->getType(), Cst->getSExtValue()));
1952 continue;
1953 }
1954 // UndefValue are typed, so we have to statically sign extend them.
1955 if (isa<UndefValue>(Opnd)) {
1956 DEBUG(dbgs() << "Statically sign extend\n");
1957 TPT.setOperand(SExtOpnd, OpIdx, UndefValue::get(SExt->getType()));
1958 continue;
1959 }
1960
1961 // Otherwise we have to explicity sign extend the operand.
1962 // Check if SExt was reused to sign extend an operand.
1963 if (!SExtForOpnd) {
1964 // If yes, create a new one.
1965 DEBUG(dbgs() << "More operands to sext\n");
1966 SExtForOpnd = TPT.createSExt(SExt, Opnd, SExt->getType());
1967 ++CreatedInsts;
1968 }
1969
1970 TPT.setOperand(SExtForOpnd, 0, Opnd);
1971
1972 // Move the sign extension before the insertion point.
1973 TPT.moveBefore(SExtForOpnd, SExtOpnd);
1974 TPT.setOperand(SExtOpnd, OpIdx, SExtForOpnd);
1975 // If more sext are required, new instructions will have to be created.
Craig Topperc0196b12014-04-14 00:51:57 +00001976 SExtForOpnd = nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001977 }
1978 if (SExtForOpnd == SExt) {
1979 DEBUG(dbgs() << "Sign extension is useless now\n");
1980 TPT.eraseInstruction(SExt);
1981 }
1982 return SExtOpnd;
1983}
1984
Quentin Colombet867c5502014-02-14 22:23:22 +00001985/// IsPromotionProfitable - Check whether or not promoting an instruction
1986/// to a wider type was profitable.
1987/// \p MatchedSize gives the number of instructions that have been matched
1988/// in the addressing mode after the promotion was applied.
1989/// \p SizeWithPromotion gives the number of created instructions for
1990/// the promotion plus the number of instructions that have been
1991/// matched in the addressing mode before the promotion.
1992/// \p PromotedOperand is the value that has been promoted.
1993/// \return True if the promotion is profitable, false otherwise.
1994bool
1995AddressingModeMatcher::IsPromotionProfitable(unsigned MatchedSize,
1996 unsigned SizeWithPromotion,
1997 Value *PromotedOperand) const {
1998 // We folded less instructions than what we created to promote the operand.
1999 // This is not profitable.
2000 if (MatchedSize < SizeWithPromotion)
2001 return false;
2002 if (MatchedSize > SizeWithPromotion)
2003 return true;
2004 // The promotion is neutral but it may help folding the sign extension in
2005 // loads for instance.
2006 // Check that we did not create an illegal instruction.
2007 Instruction *PromotedInst = dyn_cast<Instruction>(PromotedOperand);
2008 if (!PromotedInst)
2009 return false;
Quentin Colombet1627a412014-02-22 01:06:41 +00002010 int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode());
2011 // If the ISDOpcode is undefined, it was undefined before the promotion.
2012 if (!ISDOpcode)
2013 return true;
2014 // Otherwise, check if the promoted instruction is legal or not.
2015 return TLI.isOperationLegalOrCustom(ISDOpcode,
Quentin Colombet867c5502014-02-14 22:23:22 +00002016 EVT::getEVT(PromotedInst->getType()));
2017}
2018
Chandler Carruthc8925912013-01-05 02:09:22 +00002019/// MatchOperationAddr - Given an instruction or constant expr, see if we can
2020/// fold the operation into the addressing mode. If so, update the addressing
2021/// mode and return true, otherwise return false without modifying AddrMode.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002022/// If \p MovedAway is not NULL, it contains the information of whether or
2023/// not AddrInst has to be folded into the addressing mode on success.
2024/// If \p MovedAway == true, \p AddrInst will not be part of the addressing
2025/// because it has been moved away.
2026/// Thus AddrInst must not be added in the matched instructions.
2027/// This state can happen when AddrInst is a sext, since it may be moved away.
2028/// Therefore, AddrInst may not be valid when MovedAway is true and it must
2029/// not be referenced anymore.
Chandler Carruthc8925912013-01-05 02:09:22 +00002030bool AddressingModeMatcher::MatchOperationAddr(User *AddrInst, unsigned Opcode,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002031 unsigned Depth,
2032 bool *MovedAway) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002033 // Avoid exponential behavior on extremely deep expression trees.
2034 if (Depth >= 5) return false;
Stephen Lin837bba12013-07-15 17:55:02 +00002035
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002036 // By default, all matched instructions stay in place.
2037 if (MovedAway)
2038 *MovedAway = false;
2039
Chandler Carruthc8925912013-01-05 02:09:22 +00002040 switch (Opcode) {
2041 case Instruction::PtrToInt:
2042 // PtrToInt is always a noop, as we know that the int type is pointer sized.
2043 return MatchAddr(AddrInst->getOperand(0), Depth);
2044 case Instruction::IntToPtr:
2045 // This inttoptr is a no-op if the integer type is pointer sized.
2046 if (TLI.getValueType(AddrInst->getOperand(0)->getType()) ==
Matt Arsenault37d42ec2013-09-06 00:18:43 +00002047 TLI.getPointerTy(AddrInst->getType()->getPointerAddressSpace()))
Chandler Carruthc8925912013-01-05 02:09:22 +00002048 return MatchAddr(AddrInst->getOperand(0), Depth);
2049 return false;
2050 case Instruction::BitCast:
2051 // BitCast is always a noop, and we can handle it as long as it is
2052 // int->int or pointer->pointer (we don't want int<->fp or something).
2053 if ((AddrInst->getOperand(0)->getType()->isPointerTy() ||
2054 AddrInst->getOperand(0)->getType()->isIntegerTy()) &&
2055 // Don't touch identity bitcasts. These were probably put here by LSR,
2056 // and we don't want to mess around with them. Assume it knows what it
2057 // is doing.
2058 AddrInst->getOperand(0)->getType() != AddrInst->getType())
2059 return MatchAddr(AddrInst->getOperand(0), Depth);
2060 return false;
2061 case Instruction::Add: {
2062 // Check to see if we can merge in the RHS then the LHS. If so, we win.
2063 ExtAddrMode BackupAddrMode = AddrMode;
2064 unsigned OldSize = AddrModeInsts.size();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002065 // Start a transaction at this point.
2066 // The LHS may match but not the RHS.
2067 // Therefore, we need a higher level restoration point to undo partially
2068 // matched operation.
2069 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2070 TPT.getRestorationPoint();
2071
Chandler Carruthc8925912013-01-05 02:09:22 +00002072 if (MatchAddr(AddrInst->getOperand(1), Depth+1) &&
2073 MatchAddr(AddrInst->getOperand(0), Depth+1))
2074 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002075
Chandler Carruthc8925912013-01-05 02:09:22 +00002076 // Restore the old addr mode info.
2077 AddrMode = BackupAddrMode;
2078 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002079 TPT.rollback(LastKnownGood);
Stephen Lin837bba12013-07-15 17:55:02 +00002080
Chandler Carruthc8925912013-01-05 02:09:22 +00002081 // Otherwise this was over-aggressive. Try merging in the LHS then the RHS.
2082 if (MatchAddr(AddrInst->getOperand(0), Depth+1) &&
2083 MatchAddr(AddrInst->getOperand(1), Depth+1))
2084 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002085
Chandler Carruthc8925912013-01-05 02:09:22 +00002086 // Otherwise we definitely can't merge the ADD in.
2087 AddrMode = BackupAddrMode;
2088 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002089 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00002090 break;
2091 }
2092 //case Instruction::Or:
2093 // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
2094 //break;
2095 case Instruction::Mul:
2096 case Instruction::Shl: {
2097 // Can only handle X*C and X << C.
2098 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
2099 if (!RHS) return false;
2100 int64_t Scale = RHS->getSExtValue();
2101 if (Opcode == Instruction::Shl)
2102 Scale = 1LL << Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00002103
Chandler Carruthc8925912013-01-05 02:09:22 +00002104 return MatchScaledValue(AddrInst->getOperand(0), Scale, Depth);
2105 }
2106 case Instruction::GetElementPtr: {
2107 // Scan the GEP. We check it if it contains constant offsets and at most
2108 // one variable offset.
2109 int VariableOperand = -1;
2110 unsigned VariableScale = 0;
Stephen Lin837bba12013-07-15 17:55:02 +00002111
Chandler Carruthc8925912013-01-05 02:09:22 +00002112 int64_t ConstantOffset = 0;
2113 const DataLayout *TD = TLI.getDataLayout();
2114 gep_type_iterator GTI = gep_type_begin(AddrInst);
2115 for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
2116 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
2117 const StructLayout *SL = TD->getStructLayout(STy);
2118 unsigned Idx =
2119 cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
2120 ConstantOffset += SL->getElementOffset(Idx);
2121 } else {
2122 uint64_t TypeSize = TD->getTypeAllocSize(GTI.getIndexedType());
2123 if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
2124 ConstantOffset += CI->getSExtValue()*TypeSize;
2125 } else if (TypeSize) { // Scales of zero don't do anything.
2126 // We only allow one variable index at the moment.
2127 if (VariableOperand != -1)
2128 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00002129
Chandler Carruthc8925912013-01-05 02:09:22 +00002130 // Remember the variable index.
2131 VariableOperand = i;
2132 VariableScale = TypeSize;
2133 }
2134 }
2135 }
Stephen Lin837bba12013-07-15 17:55:02 +00002136
Chandler Carruthc8925912013-01-05 02:09:22 +00002137 // A common case is for the GEP to only do a constant offset. In this case,
2138 // just add it to the disp field and check validity.
2139 if (VariableOperand == -1) {
2140 AddrMode.BaseOffs += ConstantOffset;
2141 if (ConstantOffset == 0 || TLI.isLegalAddressingMode(AddrMode, AccessTy)){
2142 // Check to see if we can fold the base pointer in too.
2143 if (MatchAddr(AddrInst->getOperand(0), Depth+1))
2144 return true;
2145 }
2146 AddrMode.BaseOffs -= ConstantOffset;
2147 return false;
2148 }
2149
2150 // Save the valid addressing mode in case we can't match.
2151 ExtAddrMode BackupAddrMode = AddrMode;
2152 unsigned OldSize = AddrModeInsts.size();
2153
2154 // See if the scale and offset amount is valid for this target.
2155 AddrMode.BaseOffs += ConstantOffset;
2156
2157 // Match the base operand of the GEP.
2158 if (!MatchAddr(AddrInst->getOperand(0), Depth+1)) {
2159 // If it couldn't be matched, just stuff the value in a register.
2160 if (AddrMode.HasBaseReg) {
2161 AddrMode = BackupAddrMode;
2162 AddrModeInsts.resize(OldSize);
2163 return false;
2164 }
2165 AddrMode.HasBaseReg = true;
2166 AddrMode.BaseReg = AddrInst->getOperand(0);
2167 }
2168
2169 // Match the remaining variable portion of the GEP.
2170 if (!MatchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
2171 Depth)) {
2172 // If it couldn't be matched, try stuffing the base into a register
2173 // instead of matching it, and retrying the match of the scale.
2174 AddrMode = BackupAddrMode;
2175 AddrModeInsts.resize(OldSize);
2176 if (AddrMode.HasBaseReg)
2177 return false;
2178 AddrMode.HasBaseReg = true;
2179 AddrMode.BaseReg = AddrInst->getOperand(0);
2180 AddrMode.BaseOffs += ConstantOffset;
2181 if (!MatchScaledValue(AddrInst->getOperand(VariableOperand),
2182 VariableScale, Depth)) {
2183 // If even that didn't work, bail.
2184 AddrMode = BackupAddrMode;
2185 AddrModeInsts.resize(OldSize);
2186 return false;
2187 }
2188 }
2189
2190 return true;
2191 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002192 case Instruction::SExt: {
2193 // Try to move this sext out of the way of the addressing mode.
2194 Instruction *SExt = cast<Instruction>(AddrInst);
2195 // Ask for a method for doing so.
2196 TypePromotionHelper::Action TPH = TypePromotionHelper::getAction(
2197 SExt, InsertedTruncs, TLI, PromotedInsts);
2198 if (!TPH)
2199 return false;
2200
2201 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2202 TPT.getRestorationPoint();
2203 unsigned CreatedInsts = 0;
2204 Value *PromotedOperand = TPH(SExt, TPT, PromotedInsts, CreatedInsts);
2205 // SExt has been moved away.
2206 // Thus either it will be rematched later in the recursive calls or it is
2207 // gone. Anyway, we must not fold it into the addressing mode at this point.
2208 // E.g.,
2209 // op = add opnd, 1
2210 // idx = sext op
2211 // addr = gep base, idx
2212 // is now:
2213 // promotedOpnd = sext opnd <- no match here
2214 // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls)
2215 // addr = gep base, op <- match
2216 if (MovedAway)
2217 *MovedAway = true;
2218
2219 assert(PromotedOperand &&
2220 "TypePromotionHelper should have filtered out those cases");
2221
2222 ExtAddrMode BackupAddrMode = AddrMode;
2223 unsigned OldSize = AddrModeInsts.size();
2224
2225 if (!MatchAddr(PromotedOperand, Depth) ||
Quentin Colombet867c5502014-02-14 22:23:22 +00002226 !IsPromotionProfitable(AddrModeInsts.size(), OldSize + CreatedInsts,
2227 PromotedOperand)) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002228 AddrMode = BackupAddrMode;
2229 AddrModeInsts.resize(OldSize);
2230 DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
2231 TPT.rollback(LastKnownGood);
2232 return false;
2233 }
2234 return true;
2235 }
Chandler Carruthc8925912013-01-05 02:09:22 +00002236 }
2237 return false;
2238}
2239
2240/// MatchAddr - If we can, try to add the value of 'Addr' into the current
2241/// addressing mode. If Addr can't be added to AddrMode this returns false and
2242/// leaves AddrMode unmodified. This assumes that Addr is either a pointer type
2243/// or intptr_t for the target.
2244///
2245bool AddressingModeMatcher::MatchAddr(Value *Addr, unsigned Depth) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002246 // Start a transaction at this point that we will rollback if the matching
2247 // fails.
2248 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2249 TPT.getRestorationPoint();
Chandler Carruthc8925912013-01-05 02:09:22 +00002250 if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
2251 // Fold in immediates if legal for the target.
2252 AddrMode.BaseOffs += CI->getSExtValue();
2253 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2254 return true;
2255 AddrMode.BaseOffs -= CI->getSExtValue();
2256 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
2257 // If this is a global variable, try to fold it into the addressing mode.
Craig Topperc0196b12014-04-14 00:51:57 +00002258 if (!AddrMode.BaseGV) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002259 AddrMode.BaseGV = GV;
2260 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2261 return true;
Craig Topperc0196b12014-04-14 00:51:57 +00002262 AddrMode.BaseGV = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00002263 }
2264 } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
2265 ExtAddrMode BackupAddrMode = AddrMode;
2266 unsigned OldSize = AddrModeInsts.size();
2267
2268 // Check to see if it is possible to fold this operation.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002269 bool MovedAway = false;
2270 if (MatchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
2271 // This instruction may have been move away. If so, there is nothing
2272 // to check here.
2273 if (MovedAway)
2274 return true;
Chandler Carruthc8925912013-01-05 02:09:22 +00002275 // Okay, it's possible to fold this. Check to see if it is actually
2276 // *profitable* to do so. We use a simple cost model to avoid increasing
2277 // register pressure too much.
2278 if (I->hasOneUse() ||
2279 IsProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
2280 AddrModeInsts.push_back(I);
2281 return true;
2282 }
Stephen Lin837bba12013-07-15 17:55:02 +00002283
Chandler Carruthc8925912013-01-05 02:09:22 +00002284 // It isn't profitable to do this, roll back.
2285 //cerr << "NOT FOLDING: " << *I;
2286 AddrMode = BackupAddrMode;
2287 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002288 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00002289 }
2290 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
2291 if (MatchOperationAddr(CE, CE->getOpcode(), Depth))
2292 return true;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002293 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00002294 } else if (isa<ConstantPointerNull>(Addr)) {
2295 // Null pointer gets folded without affecting the addressing mode.
2296 return true;
2297 }
2298
2299 // Worse case, the target should support [reg] addressing modes. :)
2300 if (!AddrMode.HasBaseReg) {
2301 AddrMode.HasBaseReg = true;
2302 AddrMode.BaseReg = Addr;
2303 // Still check for legality in case the target supports [imm] but not [i+r].
2304 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2305 return true;
2306 AddrMode.HasBaseReg = false;
Craig Topperc0196b12014-04-14 00:51:57 +00002307 AddrMode.BaseReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00002308 }
2309
2310 // If the base register is already taken, see if we can do [r+r].
2311 if (AddrMode.Scale == 0) {
2312 AddrMode.Scale = 1;
2313 AddrMode.ScaledReg = Addr;
2314 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2315 return true;
2316 AddrMode.Scale = 0;
Craig Topperc0196b12014-04-14 00:51:57 +00002317 AddrMode.ScaledReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00002318 }
2319 // Couldn't match.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002320 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00002321 return false;
2322}
2323
2324/// IsOperandAMemoryOperand - Check to see if all uses of OpVal by the specified
2325/// inline asm call are due to memory operands. If so, return true, otherwise
2326/// return false.
2327static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
2328 const TargetLowering &TLI) {
2329 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(ImmutableCallSite(CI));
2330 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
2331 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Stephen Lin837bba12013-07-15 17:55:02 +00002332
Chandler Carruthc8925912013-01-05 02:09:22 +00002333 // Compute the constraint code and ConstraintType to use.
2334 TLI.ComputeConstraintToUse(OpInfo, SDValue());
2335
2336 // If this asm operand is our Value*, and if it isn't an indirect memory
2337 // operand, we can't fold it!
2338 if (OpInfo.CallOperandVal == OpVal &&
2339 (OpInfo.ConstraintType != TargetLowering::C_Memory ||
2340 !OpInfo.isIndirect))
2341 return false;
2342 }
2343
2344 return true;
2345}
2346
2347/// FindAllMemoryUses - Recursively walk all the uses of I until we find a
2348/// memory use. If we find an obviously non-foldable instruction, return true.
2349/// Add the ultimately found memory instructions to MemoryUses.
2350static bool FindAllMemoryUses(Instruction *I,
2351 SmallVectorImpl<std::pair<Instruction*,unsigned> > &MemoryUses,
2352 SmallPtrSet<Instruction*, 16> &ConsideredInsts,
2353 const TargetLowering &TLI) {
2354 // If we already considered this instruction, we're done.
2355 if (!ConsideredInsts.insert(I))
2356 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00002357
Chandler Carruthc8925912013-01-05 02:09:22 +00002358 // If this is an obviously unfoldable instruction, bail out.
2359 if (!MightBeFoldableInst(I))
2360 return true;
2361
2362 // Loop over all the uses, recursively processing them.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002363 for (Use &U : I->uses()) {
2364 Instruction *UserI = cast<Instruction>(U.getUser());
Chandler Carruthc8925912013-01-05 02:09:22 +00002365
Chandler Carruthcdf47882014-03-09 03:16:01 +00002366 if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
2367 MemoryUses.push_back(std::make_pair(LI, U.getOperandNo()));
Chandler Carruthc8925912013-01-05 02:09:22 +00002368 continue;
2369 }
Stephen Lin837bba12013-07-15 17:55:02 +00002370
Chandler Carruthcdf47882014-03-09 03:16:01 +00002371 if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
2372 unsigned opNo = U.getOperandNo();
Chandler Carruthc8925912013-01-05 02:09:22 +00002373 if (opNo == 0) return true; // Storing addr, not into addr.
2374 MemoryUses.push_back(std::make_pair(SI, opNo));
2375 continue;
2376 }
Stephen Lin837bba12013-07-15 17:55:02 +00002377
Chandler Carruthcdf47882014-03-09 03:16:01 +00002378 if (CallInst *CI = dyn_cast<CallInst>(UserI)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002379 InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
2380 if (!IA) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002381
Chandler Carruthc8925912013-01-05 02:09:22 +00002382 // If this is a memory operand, we're cool, otherwise bail out.
2383 if (!IsOperandAMemoryOperand(CI, IA, I, TLI))
2384 return true;
2385 continue;
2386 }
Stephen Lin837bba12013-07-15 17:55:02 +00002387
Chandler Carruthcdf47882014-03-09 03:16:01 +00002388 if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TLI))
Chandler Carruthc8925912013-01-05 02:09:22 +00002389 return true;
2390 }
2391
2392 return false;
2393}
2394
2395/// ValueAlreadyLiveAtInst - Retrn true if Val is already known to be live at
2396/// the use site that we're folding it into. If so, there is no cost to
2397/// include it in the addressing mode. KnownLive1 and KnownLive2 are two values
2398/// that we know are live at the instruction already.
2399bool AddressingModeMatcher::ValueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
2400 Value *KnownLive2) {
2401 // If Val is either of the known-live values, we know it is live!
Craig Topperc0196b12014-04-14 00:51:57 +00002402 if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2)
Chandler Carruthc8925912013-01-05 02:09:22 +00002403 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002404
Chandler Carruthc8925912013-01-05 02:09:22 +00002405 // All values other than instructions and arguments (e.g. constants) are live.
2406 if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002407
Chandler Carruthc8925912013-01-05 02:09:22 +00002408 // If Val is a constant sized alloca in the entry block, it is live, this is
2409 // true because it is just a reference to the stack/frame pointer, which is
2410 // live for the whole function.
2411 if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
2412 if (AI->isStaticAlloca())
2413 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002414
Chandler Carruthc8925912013-01-05 02:09:22 +00002415 // Check to see if this value is already used in the memory instruction's
2416 // block. If so, it's already live into the block at the very least, so we
2417 // can reasonably fold it.
2418 return Val->isUsedInBasicBlock(MemoryInst->getParent());
2419}
2420
2421/// IsProfitableToFoldIntoAddressingMode - It is possible for the addressing
2422/// mode of the machine to fold the specified instruction into a load or store
2423/// that ultimately uses it. However, the specified instruction has multiple
2424/// uses. Given this, it may actually increase register pressure to fold it
2425/// into the load. For example, consider this code:
2426///
2427/// X = ...
2428/// Y = X+1
2429/// use(Y) -> nonload/store
2430/// Z = Y+1
2431/// load Z
2432///
2433/// In this case, Y has multiple uses, and can be folded into the load of Z
2434/// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to
2435/// be live at the use(Y) line. If we don't fold Y into load Z, we use one
2436/// fewer register. Since Y can't be folded into "use(Y)" we don't increase the
2437/// number of computations either.
2438///
2439/// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If
2440/// X was live across 'load Z' for other reasons, we actually *would* want to
2441/// fold the addressing mode in the Z case. This would make Y die earlier.
2442bool AddressingModeMatcher::
2443IsProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
2444 ExtAddrMode &AMAfter) {
2445 if (IgnoreProfitability) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002446
Chandler Carruthc8925912013-01-05 02:09:22 +00002447 // AMBefore is the addressing mode before this instruction was folded into it,
2448 // and AMAfter is the addressing mode after the instruction was folded. Get
2449 // the set of registers referenced by AMAfter and subtract out those
2450 // referenced by AMBefore: this is the set of values which folding in this
2451 // address extends the lifetime of.
2452 //
2453 // Note that there are only two potential values being referenced here,
2454 // BaseReg and ScaleReg (global addresses are always available, as are any
2455 // folded immediates).
2456 Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
Stephen Lin837bba12013-07-15 17:55:02 +00002457
Chandler Carruthc8925912013-01-05 02:09:22 +00002458 // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
2459 // lifetime wasn't extended by adding this instruction.
2460 if (ValueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
Craig Topperc0196b12014-04-14 00:51:57 +00002461 BaseReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00002462 if (ValueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
Craig Topperc0196b12014-04-14 00:51:57 +00002463 ScaledReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00002464
2465 // If folding this instruction (and it's subexprs) didn't extend any live
2466 // ranges, we're ok with it.
Craig Topperc0196b12014-04-14 00:51:57 +00002467 if (!BaseReg && !ScaledReg)
Chandler Carruthc8925912013-01-05 02:09:22 +00002468 return true;
2469
2470 // If all uses of this instruction are ultimately load/store/inlineasm's,
2471 // check to see if their addressing modes will include this instruction. If
2472 // so, we can fold it into all uses, so it doesn't matter if it has multiple
2473 // uses.
2474 SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
2475 SmallPtrSet<Instruction*, 16> ConsideredInsts;
2476 if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TLI))
2477 return false; // Has a non-memory, non-foldable use!
Stephen Lin837bba12013-07-15 17:55:02 +00002478
Chandler Carruthc8925912013-01-05 02:09:22 +00002479 // Now that we know that all uses of this instruction are part of a chain of
2480 // computation involving only operations that could theoretically be folded
2481 // into a memory use, loop over each of these uses and see if they could
2482 // *actually* fold the instruction.
2483 SmallVector<Instruction*, 32> MatchedAddrModeInsts;
2484 for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
2485 Instruction *User = MemoryUses[i].first;
2486 unsigned OpNo = MemoryUses[i].second;
Stephen Lin837bba12013-07-15 17:55:02 +00002487
Chandler Carruthc8925912013-01-05 02:09:22 +00002488 // Get the access type of this use. If the use isn't a pointer, we don't
2489 // know what it accesses.
2490 Value *Address = User->getOperand(OpNo);
2491 if (!Address->getType()->isPointerTy())
2492 return false;
Matt Arsenault8227b9f2013-09-06 00:37:24 +00002493 Type *AddressAccessTy = Address->getType()->getPointerElementType();
Stephen Lin837bba12013-07-15 17:55:02 +00002494
Chandler Carruthc8925912013-01-05 02:09:22 +00002495 // Do a match against the root of this address, ignoring profitability. This
2496 // will tell us if the addressing mode for the memory operation will
2497 // *actually* cover the shared instruction.
2498 ExtAddrMode Result;
Quentin Colombet5a69dda2014-02-11 01:59:02 +00002499 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2500 TPT.getRestorationPoint();
Chandler Carruthc8925912013-01-05 02:09:22 +00002501 AddressingModeMatcher Matcher(MatchedAddrModeInsts, TLI, AddressAccessTy,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002502 MemoryInst, Result, InsertedTruncs,
2503 PromotedInsts, TPT);
Chandler Carruthc8925912013-01-05 02:09:22 +00002504 Matcher.IgnoreProfitability = true;
2505 bool Success = Matcher.MatchAddr(Address, 0);
2506 (void)Success; assert(Success && "Couldn't select *anything*?");
2507
Quentin Colombet5a69dda2014-02-11 01:59:02 +00002508 // The match was to check the profitability, the changes made are not
2509 // part of the original matcher. Therefore, they should be dropped
2510 // otherwise the original matcher will not present the right state.
2511 TPT.rollback(LastKnownGood);
2512
Chandler Carruthc8925912013-01-05 02:09:22 +00002513 // If the match didn't cover I, then it won't be shared by it.
2514 if (std::find(MatchedAddrModeInsts.begin(), MatchedAddrModeInsts.end(),
2515 I) == MatchedAddrModeInsts.end())
2516 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00002517
Chandler Carruthc8925912013-01-05 02:09:22 +00002518 MatchedAddrModeInsts.clear();
2519 }
Stephen Lin837bba12013-07-15 17:55:02 +00002520
Chandler Carruthc8925912013-01-05 02:09:22 +00002521 return true;
2522}
2523
2524} // end anonymous namespace
2525
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002526/// IsNonLocalValue - Return true if the specified values are defined in a
2527/// different basic block than BB.
2528static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
2529 if (Instruction *I = dyn_cast<Instruction>(V))
2530 return I->getParent() != BB;
2531 return false;
2532}
2533
Bob Wilson53bdae32009-12-03 21:47:07 +00002534/// OptimizeMemoryInst - Load and Store Instructions often have
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002535/// addressing modes that can do significant amounts of computation. As such,
2536/// instruction selection will try to get the load or store to do as much
2537/// computation as possible for the program. The problem is that isel can only
2538/// see within a single block. As such, we sink as much legal addressing mode
2539/// stuff into the block as possible.
Chris Lattner728f9022008-11-25 07:09:13 +00002540///
2541/// This method is used to optimize both load/store and inline asms with memory
2542/// operands.
Chris Lattner6d71b7f2008-11-26 03:20:37 +00002543bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
Chris Lattner229907c2011-07-18 04:54:35 +00002544 Type *AccessTy) {
Owen Anderson8ba5f392010-11-27 08:15:55 +00002545 Value *Repl = Addr;
Nadav Rotem465834c2012-07-24 10:51:42 +00002546
2547 // Try to collapse single-value PHI nodes. This is necessary to undo
Owen Andersondfb8c3b2010-11-19 22:15:03 +00002548 // unprofitable PRE transformations.
Cameron Zwarich43cecb12011-01-03 06:33:01 +00002549 SmallVector<Value*, 8> worklist;
2550 SmallPtrSet<Value*, 16> Visited;
Owen Anderson8ba5f392010-11-27 08:15:55 +00002551 worklist.push_back(Addr);
Nadav Rotem465834c2012-07-24 10:51:42 +00002552
Owen Anderson8ba5f392010-11-27 08:15:55 +00002553 // Use a worklist to iteratively look through PHI nodes, and ensure that
2554 // the addressing mode obtained from the non-PHI roots of the graph
2555 // are equivalent.
Craig Topperc0196b12014-04-14 00:51:57 +00002556 Value *Consensus = nullptr;
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00002557 unsigned NumUsesConsensus = 0;
Cameron Zwarich13c885d2011-03-05 08:12:26 +00002558 bool IsNumUsesConsensusValid = false;
Owen Anderson8ba5f392010-11-27 08:15:55 +00002559 SmallVector<Instruction*, 16> AddrModeInsts;
2560 ExtAddrMode AddrMode;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002561 TypePromotionTransaction TPT;
2562 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2563 TPT.getRestorationPoint();
Owen Anderson8ba5f392010-11-27 08:15:55 +00002564 while (!worklist.empty()) {
2565 Value *V = worklist.back();
2566 worklist.pop_back();
Nadav Rotem465834c2012-07-24 10:51:42 +00002567
Owen Anderson8ba5f392010-11-27 08:15:55 +00002568 // Break use-def graph loops.
Nick Lewyckya3e7ffd2011-09-29 23:40:12 +00002569 if (!Visited.insert(V)) {
Craig Topperc0196b12014-04-14 00:51:57 +00002570 Consensus = nullptr;
Owen Anderson8ba5f392010-11-27 08:15:55 +00002571 break;
Owen Andersondfb8c3b2010-11-19 22:15:03 +00002572 }
Nadav Rotem465834c2012-07-24 10:51:42 +00002573
Owen Anderson8ba5f392010-11-27 08:15:55 +00002574 // For a PHI node, push all of its incoming values.
2575 if (PHINode *P = dyn_cast<PHINode>(V)) {
2576 for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i)
2577 worklist.push_back(P->getIncomingValue(i));
2578 continue;
2579 }
Nadav Rotem465834c2012-07-24 10:51:42 +00002580
Owen Anderson8ba5f392010-11-27 08:15:55 +00002581 // For non-PHIs, determine the addressing mode being computed.
2582 SmallVector<Instruction*, 16> NewAddrModeInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002583 ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
2584 V, AccessTy, MemoryInst, NewAddrModeInsts, *TLI, InsertedTruncsSet,
2585 PromotedInsts, TPT);
Cameron Zwarich13c885d2011-03-05 08:12:26 +00002586
2587 // This check is broken into two cases with very similar code to avoid using
2588 // getNumUses() as much as possible. Some values have a lot of uses, so
2589 // calling getNumUses() unconditionally caused a significant compile-time
2590 // regression.
2591 if (!Consensus) {
2592 Consensus = V;
2593 AddrMode = NewAddrMode;
2594 AddrModeInsts = NewAddrModeInsts;
2595 continue;
2596 } else if (NewAddrMode == AddrMode) {
2597 if (!IsNumUsesConsensusValid) {
2598 NumUsesConsensus = Consensus->getNumUses();
2599 IsNumUsesConsensusValid = true;
2600 }
2601
2602 // Ensure that the obtained addressing mode is equivalent to that obtained
2603 // for all other roots of the PHI traversal. Also, when choosing one
2604 // such root as representative, select the one with the most uses in order
2605 // to keep the cost modeling heuristics in AddressingModeMatcher
2606 // applicable.
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00002607 unsigned NumUses = V->getNumUses();
2608 if (NumUses > NumUsesConsensus) {
Owen Anderson8ba5f392010-11-27 08:15:55 +00002609 Consensus = V;
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00002610 NumUsesConsensus = NumUses;
Owen Anderson8ba5f392010-11-27 08:15:55 +00002611 AddrModeInsts = NewAddrModeInsts;
2612 }
2613 continue;
2614 }
Nadav Rotem465834c2012-07-24 10:51:42 +00002615
Craig Topperc0196b12014-04-14 00:51:57 +00002616 Consensus = nullptr;
Owen Anderson8ba5f392010-11-27 08:15:55 +00002617 break;
Owen Andersondfb8c3b2010-11-19 22:15:03 +00002618 }
Nadav Rotem465834c2012-07-24 10:51:42 +00002619
Owen Anderson8ba5f392010-11-27 08:15:55 +00002620 // If the addressing mode couldn't be determined, or if multiple different
2621 // ones were determined, bail out now.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002622 if (!Consensus) {
2623 TPT.rollback(LastKnownGood);
2624 return false;
2625 }
2626 TPT.commit();
Nadav Rotem465834c2012-07-24 10:51:42 +00002627
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002628 // Check to see if any of the instructions supersumed by this addr mode are
2629 // non-local to I's BB.
2630 bool AnyNonLocal = false;
2631 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
Chris Lattner6d71b7f2008-11-26 03:20:37 +00002632 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002633 AnyNonLocal = true;
2634 break;
2635 }
2636 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00002637
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002638 // If all the instructions matched are already in this BB, don't do anything.
2639 if (!AnyNonLocal) {
David Greene74e2d492010-01-05 01:27:11 +00002640 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002641 return false;
2642 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00002643
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002644 // Insert this computation right after this user. Since our caller is
2645 // scanning from the top of the BB to the bottom, reuse of the expr are
2646 // guaranteed to happen later.
Devang Patelc10e52a2011-09-06 18:49:53 +00002647 IRBuilder<> Builder(MemoryInst);
Eric Christopherc1ea1492008-09-24 05:32:41 +00002648
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002649 // Now that we determined the addressing expression we want to use and know
2650 // that we have to sink it into this block. Check to see if we have already
2651 // done this for some other load/store instr in this block. If so, reuse the
2652 // computation.
2653 Value *&SunkAddr = SunkAddrs[Addr];
2654 if (SunkAddr) {
David Greene74e2d492010-01-05 01:27:11 +00002655 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
Dan Gohman29f2baf2009-07-25 01:13:51 +00002656 << *MemoryInst);
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002657 if (SunkAddr->getType() != Addr->getType())
Benjamin Kramer547b6c52011-09-27 20:39:19 +00002658 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
Hal Finkelc3998302014-04-12 00:59:48 +00002659 } else if (AddrSinkUsingGEPs || (!AddrSinkUsingGEPs.getNumOccurrences() &&
2660 TM && TM->getSubtarget<TargetSubtargetInfo>().useAA())) {
2661 // By default, we use the GEP-based method when AA is used later. This
2662 // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities.
2663 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
2664 << *MemoryInst);
2665 Type *IntPtrTy = TLI->getDataLayout()->getIntPtrType(Addr->getType());
Craig Topperc0196b12014-04-14 00:51:57 +00002666 Value *ResultPtr = nullptr, *ResultIndex = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00002667
2668 // First, find the pointer.
2669 if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) {
2670 ResultPtr = AddrMode.BaseReg;
Craig Topperc0196b12014-04-14 00:51:57 +00002671 AddrMode.BaseReg = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00002672 }
2673
2674 if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) {
2675 // We can't add more than one pointer together, nor can we scale a
2676 // pointer (both of which seem meaningless).
2677 if (ResultPtr || AddrMode.Scale != 1)
2678 return false;
2679
2680 ResultPtr = AddrMode.ScaledReg;
2681 AddrMode.Scale = 0;
2682 }
2683
2684 if (AddrMode.BaseGV) {
2685 if (ResultPtr)
2686 return false;
2687
2688 ResultPtr = AddrMode.BaseGV;
2689 }
2690
2691 // If the real base value actually came from an inttoptr, then the matcher
2692 // will look through it and provide only the integer value. In that case,
2693 // use it here.
2694 if (!ResultPtr && AddrMode.BaseReg) {
2695 ResultPtr =
2696 Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(), "sunkaddr");
Craig Topperc0196b12014-04-14 00:51:57 +00002697 AddrMode.BaseReg = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00002698 } else if (!ResultPtr && AddrMode.Scale == 1) {
2699 ResultPtr =
2700 Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(), "sunkaddr");
2701 AddrMode.Scale = 0;
2702 }
2703
2704 if (!ResultPtr &&
2705 !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) {
2706 SunkAddr = Constant::getNullValue(Addr->getType());
2707 } else if (!ResultPtr) {
2708 return false;
2709 } else {
2710 Type *I8PtrTy =
2711 Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace());
2712
2713 // Start with the base register. Do this first so that subsequent address
2714 // matching finds it last, which will prevent it from trying to match it
2715 // as the scaled value in case it happens to be a mul. That would be
2716 // problematic if we've sunk a different mul for the scale, because then
2717 // we'd end up sinking both muls.
2718 if (AddrMode.BaseReg) {
2719 Value *V = AddrMode.BaseReg;
2720 if (V->getType() != IntPtrTy)
2721 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
2722
2723 ResultIndex = V;
2724 }
2725
2726 // Add the scale value.
2727 if (AddrMode.Scale) {
2728 Value *V = AddrMode.ScaledReg;
2729 if (V->getType() == IntPtrTy) {
2730 // done.
2731 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
2732 cast<IntegerType>(V->getType())->getBitWidth()) {
2733 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
2734 } else {
2735 // It is only safe to sign extend the BaseReg if we know that the math
2736 // required to create it did not overflow before we extend it. Since
2737 // the original IR value was tossed in favor of a constant back when
2738 // the AddrMode was created we need to bail out gracefully if widths
2739 // do not match instead of extending it.
2740 Instruction *I = dyn_cast_or_null<Instruction>(ResultIndex);
2741 if (I && (ResultIndex != AddrMode.BaseReg))
2742 I->eraseFromParent();
2743 return false;
2744 }
2745
2746 if (AddrMode.Scale != 1)
2747 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
2748 "sunkaddr");
2749 if (ResultIndex)
2750 ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr");
2751 else
2752 ResultIndex = V;
2753 }
2754
2755 // Add in the Base Offset if present.
2756 if (AddrMode.BaseOffs) {
2757 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
2758 if (ResultIndex) {
2759 // We need to add this separately from the scale above to help with
2760 // SDAG consecutive load/store merging.
2761 if (ResultPtr->getType() != I8PtrTy)
2762 ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
2763 ResultPtr = Builder.CreateGEP(ResultPtr, ResultIndex, "sunkaddr");
2764 }
2765
2766 ResultIndex = V;
2767 }
2768
2769 if (!ResultIndex) {
2770 SunkAddr = ResultPtr;
2771 } else {
2772 if (ResultPtr->getType() != I8PtrTy)
2773 ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
2774 SunkAddr = Builder.CreateGEP(ResultPtr, ResultIndex, "sunkaddr");
2775 }
2776
2777 if (SunkAddr->getType() != Addr->getType())
2778 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
2779 }
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002780 } else {
David Greene74e2d492010-01-05 01:27:11 +00002781 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Dan Gohman29f2baf2009-07-25 01:13:51 +00002782 << *MemoryInst);
Matt Arsenault37d42ec2013-09-06 00:18:43 +00002783 Type *IntPtrTy = TLI->getDataLayout()->getIntPtrType(Addr->getType());
Craig Topperc0196b12014-04-14 00:51:57 +00002784 Value *Result = nullptr;
Dan Gohmanca194452010-01-19 22:45:06 +00002785
2786 // Start with the base register. Do this first so that subsequent address
2787 // matching finds it last, which will prevent it from trying to match it
2788 // as the scaled value in case it happens to be a mul. That would be
2789 // problematic if we've sunk a different mul for the scale, because then
2790 // we'd end up sinking both muls.
2791 if (AddrMode.BaseReg) {
2792 Value *V = AddrMode.BaseReg;
Duncan Sands19d0b472010-02-16 11:11:14 +00002793 if (V->getType()->isPointerTy())
Devang Patelc10e52a2011-09-06 18:49:53 +00002794 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00002795 if (V->getType() != IntPtrTy)
Devang Patelc10e52a2011-09-06 18:49:53 +00002796 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00002797 Result = V;
2798 }
2799
2800 // Add the scale value.
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002801 if (AddrMode.Scale) {
2802 Value *V = AddrMode.ScaledReg;
2803 if (V->getType() == IntPtrTy) {
2804 // done.
Duncan Sands19d0b472010-02-16 11:11:14 +00002805 } else if (V->getType()->isPointerTy()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00002806 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002807 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
2808 cast<IntegerType>(V->getType())->getBitWidth()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00002809 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002810 } else {
Jim Grosbached2cd392014-03-26 17:27:01 +00002811 // It is only safe to sign extend the BaseReg if we know that the math
2812 // required to create it did not overflow before we extend it. Since
2813 // the original IR value was tossed in favor of a constant back when
2814 // the AddrMode was created we need to bail out gracefully if widths
2815 // do not match instead of extending it.
Jim Grosbach83b44e12014-04-10 00:27:45 +00002816 Instruction *I = dyn_cast<Instruction>(Result);
2817 if (I && (Result != AddrMode.BaseReg))
2818 I->eraseFromParent();
Jim Grosbached2cd392014-03-26 17:27:01 +00002819 return false;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002820 }
2821 if (AddrMode.Scale != 1)
Devang Patelc10e52a2011-09-06 18:49:53 +00002822 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
2823 "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002824 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00002825 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002826 else
2827 Result = V;
2828 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00002829
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002830 // Add in the BaseGV if present.
2831 if (AddrMode.BaseGV) {
Devang Patelc10e52a2011-09-06 18:49:53 +00002832 Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002833 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00002834 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002835 else
2836 Result = V;
2837 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00002838
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002839 // Add in the Base Offset if present.
2840 if (AddrMode.BaseOffs) {
Owen Andersonedb4a702009-07-24 23:12:02 +00002841 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002842 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00002843 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002844 else
2845 Result = V;
2846 }
2847
Craig Topperc0196b12014-04-14 00:51:57 +00002848 if (!Result)
Owen Anderson5a1acd92009-07-31 20:28:14 +00002849 SunkAddr = Constant::getNullValue(Addr->getType());
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002850 else
Devang Patelc10e52a2011-09-06 18:49:53 +00002851 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002852 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00002853
Owen Andersondfb8c3b2010-11-19 22:15:03 +00002854 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
Eric Christopherc1ea1492008-09-24 05:32:41 +00002855
Chris Lattneraf1bcce2011-04-09 07:05:44 +00002856 // If we have no uses, recursively delete the value and all dead instructions
2857 // using it.
Owen Andersondfb8c3b2010-11-19 22:15:03 +00002858 if (Repl->use_empty()) {
Chris Lattneraf1bcce2011-04-09 07:05:44 +00002859 // This can cause recursive deletion, which can invalidate our iterator.
2860 // Use a WeakVH to hold onto it in case this happens.
2861 WeakVH IterHandle(CurInstIterator);
2862 BasicBlock *BB = CurInstIterator->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +00002863
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00002864 RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
Chris Lattneraf1bcce2011-04-09 07:05:44 +00002865
2866 if (IterHandle != CurInstIterator) {
2867 // If the iterator instruction was recursively deleted, start over at the
2868 // start of the block.
2869 CurInstIterator = BB->begin();
2870 SunkAddrs.clear();
Nadav Rotem465834c2012-07-24 10:51:42 +00002871 }
Dale Johannesenb67a6e662010-03-31 20:37:15 +00002872 }
Cameron Zwarichced753f2011-01-05 17:27:27 +00002873 ++NumMemoryInsts;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002874 return true;
2875}
2876
Evan Cheng1da25002008-02-26 02:42:37 +00002877/// OptimizeInlineAsmInst - If there are any memory operands, use
Chris Lattner728f9022008-11-25 07:09:13 +00002878/// OptimizeMemoryInst to sink their address computing into the block when
Evan Cheng1da25002008-02-26 02:42:37 +00002879/// possible / profitable.
Chris Lattner7a277142011-01-15 07:14:54 +00002880bool CodeGenPrepare::OptimizeInlineAsmInst(CallInst *CS) {
Evan Cheng1da25002008-02-26 02:42:37 +00002881 bool MadeChange = false;
Evan Cheng1da25002008-02-26 02:42:37 +00002882
Nadav Rotem465834c2012-07-24 10:51:42 +00002883 TargetLowering::AsmOperandInfoVector
Chris Lattner7a277142011-01-15 07:14:54 +00002884 TargetConstraints = TLI->ParseConstraints(CS);
Dale Johannesenf95f59a2010-09-16 18:30:55 +00002885 unsigned ArgNo = 0;
John Thompson1094c802010-09-13 18:15:37 +00002886 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
2887 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Nadav Rotem465834c2012-07-24 10:51:42 +00002888
Evan Cheng1da25002008-02-26 02:42:37 +00002889 // Compute the constraint code and ConstraintType to use.
Dale Johannesence97d552010-06-25 21:55:36 +00002890 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Evan Cheng1da25002008-02-26 02:42:37 +00002891
Eli Friedman666bbe32008-02-26 18:37:49 +00002892 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
2893 OpInfo.isIndirect) {
Chris Lattner7a277142011-01-15 07:14:54 +00002894 Value *OpVal = CS->getArgOperand(ArgNo++);
Chris Lattneree588de2011-01-15 07:29:01 +00002895 MadeChange |= OptimizeMemoryInst(CS, OpVal, OpVal->getType());
Dale Johannesenf95f59a2010-09-16 18:30:55 +00002896 } else if (OpInfo.Type == InlineAsm::isInput)
2897 ArgNo++;
Evan Cheng1da25002008-02-26 02:42:37 +00002898 }
2899
2900 return MadeChange;
2901}
2902
Dan Gohman99429a02009-10-16 20:59:35 +00002903/// MoveExtToFormExtLoad - Move a zext or sext fed by a load into the same
2904/// basic block as the load, unless conditions are unfavorable. This allows
2905/// SelectionDAG to fold the extend into the load.
2906///
2907bool CodeGenPrepare::MoveExtToFormExtLoad(Instruction *I) {
2908 // Look for a load being extended.
2909 LoadInst *LI = dyn_cast<LoadInst>(I->getOperand(0));
2910 if (!LI) return false;
2911
2912 // If they're already in the same block, there's nothing to do.
2913 if (LI->getParent() == I->getParent())
2914 return false;
2915
2916 // If the load has other users and the truncate is not free, this probably
2917 // isn't worthwhile.
2918 if (!LI->hasOneUse() &&
Bob Wilsonb6832a42010-09-22 18:44:56 +00002919 TLI && (TLI->isTypeLegal(TLI->getValueType(LI->getType())) ||
2920 !TLI->isTypeLegal(TLI->getValueType(I->getType()))) &&
Bob Wilson4ddcb6a2010-09-21 21:54:27 +00002921 !TLI->isTruncateFree(I->getType(), LI->getType()))
Dan Gohman99429a02009-10-16 20:59:35 +00002922 return false;
2923
2924 // Check whether the target supports casts folded into loads.
2925 unsigned LType;
2926 if (isa<ZExtInst>(I))
2927 LType = ISD::ZEXTLOAD;
2928 else {
2929 assert(isa<SExtInst>(I) && "Unexpected ext type!");
2930 LType = ISD::SEXTLOAD;
2931 }
Patrik Hagglunde98b7a02012-12-11 11:14:33 +00002932 if (TLI && !TLI->isLoadExtLegal(LType, TLI->getValueType(LI->getType())))
Dan Gohman99429a02009-10-16 20:59:35 +00002933 return false;
2934
2935 // Move the extend into the same block as the load, so that SelectionDAG
2936 // can fold it.
2937 I->removeFromParent();
2938 I->insertAfter(LI);
Cameron Zwarichced753f2011-01-05 17:27:27 +00002939 ++NumExtsMoved;
Dan Gohman99429a02009-10-16 20:59:35 +00002940 return true;
2941}
2942
Evan Chengd3d80172007-12-05 23:58:20 +00002943bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
2944 BasicBlock *DefBB = I->getParent();
2945
Bob Wilsonff714f92010-09-21 21:44:14 +00002946 // If the result of a {s|z}ext and its source are both live out, rewrite all
Evan Chengd3d80172007-12-05 23:58:20 +00002947 // other uses of the source with result of extension.
2948 Value *Src = I->getOperand(0);
2949 if (Src->hasOneUse())
2950 return false;
2951
Evan Cheng2011df42007-12-13 07:50:36 +00002952 // Only do this xform if truncating is free.
Gabor Greifaa261722008-02-26 19:13:21 +00002953 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
Evan Cheng37c36ed2007-12-13 03:32:53 +00002954 return false;
2955
Evan Cheng7bc89422007-12-12 00:51:06 +00002956 // Only safe to perform the optimization if the source is also defined in
Evan Cheng63d33cf2007-12-12 02:53:41 +00002957 // this block.
2958 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
Evan Cheng7bc89422007-12-12 00:51:06 +00002959 return false;
2960
Evan Chengd3d80172007-12-05 23:58:20 +00002961 bool DefIsLiveOut = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00002962 for (User *U : I->users()) {
2963 Instruction *UI = cast<Instruction>(U);
Evan Chengd3d80172007-12-05 23:58:20 +00002964
2965 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002966 BasicBlock *UserBB = UI->getParent();
Evan Chengd3d80172007-12-05 23:58:20 +00002967 if (UserBB == DefBB) continue;
2968 DefIsLiveOut = true;
2969 break;
2970 }
2971 if (!DefIsLiveOut)
2972 return false;
2973
Jim Grosbach0f38c1e2013-04-15 17:40:48 +00002974 // Make sure none of the uses are PHI nodes.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002975 for (User *U : Src->users()) {
2976 Instruction *UI = cast<Instruction>(U);
2977 BasicBlock *UserBB = UI->getParent();
Evan Cheng37c36ed2007-12-13 03:32:53 +00002978 if (UserBB == DefBB) continue;
2979 // Be conservative. We don't want this xform to end up introducing
2980 // reloads just before load / store instructions.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002981 if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI))
Evan Cheng63d33cf2007-12-12 02:53:41 +00002982 return false;
2983 }
2984
Evan Chengd3d80172007-12-05 23:58:20 +00002985 // InsertedTruncs - Only insert one trunc in each block once.
2986 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
2987
2988 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00002989 for (Use &U : Src->uses()) {
2990 Instruction *User = cast<Instruction>(U.getUser());
Evan Chengd3d80172007-12-05 23:58:20 +00002991
2992 // Figure out which BB this ext is used in.
2993 BasicBlock *UserBB = User->getParent();
2994 if (UserBB == DefBB) continue;
2995
2996 // Both src and def are live in this block. Rewrite the use.
2997 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
2998
2999 if (!InsertedTrunc) {
Bill Wendling8ddfc092011-08-16 20:45:24 +00003000 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Evan Chengd3d80172007-12-05 23:58:20 +00003001 InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003002 InsertedTruncsSet.insert(InsertedTrunc);
Evan Chengd3d80172007-12-05 23:58:20 +00003003 }
3004
3005 // Replace a use of the {s|z}ext source with a use of the result.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003006 U = InsertedTrunc;
Cameron Zwarichced753f2011-01-05 17:27:27 +00003007 ++NumExtUses;
Evan Chengd3d80172007-12-05 23:58:20 +00003008 MadeChange = true;
3009 }
3010
3011 return MadeChange;
3012}
3013
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00003014/// isFormingBranchFromSelectProfitable - Returns true if a SelectInst should be
3015/// turned into an explicit branch.
3016static bool isFormingBranchFromSelectProfitable(SelectInst *SI) {
3017 // FIXME: This should use the same heuristics as IfConversion to determine
3018 // whether a select is better represented as a branch. This requires that
3019 // branch probability metadata is preserved for the select, which is not the
3020 // case currently.
3021
3022 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
3023
3024 // If the branch is predicted right, an out of order CPU can avoid blocking on
3025 // the compare. Emit cmovs on compares with a memory operand as branches to
3026 // avoid stalls on the load from memory. If the compare has more than one use
3027 // there's probably another cmov or setcc around so it's not worth emitting a
3028 // branch.
3029 if (!Cmp)
3030 return false;
3031
3032 Value *CmpOp0 = Cmp->getOperand(0);
3033 Value *CmpOp1 = Cmp->getOperand(1);
3034
3035 // We check that the memory operand has one use to avoid uses of the loaded
3036 // value directly after the compare, making branches unprofitable.
3037 return Cmp->hasOneUse() &&
3038 ((isa<LoadInst>(CmpOp0) && CmpOp0->hasOneUse()) ||
3039 (isa<LoadInst>(CmpOp1) && CmpOp1->hasOneUse()));
3040}
3041
3042
Nadav Rotem9d832022012-09-02 12:10:19 +00003043/// If we have a SelectInst that will likely profit from branch prediction,
3044/// turn it into a branch.
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00003045bool CodeGenPrepare::OptimizeSelectInst(SelectInst *SI) {
Nadav Rotem9d832022012-09-02 12:10:19 +00003046 bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
3047
3048 // Can we convert the 'select' to CF ?
3049 if (DisableSelectToBranch || OptSize || !TLI || VectorCond)
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00003050 return false;
3051
Nadav Rotem9d832022012-09-02 12:10:19 +00003052 TargetLowering::SelectSupportKind SelectKind;
3053 if (VectorCond)
3054 SelectKind = TargetLowering::VectorMaskSelect;
3055 else if (SI->getType()->isVectorTy())
3056 SelectKind = TargetLowering::ScalarCondVectorVal;
3057 else
3058 SelectKind = TargetLowering::ScalarValSelect;
3059
3060 // Do we have efficient codegen support for this kind of 'selects' ?
3061 if (TLI->isSelectSupported(SelectKind)) {
3062 // We have efficient codegen support for the select instruction.
3063 // Check if it is profitable to keep this 'select'.
3064 if (!TLI->isPredictableSelectExpensive() ||
3065 !isFormingBranchFromSelectProfitable(SI))
3066 return false;
3067 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00003068
3069 ModifiedDT = true;
3070
3071 // First, we split the block containing the select into 2 blocks.
3072 BasicBlock *StartBlock = SI->getParent();
3073 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(SI));
3074 BasicBlock *NextBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
3075
3076 // Create a new block serving as the landing pad for the branch.
3077 BasicBlock *SmallBlock = BasicBlock::Create(SI->getContext(), "select.mid",
3078 NextBlock->getParent(), NextBlock);
3079
3080 // Move the unconditional branch from the block with the select in it into our
3081 // landing pad block.
3082 StartBlock->getTerminator()->eraseFromParent();
3083 BranchInst::Create(NextBlock, SmallBlock);
3084
3085 // Insert the real conditional branch based on the original condition.
3086 BranchInst::Create(NextBlock, SmallBlock, SI->getCondition(), SI);
3087
3088 // The select itself is replaced with a PHI Node.
3089 PHINode *PN = PHINode::Create(SI->getType(), 2, "", NextBlock->begin());
3090 PN->takeName(SI);
3091 PN->addIncoming(SI->getTrueValue(), StartBlock);
3092 PN->addIncoming(SI->getFalseValue(), SmallBlock);
3093 SI->replaceAllUsesWith(PN);
3094 SI->eraseFromParent();
3095
3096 // Instruct OptimizeBlock to skip to the next block.
3097 CurInstIterator = StartBlock->end();
3098 ++NumSelectsExpanded;
3099 return true;
3100}
3101
Benjamin Kramer573ff362014-03-01 17:24:40 +00003102static bool isBroadcastShuffle(ShuffleVectorInst *SVI) {
Tim Northoveraeb8e062014-02-19 10:02:43 +00003103 SmallVector<int, 16> Mask(SVI->getShuffleMask());
3104 int SplatElem = -1;
3105 for (unsigned i = 0; i < Mask.size(); ++i) {
3106 if (SplatElem != -1 && Mask[i] != -1 && Mask[i] != SplatElem)
3107 return false;
3108 SplatElem = Mask[i];
3109 }
3110
3111 return true;
3112}
3113
3114/// Some targets have expensive vector shifts if the lanes aren't all the same
3115/// (e.g. x86 only introduced "vpsllvd" and friends with AVX2). In these cases
3116/// it's often worth sinking a shufflevector splat down to its use so that
3117/// codegen can spot all lanes are identical.
3118bool CodeGenPrepare::OptimizeShuffleVectorInst(ShuffleVectorInst *SVI) {
3119 BasicBlock *DefBB = SVI->getParent();
3120
3121 // Only do this xform if variable vector shifts are particularly expensive.
3122 if (!TLI || !TLI->isVectorShiftByScalarCheap(SVI->getType()))
3123 return false;
3124
3125 // We only expect better codegen by sinking a shuffle if we can recognise a
3126 // constant splat.
3127 if (!isBroadcastShuffle(SVI))
3128 return false;
3129
3130 // InsertedShuffles - Only insert a shuffle in each block once.
3131 DenseMap<BasicBlock*, Instruction*> InsertedShuffles;
3132
3133 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00003134 for (User *U : SVI->users()) {
3135 Instruction *UI = cast<Instruction>(U);
Tim Northoveraeb8e062014-02-19 10:02:43 +00003136
3137 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003138 BasicBlock *UserBB = UI->getParent();
Tim Northoveraeb8e062014-02-19 10:02:43 +00003139 if (UserBB == DefBB) continue;
3140
3141 // For now only apply this when the splat is used by a shift instruction.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003142 if (!UI->isShift()) continue;
Tim Northoveraeb8e062014-02-19 10:02:43 +00003143
3144 // Everything checks out, sink the shuffle if the user's block doesn't
3145 // already have a copy.
3146 Instruction *&InsertedShuffle = InsertedShuffles[UserBB];
3147
3148 if (!InsertedShuffle) {
3149 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
3150 InsertedShuffle = new ShuffleVectorInst(SVI->getOperand(0),
3151 SVI->getOperand(1),
3152 SVI->getOperand(2), "", InsertPt);
3153 }
3154
Chandler Carruthcdf47882014-03-09 03:16:01 +00003155 UI->replaceUsesOfWith(SVI, InsertedShuffle);
Tim Northoveraeb8e062014-02-19 10:02:43 +00003156 MadeChange = true;
3157 }
3158
3159 // If we removed all uses, nuke the shuffle.
3160 if (SVI->use_empty()) {
3161 SVI->eraseFromParent();
3162 MadeChange = true;
3163 }
3164
3165 return MadeChange;
3166}
3167
Cameron Zwarich14ac8652011-01-06 02:37:26 +00003168bool CodeGenPrepare::OptimizeInst(Instruction *I) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00003169 if (PHINode *P = dyn_cast<PHINode>(I)) {
3170 // It is possible for very late stage optimizations (such as SimplifyCFG)
3171 // to introduce PHI nodes too late to be cleaned up. If we detect such a
3172 // trivial PHI, go ahead and zap it here.
Craig Topperc0196b12014-04-14 00:51:57 +00003173 if (Value *V = SimplifyInstruction(P, TLI ? TLI->getDataLayout() : nullptr,
Benjamin Kramer30d249a2013-09-24 16:37:40 +00003174 TLInfo, DT)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00003175 P->replaceAllUsesWith(V);
3176 P->eraseFromParent();
3177 ++NumPHIsElim;
Chris Lattneree588de2011-01-15 07:29:01 +00003178 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00003179 }
Chris Lattneree588de2011-01-15 07:29:01 +00003180 return false;
3181 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003182
Chris Lattneree588de2011-01-15 07:29:01 +00003183 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00003184 // If the source of the cast is a constant, then this should have
3185 // already been constant folded. The only reason NOT to constant fold
3186 // it is if something (e.g. LSR) was careful to place the constant
3187 // evaluation in a block other than then one that uses it (e.g. to hoist
3188 // the address of globals out of a loop). If this is the case, we don't
3189 // want to forward-subst the cast.
3190 if (isa<Constant>(CI->getOperand(0)))
3191 return false;
3192
Chris Lattneree588de2011-01-15 07:29:01 +00003193 if (TLI && OptimizeNoopCopyExpression(CI, *TLI))
3194 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00003195
Chris Lattneree588de2011-01-15 07:29:01 +00003196 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +00003197 /// Sink a zext or sext into its user blocks if the target type doesn't
3198 /// fit in one register
3199 if (TLI && TLI->getTypeAction(CI->getContext(),
3200 TLI->getValueType(CI->getType())) ==
3201 TargetLowering::TypeExpandInteger) {
3202 return SinkCast(CI);
3203 } else {
3204 bool MadeChange = MoveExtToFormExtLoad(I);
3205 return MadeChange | OptimizeExtUses(I);
3206 }
Cameron Zwarich14ac8652011-01-06 02:37:26 +00003207 }
Chris Lattneree588de2011-01-15 07:29:01 +00003208 return false;
3209 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003210
Chris Lattneree588de2011-01-15 07:29:01 +00003211 if (CmpInst *CI = dyn_cast<CmpInst>(I))
Hal Finkeldecb0242014-01-02 21:13:43 +00003212 if (!TLI || !TLI->hasMultipleConditionRegisters())
3213 return OptimizeCmpExpression(CI);
Nadav Rotem465834c2012-07-24 10:51:42 +00003214
Chris Lattneree588de2011-01-15 07:29:01 +00003215 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00003216 if (TLI)
Hans Wennborgf3254832012-10-30 11:23:25 +00003217 return OptimizeMemoryInst(I, I->getOperand(0), LI->getType());
3218 return false;
Chris Lattneree588de2011-01-15 07:29:01 +00003219 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003220
Chris Lattneree588de2011-01-15 07:29:01 +00003221 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00003222 if (TLI)
Chris Lattneree588de2011-01-15 07:29:01 +00003223 return OptimizeMemoryInst(I, SI->getOperand(1),
3224 SI->getOperand(0)->getType());
3225 return false;
3226 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003227
Chris Lattneree588de2011-01-15 07:29:01 +00003228 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00003229 if (GEPI->hasAllZeroIndices()) {
3230 /// The GEP operand must be a pointer, so must its result -> BitCast
3231 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
3232 GEPI->getName(), GEPI);
3233 GEPI->replaceAllUsesWith(NC);
3234 GEPI->eraseFromParent();
3235 ++NumGEPsElim;
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00003236 OptimizeInst(NC);
Chris Lattneree588de2011-01-15 07:29:01 +00003237 return true;
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00003238 }
Chris Lattneree588de2011-01-15 07:29:01 +00003239 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00003240 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003241
Chris Lattneree588de2011-01-15 07:29:01 +00003242 if (CallInst *CI = dyn_cast<CallInst>(I))
3243 return OptimizeCallInst(CI);
Cameron Zwarich14ac8652011-01-06 02:37:26 +00003244
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00003245 if (SelectInst *SI = dyn_cast<SelectInst>(I))
3246 return OptimizeSelectInst(SI);
3247
Tim Northoveraeb8e062014-02-19 10:02:43 +00003248 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I))
3249 return OptimizeShuffleVectorInst(SVI);
3250
Chris Lattneree588de2011-01-15 07:29:01 +00003251 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00003252}
3253
Chris Lattnerf2836d12007-03-31 04:06:36 +00003254// In this pass we look for GEP and cast instructions that are used
3255// across basic blocks and rewrite them to improve basic-block-at-a-time
3256// selection.
3257bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
Cameron Zwarichce3b9302011-01-06 00:42:50 +00003258 SunkAddrs.clear();
Cameron Zwarich5dd2aa22011-03-02 03:31:46 +00003259 bool MadeChange = false;
Eric Christopherc1ea1492008-09-24 05:32:41 +00003260
Chris Lattner7a277142011-01-15 07:14:54 +00003261 CurInstIterator = BB.begin();
Hans Wennborg02fbc712012-09-19 07:48:16 +00003262 while (CurInstIterator != BB.end())
Chris Lattner1b93be52011-01-15 07:25:29 +00003263 MadeChange |= OptimizeInst(CurInstIterator++);
Eric Christopherc1ea1492008-09-24 05:32:41 +00003264
Benjamin Kramer455fa352012-11-23 19:17:06 +00003265 MadeChange |= DupRetToEnableTailCallOpts(&BB);
3266
Chris Lattnerf2836d12007-03-31 04:06:36 +00003267 return MadeChange;
3268}
Devang Patel53771ba2011-08-18 00:50:51 +00003269
3270// llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotem465834c2012-07-24 10:51:42 +00003271// handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patel53771ba2011-08-18 00:50:51 +00003272// find a node corresponding to the value.
3273bool CodeGenPrepare::PlaceDbgValues(Function &F) {
3274 bool MadeChange = false;
3275 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
Craig Topperc0196b12014-04-14 00:51:57 +00003276 Instruction *PrevNonDbgInst = nullptr;
Devang Patel53771ba2011-08-18 00:50:51 +00003277 for (BasicBlock::iterator BI = I->begin(), BE = I->end(); BI != BE;) {
3278 Instruction *Insn = BI; ++BI;
3279 DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
3280 if (!DVI) {
3281 PrevNonDbgInst = Insn;
3282 continue;
3283 }
3284
3285 Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
3286 if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
3287 DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
3288 DVI->removeFromParent();
3289 if (isa<PHINode>(VI))
3290 DVI->insertBefore(VI->getParent()->getFirstInsertionPt());
3291 else
3292 DVI->insertAfter(VI);
3293 MadeChange = true;
3294 ++NumDbgValueMoved;
3295 }
3296 }
3297 }
3298 return MadeChange;
3299}
Tim Northovercea0abb2014-03-29 08:22:29 +00003300
3301// If there is a sequence that branches based on comparing a single bit
3302// against zero that can be combined into a single instruction, and the
3303// target supports folding these into a single instruction, sink the
3304// mask and compare into the branch uses. Do this before OptimizeBlock ->
3305// OptimizeInst -> OptimizeCmpExpression, which perturbs the pattern being
3306// searched for.
3307bool CodeGenPrepare::sinkAndCmp(Function &F) {
3308 if (!EnableAndCmpSinking)
3309 return false;
3310 if (!TLI || !TLI->isMaskAndBranchFoldingLegal())
3311 return false;
3312 bool MadeChange = false;
3313 for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
3314 BasicBlock *BB = I++;
3315
3316 // Does this BB end with the following?
3317 // %andVal = and %val, #single-bit-set
3318 // %icmpVal = icmp %andResult, 0
3319 // br i1 %cmpVal label %dest1, label %dest2"
3320 BranchInst *Brcc = dyn_cast<BranchInst>(BB->getTerminator());
3321 if (!Brcc || !Brcc->isConditional())
3322 continue;
3323 ICmpInst *Cmp = dyn_cast<ICmpInst>(Brcc->getOperand(0));
3324 if (!Cmp || Cmp->getParent() != BB)
3325 continue;
3326 ConstantInt *Zero = dyn_cast<ConstantInt>(Cmp->getOperand(1));
3327 if (!Zero || !Zero->isZero())
3328 continue;
3329 Instruction *And = dyn_cast<Instruction>(Cmp->getOperand(0));
3330 if (!And || And->getOpcode() != Instruction::And || And->getParent() != BB)
3331 continue;
3332 ConstantInt* Mask = dyn_cast<ConstantInt>(And->getOperand(1));
3333 if (!Mask || !Mask->getUniqueInteger().isPowerOf2())
3334 continue;
3335 DEBUG(dbgs() << "found and; icmp ?,0; brcc\n"); DEBUG(BB->dump());
3336
3337 // Push the "and; icmp" for any users that are conditional branches.
3338 // Since there can only be one branch use per BB, we don't need to keep
3339 // track of which BBs we insert into.
3340 for (Value::use_iterator UI = Cmp->use_begin(), E = Cmp->use_end();
3341 UI != E; ) {
3342 Use &TheUse = *UI;
3343 // Find brcc use.
3344 BranchInst *BrccUser = dyn_cast<BranchInst>(*UI);
3345 ++UI;
3346 if (!BrccUser || !BrccUser->isConditional())
3347 continue;
3348 BasicBlock *UserBB = BrccUser->getParent();
3349 if (UserBB == BB) continue;
3350 DEBUG(dbgs() << "found Brcc use\n");
3351
3352 // Sink the "and; icmp" to use.
3353 MadeChange = true;
3354 BinaryOperator *NewAnd =
3355 BinaryOperator::CreateAnd(And->getOperand(0), And->getOperand(1), "",
3356 BrccUser);
3357 CmpInst *NewCmp =
3358 CmpInst::Create(Cmp->getOpcode(), Cmp->getPredicate(), NewAnd, Zero,
3359 "", BrccUser);
3360 TheUse = NewCmp;
3361 ++NumAndCmpsMoved;
3362 DEBUG(BrccUser->getParent()->dump());
3363 }
3364 }
3365 return MadeChange;
3366}