blob: a6c540b619c958a7b2645d0ac9e30be6791eda8d [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
Quentin Colombeta3490842014-02-22 00:07:45 +000016#include "llvm/CodeGen/Passes.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000017#include "llvm/ADT/DenseMap.h"
18#include "llvm/ADT/SmallSet.h"
19#include "llvm/ADT/Statistic.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000020#include "llvm/Analysis/InstructionSimplify.h"
Quentin Colombetc32615d2014-10-31 17:52:53 +000021#include "llvm/Analysis/TargetTransformInfo.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
Chandler Carruth1b9dde02014-04-22 02:02:50 +000050#define DEBUG_TYPE "codegenprepare"
51
Cameron Zwarichced753f2011-01-05 17:27:27 +000052STATISTIC(NumBlocksElim, "Number of blocks eliminated");
Evan Cheng0663f232011-03-21 01:19:09 +000053STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated");
54STATISTIC(NumGEPsElim, "Number of GEPs converted to casts");
Cameron Zwarichced753f2011-01-05 17:27:27 +000055STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "
56 "sunken Cmps");
57STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
58 "of sunken Casts");
59STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "
60 "computations were sunk");
Evan Cheng0663f232011-03-21 01:19:09 +000061STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads");
62STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized");
63STATISTIC(NumRetsDup, "Number of return instructions duplicated");
Devang Patel53771ba2011-08-18 00:50:51 +000064STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved");
Benjamin Kramer047d7ca2012-05-05 12:49:22 +000065STATISTIC(NumSelectsExpanded, "Number of selects turned into branches");
Tim Northovercea0abb2014-03-29 08:22:29 +000066STATISTIC(NumAndCmpsMoved, "Number of and/cmp's pushed into branches");
Quentin Colombetc32615d2014-10-31 17:52:53 +000067STATISTIC(NumStoreExtractExposed, "Number of store(extractelement) exposed");
Jakob Stoklund Oleseneb12f492010-09-30 20:51:52 +000068
Cameron Zwarich338d3622011-03-11 21:52:04 +000069static cl::opt<bool> DisableBranchOpts(
70 "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
71 cl::desc("Disable branch optimizations in CodeGenPrepare"));
72
Benjamin Kramer3d38c172012-05-06 14:25:16 +000073static cl::opt<bool> DisableSelectToBranch(
74 "disable-cgp-select2branch", cl::Hidden, cl::init(false),
75 cl::desc("Disable select to branch conversion."));
Benjamin Kramer047d7ca2012-05-05 12:49:22 +000076
Hal Finkelc3998302014-04-12 00:59:48 +000077static cl::opt<bool> AddrSinkUsingGEPs(
78 "addr-sink-using-gep", cl::Hidden, cl::init(false),
79 cl::desc("Address sinking in CGP using GEPs."));
80
Tim Northovercea0abb2014-03-29 08:22:29 +000081static cl::opt<bool> EnableAndCmpSinking(
82 "enable-andcmp-sinking", cl::Hidden, cl::init(true),
83 cl::desc("Enable sinkinig and/cmp into branches."));
84
Quentin Colombetc32615d2014-10-31 17:52:53 +000085static cl::opt<bool> DisableStoreExtract(
86 "disable-cgp-store-extract", cl::Hidden, cl::init(false),
87 cl::desc("Disable store(extract) optimizations in CodeGenPrepare"));
88
89static cl::opt<bool> StressStoreExtract(
90 "stress-cgp-store-extract", cl::Hidden, cl::init(false),
91 cl::desc("Stress test store(extract) optimizations in CodeGenPrepare"));
92
Eric Christopherc1ea1492008-09-24 05:32:41 +000093namespace {
Quentin Colombet3a4bf042014-02-06 21:44:56 +000094typedef SmallPtrSet<Instruction *, 16> SetOfInstrs;
Quentin Colombetf5485bb2014-11-13 01:44:51 +000095struct TypeIsSExt {
96 Type *Ty;
97 bool IsSExt;
98 TypeIsSExt(Type *Ty, bool IsSExt) : Ty(Ty), IsSExt(IsSExt) {}
99};
100typedef DenseMap<Instruction *, TypeIsSExt> InstrToOrigTy;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000101
Chris Lattner2dd09db2009-09-02 06:11:42 +0000102 class CodeGenPrepare : public FunctionPass {
Chris Lattnerf2836d12007-03-31 04:06:36 +0000103 /// TLI - Keep a pointer of a TargetLowering to consult for determining
104 /// transformation profitability.
Bill Wendling7a639ea2013-06-19 21:07:11 +0000105 const TargetMachine *TM;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000106 const TargetLowering *TLI;
Quentin Colombetc32615d2014-10-31 17:52:53 +0000107 const TargetTransformInfo *TTI;
Chad Rosierc24b86f2011-12-01 03:08:23 +0000108 const TargetLibraryInfo *TLInfo;
Cameron Zwarich84986b22011-01-08 17:01:52 +0000109 DominatorTree *DT;
Nadav Rotem465834c2012-07-24 10:51:42 +0000110
Chris Lattner7a277142011-01-15 07:14:54 +0000111 /// CurInstIterator - As we scan instructions optimizing them, this is the
112 /// next instruction to optimize. Xforms that can invalidate this should
113 /// update it.
114 BasicBlock::iterator CurInstIterator;
Evan Cheng3b3de7c2008-12-19 18:03:11 +0000115
Evan Cheng0663f232011-03-21 01:19:09 +0000116 /// Keeps track of non-local addresses that have been sunk into a block.
117 /// This allows us to avoid inserting duplicate code for blocks with
118 /// multiple load/stores of the same address.
Nick Lewycky5fb19632013-05-08 09:00:10 +0000119 ValueMap<Value*, Value*> SunkAddrs;
Cameron Zwarichce3b9302011-01-06 00:42:50 +0000120
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000121 /// Keeps track of all truncates inserted for the current function.
122 SetOfInstrs InsertedTruncsSet;
123 /// Keeps track of the type of the related instruction before their
124 /// promotion for the current function.
125 InstrToOrigTy PromotedInsts;
126
Devang Patel8f606d72011-03-24 15:35:25 +0000127 /// ModifiedDT - If CFG is modified in anyway, dominator tree may need to
Evan Cheng0663f232011-03-21 01:19:09 +0000128 /// be updated.
Devang Patel8f606d72011-03-24 15:35:25 +0000129 bool ModifiedDT;
Evan Cheng0663f232011-03-21 01:19:09 +0000130
Benjamin Kramer047d7ca2012-05-05 12:49:22 +0000131 /// OptSize - True if optimizing for size.
132 bool OptSize;
133
Chris Lattnerf2836d12007-03-31 04:06:36 +0000134 public:
Nick Lewyckye7da2d62007-05-06 13:37:16 +0000135 static char ID; // Pass identification, replacement for typeid
Craig Topperc0196b12014-04-14 00:51:57 +0000136 explicit CodeGenPrepare(const TargetMachine *TM = nullptr)
Quentin Colombetc32615d2014-10-31 17:52:53 +0000137 : FunctionPass(ID), TM(TM), TLI(nullptr), TTI(nullptr) {
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000138 initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
139 }
Craig Topper4584cd52014-03-07 09:26:03 +0000140 bool runOnFunction(Function &F) override;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000141
Craig Topper4584cd52014-03-07 09:26:03 +0000142 const char *getPassName() const override { return "CodeGen Prepare"; }
Evan Cheng99cafb12012-12-21 01:48:14 +0000143
Craig Topper4584cd52014-03-07 09:26:03 +0000144 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruth73523022014-01-13 13:07:17 +0000145 AU.addPreserved<DominatorTreeWrapperPass>();
Chad Rosierc24b86f2011-12-01 03:08:23 +0000146 AU.addRequired<TargetLibraryInfo>();
Quentin Colombetc32615d2014-10-31 17:52:53 +0000147 AU.addRequired<TargetTransformInfo>();
Andreas Neustifterf8cb7582009-09-16 09:26:52 +0000148 }
149
Chris Lattnerf2836d12007-03-31 04:06:36 +0000150 private:
Nadav Rotem70409992012-08-14 05:19:07 +0000151 bool EliminateFallThrough(Function &F);
Chris Lattnerc3748562007-04-02 01:35:34 +0000152 bool EliminateMostlyEmptyBlocks(Function &F);
153 bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
154 void EliminateMostlyEmptyBlock(BasicBlock *BB);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000155 bool OptimizeBlock(BasicBlock &BB);
Cameron Zwarich14ac8652011-01-06 02:37:26 +0000156 bool OptimizeInst(Instruction *I);
Chris Lattner229907c2011-07-18 04:54:35 +0000157 bool OptimizeMemoryInst(Instruction *I, Value *Addr, Type *AccessTy);
Chris Lattner7a277142011-01-15 07:14:54 +0000158 bool OptimizeInlineAsmInst(CallInst *CS);
Eric Christopher4b7948e2010-03-11 02:41:03 +0000159 bool OptimizeCallInst(CallInst *CI);
Dan Gohman99429a02009-10-16 20:59:35 +0000160 bool MoveExtToFormExtLoad(Instruction *I);
Evan Chengd3d80172007-12-05 23:58:20 +0000161 bool OptimizeExtUses(Instruction *I);
Benjamin Kramer047d7ca2012-05-05 12:49:22 +0000162 bool OptimizeSelectInst(SelectInst *SI);
Tim Northoveraeb8e062014-02-19 10:02:43 +0000163 bool OptimizeShuffleVectorInst(ShuffleVectorInst *SI);
Quentin Colombetc32615d2014-10-31 17:52:53 +0000164 bool OptimizeExtractElementInst(Instruction *Inst);
Benjamin Kramer455fa352012-11-23 19:17:06 +0000165 bool DupRetToEnableTailCallOpts(BasicBlock *BB);
Devang Patel53771ba2011-08-18 00:50:51 +0000166 bool PlaceDbgValues(Function &F);
Tim Northovercea0abb2014-03-29 08:22:29 +0000167 bool sinkAndCmp(Function &F);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000168 };
169}
Devang Patel09f162c2007-05-01 21:15:47 +0000170
Devang Patel8c78a0b2007-05-03 01:11:54 +0000171char CodeGenPrepare::ID = 0;
Jiangning Liud623c522014-06-11 07:04:37 +0000172INITIALIZE_TM_PASS(CodeGenPrepare, "codegenprepare",
173 "Optimize for code generation", false, false)
Chris Lattnerf2836d12007-03-31 04:06:36 +0000174
Bill Wendling7a639ea2013-06-19 21:07:11 +0000175FunctionPass *llvm::createCodeGenPreparePass(const TargetMachine *TM) {
176 return new CodeGenPrepare(TM);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000177}
178
Chris Lattnerf2836d12007-03-31 04:06:36 +0000179bool CodeGenPrepare::runOnFunction(Function &F) {
Paul Robinson7c99ec52014-03-31 17:43:35 +0000180 if (skipOptnoneFunction(F))
181 return false;
182
Chris Lattnerf2836d12007-03-31 04:06:36 +0000183 bool EverMadeChange = false;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000184 // Clear per function information.
185 InsertedTruncsSet.clear();
186 PromotedInsts.clear();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000187
Devang Patel8f606d72011-03-24 15:35:25 +0000188 ModifiedDT = false;
Eric Christopherd9134482014-08-04 21:25:23 +0000189 if (TM)
190 TLI = TM->getSubtargetImpl()->getTargetLowering();
Chad Rosierc24b86f2011-12-01 03:08:23 +0000191 TLInfo = &getAnalysis<TargetLibraryInfo>();
Quentin Colombetc32615d2014-10-31 17:52:53 +0000192 TTI = &getAnalysis<TargetTransformInfo>();
Chandler Carruth73523022014-01-13 13:07:17 +0000193 DominatorTreeWrapperPass *DTWP =
194 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
Craig Topperc0196b12014-04-14 00:51:57 +0000195 DT = DTWP ? &DTWP->getDomTree() : nullptr;
Bill Wendling698e84f2012-12-30 10:32:01 +0000196 OptSize = F.getAttributes().hasAttribute(AttributeSet::FunctionIndex,
197 Attribute::OptimizeForSize);
Evan Cheng0663f232011-03-21 01:19:09 +0000198
Preston Gurdcdf540d2012-09-04 18:22:17 +0000199 /// This optimization identifies DIV instructions that can be
200 /// profitably bypassed and carried out with a shorter, faster divide.
Preston Gurd485296d2013-03-04 18:13:57 +0000201 if (!OptSize && TLI && TLI->isSlowDivBypassed()) {
Preston Gurd0d67f512012-10-04 21:33:40 +0000202 const DenseMap<unsigned int, unsigned int> &BypassWidths =
203 TLI->getBypassSlowDivWidths();
Evan Cheng71be12b2012-09-14 21:25:34 +0000204 for (Function::iterator I = F.begin(); I != F.end(); I++)
Preston Gurd0d67f512012-10-04 21:33:40 +0000205 EverMadeChange |= bypassSlowDivision(F, I, BypassWidths);
Preston Gurdcdf540d2012-09-04 18:22:17 +0000206 }
207
208 // Eliminate blocks that contain only PHI nodes and an
Chris Lattnerc3748562007-04-02 01:35:34 +0000209 // unconditional branch.
210 EverMadeChange |= EliminateMostlyEmptyBlocks(F);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000211
Devang Patel53771ba2011-08-18 00:50:51 +0000212 // llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotem465834c2012-07-24 10:51:42 +0000213 // handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patel53771ba2011-08-18 00:50:51 +0000214 // find a node corresponding to the value.
215 EverMadeChange |= PlaceDbgValues(F);
216
Tim Northovercea0abb2014-03-29 08:22:29 +0000217 // If there is a mask, compare against zero, and branch that can be combined
218 // into a single target instruction, push the mask and compare into branch
219 // users. Do this before OptimizeBlock -> OptimizeInst ->
220 // OptimizeCmpExpression, which perturbs the pattern being searched for.
221 if (!DisableBranchOpts)
222 EverMadeChange |= sinkAndCmp(F);
223
Chris Lattnerc3748562007-04-02 01:35:34 +0000224 bool MadeChange = true;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000225 while (MadeChange) {
226 MadeChange = false;
Hans Wennborg02fbc712012-09-19 07:48:16 +0000227 for (Function::iterator I = F.begin(); I != F.end(); ) {
Evan Cheng0663f232011-03-21 01:19:09 +0000228 BasicBlock *BB = I++;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000229 MadeChange |= OptimizeBlock(*BB);
Evan Cheng0663f232011-03-21 01:19:09 +0000230 }
Chris Lattnerf2836d12007-03-31 04:06:36 +0000231 EverMadeChange |= MadeChange;
232 }
Cameron Zwarichce3b9302011-01-06 00:42:50 +0000233
234 SunkAddrs.clear();
235
Cameron Zwarich338d3622011-03-11 21:52:04 +0000236 if (!DisableBranchOpts) {
237 MadeChange = false;
Bill Wendling97b93592012-03-04 10:46:01 +0000238 SmallPtrSet<BasicBlock*, 8> WorkList;
239 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
240 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
Frits van Bommelad964552011-05-22 16:24:18 +0000241 MadeChange |= ConstantFoldTerminator(BB, true);
Bill Wendling97b93592012-03-04 10:46:01 +0000242 if (!MadeChange) continue;
243
244 for (SmallVectorImpl<BasicBlock*>::iterator
245 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
246 if (pred_begin(*II) == pred_end(*II))
247 WorkList.insert(*II);
248 }
249
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000250 // Delete the dead blocks and any of their dead successors.
Bill Wendlingab417b62012-12-06 00:30:20 +0000251 MadeChange |= !WorkList.empty();
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000252 while (!WorkList.empty()) {
253 BasicBlock *BB = *WorkList.begin();
254 WorkList.erase(BB);
255 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
256
257 DeleteDeadBlock(BB);
Stephen Lin837bba12013-07-15 17:55:02 +0000258
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000259 for (SmallVectorImpl<BasicBlock*>::iterator
260 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
261 if (pred_begin(*II) == pred_end(*II))
262 WorkList.insert(*II);
263 }
Cameron Zwarich338d3622011-03-11 21:52:04 +0000264
Nadav Rotem70409992012-08-14 05:19:07 +0000265 // Merge pairs of basic blocks with unconditional branches, connected by
266 // a single edge.
267 if (EverMadeChange || MadeChange)
268 MadeChange |= EliminateFallThrough(F);
269
Evan Cheng0663f232011-03-21 01:19:09 +0000270 if (MadeChange)
Devang Patel8f606d72011-03-24 15:35:25 +0000271 ModifiedDT = true;
Cameron Zwarich338d3622011-03-11 21:52:04 +0000272 EverMadeChange |= MadeChange;
273 }
274
Devang Patel8f606d72011-03-24 15:35:25 +0000275 if (ModifiedDT && DT)
Chandler Carruth73523022014-01-13 13:07:17 +0000276 DT->recalculate(F);
Evan Cheng0663f232011-03-21 01:19:09 +0000277
Chris Lattnerf2836d12007-03-31 04:06:36 +0000278 return EverMadeChange;
279}
280
Nadav Rotem70409992012-08-14 05:19:07 +0000281/// EliminateFallThrough - Merge basic blocks which are connected
282/// by a single edge, where one of the basic blocks has a single successor
283/// pointing to the other basic block, which has a single predecessor.
284bool CodeGenPrepare::EliminateFallThrough(Function &F) {
285 bool Changed = false;
286 // Scan all of the blocks in the function, except for the entry block.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000287 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
Nadav Rotem70409992012-08-14 05:19:07 +0000288 BasicBlock *BB = I++;
289 // If the destination block has a single pred, then this is a trivial
290 // edge, just collapse it.
291 BasicBlock *SinglePred = BB->getSinglePredecessor();
292
Evan Cheng64a223a2012-09-28 23:58:57 +0000293 // Don't merge if BB's address is taken.
294 if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue;
Nadav Rotem70409992012-08-14 05:19:07 +0000295
296 BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
297 if (Term && !Term->isConditional()) {
298 Changed = true;
Michael Liao6e12d122012-08-21 05:55:22 +0000299 DEBUG(dbgs() << "To merge:\n"<< *SinglePred << "\n\n\n");
Nadav Rotem70409992012-08-14 05:19:07 +0000300 // Remember if SinglePred was the entry block of the function.
301 // If so, we will need to move BB back to the entry position.
302 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
303 MergeBasicBlockIntoOnlyPred(BB, this);
304
305 if (isEntry && BB != &BB->getParent()->getEntryBlock())
306 BB->moveBefore(&BB->getParent()->getEntryBlock());
307
308 // We have erased a block. Update the iterator.
309 I = BB;
Nadav Rotem70409992012-08-14 05:19:07 +0000310 }
311 }
312 return Changed;
313}
314
Dale Johannesen4026b042009-03-27 01:13:37 +0000315/// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes,
316/// debug info directives, and an unconditional branch. Passes before isel
317/// (e.g. LSR/loopsimplify) often split edges in ways that are non-optimal for
318/// isel. Start by eliminating these blocks so we can split them the way we
319/// want them.
Chris Lattnerc3748562007-04-02 01:35:34 +0000320bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
321 bool MadeChange = false;
322 // Note that this intentionally skips the entry block.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000323 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
Chris Lattnerc3748562007-04-02 01:35:34 +0000324 BasicBlock *BB = I++;
325
326 // If this block doesn't end with an uncond branch, ignore it.
327 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
328 if (!BI || !BI->isUnconditional())
329 continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000330
Dale Johannesen4026b042009-03-27 01:13:37 +0000331 // If the instruction before the branch (skipping debug info) isn't a phi
332 // node, then other stuff is happening here.
Chris Lattnerc3748562007-04-02 01:35:34 +0000333 BasicBlock::iterator BBI = BI;
334 if (BBI != BB->begin()) {
335 --BBI;
Dale Johannesen4026b042009-03-27 01:13:37 +0000336 while (isa<DbgInfoIntrinsic>(BBI)) {
337 if (BBI == BB->begin())
338 break;
339 --BBI;
340 }
341 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
342 continue;
Chris Lattnerc3748562007-04-02 01:35:34 +0000343 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000344
Chris Lattnerc3748562007-04-02 01:35:34 +0000345 // Do not break infinite loops.
346 BasicBlock *DestBB = BI->getSuccessor(0);
347 if (DestBB == BB)
348 continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000349
Chris Lattnerc3748562007-04-02 01:35:34 +0000350 if (!CanMergeBlocks(BB, DestBB))
351 continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000352
Chris Lattnerc3748562007-04-02 01:35:34 +0000353 EliminateMostlyEmptyBlock(BB);
354 MadeChange = true;
355 }
356 return MadeChange;
357}
358
359/// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
360/// single uncond branch between them, and BB contains no other non-phi
361/// instructions.
362bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
363 const BasicBlock *DestBB) const {
364 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
365 // the successor. If there are more complex condition (e.g. preheaders),
366 // don't mess around with them.
367 BasicBlock::const_iterator BBI = BB->begin();
368 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000369 for (const User *U : PN->users()) {
370 const Instruction *UI = cast<Instruction>(U);
371 if (UI->getParent() != DestBB || !isa<PHINode>(UI))
Chris Lattnerc3748562007-04-02 01:35:34 +0000372 return false;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000373 // If User is inside DestBB block and it is a PHINode then check
374 // incoming value. If incoming value is not from BB then this is
Devang Pateld3208522007-04-25 00:37:04 +0000375 // a complex condition (e.g. preheaders) we want to avoid here.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000376 if (UI->getParent() == DestBB) {
377 if (const PHINode *UPN = dyn_cast<PHINode>(UI))
Devang Pateld3208522007-04-25 00:37:04 +0000378 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
379 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
380 if (Insn && Insn->getParent() == BB &&
381 Insn->getParent() != UPN->getIncomingBlock(I))
382 return false;
383 }
384 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000385 }
386 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000387
Chris Lattnerc3748562007-04-02 01:35:34 +0000388 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
389 // and DestBB may have conflicting incoming values for the block. If so, we
390 // can't merge the block.
391 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
392 if (!DestBBPN) return true; // no conflict.
Eric Christopherc1ea1492008-09-24 05:32:41 +0000393
Chris Lattnerc3748562007-04-02 01:35:34 +0000394 // Collect the preds of BB.
Chris Lattner8201a9b2007-11-06 22:07:40 +0000395 SmallPtrSet<const BasicBlock*, 16> BBPreds;
Chris Lattnerc3748562007-04-02 01:35:34 +0000396 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
397 // It is faster to get preds from a PHI than with pred_iterator.
398 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
399 BBPreds.insert(BBPN->getIncomingBlock(i));
400 } else {
401 BBPreds.insert(pred_begin(BB), pred_end(BB));
402 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000403
Chris Lattnerc3748562007-04-02 01:35:34 +0000404 // Walk the preds of DestBB.
405 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
406 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
407 if (BBPreds.count(Pred)) { // Common predecessor?
408 BBI = DestBB->begin();
409 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
410 const Value *V1 = PN->getIncomingValueForBlock(Pred);
411 const Value *V2 = PN->getIncomingValueForBlock(BB);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000412
Chris Lattnerc3748562007-04-02 01:35:34 +0000413 // If V2 is a phi node in BB, look up what the mapped value will be.
414 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
415 if (V2PN->getParent() == BB)
416 V2 = V2PN->getIncomingValueForBlock(Pred);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000417
Chris Lattnerc3748562007-04-02 01:35:34 +0000418 // If there is a conflict, bail out.
419 if (V1 != V2) return false;
420 }
421 }
422 }
423
424 return true;
425}
426
427
428/// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
429/// an unconditional branch in it.
430void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
431 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
432 BasicBlock *DestBB = BI->getSuccessor(0);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000433
David Greene74e2d492010-01-05 01:27:11 +0000434 DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000435
Chris Lattnerc3748562007-04-02 01:35:34 +0000436 // If the destination block has a single pred, then this is a trivial edge,
437 // just collapse it.
Chris Lattner4059f432008-11-27 19:29:14 +0000438 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
Chris Lattner8a172da2008-11-28 19:54:49 +0000439 if (SinglePred != DestBB) {
440 // Remember if SinglePred was the entry block of the function. If so, we
441 // will need to move BB back to the entry position.
442 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Andreas Neustifterf8cb7582009-09-16 09:26:52 +0000443 MergeBasicBlockIntoOnlyPred(DestBB, this);
Chris Lattner4059f432008-11-27 19:29:14 +0000444
Chris Lattner8a172da2008-11-28 19:54:49 +0000445 if (isEntry && BB != &BB->getParent()->getEntryBlock())
446 BB->moveBefore(&BB->getParent()->getEntryBlock());
Nadav Rotem465834c2012-07-24 10:51:42 +0000447
David Greene74e2d492010-01-05 01:27:11 +0000448 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattner8a172da2008-11-28 19:54:49 +0000449 return;
450 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000451 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000452
Chris Lattnerc3748562007-04-02 01:35:34 +0000453 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
454 // to handle the new incoming edges it is about to have.
455 PHINode *PN;
456 for (BasicBlock::iterator BBI = DestBB->begin();
457 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
458 // Remove the incoming value for BB, and remember it.
459 Value *InVal = PN->removeIncomingValue(BB, false);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000460
Chris Lattnerc3748562007-04-02 01:35:34 +0000461 // Two options: either the InVal is a phi node defined in BB or it is some
462 // value that dominates BB.
463 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
464 if (InValPhi && InValPhi->getParent() == BB) {
465 // Add all of the input values of the input PHI as inputs of this phi.
466 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
467 PN->addIncoming(InValPhi->getIncomingValue(i),
468 InValPhi->getIncomingBlock(i));
469 } else {
470 // Otherwise, add one instance of the dominating value for each edge that
471 // we will be adding.
472 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
473 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
474 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
475 } else {
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000476 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
477 PN->addIncoming(InVal, *PI);
Chris Lattnerc3748562007-04-02 01:35:34 +0000478 }
479 }
480 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000481
Chris Lattnerc3748562007-04-02 01:35:34 +0000482 // The PHIs are now updated, change everything that refers to BB to use
483 // DestBB and remove BB.
484 BB->replaceAllUsesWith(DestBB);
Devang Patel8f606d72011-03-24 15:35:25 +0000485 if (DT && !ModifiedDT) {
Cameron Zwarich84986b22011-01-08 17:01:52 +0000486 BasicBlock *BBIDom = DT->getNode(BB)->getIDom()->getBlock();
487 BasicBlock *DestBBIDom = DT->getNode(DestBB)->getIDom()->getBlock();
488 BasicBlock *NewIDom = DT->findNearestCommonDominator(BBIDom, DestBBIDom);
489 DT->changeImmediateDominator(DestBB, NewIDom);
490 DT->eraseNode(BB);
491 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000492 BB->eraseFromParent();
Cameron Zwarichced753f2011-01-05 17:27:27 +0000493 ++NumBlocksElim;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000494
David Greene74e2d492010-01-05 01:27:11 +0000495 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerc3748562007-04-02 01:35:34 +0000496}
497
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000498/// SinkCast - Sink the specified cast instruction into its user blocks
499static bool SinkCast(CastInst *CI) {
Chris Lattnerf2836d12007-03-31 04:06:36 +0000500 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000501
Chris Lattnerf2836d12007-03-31 04:06:36 +0000502 /// InsertedCasts - Only insert a cast in each block once.
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000503 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000504
Chris Lattnerf2836d12007-03-31 04:06:36 +0000505 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000506 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
Chris Lattnerf2836d12007-03-31 04:06:36 +0000507 UI != E; ) {
508 Use &TheUse = UI.getUse();
509 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000510
Chris Lattnerf2836d12007-03-31 04:06:36 +0000511 // Figure out which BB this cast is used in. For PHI's this is the
512 // appropriate predecessor block.
513 BasicBlock *UserBB = User->getParent();
514 if (PHINode *PN = dyn_cast<PHINode>(User)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000515 UserBB = PN->getIncomingBlock(TheUse);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000516 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000517
Chris Lattnerf2836d12007-03-31 04:06:36 +0000518 // Preincrement use iterator so we don't invalidate it.
519 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000520
Chris Lattnerf2836d12007-03-31 04:06:36 +0000521 // If this user is in the same block as the cast, don't change the cast.
522 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000523
Chris Lattnerf2836d12007-03-31 04:06:36 +0000524 // If we have already inserted a cast into this block, use it.
525 CastInst *&InsertedCast = InsertedCasts[UserBB];
526
527 if (!InsertedCast) {
Bill Wendling8ddfc092011-08-16 20:45:24 +0000528 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000529 InsertedCast =
530 CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
Chris Lattnerf2836d12007-03-31 04:06:36 +0000531 InsertPt);
532 MadeChange = true;
533 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000534
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000535 // Replace a use of the cast with a use of the new cast.
Chris Lattnerf2836d12007-03-31 04:06:36 +0000536 TheUse = InsertedCast;
Cameron Zwarichced753f2011-01-05 17:27:27 +0000537 ++NumCastUses;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000538 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000539
Chris Lattnerf2836d12007-03-31 04:06:36 +0000540 // If we removed all uses, nuke the cast.
Duncan Sandsafa84da42008-01-20 16:51:46 +0000541 if (CI->use_empty()) {
Chris Lattnerf2836d12007-03-31 04:06:36 +0000542 CI->eraseFromParent();
Duncan Sandsafa84da42008-01-20 16:51:46 +0000543 MadeChange = true;
544 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000545
Chris Lattnerf2836d12007-03-31 04:06:36 +0000546 return MadeChange;
547}
548
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000549/// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
550/// copy (e.g. it's casting from one pointer type to another, i32->i8 on PPC),
551/// sink it into user blocks to reduce the number of virtual
552/// registers that must be created and coalesced.
553///
554/// Return true if any changes are made.
555///
556static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
557 // If this is a noop copy,
558 EVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
559 EVT DstVT = TLI.getValueType(CI->getType());
560
561 // This is an fp<->int conversion?
562 if (SrcVT.isInteger() != DstVT.isInteger())
563 return false;
564
565 // If this is an extension, it will be a zero or sign extension, which
566 // isn't a noop.
567 if (SrcVT.bitsLT(DstVT)) return false;
568
569 // If these values will be promoted, find out what they will be promoted
570 // to. This helps us consider truncates on PPC as noop copies when they
571 // are.
572 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
573 TargetLowering::TypePromoteInteger)
574 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
575 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
576 TargetLowering::TypePromoteInteger)
577 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
578
579 // If, after promotion, these are the same types, this is a noop copy.
580 if (SrcVT != DstVT)
581 return false;
582
583 return SinkCast(CI);
584}
585
Eric Christopherc1ea1492008-09-24 05:32:41 +0000586/// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000587/// the number of virtual registers that must be created and coalesced. This is
Chris Lattner27406942007-08-02 16:53:43 +0000588/// a clear win except on targets with multiple condition code registers
589/// (PowerPC), where it might lose; some adjustment may be wanted there.
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000590///
591/// Return true if any changes are made.
Chris Lattner6416a6b2008-11-24 22:44:16 +0000592static bool OptimizeCmpExpression(CmpInst *CI) {
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000593 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000594
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000595 /// InsertedCmp - Only insert a cmp in each block once.
596 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000597
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000598 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000599 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000600 UI != E; ) {
601 Use &TheUse = UI.getUse();
602 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000603
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000604 // Preincrement use iterator so we don't invalidate it.
605 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000606
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000607 // Don't bother for PHI nodes.
608 if (isa<PHINode>(User))
609 continue;
610
611 // Figure out which BB this cmp is used in.
612 BasicBlock *UserBB = User->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000613
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000614 // If this user is in the same block as the cmp, don't change the cmp.
615 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000616
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000617 // If we have already inserted a cmp into this block, use it.
618 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
619
620 if (!InsertedCmp) {
Bill Wendling8ddfc092011-08-16 20:45:24 +0000621 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000622 InsertedCmp =
Dan Gohmanad1f0a12009-08-25 23:17:54 +0000623 CmpInst::Create(CI->getOpcode(),
Owen Anderson1e5f00e2009-07-09 23:48:35 +0000624 CI->getPredicate(), CI->getOperand(0),
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000625 CI->getOperand(1), "", InsertPt);
626 MadeChange = true;
627 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000628
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000629 // Replace a use of the cmp with a use of the new cmp.
630 TheUse = InsertedCmp;
Cameron Zwarichced753f2011-01-05 17:27:27 +0000631 ++NumCmpUses;
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000632 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000633
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000634 // If we removed all uses, nuke the cmp.
635 if (CI->use_empty())
636 CI->eraseFromParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000637
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000638 return MadeChange;
639}
640
Yi Jiangd069f632014-04-21 19:34:27 +0000641/// isExtractBitsCandidateUse - Check if the candidates could
642/// be combined with shift instruction, which includes:
643/// 1. Truncate instruction
644/// 2. And instruction and the imm is a mask of the low bits:
645/// imm & (imm+1) == 0
Benjamin Kramer322053c2014-04-27 14:54:59 +0000646static bool isExtractBitsCandidateUse(Instruction *User) {
Yi Jiangd069f632014-04-21 19:34:27 +0000647 if (!isa<TruncInst>(User)) {
648 if (User->getOpcode() != Instruction::And ||
649 !isa<ConstantInt>(User->getOperand(1)))
650 return false;
651
Quentin Colombetd4f44692014-04-22 01:20:34 +0000652 const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue();
Yi Jiangd069f632014-04-21 19:34:27 +0000653
Quentin Colombetd4f44692014-04-22 01:20:34 +0000654 if ((Cimm & (Cimm + 1)).getBoolValue())
Yi Jiangd069f632014-04-21 19:34:27 +0000655 return false;
656 }
657 return true;
658}
659
660/// SinkShiftAndTruncate - sink both shift and truncate instruction
661/// to the use of truncate's BB.
Benjamin Kramer322053c2014-04-27 14:54:59 +0000662static bool
Yi Jiangd069f632014-04-21 19:34:27 +0000663SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI,
664 DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts,
665 const TargetLowering &TLI) {
666 BasicBlock *UserBB = User->getParent();
667 DenseMap<BasicBlock *, CastInst *> InsertedTruncs;
668 TruncInst *TruncI = dyn_cast<TruncInst>(User);
669 bool MadeChange = false;
670
671 for (Value::user_iterator TruncUI = TruncI->user_begin(),
672 TruncE = TruncI->user_end();
673 TruncUI != TruncE;) {
674
675 Use &TruncTheUse = TruncUI.getUse();
676 Instruction *TruncUser = cast<Instruction>(*TruncUI);
677 // Preincrement use iterator so we don't invalidate it.
678
679 ++TruncUI;
680
681 int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode());
682 if (!ISDOpcode)
683 continue;
684
Tim Northovere2239ff2014-07-29 10:20:22 +0000685 // If the use is actually a legal node, there will not be an
686 // implicit truncate.
687 // FIXME: always querying the result type is just an
688 // approximation; some nodes' legality is determined by the
689 // operand or other means. There's no good way to find out though.
Ahmed Bougacha0788d492014-11-12 22:16:55 +0000690 if (TLI.isOperationLegalOrCustom(
691 ISDOpcode, TLI.getValueType(TruncUser->getType(), true)))
Yi Jiangd069f632014-04-21 19:34:27 +0000692 continue;
693
694 // Don't bother for PHI nodes.
695 if (isa<PHINode>(TruncUser))
696 continue;
697
698 BasicBlock *TruncUserBB = TruncUser->getParent();
699
700 if (UserBB == TruncUserBB)
701 continue;
702
703 BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB];
704 CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB];
705
706 if (!InsertedShift && !InsertedTrunc) {
707 BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt();
708 // Sink the shift
709 if (ShiftI->getOpcode() == Instruction::AShr)
710 InsertedShift =
711 BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, "", InsertPt);
712 else
713 InsertedShift =
714 BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, "", InsertPt);
715
716 // Sink the trunc
717 BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt();
718 TruncInsertPt++;
719
720 InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift,
721 TruncI->getType(), "", TruncInsertPt);
722
723 MadeChange = true;
724
725 TruncTheUse = InsertedTrunc;
726 }
727 }
728 return MadeChange;
729}
730
731/// OptimizeExtractBits - sink the shift *right* instruction into user blocks if
732/// the uses could potentially be combined with this shift instruction and
733/// generate BitExtract instruction. It will only be applied if the architecture
734/// supports BitExtract instruction. Here is an example:
735/// BB1:
736/// %x.extract.shift = lshr i64 %arg1, 32
737/// BB2:
738/// %x.extract.trunc = trunc i64 %x.extract.shift to i16
739/// ==>
740///
741/// BB2:
742/// %x.extract.shift.1 = lshr i64 %arg1, 32
743/// %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16
744///
745/// CodeGen will recoginze the pattern in BB2 and generate BitExtract
746/// instruction.
747/// Return true if any changes are made.
748static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI,
749 const TargetLowering &TLI) {
750 BasicBlock *DefBB = ShiftI->getParent();
751
752 /// Only insert instructions in each block once.
753 DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts;
754
755 bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(ShiftI->getType()));
756
757 bool MadeChange = false;
758 for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end();
759 UI != E;) {
760 Use &TheUse = UI.getUse();
761 Instruction *User = cast<Instruction>(*UI);
762 // Preincrement use iterator so we don't invalidate it.
763 ++UI;
764
765 // Don't bother for PHI nodes.
766 if (isa<PHINode>(User))
767 continue;
768
769 if (!isExtractBitsCandidateUse(User))
770 continue;
771
772 BasicBlock *UserBB = User->getParent();
773
774 if (UserBB == DefBB) {
775 // If the shift and truncate instruction are in the same BB. The use of
776 // the truncate(TruncUse) may still introduce another truncate if not
777 // legal. In this case, we would like to sink both shift and truncate
778 // instruction to the BB of TruncUse.
779 // for example:
780 // BB1:
781 // i64 shift.result = lshr i64 opnd, imm
782 // trunc.result = trunc shift.result to i16
783 //
784 // BB2:
785 // ----> We will have an implicit truncate here if the architecture does
786 // not have i16 compare.
787 // cmp i16 trunc.result, opnd2
788 //
789 if (isa<TruncInst>(User) && shiftIsLegal
790 // If the type of the truncate is legal, no trucate will be
791 // introduced in other basic blocks.
792 && (!TLI.isTypeLegal(TLI.getValueType(User->getType()))))
793 MadeChange =
794 SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI);
795
796 continue;
797 }
798 // If we have already inserted a shift into this block, use it.
799 BinaryOperator *&InsertedShift = InsertedShifts[UserBB];
800
801 if (!InsertedShift) {
802 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
803
804 if (ShiftI->getOpcode() == Instruction::AShr)
805 InsertedShift =
806 BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, "", InsertPt);
807 else
808 InsertedShift =
809 BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, "", InsertPt);
810
811 MadeChange = true;
812 }
813
814 // Replace a use of the shift with a use of the new shift.
815 TheUse = InsertedShift;
816 }
817
818 // If we removed all uses, nuke the shift.
819 if (ShiftI->use_empty())
820 ShiftI->eraseFromParent();
821
822 return MadeChange;
823}
824
Benjamin Kramer7b88a492010-03-12 09:27:41 +0000825namespace {
826class CodeGenPrepareFortifiedLibCalls : public SimplifyFortifiedLibCalls {
827protected:
Craig Topper4584cd52014-03-07 09:26:03 +0000828 void replaceCall(Value *With) override {
Benjamin Kramer7b88a492010-03-12 09:27:41 +0000829 CI->replaceAllUsesWith(With);
830 CI->eraseFromParent();
831 }
Craig Topper4584cd52014-03-07 09:26:03 +0000832 bool isFoldable(unsigned SizeCIOp, unsigned, bool) const override {
Gabor Greif6d673952010-07-16 09:38:02 +0000833 if (ConstantInt *SizeCI =
834 dyn_cast<ConstantInt>(CI->getArgOperand(SizeCIOp)))
835 return SizeCI->isAllOnesValue();
Benjamin Kramer7b88a492010-03-12 09:27:41 +0000836 return false;
837 }
838};
839} // end anonymous namespace
840
Eric Christopher4b7948e2010-03-11 02:41:03 +0000841bool CodeGenPrepare::OptimizeCallInst(CallInst *CI) {
Chris Lattner7a277142011-01-15 07:14:54 +0000842 BasicBlock *BB = CI->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +0000843
Chris Lattner7a277142011-01-15 07:14:54 +0000844 // Lower inline assembly if we can.
845 // If we found an inline asm expession, and if the target knows how to
846 // lower it to normal LLVM code, do so now.
847 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
848 if (TLI->ExpandInlineAsm(CI)) {
849 // Avoid invalidating the iterator.
850 CurInstIterator = BB->begin();
851 // Avoid processing instructions out of order, which could cause
852 // reuse before a value is defined.
853 SunkAddrs.clear();
854 return true;
855 }
856 // Sink address computing for memory operands into the block.
857 if (OptimizeInlineAsmInst(CI))
858 return true;
859 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000860
Eric Christopher4b7948e2010-03-11 02:41:03 +0000861 // Lower all uses of llvm.objectsize.*
862 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
863 if (II && II->getIntrinsicID() == Intrinsic::objectsize) {
Gabor Greif4a39b842010-06-24 00:44:01 +0000864 bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
Chris Lattner229907c2011-07-18 04:54:35 +0000865 Type *ReturnTy = CI->getType();
Nadav Rotem465834c2012-07-24 10:51:42 +0000866 Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
867
Chris Lattner1b93be52011-01-15 07:25:29 +0000868 // Substituting this can cause recursive simplifications, which can
869 // invalidate our iterator. Use a WeakVH to hold onto it in case this
870 // happens.
871 WeakVH IterHandle(CurInstIterator);
Nadav Rotem465834c2012-07-24 10:51:42 +0000872
Craig Topperc0196b12014-04-14 00:51:57 +0000873 replaceAndRecursivelySimplify(CI, RetVal,
874 TLI ? TLI->getDataLayout() : nullptr,
875 TLInfo, ModifiedDT ? nullptr : DT);
Chris Lattner1b93be52011-01-15 07:25:29 +0000876
877 // If the iterator instruction was recursively deleted, start over at the
878 // start of the block.
Chris Lattner86d56c62011-01-18 20:53:04 +0000879 if (IterHandle != CurInstIterator) {
Chris Lattner1b93be52011-01-15 07:25:29 +0000880 CurInstIterator = BB->begin();
Chris Lattner86d56c62011-01-18 20:53:04 +0000881 SunkAddrs.clear();
882 }
Eric Christopher4b7948e2010-03-11 02:41:03 +0000883 return true;
884 }
885
Pete Cooper615fd892012-03-13 20:59:56 +0000886 if (II && TLI) {
887 SmallVector<Value*, 2> PtrOps;
888 Type *AccessTy;
889 if (TLI->GetAddrModeArguments(II, PtrOps, AccessTy))
890 while (!PtrOps.empty())
891 if (OptimizeMemoryInst(II, PtrOps.pop_back_val(), AccessTy))
892 return true;
893 }
894
Eric Christopher4b7948e2010-03-11 02:41:03 +0000895 // From here on out we're working with named functions.
Craig Topperc0196b12014-04-14 00:51:57 +0000896 if (!CI->getCalledFunction()) return false;
Devang Patel0da52502011-05-26 21:51:06 +0000897
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000898 // We'll need DataLayout from here on out.
Craig Topperc0196b12014-04-14 00:51:57 +0000899 const DataLayout *TD = TLI ? TLI->getDataLayout() : nullptr;
Eric Christopher4b7948e2010-03-11 02:41:03 +0000900 if (!TD) return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000901
Benjamin Kramer7b88a492010-03-12 09:27:41 +0000902 // Lower all default uses of _chk calls. This is very similar
903 // to what InstCombineCalls does, but here we are only lowering calls
Eric Christopher4b7948e2010-03-11 02:41:03 +0000904 // that have the default "don't know" as the objectsize. Anything else
905 // should be left alone.
Benjamin Kramer7b88a492010-03-12 09:27:41 +0000906 CodeGenPrepareFortifiedLibCalls Simplifier;
Nuno Lopes89702e92012-07-25 16:46:31 +0000907 return Simplifier.fold(CI, TD, TLInfo);
Eric Christopher4b7948e2010-03-11 02:41:03 +0000908}
Chris Lattner1b93be52011-01-15 07:25:29 +0000909
Evan Cheng0663f232011-03-21 01:19:09 +0000910/// DupRetToEnableTailCallOpts - Look for opportunities to duplicate return
911/// instructions to the predecessor to enable tail call optimizations. The
912/// case it is currently looking for is:
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +0000913/// @code
Evan Cheng0663f232011-03-21 01:19:09 +0000914/// bb0:
915/// %tmp0 = tail call i32 @f0()
916/// br label %return
917/// bb1:
918/// %tmp1 = tail call i32 @f1()
919/// br label %return
920/// bb2:
921/// %tmp2 = tail call i32 @f2()
922/// br label %return
923/// return:
924/// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
925/// ret i32 %retval
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +0000926/// @endcode
Evan Cheng0663f232011-03-21 01:19:09 +0000927///
928/// =>
929///
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +0000930/// @code
Evan Cheng0663f232011-03-21 01:19:09 +0000931/// bb0:
932/// %tmp0 = tail call i32 @f0()
933/// ret i32 %tmp0
934/// bb1:
935/// %tmp1 = tail call i32 @f1()
936/// ret i32 %tmp1
937/// bb2:
938/// %tmp2 = tail call i32 @f2()
939/// ret i32 %tmp2
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +0000940/// @endcode
Benjamin Kramer455fa352012-11-23 19:17:06 +0000941bool CodeGenPrepare::DupRetToEnableTailCallOpts(BasicBlock *BB) {
Cameron Zwarich47e71752011-03-24 04:51:51 +0000942 if (!TLI)
943 return false;
944
Benjamin Kramer455fa352012-11-23 19:17:06 +0000945 ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
946 if (!RI)
947 return false;
948
Craig Topperc0196b12014-04-14 00:51:57 +0000949 PHINode *PN = nullptr;
950 BitCastInst *BCI = nullptr;
Evan Cheng0663f232011-03-21 01:19:09 +0000951 Value *V = RI->getReturnValue();
Evan Cheng249716e2012-07-27 21:21:26 +0000952 if (V) {
953 BCI = dyn_cast<BitCastInst>(V);
954 if (BCI)
955 V = BCI->getOperand(0);
956
957 PN = dyn_cast<PHINode>(V);
958 if (!PN)
959 return false;
960 }
Evan Cheng0663f232011-03-21 01:19:09 +0000961
Cameron Zwarich4649f172011-03-24 04:52:10 +0000962 if (PN && PN->getParent() != BB)
Cameron Zwarich0e331c02011-03-24 04:52:07 +0000963 return false;
Evan Cheng0663f232011-03-21 01:19:09 +0000964
Cameron Zwarich0e331c02011-03-24 04:52:07 +0000965 // It's not safe to eliminate the sign / zero extension of the return value.
966 // See llvm::isInTailCallPosition().
967 const Function *F = BB->getParent();
Bill Wendling658d24d2013-01-18 21:53:16 +0000968 AttributeSet CallerAttrs = F->getAttributes();
969 if (CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::ZExt) ||
970 CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::SExt))
Cameron Zwarich0e331c02011-03-24 04:52:07 +0000971 return false;
Evan Cheng0663f232011-03-21 01:19:09 +0000972
Cameron Zwarich4649f172011-03-24 04:52:10 +0000973 // Make sure there are no instructions between the PHI and return, or that the
974 // return is the first instruction in the block.
975 if (PN) {
976 BasicBlock::iterator BI = BB->begin();
977 do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
Evan Cheng249716e2012-07-27 21:21:26 +0000978 if (&*BI == BCI)
979 // Also skip over the bitcast.
980 ++BI;
Cameron Zwarich4649f172011-03-24 04:52:10 +0000981 if (&*BI != RI)
982 return false;
983 } else {
Cameron Zwarich74157ab2011-03-24 16:34:59 +0000984 BasicBlock::iterator BI = BB->begin();
985 while (isa<DbgInfoIntrinsic>(BI)) ++BI;
986 if (&*BI != RI)
Cameron Zwarich4649f172011-03-24 04:52:10 +0000987 return false;
988 }
Evan Cheng0663f232011-03-21 01:19:09 +0000989
Cameron Zwarich0e331c02011-03-24 04:52:07 +0000990 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
991 /// call.
992 SmallVector<CallInst*, 4> TailCalls;
Cameron Zwarich4649f172011-03-24 04:52:10 +0000993 if (PN) {
994 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
995 CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
996 // Make sure the phi value is indeed produced by the tail call.
997 if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
998 TLI->mayBeEmittedAsTailCall(CI))
999 TailCalls.push_back(CI);
1000 }
1001 } else {
1002 SmallPtrSet<BasicBlock*, 4> VisitedBBs;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001003 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
David Blaikie70573dc2014-11-19 07:49:26 +00001004 if (!VisitedBBs.insert(*PI).second)
Cameron Zwarich4649f172011-03-24 04:52:10 +00001005 continue;
1006
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001007 BasicBlock::InstListType &InstList = (*PI)->getInstList();
Cameron Zwarich4649f172011-03-24 04:52:10 +00001008 BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
1009 BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
Cameron Zwarich74157ab2011-03-24 16:34:59 +00001010 do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
1011 if (RI == RE)
Cameron Zwarich4649f172011-03-24 04:52:10 +00001012 continue;
Cameron Zwarich74157ab2011-03-24 16:34:59 +00001013
Cameron Zwarich4649f172011-03-24 04:52:10 +00001014 CallInst *CI = dyn_cast<CallInst>(&*RI);
Cameron Zwarich2edfe772011-03-24 15:54:11 +00001015 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI))
Cameron Zwarich4649f172011-03-24 04:52:10 +00001016 TailCalls.push_back(CI);
1017 }
Evan Cheng0663f232011-03-21 01:19:09 +00001018 }
1019
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001020 bool Changed = false;
1021 for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
1022 CallInst *CI = TailCalls[i];
1023 CallSite CS(CI);
1024
1025 // Conservatively require the attributes of the call to match those of the
1026 // return. Ignore noalias because it doesn't affect the call sequence.
Bill Wendling658d24d2013-01-18 21:53:16 +00001027 AttributeSet CalleeAttrs = CS.getAttributes();
1028 if (AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001029 removeAttribute(Attribute::NoAlias) !=
Bill Wendling658d24d2013-01-18 21:53:16 +00001030 AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001031 removeAttribute(Attribute::NoAlias))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001032 continue;
1033
1034 // Make sure the call instruction is followed by an unconditional branch to
1035 // the return block.
1036 BasicBlock *CallBB = CI->getParent();
1037 BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
1038 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
1039 continue;
1040
1041 // Duplicate the return into CallBB.
1042 (void)FoldReturnIntoUncondBranch(RI, BB, CallBB);
Devang Patel8f606d72011-03-24 15:35:25 +00001043 ModifiedDT = Changed = true;
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001044 ++NumRetsDup;
1045 }
1046
1047 // If we eliminated all predecessors of the block, delete the block now.
Evan Cheng64a223a2012-09-28 23:58:57 +00001048 if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001049 BB->eraseFromParent();
1050
1051 return Changed;
Evan Cheng0663f232011-03-21 01:19:09 +00001052}
1053
Chris Lattner728f9022008-11-25 07:09:13 +00001054//===----------------------------------------------------------------------===//
Chris Lattner728f9022008-11-25 07:09:13 +00001055// Memory Optimization
1056//===----------------------------------------------------------------------===//
1057
Chandler Carruthc8925912013-01-05 02:09:22 +00001058namespace {
1059
1060/// ExtAddrMode - This is an extended version of TargetLowering::AddrMode
1061/// which holds actual Value*'s for register values.
Chandler Carruth95f83e02013-01-07 15:14:13 +00001062struct ExtAddrMode : public TargetLowering::AddrMode {
Chandler Carruthc8925912013-01-05 02:09:22 +00001063 Value *BaseReg;
1064 Value *ScaledReg;
Craig Topperc0196b12014-04-14 00:51:57 +00001065 ExtAddrMode() : BaseReg(nullptr), ScaledReg(nullptr) {}
Chandler Carruthc8925912013-01-05 02:09:22 +00001066 void print(raw_ostream &OS) const;
1067 void dump() const;
Stephen Lin837bba12013-07-15 17:55:02 +00001068
Chandler Carruthc8925912013-01-05 02:09:22 +00001069 bool operator==(const ExtAddrMode& O) const {
1070 return (BaseReg == O.BaseReg) && (ScaledReg == O.ScaledReg) &&
1071 (BaseGV == O.BaseGV) && (BaseOffs == O.BaseOffs) &&
1072 (HasBaseReg == O.HasBaseReg) && (Scale == O.Scale);
1073 }
1074};
1075
Eli Friedmanc1f1f852013-09-10 23:09:24 +00001076#ifndef NDEBUG
1077static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
1078 AM.print(OS);
1079 return OS;
1080}
1081#endif
1082
Chandler Carruthc8925912013-01-05 02:09:22 +00001083void ExtAddrMode::print(raw_ostream &OS) const {
1084 bool NeedPlus = false;
1085 OS << "[";
1086 if (BaseGV) {
1087 OS << (NeedPlus ? " + " : "")
1088 << "GV:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00001089 BaseGV->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00001090 NeedPlus = true;
1091 }
1092
Richard Trieuc0f91212014-05-30 03:15:17 +00001093 if (BaseOffs) {
1094 OS << (NeedPlus ? " + " : "")
1095 << BaseOffs;
1096 NeedPlus = true;
1097 }
Chandler Carruthc8925912013-01-05 02:09:22 +00001098
1099 if (BaseReg) {
1100 OS << (NeedPlus ? " + " : "")
1101 << "Base:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00001102 BaseReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00001103 NeedPlus = true;
1104 }
1105 if (Scale) {
1106 OS << (NeedPlus ? " + " : "")
1107 << Scale << "*";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00001108 ScaledReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00001109 }
1110
1111 OS << ']';
1112}
1113
1114#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1115void ExtAddrMode::dump() const {
1116 print(dbgs());
1117 dbgs() << '\n';
1118}
1119#endif
1120
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001121/// \brief This class provides transaction based operation on the IR.
1122/// Every change made through this class is recorded in the internal state and
1123/// can be undone (rollback) until commit is called.
1124class TypePromotionTransaction {
1125
1126 /// \brief This represents the common interface of the individual transaction.
1127 /// Each class implements the logic for doing one specific modification on
1128 /// the IR via the TypePromotionTransaction.
1129 class TypePromotionAction {
1130 protected:
1131 /// The Instruction modified.
1132 Instruction *Inst;
1133
1134 public:
1135 /// \brief Constructor of the action.
1136 /// The constructor performs the related action on the IR.
1137 TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
1138
1139 virtual ~TypePromotionAction() {}
1140
1141 /// \brief Undo the modification done by this action.
1142 /// When this method is called, the IR must be in the same state as it was
1143 /// before this action was applied.
1144 /// \pre Undoing the action works if and only if the IR is in the exact same
1145 /// state as it was directly after this action was applied.
1146 virtual void undo() = 0;
1147
1148 /// \brief Advocate every change made by this action.
1149 /// When the results on the IR of the action are to be kept, it is important
1150 /// to call this function, otherwise hidden information may be kept forever.
1151 virtual void commit() {
1152 // Nothing to be done, this action is not doing anything.
1153 }
1154 };
1155
1156 /// \brief Utility to remember the position of an instruction.
1157 class InsertionHandler {
1158 /// Position of an instruction.
1159 /// Either an instruction:
1160 /// - Is the first in a basic block: BB is used.
1161 /// - Has a previous instructon: PrevInst is used.
1162 union {
1163 Instruction *PrevInst;
1164 BasicBlock *BB;
1165 } Point;
1166 /// Remember whether or not the instruction had a previous instruction.
1167 bool HasPrevInstruction;
1168
1169 public:
1170 /// \brief Record the position of \p Inst.
1171 InsertionHandler(Instruction *Inst) {
1172 BasicBlock::iterator It = Inst;
1173 HasPrevInstruction = (It != (Inst->getParent()->begin()));
1174 if (HasPrevInstruction)
1175 Point.PrevInst = --It;
1176 else
1177 Point.BB = Inst->getParent();
1178 }
1179
1180 /// \brief Insert \p Inst at the recorded position.
1181 void insert(Instruction *Inst) {
1182 if (HasPrevInstruction) {
1183 if (Inst->getParent())
1184 Inst->removeFromParent();
1185 Inst->insertAfter(Point.PrevInst);
1186 } else {
1187 Instruction *Position = Point.BB->getFirstInsertionPt();
1188 if (Inst->getParent())
1189 Inst->moveBefore(Position);
1190 else
1191 Inst->insertBefore(Position);
1192 }
1193 }
1194 };
1195
1196 /// \brief Move an instruction before another.
1197 class InstructionMoveBefore : public TypePromotionAction {
1198 /// Original position of the instruction.
1199 InsertionHandler Position;
1200
1201 public:
1202 /// \brief Move \p Inst before \p Before.
1203 InstructionMoveBefore(Instruction *Inst, Instruction *Before)
1204 : TypePromotionAction(Inst), Position(Inst) {
1205 DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before << "\n");
1206 Inst->moveBefore(Before);
1207 }
1208
1209 /// \brief Move the instruction back to its original position.
Craig Topper4584cd52014-03-07 09:26:03 +00001210 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001211 DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n");
1212 Position.insert(Inst);
1213 }
1214 };
1215
1216 /// \brief Set the operand of an instruction with a new value.
1217 class OperandSetter : public TypePromotionAction {
1218 /// Original operand of the instruction.
1219 Value *Origin;
1220 /// Index of the modified instruction.
1221 unsigned Idx;
1222
1223 public:
1224 /// \brief Set \p Idx operand of \p Inst with \p NewVal.
1225 OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
1226 : TypePromotionAction(Inst), Idx(Idx) {
1227 DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"
1228 << "for:" << *Inst << "\n"
1229 << "with:" << *NewVal << "\n");
1230 Origin = Inst->getOperand(Idx);
1231 Inst->setOperand(Idx, NewVal);
1232 }
1233
1234 /// \brief Restore the original value of the instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00001235 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001236 DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"
1237 << "for: " << *Inst << "\n"
1238 << "with: " << *Origin << "\n");
1239 Inst->setOperand(Idx, Origin);
1240 }
1241 };
1242
1243 /// \brief Hide the operands of an instruction.
1244 /// Do as if this instruction was not using any of its operands.
1245 class OperandsHider : public TypePromotionAction {
1246 /// The list of original operands.
1247 SmallVector<Value *, 4> OriginalValues;
1248
1249 public:
1250 /// \brief Remove \p Inst from the uses of the operands of \p Inst.
1251 OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
1252 DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n");
1253 unsigned NumOpnds = Inst->getNumOperands();
1254 OriginalValues.reserve(NumOpnds);
1255 for (unsigned It = 0; It < NumOpnds; ++It) {
1256 // Save the current operand.
1257 Value *Val = Inst->getOperand(It);
1258 OriginalValues.push_back(Val);
1259 // Set a dummy one.
1260 // We could use OperandSetter here, but that would implied an overhead
1261 // that we are not willing to pay.
1262 Inst->setOperand(It, UndefValue::get(Val->getType()));
1263 }
1264 }
1265
1266 /// \brief Restore the original list of uses.
Craig Topper4584cd52014-03-07 09:26:03 +00001267 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001268 DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n");
1269 for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
1270 Inst->setOperand(It, OriginalValues[It]);
1271 }
1272 };
1273
1274 /// \brief Build a truncate instruction.
1275 class TruncBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00001276 Value *Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001277 public:
1278 /// \brief Build a truncate instruction of \p Opnd producing a \p Ty
1279 /// result.
1280 /// trunc Opnd to Ty.
1281 TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
1282 IRBuilder<> Builder(Opnd);
Quentin Colombetac55b152014-09-16 22:36:07 +00001283 Val = Builder.CreateTrunc(Opnd, Ty, "promoted");
1284 DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001285 }
1286
Quentin Colombetac55b152014-09-16 22:36:07 +00001287 /// \brief Get the built value.
1288 Value *getBuiltValue() { return Val; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001289
1290 /// \brief Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00001291 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00001292 DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n");
1293 if (Instruction *IVal = dyn_cast<Instruction>(Val))
1294 IVal->eraseFromParent();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001295 }
1296 };
1297
1298 /// \brief Build a sign extension instruction.
1299 class SExtBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00001300 Value *Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001301 public:
1302 /// \brief Build a sign extension instruction of \p Opnd producing a \p Ty
1303 /// result.
1304 /// sext Opnd to Ty.
1305 SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
Quentin Colombetac55b152014-09-16 22:36:07 +00001306 : TypePromotionAction(InsertPt) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001307 IRBuilder<> Builder(InsertPt);
Quentin Colombetac55b152014-09-16 22:36:07 +00001308 Val = Builder.CreateSExt(Opnd, Ty, "promoted");
1309 DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001310 }
1311
Quentin Colombetac55b152014-09-16 22:36:07 +00001312 /// \brief Get the built value.
1313 Value *getBuiltValue() { return Val; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001314
1315 /// \brief Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00001316 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00001317 DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n");
1318 if (Instruction *IVal = dyn_cast<Instruction>(Val))
1319 IVal->eraseFromParent();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001320 }
1321 };
1322
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001323 /// \brief Build a zero extension instruction.
1324 class ZExtBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00001325 Value *Val;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001326 public:
1327 /// \brief Build a zero extension instruction of \p Opnd producing a \p Ty
1328 /// result.
1329 /// zext Opnd to Ty.
1330 ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
Quentin Colombetac55b152014-09-16 22:36:07 +00001331 : TypePromotionAction(InsertPt) {
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001332 IRBuilder<> Builder(InsertPt);
Quentin Colombetac55b152014-09-16 22:36:07 +00001333 Val = Builder.CreateZExt(Opnd, Ty, "promoted");
1334 DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n");
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001335 }
1336
Quentin Colombetac55b152014-09-16 22:36:07 +00001337 /// \brief Get the built value.
1338 Value *getBuiltValue() { return Val; }
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001339
1340 /// \brief Remove the built instruction.
1341 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00001342 DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n");
1343 if (Instruction *IVal = dyn_cast<Instruction>(Val))
1344 IVal->eraseFromParent();
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001345 }
1346 };
1347
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001348 /// \brief Mutate an instruction to another type.
1349 class TypeMutator : public TypePromotionAction {
1350 /// Record the original type.
1351 Type *OrigTy;
1352
1353 public:
1354 /// \brief Mutate the type of \p Inst into \p NewTy.
1355 TypeMutator(Instruction *Inst, Type *NewTy)
1356 : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
1357 DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy
1358 << "\n");
1359 Inst->mutateType(NewTy);
1360 }
1361
1362 /// \brief Mutate the instruction back to its original type.
Craig Topper4584cd52014-03-07 09:26:03 +00001363 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001364 DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy
1365 << "\n");
1366 Inst->mutateType(OrigTy);
1367 }
1368 };
1369
1370 /// \brief Replace the uses of an instruction by another instruction.
1371 class UsesReplacer : public TypePromotionAction {
1372 /// Helper structure to keep track of the replaced uses.
1373 struct InstructionAndIdx {
1374 /// The instruction using the instruction.
1375 Instruction *Inst;
1376 /// The index where this instruction is used for Inst.
1377 unsigned Idx;
1378 InstructionAndIdx(Instruction *Inst, unsigned Idx)
1379 : Inst(Inst), Idx(Idx) {}
1380 };
1381
1382 /// Keep track of the original uses (pair Instruction, Index).
1383 SmallVector<InstructionAndIdx, 4> OriginalUses;
1384 typedef SmallVectorImpl<InstructionAndIdx>::iterator use_iterator;
1385
1386 public:
1387 /// \brief Replace all the use of \p Inst by \p New.
1388 UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) {
1389 DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New
1390 << "\n");
1391 // Record the original uses.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001392 for (Use &U : Inst->uses()) {
1393 Instruction *UserI = cast<Instruction>(U.getUser());
1394 OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo()));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001395 }
1396 // Now, we can replace the uses.
1397 Inst->replaceAllUsesWith(New);
1398 }
1399
1400 /// \brief Reassign the original uses of Inst to Inst.
Craig Topper4584cd52014-03-07 09:26:03 +00001401 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001402 DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n");
1403 for (use_iterator UseIt = OriginalUses.begin(),
1404 EndIt = OriginalUses.end();
1405 UseIt != EndIt; ++UseIt) {
1406 UseIt->Inst->setOperand(UseIt->Idx, Inst);
1407 }
1408 }
1409 };
1410
1411 /// \brief Remove an instruction from the IR.
1412 class InstructionRemover : public TypePromotionAction {
1413 /// Original position of the instruction.
1414 InsertionHandler Inserter;
1415 /// Helper structure to hide all the link to the instruction. In other
1416 /// words, this helps to do as if the instruction was removed.
1417 OperandsHider Hider;
1418 /// Keep track of the uses replaced, if any.
1419 UsesReplacer *Replacer;
1420
1421 public:
1422 /// \brief Remove all reference of \p Inst and optinally replace all its
1423 /// uses with New.
Craig Topperc0196b12014-04-14 00:51:57 +00001424 /// \pre If !Inst->use_empty(), then New != nullptr
1425 InstructionRemover(Instruction *Inst, Value *New = nullptr)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001426 : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
Craig Topperc0196b12014-04-14 00:51:57 +00001427 Replacer(nullptr) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001428 if (New)
1429 Replacer = new UsesReplacer(Inst, New);
1430 DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n");
1431 Inst->removeFromParent();
1432 }
1433
1434 ~InstructionRemover() { delete Replacer; }
1435
1436 /// \brief Really remove the instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00001437 void commit() override { delete Inst; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001438
1439 /// \brief Resurrect the instruction and reassign it to the proper uses if
1440 /// new value was provided when build this action.
Craig Topper4584cd52014-03-07 09:26:03 +00001441 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001442 DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n");
1443 Inserter.insert(Inst);
1444 if (Replacer)
1445 Replacer->undo();
1446 Hider.undo();
1447 }
1448 };
1449
1450public:
1451 /// Restoration point.
1452 /// The restoration point is a pointer to an action instead of an iterator
1453 /// because the iterator may be invalidated but not the pointer.
1454 typedef const TypePromotionAction *ConstRestorationPt;
1455 /// Advocate every changes made in that transaction.
1456 void commit();
1457 /// Undo all the changes made after the given point.
1458 void rollback(ConstRestorationPt Point);
1459 /// Get the current restoration point.
1460 ConstRestorationPt getRestorationPoint() const;
1461
1462 /// \name API for IR modification with state keeping to support rollback.
1463 /// @{
1464 /// Same as Instruction::setOperand.
1465 void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
1466 /// Same as Instruction::eraseFromParent.
Craig Topperc0196b12014-04-14 00:51:57 +00001467 void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001468 /// Same as Value::replaceAllUsesWith.
1469 void replaceAllUsesWith(Instruction *Inst, Value *New);
1470 /// Same as Value::mutateType.
1471 void mutateType(Instruction *Inst, Type *NewTy);
1472 /// Same as IRBuilder::createTrunc.
Quentin Colombetac55b152014-09-16 22:36:07 +00001473 Value *createTrunc(Instruction *Opnd, Type *Ty);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001474 /// Same as IRBuilder::createSExt.
Quentin Colombetac55b152014-09-16 22:36:07 +00001475 Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001476 /// Same as IRBuilder::createZExt.
Quentin Colombetac55b152014-09-16 22:36:07 +00001477 Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001478 /// Same as Instruction::moveBefore.
1479 void moveBefore(Instruction *Inst, Instruction *Before);
1480 /// @}
1481
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001482private:
1483 /// The ordered list of actions made so far.
David Blaikie7620b312014-04-15 06:17:44 +00001484 SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions;
1485 typedef SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator CommitPt;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001486};
1487
1488void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
1489 Value *NewVal) {
1490 Actions.push_back(
David Blaikie7620b312014-04-15 06:17:44 +00001491 make_unique<TypePromotionTransaction::OperandSetter>(Inst, Idx, NewVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001492}
1493
1494void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
1495 Value *NewVal) {
1496 Actions.push_back(
David Blaikie7620b312014-04-15 06:17:44 +00001497 make_unique<TypePromotionTransaction::InstructionRemover>(Inst, NewVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001498}
1499
1500void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
1501 Value *New) {
David Blaikie7620b312014-04-15 06:17:44 +00001502 Actions.push_back(make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001503}
1504
1505void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
David Blaikie7620b312014-04-15 06:17:44 +00001506 Actions.push_back(make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001507}
1508
Quentin Colombetac55b152014-09-16 22:36:07 +00001509Value *TypePromotionTransaction::createTrunc(Instruction *Opnd,
1510 Type *Ty) {
David Blaikie7620b312014-04-15 06:17:44 +00001511 std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00001512 Value *Val = Ptr->getBuiltValue();
David Blaikie7620b312014-04-15 06:17:44 +00001513 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00001514 return Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001515}
1516
Quentin Colombetac55b152014-09-16 22:36:07 +00001517Value *TypePromotionTransaction::createSExt(Instruction *Inst,
1518 Value *Opnd, Type *Ty) {
David Blaikie7620b312014-04-15 06:17:44 +00001519 std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00001520 Value *Val = Ptr->getBuiltValue();
David Blaikie7620b312014-04-15 06:17:44 +00001521 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00001522 return Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001523}
1524
Quentin Colombetac55b152014-09-16 22:36:07 +00001525Value *TypePromotionTransaction::createZExt(Instruction *Inst,
1526 Value *Opnd, Type *Ty) {
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001527 std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00001528 Value *Val = Ptr->getBuiltValue();
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001529 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00001530 return Val;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001531}
1532
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001533void 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:
Eli Benderskyf13a0562014-05-22 00:02:52 +00001697 case Instruction::AddrSpaceCast:
Chandler Carruthc8925912013-01-05 02:09:22 +00001698 // Don't touch identity bitcasts.
1699 if (I->getType() == I->getOperand(0)->getType())
1700 return false;
1701 return I->getType()->isPointerTy() || I->getType()->isIntegerTy();
1702 case Instruction::PtrToInt:
1703 // PtrToInt is always a noop, as we know that the int type is pointer sized.
1704 return true;
1705 case Instruction::IntToPtr:
1706 // We know the input is intptr_t, so this is foldable.
1707 return true;
1708 case Instruction::Add:
1709 return true;
1710 case Instruction::Mul:
1711 case Instruction::Shl:
1712 // Can only handle X*C and X << C.
1713 return isa<ConstantInt>(I->getOperand(1));
1714 case Instruction::GetElementPtr:
1715 return true;
1716 default:
1717 return false;
1718 }
1719}
1720
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001721/// \brief Hepler class to perform type promotion.
1722class TypePromotionHelper {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00001723 /// \brief Utility function to check whether or not a sign or zero extension
1724 /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by
1725 /// either using the operands of \p Inst or promoting \p Inst.
1726 /// The type of the extension is defined by \p IsSExt.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001727 /// In other words, check if:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00001728 /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001729 /// #1 Promotion applies:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00001730 /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...).
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001731 /// #2 Operand reuses:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00001732 /// ext opnd1 to ConsideredExtType.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001733 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00001734 static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType,
1735 const InstrToOrigTy &PromotedInsts, bool IsSExt);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001736
1737 /// \brief Utility function to determine if \p OpIdx should be promoted when
1738 /// promoting \p Inst.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00001739 static bool shouldExtOperand(const Instruction *Inst, int OpIdx) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001740 if (isa<SelectInst>(Inst) && OpIdx == 0)
1741 return false;
1742 return true;
1743 }
1744
Quentin Colombetf5485bb2014-11-13 01:44:51 +00001745 /// \brief Utility function to promote the operand of \p Ext when this
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001746 /// operand is a promotable trunc or sext or zext.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001747 /// \p PromotedInsts maps the instructions to their type before promotion.
1748 /// \p CreatedInsts[out] contains how many non-free instructions have been
Quentin Colombetf5485bb2014-11-13 01:44:51 +00001749 /// created to promote the operand of Ext.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001750 /// Should never be called directly.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00001751 /// \return The promoted value which is used instead of Ext.
1752 static Value *promoteOperandForTruncAndAnyExt(Instruction *Ext,
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001753 TypePromotionTransaction &TPT,
1754 InstrToOrigTy &PromotedInsts,
1755 unsigned &CreatedInsts);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001756
Quentin Colombetf5485bb2014-11-13 01:44:51 +00001757 /// \brief Utility function to promote the operand of \p Ext when this
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001758 /// operand is promotable and is not a supported trunc or sext.
1759 /// \p PromotedInsts maps the instructions to their type before promotion.
1760 /// \p CreatedInsts[out] contains how many non-free instructions have been
Quentin Colombetf5485bb2014-11-13 01:44:51 +00001761 /// created to promote the operand of Ext.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001762 /// Should never be called directly.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00001763 /// \return The promoted value which is used instead of Ext.
1764 static Value *promoteOperandForOther(Instruction *Ext,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001765 TypePromotionTransaction &TPT,
1766 InstrToOrigTy &PromotedInsts,
Quentin Colombetf5485bb2014-11-13 01:44:51 +00001767 unsigned &CreatedInsts, bool IsSExt);
1768
1769 /// \see promoteOperandForOther.
1770 static Value *signExtendOperandForOther(Instruction *Ext,
1771 TypePromotionTransaction &TPT,
1772 InstrToOrigTy &PromotedInsts,
1773 unsigned &CreatedInsts) {
1774 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInsts, true);
1775 }
1776
1777 /// \see promoteOperandForOther.
1778 static Value *zeroExtendOperandForOther(Instruction *Ext,
1779 TypePromotionTransaction &TPT,
1780 InstrToOrigTy &PromotedInsts,
1781 unsigned &CreatedInsts) {
1782 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInsts, false);
1783 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001784
1785public:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00001786 /// Type for the utility function that promotes the operand of Ext.
1787 typedef Value *(*Action)(Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001788 InstrToOrigTy &PromotedInsts,
1789 unsigned &CreatedInsts);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00001790 /// \brief Given a sign/zero extend instruction \p Ext, return the approriate
1791 /// action to promote the operand of \p Ext instead of using Ext.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001792 /// \return NULL if no promotable action is possible with the current
1793 /// sign extension.
1794 /// \p InsertedTruncs keeps track of all the truncate instructions inserted by
1795 /// the others CodeGenPrepare optimizations. This information is important
1796 /// because we do not want to promote these instructions as CodeGenPrepare
1797 /// will reinsert them later. Thus creating an infinite loop: create/remove.
1798 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00001799 static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedTruncs,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001800 const TargetLowering &TLI,
1801 const InstrToOrigTy &PromotedInsts);
1802};
1803
1804bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
Quentin Colombetf5485bb2014-11-13 01:44:51 +00001805 Type *ConsideredExtType,
1806 const InstrToOrigTy &PromotedInsts,
1807 bool IsSExt) {
1808 // We can always get through zext.
1809 if (isa<ZExtInst>(Inst))
1810 return true;
1811
1812 // sext(sext) is ok too.
1813 if (IsSExt && isa<SExtInst>(Inst))
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001814 return true;
1815
1816 // We can get through binary operator, if it is legal. In other words, the
1817 // binary operator must have a nuw or nsw flag.
1818 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
1819 if (BinOp && isa<OverflowingBinaryOperator>(BinOp) &&
Quentin Colombetf5485bb2014-11-13 01:44:51 +00001820 ((!IsSExt && BinOp->hasNoUnsignedWrap()) ||
1821 (IsSExt && BinOp->hasNoSignedWrap())))
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001822 return true;
1823
1824 // Check if we can do the following simplification.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00001825 // ext(trunc(opnd)) --> ext(opnd)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001826 if (!isa<TruncInst>(Inst))
1827 return false;
1828
1829 Value *OpndVal = Inst->getOperand(0);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00001830 // Check if we can use this operand in the extension.
1831 // If the type is larger than the result type of the extension,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001832 // we cannot.
1833 if (OpndVal->getType()->getIntegerBitWidth() >
Quentin Colombetf5485bb2014-11-13 01:44:51 +00001834 ConsideredExtType->getIntegerBitWidth())
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001835 return false;
1836
1837 // If the operand of the truncate is not an instruction, we will not have
1838 // any information on the dropped bits.
1839 // (Actually we could for constant but it is not worth the extra logic).
1840 Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
1841 if (!Opnd)
1842 return false;
1843
1844 // Check if the source of the type is narrow enough.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00001845 // I.e., check that trunc just drops extended bits of the same kind of
1846 // the extension.
1847 // #1 get the type of the operand and check the kind of the extended bits.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001848 const Type *OpndType;
1849 InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00001850 if (It != PromotedInsts.end() && It->second.IsSExt == IsSExt)
1851 OpndType = It->second.Ty;
1852 else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd)))
1853 OpndType = Opnd->getOperand(0)->getType();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001854 else
1855 return false;
1856
Quentin Colombetf5485bb2014-11-13 01:44:51 +00001857 // #2 check that the truncate just drop extended bits.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001858 if (Inst->getType()->getIntegerBitWidth() >= OpndType->getIntegerBitWidth())
1859 return true;
1860
1861 return false;
1862}
1863
1864TypePromotionHelper::Action TypePromotionHelper::getAction(
Quentin Colombetf5485bb2014-11-13 01:44:51 +00001865 Instruction *Ext, const SetOfInstrs &InsertedTruncs,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001866 const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00001867 assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
1868 "Unexpected instruction type");
1869 Instruction *ExtOpnd = dyn_cast<Instruction>(Ext->getOperand(0));
1870 Type *ExtTy = Ext->getType();
1871 bool IsSExt = isa<SExtInst>(Ext);
1872 // If the operand of the extension is not an instruction, we cannot
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001873 // get through.
1874 // If it, check we can get through.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00001875 if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt))
Craig Topperc0196b12014-04-14 00:51:57 +00001876 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001877
1878 // Do not promote if the operand has been added by codegenprepare.
1879 // Otherwise, it means we are undoing an optimization that is likely to be
1880 // redone, thus causing potential infinite loop.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00001881 if (isa<TruncInst>(ExtOpnd) && InsertedTruncs.count(ExtOpnd))
Craig Topperc0196b12014-04-14 00:51:57 +00001882 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001883
1884 // SExt or Trunc instructions.
1885 // Return the related handler.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00001886 if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) ||
1887 isa<ZExtInst>(ExtOpnd))
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001888 return promoteOperandForTruncAndAnyExt;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001889
1890 // Regular instruction.
1891 // Abort early if we will have to insert non-free instructions.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00001892 if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(ExtTy, ExtOpnd->getType()))
Craig Topperc0196b12014-04-14 00:51:57 +00001893 return nullptr;
Quentin Colombetf5485bb2014-11-13 01:44:51 +00001894 return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001895}
1896
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001897Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt(
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001898 llvm::Instruction *SExt, TypePromotionTransaction &TPT,
1899 InstrToOrigTy &PromotedInsts, 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));
Quentin Colombetac55b152014-09-16 22:36:07 +00001903 Value *ExtVal = SExt;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001904 if (isa<ZExtInst>(SExtOpnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00001905 // Replace s|zext(zext(opnd))
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001906 // => zext(opnd).
Quentin Colombetac55b152014-09-16 22:36:07 +00001907 Value *ZExt =
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001908 TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType());
1909 TPT.replaceAllUsesWith(SExt, ZExt);
1910 TPT.eraseInstruction(SExt);
Quentin Colombetac55b152014-09-16 22:36:07 +00001911 ExtVal = ZExt;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001912 } else {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00001913 // Replace z|sext(trunc(opnd)) or sext(sext(opnd))
1914 // => z|sext(opnd).
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001915 TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
1916 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001917 CreatedInsts = 0;
1918
1919 // Remove dead code.
1920 if (SExtOpnd->use_empty())
1921 TPT.eraseInstruction(SExtOpnd);
1922
Quentin Colombet9dcb7242014-09-15 18:26:58 +00001923 // Check if the extension is still needed.
Quentin Colombetac55b152014-09-16 22:36:07 +00001924 Instruction *ExtInst = dyn_cast<Instruction>(ExtVal);
1925 if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType())
1926 return ExtVal;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001927
Quentin Colombet9dcb7242014-09-15 18:26:58 +00001928 // At this point we have: ext ty opnd to ty.
1929 // Reassign the uses of ExtInst to the opnd and remove ExtInst.
1930 Value *NextVal = ExtInst->getOperand(0);
1931 TPT.eraseInstruction(ExtInst, NextVal);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001932 return NextVal;
1933}
1934
Quentin Colombetf5485bb2014-11-13 01:44:51 +00001935Value *TypePromotionHelper::promoteOperandForOther(
1936 Instruction *Ext, TypePromotionTransaction &TPT,
1937 InstrToOrigTy &PromotedInsts, unsigned &CreatedInsts, bool IsSExt) {
1938 // By construction, the operand of Ext is an instruction. Otherwise we cannot
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001939 // get through it and this method should not be called.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00001940 Instruction *ExtOpnd = cast<Instruction>(Ext->getOperand(0));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001941 CreatedInsts = 0;
Quentin Colombetf5485bb2014-11-13 01:44:51 +00001942 if (!ExtOpnd->hasOneUse()) {
1943 // ExtOpnd will be promoted.
1944 // All its uses, but Ext, will need to use a truncated value of the
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001945 // promoted version.
1946 // Create the truncate now.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00001947 Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->getType());
Quentin Colombetac55b152014-09-16 22:36:07 +00001948 if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) {
1949 ITrunc->removeFromParent();
1950 // Insert it just after the definition.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00001951 ITrunc->insertAfter(ExtOpnd);
Quentin Colombetac55b152014-09-16 22:36:07 +00001952 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001953
Quentin Colombetf5485bb2014-11-13 01:44:51 +00001954 TPT.replaceAllUsesWith(ExtOpnd, Trunc);
1955 // Restore the operand of Ext (which has been replace by the previous call
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001956 // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00001957 TPT.setOperand(Ext, 0, ExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001958 }
1959
1960 // Get through the Instruction:
1961 // 1. Update its type.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00001962 // 2. Replace the uses of Ext by Inst.
1963 // 3. Extend each operand that needs to be extended.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001964
1965 // Remember the original type of the instruction before promotion.
1966 // This is useful to know that the high bits are sign extended bits.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00001967 PromotedInsts.insert(std::pair<Instruction *, TypeIsSExt>(
1968 ExtOpnd, TypeIsSExt(ExtOpnd->getType(), IsSExt)));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001969 // Step #1.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00001970 TPT.mutateType(ExtOpnd, Ext->getType());
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001971 // Step #2.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00001972 TPT.replaceAllUsesWith(Ext, ExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001973 // Step #3.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00001974 Instruction *ExtForOpnd = Ext;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001975
Quentin Colombetf5485bb2014-11-13 01:44:51 +00001976 DEBUG(dbgs() << "Propagate Ext to operands\n");
1977 for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001978 ++OpIdx) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00001979 DEBUG(dbgs() << "Operand:\n" << *(ExtOpnd->getOperand(OpIdx)) << '\n');
1980 if (ExtOpnd->getOperand(OpIdx)->getType() == Ext->getType() ||
1981 !shouldExtOperand(ExtOpnd, OpIdx)) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001982 DEBUG(dbgs() << "No need to propagate\n");
1983 continue;
1984 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00001985 // Check if we can statically extend the operand.
1986 Value *Opnd = ExtOpnd->getOperand(OpIdx);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001987 if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00001988 DEBUG(dbgs() << "Statically extend\n");
1989 unsigned BitWidth = Ext->getType()->getIntegerBitWidth();
1990 APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth)
1991 : Cst->getValue().zext(BitWidth);
1992 TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->getType(), CstVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001993 continue;
1994 }
1995 // UndefValue are typed, so we have to statically sign extend them.
1996 if (isa<UndefValue>(Opnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00001997 DEBUG(dbgs() << "Statically extend\n");
1998 TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->getType()));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001999 continue;
2000 }
2001
2002 // Otherwise we have to explicity sign extend the operand.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002003 // Check if Ext was reused to extend an operand.
2004 if (!ExtForOpnd) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002005 // If yes, create a new one.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002006 DEBUG(dbgs() << "More operands to ext\n");
2007 ExtForOpnd =
2008 cast<Instruction>(IsSExt ? TPT.createSExt(Ext, Opnd, Ext->getType())
2009 : TPT.createZExt(Ext, Opnd, Ext->getType()));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002010 ++CreatedInsts;
2011 }
2012
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002013 TPT.setOperand(ExtForOpnd, 0, Opnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002014
2015 // Move the sign extension before the insertion point.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002016 TPT.moveBefore(ExtForOpnd, ExtOpnd);
2017 TPT.setOperand(ExtOpnd, OpIdx, ExtForOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002018 // If more sext are required, new instructions will have to be created.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002019 ExtForOpnd = nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002020 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002021 if (ExtForOpnd == Ext) {
2022 DEBUG(dbgs() << "Extension is useless now\n");
2023 TPT.eraseInstruction(Ext);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002024 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002025 return ExtOpnd;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002026}
2027
Quentin Colombet867c5502014-02-14 22:23:22 +00002028/// IsPromotionProfitable - Check whether or not promoting an instruction
2029/// to a wider type was profitable.
2030/// \p MatchedSize gives the number of instructions that have been matched
2031/// in the addressing mode after the promotion was applied.
2032/// \p SizeWithPromotion gives the number of created instructions for
2033/// the promotion plus the number of instructions that have been
2034/// matched in the addressing mode before the promotion.
2035/// \p PromotedOperand is the value that has been promoted.
2036/// \return True if the promotion is profitable, false otherwise.
2037bool
2038AddressingModeMatcher::IsPromotionProfitable(unsigned MatchedSize,
2039 unsigned SizeWithPromotion,
2040 Value *PromotedOperand) const {
2041 // We folded less instructions than what we created to promote the operand.
2042 // This is not profitable.
2043 if (MatchedSize < SizeWithPromotion)
2044 return false;
2045 if (MatchedSize > SizeWithPromotion)
2046 return true;
2047 // The promotion is neutral but it may help folding the sign extension in
2048 // loads for instance.
2049 // Check that we did not create an illegal instruction.
2050 Instruction *PromotedInst = dyn_cast<Instruction>(PromotedOperand);
2051 if (!PromotedInst)
2052 return false;
Quentin Colombet1627a412014-02-22 01:06:41 +00002053 int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode());
2054 // If the ISDOpcode is undefined, it was undefined before the promotion.
2055 if (!ISDOpcode)
2056 return true;
2057 // Otherwise, check if the promoted instruction is legal or not.
Ahmed Bougacha026600d2014-11-12 23:05:03 +00002058 return TLI.isOperationLegalOrCustom(
2059 ISDOpcode, TLI.getValueType(PromotedInst->getType()));
Quentin Colombet867c5502014-02-14 22:23:22 +00002060}
2061
Chandler Carruthc8925912013-01-05 02:09:22 +00002062/// MatchOperationAddr - Given an instruction or constant expr, see if we can
2063/// fold the operation into the addressing mode. If so, update the addressing
2064/// mode and return true, otherwise return false without modifying AddrMode.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002065/// If \p MovedAway is not NULL, it contains the information of whether or
2066/// not AddrInst has to be folded into the addressing mode on success.
2067/// If \p MovedAway == true, \p AddrInst will not be part of the addressing
2068/// because it has been moved away.
2069/// Thus AddrInst must not be added in the matched instructions.
2070/// This state can happen when AddrInst is a sext, since it may be moved away.
2071/// Therefore, AddrInst may not be valid when MovedAway is true and it must
2072/// not be referenced anymore.
Chandler Carruthc8925912013-01-05 02:09:22 +00002073bool AddressingModeMatcher::MatchOperationAddr(User *AddrInst, unsigned Opcode,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002074 unsigned Depth,
2075 bool *MovedAway) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002076 // Avoid exponential behavior on extremely deep expression trees.
2077 if (Depth >= 5) return false;
Stephen Lin837bba12013-07-15 17:55:02 +00002078
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002079 // By default, all matched instructions stay in place.
2080 if (MovedAway)
2081 *MovedAway = false;
2082
Chandler Carruthc8925912013-01-05 02:09:22 +00002083 switch (Opcode) {
2084 case Instruction::PtrToInt:
2085 // PtrToInt is always a noop, as we know that the int type is pointer sized.
2086 return MatchAddr(AddrInst->getOperand(0), Depth);
2087 case Instruction::IntToPtr:
2088 // This inttoptr is a no-op if the integer type is pointer sized.
2089 if (TLI.getValueType(AddrInst->getOperand(0)->getType()) ==
Matt Arsenault37d42ec2013-09-06 00:18:43 +00002090 TLI.getPointerTy(AddrInst->getType()->getPointerAddressSpace()))
Chandler Carruthc8925912013-01-05 02:09:22 +00002091 return MatchAddr(AddrInst->getOperand(0), Depth);
2092 return false;
2093 case Instruction::BitCast:
Eli Benderskyf13a0562014-05-22 00:02:52 +00002094 case Instruction::AddrSpaceCast:
Chandler Carruthc8925912013-01-05 02:09:22 +00002095 // BitCast is always a noop, and we can handle it as long as it is
2096 // int->int or pointer->pointer (we don't want int<->fp or something).
2097 if ((AddrInst->getOperand(0)->getType()->isPointerTy() ||
2098 AddrInst->getOperand(0)->getType()->isIntegerTy()) &&
2099 // Don't touch identity bitcasts. These were probably put here by LSR,
2100 // and we don't want to mess around with them. Assume it knows what it
2101 // is doing.
2102 AddrInst->getOperand(0)->getType() != AddrInst->getType())
2103 return MatchAddr(AddrInst->getOperand(0), Depth);
2104 return false;
2105 case Instruction::Add: {
2106 // Check to see if we can merge in the RHS then the LHS. If so, we win.
2107 ExtAddrMode BackupAddrMode = AddrMode;
2108 unsigned OldSize = AddrModeInsts.size();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002109 // Start a transaction at this point.
2110 // The LHS may match but not the RHS.
2111 // Therefore, we need a higher level restoration point to undo partially
2112 // matched operation.
2113 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2114 TPT.getRestorationPoint();
2115
Chandler Carruthc8925912013-01-05 02:09:22 +00002116 if (MatchAddr(AddrInst->getOperand(1), Depth+1) &&
2117 MatchAddr(AddrInst->getOperand(0), Depth+1))
2118 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002119
Chandler Carruthc8925912013-01-05 02:09:22 +00002120 // Restore the old addr mode info.
2121 AddrMode = BackupAddrMode;
2122 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002123 TPT.rollback(LastKnownGood);
Stephen Lin837bba12013-07-15 17:55:02 +00002124
Chandler Carruthc8925912013-01-05 02:09:22 +00002125 // Otherwise this was over-aggressive. Try merging in the LHS then the RHS.
2126 if (MatchAddr(AddrInst->getOperand(0), Depth+1) &&
2127 MatchAddr(AddrInst->getOperand(1), Depth+1))
2128 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002129
Chandler Carruthc8925912013-01-05 02:09:22 +00002130 // Otherwise we definitely can't merge the ADD in.
2131 AddrMode = BackupAddrMode;
2132 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002133 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00002134 break;
2135 }
2136 //case Instruction::Or:
2137 // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
2138 //break;
2139 case Instruction::Mul:
2140 case Instruction::Shl: {
2141 // Can only handle X*C and X << C.
2142 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
Sanjay Pateld3bbfa12014-07-16 22:40:28 +00002143 if (!RHS)
2144 return false;
Chandler Carruthc8925912013-01-05 02:09:22 +00002145 int64_t Scale = RHS->getSExtValue();
2146 if (Opcode == Instruction::Shl)
2147 Scale = 1LL << Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00002148
Chandler Carruthc8925912013-01-05 02:09:22 +00002149 return MatchScaledValue(AddrInst->getOperand(0), Scale, Depth);
2150 }
2151 case Instruction::GetElementPtr: {
2152 // Scan the GEP. We check it if it contains constant offsets and at most
2153 // one variable offset.
2154 int VariableOperand = -1;
2155 unsigned VariableScale = 0;
Stephen Lin837bba12013-07-15 17:55:02 +00002156
Chandler Carruthc8925912013-01-05 02:09:22 +00002157 int64_t ConstantOffset = 0;
2158 const DataLayout *TD = TLI.getDataLayout();
2159 gep_type_iterator GTI = gep_type_begin(AddrInst);
2160 for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
2161 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
2162 const StructLayout *SL = TD->getStructLayout(STy);
2163 unsigned Idx =
2164 cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
2165 ConstantOffset += SL->getElementOffset(Idx);
2166 } else {
2167 uint64_t TypeSize = TD->getTypeAllocSize(GTI.getIndexedType());
2168 if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
2169 ConstantOffset += CI->getSExtValue()*TypeSize;
2170 } else if (TypeSize) { // Scales of zero don't do anything.
2171 // We only allow one variable index at the moment.
2172 if (VariableOperand != -1)
2173 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00002174
Chandler Carruthc8925912013-01-05 02:09:22 +00002175 // Remember the variable index.
2176 VariableOperand = i;
2177 VariableScale = TypeSize;
2178 }
2179 }
2180 }
Stephen Lin837bba12013-07-15 17:55:02 +00002181
Chandler Carruthc8925912013-01-05 02:09:22 +00002182 // A common case is for the GEP to only do a constant offset. In this case,
2183 // just add it to the disp field and check validity.
2184 if (VariableOperand == -1) {
2185 AddrMode.BaseOffs += ConstantOffset;
2186 if (ConstantOffset == 0 || TLI.isLegalAddressingMode(AddrMode, AccessTy)){
2187 // Check to see if we can fold the base pointer in too.
2188 if (MatchAddr(AddrInst->getOperand(0), Depth+1))
2189 return true;
2190 }
2191 AddrMode.BaseOffs -= ConstantOffset;
2192 return false;
2193 }
2194
2195 // Save the valid addressing mode in case we can't match.
2196 ExtAddrMode BackupAddrMode = AddrMode;
2197 unsigned OldSize = AddrModeInsts.size();
2198
2199 // See if the scale and offset amount is valid for this target.
2200 AddrMode.BaseOffs += ConstantOffset;
2201
2202 // Match the base operand of the GEP.
2203 if (!MatchAddr(AddrInst->getOperand(0), Depth+1)) {
2204 // If it couldn't be matched, just stuff the value in a register.
2205 if (AddrMode.HasBaseReg) {
2206 AddrMode = BackupAddrMode;
2207 AddrModeInsts.resize(OldSize);
2208 return false;
2209 }
2210 AddrMode.HasBaseReg = true;
2211 AddrMode.BaseReg = AddrInst->getOperand(0);
2212 }
2213
2214 // Match the remaining variable portion of the GEP.
2215 if (!MatchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
2216 Depth)) {
2217 // If it couldn't be matched, try stuffing the base into a register
2218 // instead of matching it, and retrying the match of the scale.
2219 AddrMode = BackupAddrMode;
2220 AddrModeInsts.resize(OldSize);
2221 if (AddrMode.HasBaseReg)
2222 return false;
2223 AddrMode.HasBaseReg = true;
2224 AddrMode.BaseReg = AddrInst->getOperand(0);
2225 AddrMode.BaseOffs += ConstantOffset;
2226 if (!MatchScaledValue(AddrInst->getOperand(VariableOperand),
2227 VariableScale, Depth)) {
2228 // If even that didn't work, bail.
2229 AddrMode = BackupAddrMode;
2230 AddrModeInsts.resize(OldSize);
2231 return false;
2232 }
2233 }
2234
2235 return true;
2236 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002237 case Instruction::SExt:
2238 case Instruction::ZExt: {
2239 Instruction *Ext = dyn_cast<Instruction>(AddrInst);
2240 if (!Ext)
Sanjay Pateld3bbfa12014-07-16 22:40:28 +00002241 return false;
Sanjay Patelab60d042014-07-16 21:08:10 +00002242
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002243 // Try to move this ext out of the way of the addressing mode.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002244 // Ask for a method for doing so.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002245 TypePromotionHelper::Action TPH =
2246 TypePromotionHelper::getAction(Ext, InsertedTruncs, TLI, PromotedInsts);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002247 if (!TPH)
2248 return false;
2249
2250 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2251 TPT.getRestorationPoint();
2252 unsigned CreatedInsts = 0;
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002253 Value *PromotedOperand = TPH(Ext, TPT, PromotedInsts, CreatedInsts);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002254 // SExt has been moved away.
2255 // Thus either it will be rematched later in the recursive calls or it is
2256 // gone. Anyway, we must not fold it into the addressing mode at this point.
2257 // E.g.,
2258 // op = add opnd, 1
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002259 // idx = ext op
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002260 // addr = gep base, idx
2261 // is now:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002262 // promotedOpnd = ext opnd <- no match here
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002263 // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls)
2264 // addr = gep base, op <- match
2265 if (MovedAway)
2266 *MovedAway = true;
2267
2268 assert(PromotedOperand &&
2269 "TypePromotionHelper should have filtered out those cases");
2270
2271 ExtAddrMode BackupAddrMode = AddrMode;
2272 unsigned OldSize = AddrModeInsts.size();
2273
2274 if (!MatchAddr(PromotedOperand, Depth) ||
Quentin Colombet867c5502014-02-14 22:23:22 +00002275 !IsPromotionProfitable(AddrModeInsts.size(), OldSize + CreatedInsts,
2276 PromotedOperand)) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002277 AddrMode = BackupAddrMode;
2278 AddrModeInsts.resize(OldSize);
2279 DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
2280 TPT.rollback(LastKnownGood);
2281 return false;
2282 }
2283 return true;
2284 }
Chandler Carruthc8925912013-01-05 02:09:22 +00002285 }
2286 return false;
2287}
2288
2289/// MatchAddr - If we can, try to add the value of 'Addr' into the current
2290/// addressing mode. If Addr can't be added to AddrMode this returns false and
2291/// leaves AddrMode unmodified. This assumes that Addr is either a pointer type
2292/// or intptr_t for the target.
2293///
2294bool AddressingModeMatcher::MatchAddr(Value *Addr, unsigned Depth) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002295 // Start a transaction at this point that we will rollback if the matching
2296 // fails.
2297 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2298 TPT.getRestorationPoint();
Chandler Carruthc8925912013-01-05 02:09:22 +00002299 if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
2300 // Fold in immediates if legal for the target.
2301 AddrMode.BaseOffs += CI->getSExtValue();
2302 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2303 return true;
2304 AddrMode.BaseOffs -= CI->getSExtValue();
2305 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
2306 // If this is a global variable, try to fold it into the addressing mode.
Craig Topperc0196b12014-04-14 00:51:57 +00002307 if (!AddrMode.BaseGV) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002308 AddrMode.BaseGV = GV;
2309 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2310 return true;
Craig Topperc0196b12014-04-14 00:51:57 +00002311 AddrMode.BaseGV = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00002312 }
2313 } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
2314 ExtAddrMode BackupAddrMode = AddrMode;
2315 unsigned OldSize = AddrModeInsts.size();
2316
2317 // Check to see if it is possible to fold this operation.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002318 bool MovedAway = false;
2319 if (MatchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
2320 // This instruction may have been move away. If so, there is nothing
2321 // to check here.
2322 if (MovedAway)
2323 return true;
Chandler Carruthc8925912013-01-05 02:09:22 +00002324 // Okay, it's possible to fold this. Check to see if it is actually
2325 // *profitable* to do so. We use a simple cost model to avoid increasing
2326 // register pressure too much.
2327 if (I->hasOneUse() ||
2328 IsProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
2329 AddrModeInsts.push_back(I);
2330 return true;
2331 }
Stephen Lin837bba12013-07-15 17:55:02 +00002332
Chandler Carruthc8925912013-01-05 02:09:22 +00002333 // It isn't profitable to do this, roll back.
2334 //cerr << "NOT FOLDING: " << *I;
2335 AddrMode = BackupAddrMode;
2336 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002337 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00002338 }
2339 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
2340 if (MatchOperationAddr(CE, CE->getOpcode(), Depth))
2341 return true;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002342 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00002343 } else if (isa<ConstantPointerNull>(Addr)) {
2344 // Null pointer gets folded without affecting the addressing mode.
2345 return true;
2346 }
2347
2348 // Worse case, the target should support [reg] addressing modes. :)
2349 if (!AddrMode.HasBaseReg) {
2350 AddrMode.HasBaseReg = true;
2351 AddrMode.BaseReg = Addr;
2352 // Still check for legality in case the target supports [imm] but not [i+r].
2353 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2354 return true;
2355 AddrMode.HasBaseReg = false;
Craig Topperc0196b12014-04-14 00:51:57 +00002356 AddrMode.BaseReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00002357 }
2358
2359 // If the base register is already taken, see if we can do [r+r].
2360 if (AddrMode.Scale == 0) {
2361 AddrMode.Scale = 1;
2362 AddrMode.ScaledReg = Addr;
2363 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2364 return true;
2365 AddrMode.Scale = 0;
Craig Topperc0196b12014-04-14 00:51:57 +00002366 AddrMode.ScaledReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00002367 }
2368 // Couldn't match.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002369 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00002370 return false;
2371}
2372
2373/// IsOperandAMemoryOperand - Check to see if all uses of OpVal by the specified
2374/// inline asm call are due to memory operands. If so, return true, otherwise
2375/// return false.
2376static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
2377 const TargetLowering &TLI) {
2378 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(ImmutableCallSite(CI));
2379 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
2380 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Stephen Lin837bba12013-07-15 17:55:02 +00002381
Chandler Carruthc8925912013-01-05 02:09:22 +00002382 // Compute the constraint code and ConstraintType to use.
2383 TLI.ComputeConstraintToUse(OpInfo, SDValue());
2384
2385 // If this asm operand is our Value*, and if it isn't an indirect memory
2386 // operand, we can't fold it!
2387 if (OpInfo.CallOperandVal == OpVal &&
2388 (OpInfo.ConstraintType != TargetLowering::C_Memory ||
2389 !OpInfo.isIndirect))
2390 return false;
2391 }
2392
2393 return true;
2394}
2395
2396/// FindAllMemoryUses - Recursively walk all the uses of I until we find a
2397/// memory use. If we find an obviously non-foldable instruction, return true.
2398/// Add the ultimately found memory instructions to MemoryUses.
2399static bool FindAllMemoryUses(Instruction *I,
2400 SmallVectorImpl<std::pair<Instruction*,unsigned> > &MemoryUses,
Craig Topper71b7b682014-08-21 05:55:13 +00002401 SmallPtrSetImpl<Instruction*> &ConsideredInsts,
Chandler Carruthc8925912013-01-05 02:09:22 +00002402 const TargetLowering &TLI) {
2403 // If we already considered this instruction, we're done.
David Blaikie70573dc2014-11-19 07:49:26 +00002404 if (!ConsideredInsts.insert(I).second)
Chandler Carruthc8925912013-01-05 02:09:22 +00002405 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00002406
Chandler Carruthc8925912013-01-05 02:09:22 +00002407 // If this is an obviously unfoldable instruction, bail out.
2408 if (!MightBeFoldableInst(I))
2409 return true;
2410
2411 // Loop over all the uses, recursively processing them.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002412 for (Use &U : I->uses()) {
2413 Instruction *UserI = cast<Instruction>(U.getUser());
Chandler Carruthc8925912013-01-05 02:09:22 +00002414
Chandler Carruthcdf47882014-03-09 03:16:01 +00002415 if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
2416 MemoryUses.push_back(std::make_pair(LI, U.getOperandNo()));
Chandler Carruthc8925912013-01-05 02:09:22 +00002417 continue;
2418 }
Stephen Lin837bba12013-07-15 17:55:02 +00002419
Chandler Carruthcdf47882014-03-09 03:16:01 +00002420 if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
2421 unsigned opNo = U.getOperandNo();
Chandler Carruthc8925912013-01-05 02:09:22 +00002422 if (opNo == 0) return true; // Storing addr, not into addr.
2423 MemoryUses.push_back(std::make_pair(SI, opNo));
2424 continue;
2425 }
Stephen Lin837bba12013-07-15 17:55:02 +00002426
Chandler Carruthcdf47882014-03-09 03:16:01 +00002427 if (CallInst *CI = dyn_cast<CallInst>(UserI)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002428 InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
2429 if (!IA) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002430
Chandler Carruthc8925912013-01-05 02:09:22 +00002431 // If this is a memory operand, we're cool, otherwise bail out.
2432 if (!IsOperandAMemoryOperand(CI, IA, I, TLI))
2433 return true;
2434 continue;
2435 }
Stephen Lin837bba12013-07-15 17:55:02 +00002436
Chandler Carruthcdf47882014-03-09 03:16:01 +00002437 if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TLI))
Chandler Carruthc8925912013-01-05 02:09:22 +00002438 return true;
2439 }
2440
2441 return false;
2442}
2443
2444/// ValueAlreadyLiveAtInst - Retrn true if Val is already known to be live at
2445/// the use site that we're folding it into. If so, there is no cost to
2446/// include it in the addressing mode. KnownLive1 and KnownLive2 are two values
2447/// that we know are live at the instruction already.
2448bool AddressingModeMatcher::ValueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
2449 Value *KnownLive2) {
2450 // If Val is either of the known-live values, we know it is live!
Craig Topperc0196b12014-04-14 00:51:57 +00002451 if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2)
Chandler Carruthc8925912013-01-05 02:09:22 +00002452 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002453
Chandler Carruthc8925912013-01-05 02:09:22 +00002454 // All values other than instructions and arguments (e.g. constants) are live.
2455 if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002456
Chandler Carruthc8925912013-01-05 02:09:22 +00002457 // If Val is a constant sized alloca in the entry block, it is live, this is
2458 // true because it is just a reference to the stack/frame pointer, which is
2459 // live for the whole function.
2460 if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
2461 if (AI->isStaticAlloca())
2462 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002463
Chandler Carruthc8925912013-01-05 02:09:22 +00002464 // Check to see if this value is already used in the memory instruction's
2465 // block. If so, it's already live into the block at the very least, so we
2466 // can reasonably fold it.
2467 return Val->isUsedInBasicBlock(MemoryInst->getParent());
2468}
2469
2470/// IsProfitableToFoldIntoAddressingMode - It is possible for the addressing
2471/// mode of the machine to fold the specified instruction into a load or store
2472/// that ultimately uses it. However, the specified instruction has multiple
2473/// uses. Given this, it may actually increase register pressure to fold it
2474/// into the load. For example, consider this code:
2475///
2476/// X = ...
2477/// Y = X+1
2478/// use(Y) -> nonload/store
2479/// Z = Y+1
2480/// load Z
2481///
2482/// In this case, Y has multiple uses, and can be folded into the load of Z
2483/// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to
2484/// be live at the use(Y) line. If we don't fold Y into load Z, we use one
2485/// fewer register. Since Y can't be folded into "use(Y)" we don't increase the
2486/// number of computations either.
2487///
2488/// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If
2489/// X was live across 'load Z' for other reasons, we actually *would* want to
2490/// fold the addressing mode in the Z case. This would make Y die earlier.
2491bool AddressingModeMatcher::
2492IsProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
2493 ExtAddrMode &AMAfter) {
2494 if (IgnoreProfitability) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002495
Chandler Carruthc8925912013-01-05 02:09:22 +00002496 // AMBefore is the addressing mode before this instruction was folded into it,
2497 // and AMAfter is the addressing mode after the instruction was folded. Get
2498 // the set of registers referenced by AMAfter and subtract out those
2499 // referenced by AMBefore: this is the set of values which folding in this
2500 // address extends the lifetime of.
2501 //
2502 // Note that there are only two potential values being referenced here,
2503 // BaseReg and ScaleReg (global addresses are always available, as are any
2504 // folded immediates).
2505 Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
Stephen Lin837bba12013-07-15 17:55:02 +00002506
Chandler Carruthc8925912013-01-05 02:09:22 +00002507 // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
2508 // lifetime wasn't extended by adding this instruction.
2509 if (ValueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
Craig Topperc0196b12014-04-14 00:51:57 +00002510 BaseReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00002511 if (ValueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
Craig Topperc0196b12014-04-14 00:51:57 +00002512 ScaledReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00002513
2514 // If folding this instruction (and it's subexprs) didn't extend any live
2515 // ranges, we're ok with it.
Craig Topperc0196b12014-04-14 00:51:57 +00002516 if (!BaseReg && !ScaledReg)
Chandler Carruthc8925912013-01-05 02:09:22 +00002517 return true;
2518
2519 // If all uses of this instruction are ultimately load/store/inlineasm's,
2520 // check to see if their addressing modes will include this instruction. If
2521 // so, we can fold it into all uses, so it doesn't matter if it has multiple
2522 // uses.
2523 SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
2524 SmallPtrSet<Instruction*, 16> ConsideredInsts;
2525 if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TLI))
2526 return false; // Has a non-memory, non-foldable use!
Stephen Lin837bba12013-07-15 17:55:02 +00002527
Chandler Carruthc8925912013-01-05 02:09:22 +00002528 // Now that we know that all uses of this instruction are part of a chain of
2529 // computation involving only operations that could theoretically be folded
2530 // into a memory use, loop over each of these uses and see if they could
2531 // *actually* fold the instruction.
2532 SmallVector<Instruction*, 32> MatchedAddrModeInsts;
2533 for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
2534 Instruction *User = MemoryUses[i].first;
2535 unsigned OpNo = MemoryUses[i].second;
Stephen Lin837bba12013-07-15 17:55:02 +00002536
Chandler Carruthc8925912013-01-05 02:09:22 +00002537 // Get the access type of this use. If the use isn't a pointer, we don't
2538 // know what it accesses.
2539 Value *Address = User->getOperand(OpNo);
2540 if (!Address->getType()->isPointerTy())
2541 return false;
Matt Arsenault8227b9f2013-09-06 00:37:24 +00002542 Type *AddressAccessTy = Address->getType()->getPointerElementType();
Stephen Lin837bba12013-07-15 17:55:02 +00002543
Chandler Carruthc8925912013-01-05 02:09:22 +00002544 // Do a match against the root of this address, ignoring profitability. This
2545 // will tell us if the addressing mode for the memory operation will
2546 // *actually* cover the shared instruction.
2547 ExtAddrMode Result;
Quentin Colombet5a69dda2014-02-11 01:59:02 +00002548 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2549 TPT.getRestorationPoint();
Chandler Carruthc8925912013-01-05 02:09:22 +00002550 AddressingModeMatcher Matcher(MatchedAddrModeInsts, TLI, AddressAccessTy,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002551 MemoryInst, Result, InsertedTruncs,
2552 PromotedInsts, TPT);
Chandler Carruthc8925912013-01-05 02:09:22 +00002553 Matcher.IgnoreProfitability = true;
2554 bool Success = Matcher.MatchAddr(Address, 0);
2555 (void)Success; assert(Success && "Couldn't select *anything*?");
2556
Quentin Colombet5a69dda2014-02-11 01:59:02 +00002557 // The match was to check the profitability, the changes made are not
2558 // part of the original matcher. Therefore, they should be dropped
2559 // otherwise the original matcher will not present the right state.
2560 TPT.rollback(LastKnownGood);
2561
Chandler Carruthc8925912013-01-05 02:09:22 +00002562 // If the match didn't cover I, then it won't be shared by it.
2563 if (std::find(MatchedAddrModeInsts.begin(), MatchedAddrModeInsts.end(),
2564 I) == MatchedAddrModeInsts.end())
2565 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00002566
Chandler Carruthc8925912013-01-05 02:09:22 +00002567 MatchedAddrModeInsts.clear();
2568 }
Stephen Lin837bba12013-07-15 17:55:02 +00002569
Chandler Carruthc8925912013-01-05 02:09:22 +00002570 return true;
2571}
2572
2573} // end anonymous namespace
2574
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002575/// IsNonLocalValue - Return true if the specified values are defined in a
2576/// different basic block than BB.
2577static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
2578 if (Instruction *I = dyn_cast<Instruction>(V))
2579 return I->getParent() != BB;
2580 return false;
2581}
2582
Bob Wilson53bdae32009-12-03 21:47:07 +00002583/// OptimizeMemoryInst - Load and Store Instructions often have
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002584/// addressing modes that can do significant amounts of computation. As such,
2585/// instruction selection will try to get the load or store to do as much
2586/// computation as possible for the program. The problem is that isel can only
2587/// see within a single block. As such, we sink as much legal addressing mode
2588/// stuff into the block as possible.
Chris Lattner728f9022008-11-25 07:09:13 +00002589///
2590/// This method is used to optimize both load/store and inline asms with memory
2591/// operands.
Chris Lattner6d71b7f2008-11-26 03:20:37 +00002592bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
Chris Lattner229907c2011-07-18 04:54:35 +00002593 Type *AccessTy) {
Owen Anderson8ba5f392010-11-27 08:15:55 +00002594 Value *Repl = Addr;
Nadav Rotem465834c2012-07-24 10:51:42 +00002595
2596 // Try to collapse single-value PHI nodes. This is necessary to undo
Owen Andersondfb8c3b2010-11-19 22:15:03 +00002597 // unprofitable PRE transformations.
Cameron Zwarich43cecb12011-01-03 06:33:01 +00002598 SmallVector<Value*, 8> worklist;
2599 SmallPtrSet<Value*, 16> Visited;
Owen Anderson8ba5f392010-11-27 08:15:55 +00002600 worklist.push_back(Addr);
Nadav Rotem465834c2012-07-24 10:51:42 +00002601
Owen Anderson8ba5f392010-11-27 08:15:55 +00002602 // Use a worklist to iteratively look through PHI nodes, and ensure that
2603 // the addressing mode obtained from the non-PHI roots of the graph
2604 // are equivalent.
Craig Topperc0196b12014-04-14 00:51:57 +00002605 Value *Consensus = nullptr;
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00002606 unsigned NumUsesConsensus = 0;
Cameron Zwarich13c885d2011-03-05 08:12:26 +00002607 bool IsNumUsesConsensusValid = false;
Owen Anderson8ba5f392010-11-27 08:15:55 +00002608 SmallVector<Instruction*, 16> AddrModeInsts;
2609 ExtAddrMode AddrMode;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002610 TypePromotionTransaction TPT;
2611 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2612 TPT.getRestorationPoint();
Owen Anderson8ba5f392010-11-27 08:15:55 +00002613 while (!worklist.empty()) {
2614 Value *V = worklist.back();
2615 worklist.pop_back();
Nadav Rotem465834c2012-07-24 10:51:42 +00002616
Owen Anderson8ba5f392010-11-27 08:15:55 +00002617 // Break use-def graph loops.
David Blaikie70573dc2014-11-19 07:49:26 +00002618 if (!Visited.insert(V).second) {
Craig Topperc0196b12014-04-14 00:51:57 +00002619 Consensus = nullptr;
Owen Anderson8ba5f392010-11-27 08:15:55 +00002620 break;
Owen Andersondfb8c3b2010-11-19 22:15:03 +00002621 }
Nadav Rotem465834c2012-07-24 10:51:42 +00002622
Owen Anderson8ba5f392010-11-27 08:15:55 +00002623 // For a PHI node, push all of its incoming values.
2624 if (PHINode *P = dyn_cast<PHINode>(V)) {
2625 for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i)
2626 worklist.push_back(P->getIncomingValue(i));
2627 continue;
2628 }
Nadav Rotem465834c2012-07-24 10:51:42 +00002629
Owen Anderson8ba5f392010-11-27 08:15:55 +00002630 // For non-PHIs, determine the addressing mode being computed.
2631 SmallVector<Instruction*, 16> NewAddrModeInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002632 ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
2633 V, AccessTy, MemoryInst, NewAddrModeInsts, *TLI, InsertedTruncsSet,
2634 PromotedInsts, TPT);
Cameron Zwarich13c885d2011-03-05 08:12:26 +00002635
2636 // This check is broken into two cases with very similar code to avoid using
2637 // getNumUses() as much as possible. Some values have a lot of uses, so
2638 // calling getNumUses() unconditionally caused a significant compile-time
2639 // regression.
2640 if (!Consensus) {
2641 Consensus = V;
2642 AddrMode = NewAddrMode;
2643 AddrModeInsts = NewAddrModeInsts;
2644 continue;
2645 } else if (NewAddrMode == AddrMode) {
2646 if (!IsNumUsesConsensusValid) {
2647 NumUsesConsensus = Consensus->getNumUses();
2648 IsNumUsesConsensusValid = true;
2649 }
2650
2651 // Ensure that the obtained addressing mode is equivalent to that obtained
2652 // for all other roots of the PHI traversal. Also, when choosing one
2653 // such root as representative, select the one with the most uses in order
2654 // to keep the cost modeling heuristics in AddressingModeMatcher
2655 // applicable.
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00002656 unsigned NumUses = V->getNumUses();
2657 if (NumUses > NumUsesConsensus) {
Owen Anderson8ba5f392010-11-27 08:15:55 +00002658 Consensus = V;
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00002659 NumUsesConsensus = NumUses;
Owen Anderson8ba5f392010-11-27 08:15:55 +00002660 AddrModeInsts = NewAddrModeInsts;
2661 }
2662 continue;
2663 }
Nadav Rotem465834c2012-07-24 10:51:42 +00002664
Craig Topperc0196b12014-04-14 00:51:57 +00002665 Consensus = nullptr;
Owen Anderson8ba5f392010-11-27 08:15:55 +00002666 break;
Owen Andersondfb8c3b2010-11-19 22:15:03 +00002667 }
Nadav Rotem465834c2012-07-24 10:51:42 +00002668
Owen Anderson8ba5f392010-11-27 08:15:55 +00002669 // If the addressing mode couldn't be determined, or if multiple different
2670 // ones were determined, bail out now.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002671 if (!Consensus) {
2672 TPT.rollback(LastKnownGood);
2673 return false;
2674 }
2675 TPT.commit();
Nadav Rotem465834c2012-07-24 10:51:42 +00002676
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002677 // Check to see if any of the instructions supersumed by this addr mode are
2678 // non-local to I's BB.
2679 bool AnyNonLocal = false;
2680 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
Chris Lattner6d71b7f2008-11-26 03:20:37 +00002681 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002682 AnyNonLocal = true;
2683 break;
2684 }
2685 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00002686
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002687 // If all the instructions matched are already in this BB, don't do anything.
2688 if (!AnyNonLocal) {
David Greene74e2d492010-01-05 01:27:11 +00002689 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002690 return false;
2691 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00002692
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002693 // Insert this computation right after this user. Since our caller is
2694 // scanning from the top of the BB to the bottom, reuse of the expr are
2695 // guaranteed to happen later.
Devang Patelc10e52a2011-09-06 18:49:53 +00002696 IRBuilder<> Builder(MemoryInst);
Eric Christopherc1ea1492008-09-24 05:32:41 +00002697
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002698 // Now that we determined the addressing expression we want to use and know
2699 // that we have to sink it into this block. Check to see if we have already
2700 // done this for some other load/store instr in this block. If so, reuse the
2701 // computation.
2702 Value *&SunkAddr = SunkAddrs[Addr];
2703 if (SunkAddr) {
David Greene74e2d492010-01-05 01:27:11 +00002704 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00002705 << *MemoryInst << "\n");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002706 if (SunkAddr->getType() != Addr->getType())
Benjamin Kramer547b6c52011-09-27 20:39:19 +00002707 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
Hal Finkelc3998302014-04-12 00:59:48 +00002708 } else if (AddrSinkUsingGEPs || (!AddrSinkUsingGEPs.getNumOccurrences() &&
2709 TM && TM->getSubtarget<TargetSubtargetInfo>().useAA())) {
2710 // By default, we use the GEP-based method when AA is used later. This
2711 // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities.
2712 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00002713 << *MemoryInst << "\n");
Hal Finkelc3998302014-04-12 00:59:48 +00002714 Type *IntPtrTy = TLI->getDataLayout()->getIntPtrType(Addr->getType());
Craig Topperc0196b12014-04-14 00:51:57 +00002715 Value *ResultPtr = nullptr, *ResultIndex = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00002716
2717 // First, find the pointer.
2718 if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) {
2719 ResultPtr = AddrMode.BaseReg;
Craig Topperc0196b12014-04-14 00:51:57 +00002720 AddrMode.BaseReg = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00002721 }
2722
2723 if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) {
2724 // We can't add more than one pointer together, nor can we scale a
2725 // pointer (both of which seem meaningless).
2726 if (ResultPtr || AddrMode.Scale != 1)
2727 return false;
2728
2729 ResultPtr = AddrMode.ScaledReg;
2730 AddrMode.Scale = 0;
2731 }
2732
2733 if (AddrMode.BaseGV) {
2734 if (ResultPtr)
2735 return false;
2736
2737 ResultPtr = AddrMode.BaseGV;
2738 }
2739
2740 // If the real base value actually came from an inttoptr, then the matcher
2741 // will look through it and provide only the integer value. In that case,
2742 // use it here.
2743 if (!ResultPtr && AddrMode.BaseReg) {
2744 ResultPtr =
2745 Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(), "sunkaddr");
Craig Topperc0196b12014-04-14 00:51:57 +00002746 AddrMode.BaseReg = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00002747 } else if (!ResultPtr && AddrMode.Scale == 1) {
2748 ResultPtr =
2749 Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(), "sunkaddr");
2750 AddrMode.Scale = 0;
2751 }
2752
2753 if (!ResultPtr &&
2754 !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) {
2755 SunkAddr = Constant::getNullValue(Addr->getType());
2756 } else if (!ResultPtr) {
2757 return false;
2758 } else {
2759 Type *I8PtrTy =
2760 Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace());
2761
2762 // Start with the base register. Do this first so that subsequent address
2763 // matching finds it last, which will prevent it from trying to match it
2764 // as the scaled value in case it happens to be a mul. That would be
2765 // problematic if we've sunk a different mul for the scale, because then
2766 // we'd end up sinking both muls.
2767 if (AddrMode.BaseReg) {
2768 Value *V = AddrMode.BaseReg;
2769 if (V->getType() != IntPtrTy)
2770 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
2771
2772 ResultIndex = V;
2773 }
2774
2775 // Add the scale value.
2776 if (AddrMode.Scale) {
2777 Value *V = AddrMode.ScaledReg;
2778 if (V->getType() == IntPtrTy) {
2779 // done.
2780 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
2781 cast<IntegerType>(V->getType())->getBitWidth()) {
2782 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
2783 } else {
2784 // It is only safe to sign extend the BaseReg if we know that the math
2785 // required to create it did not overflow before we extend it. Since
2786 // the original IR value was tossed in favor of a constant back when
2787 // the AddrMode was created we need to bail out gracefully if widths
2788 // do not match instead of extending it.
2789 Instruction *I = dyn_cast_or_null<Instruction>(ResultIndex);
2790 if (I && (ResultIndex != AddrMode.BaseReg))
2791 I->eraseFromParent();
2792 return false;
2793 }
2794
2795 if (AddrMode.Scale != 1)
2796 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
2797 "sunkaddr");
2798 if (ResultIndex)
2799 ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr");
2800 else
2801 ResultIndex = V;
2802 }
2803
2804 // Add in the Base Offset if present.
2805 if (AddrMode.BaseOffs) {
2806 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
2807 if (ResultIndex) {
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00002808 // We need to add this separately from the scale above to help with
2809 // SDAG consecutive load/store merging.
Hal Finkelc3998302014-04-12 00:59:48 +00002810 if (ResultPtr->getType() != I8PtrTy)
2811 ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
2812 ResultPtr = Builder.CreateGEP(ResultPtr, ResultIndex, "sunkaddr");
2813 }
2814
2815 ResultIndex = V;
2816 }
2817
2818 if (!ResultIndex) {
2819 SunkAddr = ResultPtr;
2820 } else {
2821 if (ResultPtr->getType() != I8PtrTy)
2822 ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
2823 SunkAddr = Builder.CreateGEP(ResultPtr, ResultIndex, "sunkaddr");
2824 }
2825
2826 if (SunkAddr->getType() != Addr->getType())
2827 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
2828 }
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002829 } else {
David Greene74e2d492010-01-05 01:27:11 +00002830 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00002831 << *MemoryInst << "\n");
Matt Arsenault37d42ec2013-09-06 00:18:43 +00002832 Type *IntPtrTy = TLI->getDataLayout()->getIntPtrType(Addr->getType());
Craig Topperc0196b12014-04-14 00:51:57 +00002833 Value *Result = nullptr;
Dan Gohmanca194452010-01-19 22:45:06 +00002834
2835 // Start with the base register. Do this first so that subsequent address
2836 // matching finds it last, which will prevent it from trying to match it
2837 // as the scaled value in case it happens to be a mul. That would be
2838 // problematic if we've sunk a different mul for the scale, because then
2839 // we'd end up sinking both muls.
2840 if (AddrMode.BaseReg) {
2841 Value *V = AddrMode.BaseReg;
Duncan Sands19d0b472010-02-16 11:11:14 +00002842 if (V->getType()->isPointerTy())
Devang Patelc10e52a2011-09-06 18:49:53 +00002843 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00002844 if (V->getType() != IntPtrTy)
Devang Patelc10e52a2011-09-06 18:49:53 +00002845 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00002846 Result = V;
2847 }
2848
2849 // Add the scale value.
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002850 if (AddrMode.Scale) {
2851 Value *V = AddrMode.ScaledReg;
2852 if (V->getType() == IntPtrTy) {
2853 // done.
Duncan Sands19d0b472010-02-16 11:11:14 +00002854 } else if (V->getType()->isPointerTy()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00002855 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002856 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
2857 cast<IntegerType>(V->getType())->getBitWidth()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00002858 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002859 } else {
Jim Grosbached2cd392014-03-26 17:27:01 +00002860 // It is only safe to sign extend the BaseReg if we know that the math
2861 // required to create it did not overflow before we extend it. Since
2862 // the original IR value was tossed in favor of a constant back when
2863 // the AddrMode was created we need to bail out gracefully if widths
2864 // do not match instead of extending it.
Joey Gouly12a8bf02014-05-13 15:42:45 +00002865 Instruction *I = dyn_cast_or_null<Instruction>(Result);
Jim Grosbach83b44e12014-04-10 00:27:45 +00002866 if (I && (Result != AddrMode.BaseReg))
2867 I->eraseFromParent();
Jim Grosbached2cd392014-03-26 17:27:01 +00002868 return false;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002869 }
2870 if (AddrMode.Scale != 1)
Devang Patelc10e52a2011-09-06 18:49:53 +00002871 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
2872 "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002873 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00002874 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002875 else
2876 Result = V;
2877 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00002878
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002879 // Add in the BaseGV if present.
2880 if (AddrMode.BaseGV) {
Devang Patelc10e52a2011-09-06 18:49:53 +00002881 Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002882 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00002883 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002884 else
2885 Result = V;
2886 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00002887
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002888 // Add in the Base Offset if present.
2889 if (AddrMode.BaseOffs) {
Owen Andersonedb4a702009-07-24 23:12:02 +00002890 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002891 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00002892 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002893 else
2894 Result = V;
2895 }
2896
Craig Topperc0196b12014-04-14 00:51:57 +00002897 if (!Result)
Owen Anderson5a1acd92009-07-31 20:28:14 +00002898 SunkAddr = Constant::getNullValue(Addr->getType());
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002899 else
Devang Patelc10e52a2011-09-06 18:49:53 +00002900 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002901 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00002902
Owen Andersondfb8c3b2010-11-19 22:15:03 +00002903 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
Eric Christopherc1ea1492008-09-24 05:32:41 +00002904
Chris Lattneraf1bcce2011-04-09 07:05:44 +00002905 // If we have no uses, recursively delete the value and all dead instructions
2906 // using it.
Owen Andersondfb8c3b2010-11-19 22:15:03 +00002907 if (Repl->use_empty()) {
Chris Lattneraf1bcce2011-04-09 07:05:44 +00002908 // This can cause recursive deletion, which can invalidate our iterator.
2909 // Use a WeakVH to hold onto it in case this happens.
2910 WeakVH IterHandle(CurInstIterator);
2911 BasicBlock *BB = CurInstIterator->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +00002912
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00002913 RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
Chris Lattneraf1bcce2011-04-09 07:05:44 +00002914
2915 if (IterHandle != CurInstIterator) {
2916 // If the iterator instruction was recursively deleted, start over at the
2917 // start of the block.
2918 CurInstIterator = BB->begin();
2919 SunkAddrs.clear();
Nadav Rotem465834c2012-07-24 10:51:42 +00002920 }
Dale Johannesenb67a6e662010-03-31 20:37:15 +00002921 }
Cameron Zwarichced753f2011-01-05 17:27:27 +00002922 ++NumMemoryInsts;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002923 return true;
2924}
2925
Evan Cheng1da25002008-02-26 02:42:37 +00002926/// OptimizeInlineAsmInst - If there are any memory operands, use
Chris Lattner728f9022008-11-25 07:09:13 +00002927/// OptimizeMemoryInst to sink their address computing into the block when
Evan Cheng1da25002008-02-26 02:42:37 +00002928/// possible / profitable.
Chris Lattner7a277142011-01-15 07:14:54 +00002929bool CodeGenPrepare::OptimizeInlineAsmInst(CallInst *CS) {
Evan Cheng1da25002008-02-26 02:42:37 +00002930 bool MadeChange = false;
Evan Cheng1da25002008-02-26 02:42:37 +00002931
Nadav Rotem465834c2012-07-24 10:51:42 +00002932 TargetLowering::AsmOperandInfoVector
Chris Lattner7a277142011-01-15 07:14:54 +00002933 TargetConstraints = TLI->ParseConstraints(CS);
Dale Johannesenf95f59a2010-09-16 18:30:55 +00002934 unsigned ArgNo = 0;
John Thompson1094c802010-09-13 18:15:37 +00002935 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
2936 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Nadav Rotem465834c2012-07-24 10:51:42 +00002937
Evan Cheng1da25002008-02-26 02:42:37 +00002938 // Compute the constraint code and ConstraintType to use.
Dale Johannesence97d552010-06-25 21:55:36 +00002939 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Evan Cheng1da25002008-02-26 02:42:37 +00002940
Eli Friedman666bbe32008-02-26 18:37:49 +00002941 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
2942 OpInfo.isIndirect) {
Chris Lattner7a277142011-01-15 07:14:54 +00002943 Value *OpVal = CS->getArgOperand(ArgNo++);
Chris Lattneree588de2011-01-15 07:29:01 +00002944 MadeChange |= OptimizeMemoryInst(CS, OpVal, OpVal->getType());
Dale Johannesenf95f59a2010-09-16 18:30:55 +00002945 } else if (OpInfo.Type == InlineAsm::isInput)
2946 ArgNo++;
Evan Cheng1da25002008-02-26 02:42:37 +00002947 }
2948
2949 return MadeChange;
2950}
2951
Dan Gohman99429a02009-10-16 20:59:35 +00002952/// MoveExtToFormExtLoad - Move a zext or sext fed by a load into the same
2953/// basic block as the load, unless conditions are unfavorable. This allows
2954/// SelectionDAG to fold the extend into the load.
2955///
2956bool CodeGenPrepare::MoveExtToFormExtLoad(Instruction *I) {
2957 // Look for a load being extended.
2958 LoadInst *LI = dyn_cast<LoadInst>(I->getOperand(0));
2959 if (!LI) return false;
2960
2961 // If they're already in the same block, there's nothing to do.
2962 if (LI->getParent() == I->getParent())
2963 return false;
2964
Ahmed Bougacha55e3c2d2014-12-05 18:04:40 +00002965 EVT VT = TLI->getValueType(I->getType());
2966 EVT LoadVT = TLI->getValueType(LI->getType());
2967
Dan Gohman99429a02009-10-16 20:59:35 +00002968 // If the load has other users and the truncate is not free, this probably
2969 // isn't worthwhile.
Ahmed Bougacha55e3c2d2014-12-05 18:04:40 +00002970 if (!LI->hasOneUse() && TLI &&
2971 (TLI->isTypeLegal(LoadVT) || !TLI->isTypeLegal(VT)) &&
Bob Wilson4ddcb6a2010-09-21 21:54:27 +00002972 !TLI->isTruncateFree(I->getType(), LI->getType()))
Dan Gohman99429a02009-10-16 20:59:35 +00002973 return false;
2974
2975 // Check whether the target supports casts folded into loads.
2976 unsigned LType;
2977 if (isa<ZExtInst>(I))
2978 LType = ISD::ZEXTLOAD;
2979 else {
2980 assert(isa<SExtInst>(I) && "Unexpected ext type!");
2981 LType = ISD::SEXTLOAD;
2982 }
Ahmed Bougacha55e3c2d2014-12-05 18:04:40 +00002983 if (TLI && !TLI->isLoadExtLegal(LType, LoadVT))
Dan Gohman99429a02009-10-16 20:59:35 +00002984 return false;
2985
2986 // Move the extend into the same block as the load, so that SelectionDAG
2987 // can fold it.
2988 I->removeFromParent();
2989 I->insertAfter(LI);
Cameron Zwarichced753f2011-01-05 17:27:27 +00002990 ++NumExtsMoved;
Dan Gohman99429a02009-10-16 20:59:35 +00002991 return true;
2992}
2993
Evan Chengd3d80172007-12-05 23:58:20 +00002994bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
2995 BasicBlock *DefBB = I->getParent();
2996
Bob Wilsonff714f92010-09-21 21:44:14 +00002997 // If the result of a {s|z}ext and its source are both live out, rewrite all
Evan Chengd3d80172007-12-05 23:58:20 +00002998 // other uses of the source with result of extension.
2999 Value *Src = I->getOperand(0);
3000 if (Src->hasOneUse())
3001 return false;
3002
Evan Cheng2011df42007-12-13 07:50:36 +00003003 // Only do this xform if truncating is free.
Gabor Greifaa261722008-02-26 19:13:21 +00003004 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
Evan Cheng37c36ed2007-12-13 03:32:53 +00003005 return false;
3006
Evan Cheng7bc89422007-12-12 00:51:06 +00003007 // Only safe to perform the optimization if the source is also defined in
Evan Cheng63d33cf2007-12-12 02:53:41 +00003008 // this block.
3009 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
Evan Cheng7bc89422007-12-12 00:51:06 +00003010 return false;
3011
Evan Chengd3d80172007-12-05 23:58:20 +00003012 bool DefIsLiveOut = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00003013 for (User *U : I->users()) {
3014 Instruction *UI = cast<Instruction>(U);
Evan Chengd3d80172007-12-05 23:58:20 +00003015
3016 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003017 BasicBlock *UserBB = UI->getParent();
Evan Chengd3d80172007-12-05 23:58:20 +00003018 if (UserBB == DefBB) continue;
3019 DefIsLiveOut = true;
3020 break;
3021 }
3022 if (!DefIsLiveOut)
3023 return false;
3024
Jim Grosbach0f38c1e2013-04-15 17:40:48 +00003025 // Make sure none of the uses are PHI nodes.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003026 for (User *U : Src->users()) {
3027 Instruction *UI = cast<Instruction>(U);
3028 BasicBlock *UserBB = UI->getParent();
Evan Cheng37c36ed2007-12-13 03:32:53 +00003029 if (UserBB == DefBB) continue;
3030 // Be conservative. We don't want this xform to end up introducing
3031 // reloads just before load / store instructions.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003032 if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI))
Evan Cheng63d33cf2007-12-12 02:53:41 +00003033 return false;
3034 }
3035
Evan Chengd3d80172007-12-05 23:58:20 +00003036 // InsertedTruncs - Only insert one trunc in each block once.
3037 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
3038
3039 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00003040 for (Use &U : Src->uses()) {
3041 Instruction *User = cast<Instruction>(U.getUser());
Evan Chengd3d80172007-12-05 23:58:20 +00003042
3043 // Figure out which BB this ext is used in.
3044 BasicBlock *UserBB = User->getParent();
3045 if (UserBB == DefBB) continue;
3046
3047 // Both src and def are live in this block. Rewrite the use.
3048 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
3049
3050 if (!InsertedTrunc) {
Bill Wendling8ddfc092011-08-16 20:45:24 +00003051 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Evan Chengd3d80172007-12-05 23:58:20 +00003052 InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003053 InsertedTruncsSet.insert(InsertedTrunc);
Evan Chengd3d80172007-12-05 23:58:20 +00003054 }
3055
3056 // Replace a use of the {s|z}ext source with a use of the result.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003057 U = InsertedTrunc;
Cameron Zwarichced753f2011-01-05 17:27:27 +00003058 ++NumExtUses;
Evan Chengd3d80172007-12-05 23:58:20 +00003059 MadeChange = true;
3060 }
3061
3062 return MadeChange;
3063}
3064
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00003065/// isFormingBranchFromSelectProfitable - Returns true if a SelectInst should be
3066/// turned into an explicit branch.
3067static bool isFormingBranchFromSelectProfitable(SelectInst *SI) {
3068 // FIXME: This should use the same heuristics as IfConversion to determine
3069 // whether a select is better represented as a branch. This requires that
3070 // branch probability metadata is preserved for the select, which is not the
3071 // case currently.
3072
3073 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
3074
3075 // If the branch is predicted right, an out of order CPU can avoid blocking on
3076 // the compare. Emit cmovs on compares with a memory operand as branches to
3077 // avoid stalls on the load from memory. If the compare has more than one use
3078 // there's probably another cmov or setcc around so it's not worth emitting a
3079 // branch.
3080 if (!Cmp)
3081 return false;
3082
3083 Value *CmpOp0 = Cmp->getOperand(0);
3084 Value *CmpOp1 = Cmp->getOperand(1);
3085
3086 // We check that the memory operand has one use to avoid uses of the loaded
3087 // value directly after the compare, making branches unprofitable.
3088 return Cmp->hasOneUse() &&
3089 ((isa<LoadInst>(CmpOp0) && CmpOp0->hasOneUse()) ||
3090 (isa<LoadInst>(CmpOp1) && CmpOp1->hasOneUse()));
3091}
3092
3093
Nadav Rotem9d832022012-09-02 12:10:19 +00003094/// If we have a SelectInst that will likely profit from branch prediction,
3095/// turn it into a branch.
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00003096bool CodeGenPrepare::OptimizeSelectInst(SelectInst *SI) {
Nadav Rotem9d832022012-09-02 12:10:19 +00003097 bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
3098
3099 // Can we convert the 'select' to CF ?
3100 if (DisableSelectToBranch || OptSize || !TLI || VectorCond)
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00003101 return false;
3102
Nadav Rotem9d832022012-09-02 12:10:19 +00003103 TargetLowering::SelectSupportKind SelectKind;
3104 if (VectorCond)
3105 SelectKind = TargetLowering::VectorMaskSelect;
3106 else if (SI->getType()->isVectorTy())
3107 SelectKind = TargetLowering::ScalarCondVectorVal;
3108 else
3109 SelectKind = TargetLowering::ScalarValSelect;
3110
3111 // Do we have efficient codegen support for this kind of 'selects' ?
3112 if (TLI->isSelectSupported(SelectKind)) {
3113 // We have efficient codegen support for the select instruction.
3114 // Check if it is profitable to keep this 'select'.
3115 if (!TLI->isPredictableSelectExpensive() ||
3116 !isFormingBranchFromSelectProfitable(SI))
3117 return false;
3118 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00003119
3120 ModifiedDT = true;
3121
3122 // First, we split the block containing the select into 2 blocks.
3123 BasicBlock *StartBlock = SI->getParent();
3124 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(SI));
3125 BasicBlock *NextBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
3126
3127 // Create a new block serving as the landing pad for the branch.
3128 BasicBlock *SmallBlock = BasicBlock::Create(SI->getContext(), "select.mid",
3129 NextBlock->getParent(), NextBlock);
3130
3131 // Move the unconditional branch from the block with the select in it into our
3132 // landing pad block.
3133 StartBlock->getTerminator()->eraseFromParent();
3134 BranchInst::Create(NextBlock, SmallBlock);
3135
3136 // Insert the real conditional branch based on the original condition.
3137 BranchInst::Create(NextBlock, SmallBlock, SI->getCondition(), SI);
3138
3139 // The select itself is replaced with a PHI Node.
3140 PHINode *PN = PHINode::Create(SI->getType(), 2, "", NextBlock->begin());
3141 PN->takeName(SI);
3142 PN->addIncoming(SI->getTrueValue(), StartBlock);
3143 PN->addIncoming(SI->getFalseValue(), SmallBlock);
3144 SI->replaceAllUsesWith(PN);
3145 SI->eraseFromParent();
3146
3147 // Instruct OptimizeBlock to skip to the next block.
3148 CurInstIterator = StartBlock->end();
3149 ++NumSelectsExpanded;
3150 return true;
3151}
3152
Benjamin Kramer573ff362014-03-01 17:24:40 +00003153static bool isBroadcastShuffle(ShuffleVectorInst *SVI) {
Tim Northoveraeb8e062014-02-19 10:02:43 +00003154 SmallVector<int, 16> Mask(SVI->getShuffleMask());
3155 int SplatElem = -1;
3156 for (unsigned i = 0; i < Mask.size(); ++i) {
3157 if (SplatElem != -1 && Mask[i] != -1 && Mask[i] != SplatElem)
3158 return false;
3159 SplatElem = Mask[i];
3160 }
3161
3162 return true;
3163}
3164
3165/// Some targets have expensive vector shifts if the lanes aren't all the same
3166/// (e.g. x86 only introduced "vpsllvd" and friends with AVX2). In these cases
3167/// it's often worth sinking a shufflevector splat down to its use so that
3168/// codegen can spot all lanes are identical.
3169bool CodeGenPrepare::OptimizeShuffleVectorInst(ShuffleVectorInst *SVI) {
3170 BasicBlock *DefBB = SVI->getParent();
3171
3172 // Only do this xform if variable vector shifts are particularly expensive.
3173 if (!TLI || !TLI->isVectorShiftByScalarCheap(SVI->getType()))
3174 return false;
3175
3176 // We only expect better codegen by sinking a shuffle if we can recognise a
3177 // constant splat.
3178 if (!isBroadcastShuffle(SVI))
3179 return false;
3180
3181 // InsertedShuffles - Only insert a shuffle in each block once.
3182 DenseMap<BasicBlock*, Instruction*> InsertedShuffles;
3183
3184 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00003185 for (User *U : SVI->users()) {
3186 Instruction *UI = cast<Instruction>(U);
Tim Northoveraeb8e062014-02-19 10:02:43 +00003187
3188 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003189 BasicBlock *UserBB = UI->getParent();
Tim Northoveraeb8e062014-02-19 10:02:43 +00003190 if (UserBB == DefBB) continue;
3191
3192 // For now only apply this when the splat is used by a shift instruction.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003193 if (!UI->isShift()) continue;
Tim Northoveraeb8e062014-02-19 10:02:43 +00003194
3195 // Everything checks out, sink the shuffle if the user's block doesn't
3196 // already have a copy.
3197 Instruction *&InsertedShuffle = InsertedShuffles[UserBB];
3198
3199 if (!InsertedShuffle) {
3200 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
3201 InsertedShuffle = new ShuffleVectorInst(SVI->getOperand(0),
3202 SVI->getOperand(1),
3203 SVI->getOperand(2), "", InsertPt);
3204 }
3205
Chandler Carruthcdf47882014-03-09 03:16:01 +00003206 UI->replaceUsesOfWith(SVI, InsertedShuffle);
Tim Northoveraeb8e062014-02-19 10:02:43 +00003207 MadeChange = true;
3208 }
3209
3210 // If we removed all uses, nuke the shuffle.
3211 if (SVI->use_empty()) {
3212 SVI->eraseFromParent();
3213 MadeChange = true;
3214 }
3215
3216 return MadeChange;
3217}
3218
Quentin Colombetc32615d2014-10-31 17:52:53 +00003219namespace {
3220/// \brief Helper class to promote a scalar operation to a vector one.
3221/// This class is used to move downward extractelement transition.
3222/// E.g.,
3223/// a = vector_op <2 x i32>
3224/// b = extractelement <2 x i32> a, i32 0
3225/// c = scalar_op b
3226/// store c
3227///
3228/// =>
3229/// a = vector_op <2 x i32>
3230/// c = vector_op a (equivalent to scalar_op on the related lane)
3231/// * d = extractelement <2 x i32> c, i32 0
3232/// * store d
3233/// Assuming both extractelement and store can be combine, we get rid of the
3234/// transition.
3235class VectorPromoteHelper {
3236 /// Used to perform some checks on the legality of vector operations.
3237 const TargetLowering &TLI;
3238
3239 /// Used to estimated the cost of the promoted chain.
3240 const TargetTransformInfo &TTI;
3241
3242 /// The transition being moved downwards.
3243 Instruction *Transition;
3244 /// The sequence of instructions to be promoted.
3245 SmallVector<Instruction *, 4> InstsToBePromoted;
3246 /// Cost of combining a store and an extract.
3247 unsigned StoreExtractCombineCost;
3248 /// Instruction that will be combined with the transition.
3249 Instruction *CombineInst;
3250
3251 /// \brief The instruction that represents the current end of the transition.
3252 /// Since we are faking the promotion until we reach the end of the chain
3253 /// of computation, we need a way to get the current end of the transition.
3254 Instruction *getEndOfTransition() const {
3255 if (InstsToBePromoted.empty())
3256 return Transition;
3257 return InstsToBePromoted.back();
3258 }
3259
3260 /// \brief Return the index of the original value in the transition.
3261 /// E.g., for "extractelement <2 x i32> c, i32 1" the original value,
3262 /// c, is at index 0.
3263 unsigned getTransitionOriginalValueIdx() const {
3264 assert(isa<ExtractElementInst>(Transition) &&
3265 "Other kind of transitions are not supported yet");
3266 return 0;
3267 }
3268
3269 /// \brief Return the index of the index in the transition.
3270 /// E.g., for "extractelement <2 x i32> c, i32 0" the index
3271 /// is at index 1.
3272 unsigned getTransitionIdx() const {
3273 assert(isa<ExtractElementInst>(Transition) &&
3274 "Other kind of transitions are not supported yet");
3275 return 1;
3276 }
3277
3278 /// \brief Get the type of the transition.
3279 /// This is the type of the original value.
3280 /// E.g., for "extractelement <2 x i32> c, i32 1" the type of the
3281 /// transition is <2 x i32>.
3282 Type *getTransitionType() const {
3283 return Transition->getOperand(getTransitionOriginalValueIdx())->getType();
3284 }
3285
3286 /// \brief Promote \p ToBePromoted by moving \p Def downward through.
3287 /// I.e., we have the following sequence:
3288 /// Def = Transition <ty1> a to <ty2>
3289 /// b = ToBePromoted <ty2> Def, ...
3290 /// =>
3291 /// b = ToBePromoted <ty1> a, ...
3292 /// Def = Transition <ty1> ToBePromoted to <ty2>
3293 void promoteImpl(Instruction *ToBePromoted);
3294
3295 /// \brief Check whether or not it is profitable to promote all the
3296 /// instructions enqueued to be promoted.
3297 bool isProfitableToPromote() {
3298 Value *ValIdx = Transition->getOperand(getTransitionOriginalValueIdx());
3299 unsigned Index = isa<ConstantInt>(ValIdx)
3300 ? cast<ConstantInt>(ValIdx)->getZExtValue()
3301 : -1;
3302 Type *PromotedType = getTransitionType();
3303
3304 StoreInst *ST = cast<StoreInst>(CombineInst);
3305 unsigned AS = ST->getPointerAddressSpace();
3306 unsigned Align = ST->getAlignment();
3307 // Check if this store is supported.
3308 if (!TLI.allowsMisalignedMemoryAccesses(
Ahmed Bougacha026600d2014-11-12 23:05:03 +00003309 TLI.getValueType(ST->getValueOperand()->getType()), AS, Align)) {
Quentin Colombetc32615d2014-10-31 17:52:53 +00003310 // If this is not supported, there is no way we can combine
3311 // the extract with the store.
3312 return false;
3313 }
3314
3315 // The scalar chain of computation has to pay for the transition
3316 // scalar to vector.
3317 // The vector chain has to account for the combining cost.
3318 uint64_t ScalarCost =
3319 TTI.getVectorInstrCost(Transition->getOpcode(), PromotedType, Index);
3320 uint64_t VectorCost = StoreExtractCombineCost;
3321 for (const auto &Inst : InstsToBePromoted) {
3322 // Compute the cost.
3323 // By construction, all instructions being promoted are arithmetic ones.
3324 // Moreover, one argument is a constant that can be viewed as a splat
3325 // constant.
3326 Value *Arg0 = Inst->getOperand(0);
3327 bool IsArg0Constant = isa<UndefValue>(Arg0) || isa<ConstantInt>(Arg0) ||
3328 isa<ConstantFP>(Arg0);
3329 TargetTransformInfo::OperandValueKind Arg0OVK =
3330 IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
3331 : TargetTransformInfo::OK_AnyValue;
3332 TargetTransformInfo::OperandValueKind Arg1OVK =
3333 !IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
3334 : TargetTransformInfo::OK_AnyValue;
3335 ScalarCost += TTI.getArithmeticInstrCost(
3336 Inst->getOpcode(), Inst->getType(), Arg0OVK, Arg1OVK);
3337 VectorCost += TTI.getArithmeticInstrCost(Inst->getOpcode(), PromotedType,
3338 Arg0OVK, Arg1OVK);
3339 }
3340 DEBUG(dbgs() << "Estimated cost of computation to be promoted:\nScalar: "
3341 << ScalarCost << "\nVector: " << VectorCost << '\n');
3342 return ScalarCost > VectorCost;
3343 }
3344
3345 /// \brief Generate a constant vector with \p Val with the same
3346 /// number of elements as the transition.
3347 /// \p UseSplat defines whether or not \p Val should be replicated
3348 /// accross the whole vector.
3349 /// In other words, if UseSplat == true, we generate <Val, Val, ..., Val>,
3350 /// otherwise we generate a vector with as many undef as possible:
3351 /// <undef, ..., undef, Val, undef, ..., undef> where \p Val is only
3352 /// used at the index of the extract.
3353 Value *getConstantVector(Constant *Val, bool UseSplat) const {
3354 unsigned ExtractIdx = UINT_MAX;
3355 if (!UseSplat) {
3356 // If we cannot determine where the constant must be, we have to
3357 // use a splat constant.
3358 Value *ValExtractIdx = Transition->getOperand(getTransitionIdx());
3359 if (ConstantInt *CstVal = dyn_cast<ConstantInt>(ValExtractIdx))
3360 ExtractIdx = CstVal->getSExtValue();
3361 else
3362 UseSplat = true;
3363 }
3364
3365 unsigned End = getTransitionType()->getVectorNumElements();
3366 if (UseSplat)
3367 return ConstantVector::getSplat(End, Val);
3368
3369 SmallVector<Constant *, 4> ConstVec;
3370 UndefValue *UndefVal = UndefValue::get(Val->getType());
3371 for (unsigned Idx = 0; Idx != End; ++Idx) {
3372 if (Idx == ExtractIdx)
3373 ConstVec.push_back(Val);
3374 else
3375 ConstVec.push_back(UndefVal);
3376 }
3377 return ConstantVector::get(ConstVec);
3378 }
3379
3380 /// \brief Check if promoting to a vector type an operand at \p OperandIdx
3381 /// in \p Use can trigger undefined behavior.
3382 static bool canCauseUndefinedBehavior(const Instruction *Use,
3383 unsigned OperandIdx) {
3384 // This is not safe to introduce undef when the operand is on
3385 // the right hand side of a division-like instruction.
3386 if (OperandIdx != 1)
3387 return false;
3388 switch (Use->getOpcode()) {
3389 default:
3390 return false;
3391 case Instruction::SDiv:
3392 case Instruction::UDiv:
3393 case Instruction::SRem:
3394 case Instruction::URem:
3395 return true;
3396 case Instruction::FDiv:
3397 case Instruction::FRem:
3398 return !Use->hasNoNaNs();
3399 }
3400 llvm_unreachable(nullptr);
3401 }
3402
3403public:
3404 VectorPromoteHelper(const TargetLowering &TLI, const TargetTransformInfo &TTI,
3405 Instruction *Transition, unsigned CombineCost)
3406 : TLI(TLI), TTI(TTI), Transition(Transition),
3407 StoreExtractCombineCost(CombineCost), CombineInst(nullptr) {
3408 assert(Transition && "Do not know how to promote null");
3409 }
3410
3411 /// \brief Check if we can promote \p ToBePromoted to \p Type.
3412 bool canPromote(const Instruction *ToBePromoted) const {
3413 // We could support CastInst too.
3414 return isa<BinaryOperator>(ToBePromoted);
3415 }
3416
3417 /// \brief Check if it is profitable to promote \p ToBePromoted
3418 /// by moving downward the transition through.
3419 bool shouldPromote(const Instruction *ToBePromoted) const {
3420 // Promote only if all the operands can be statically expanded.
3421 // Indeed, we do not want to introduce any new kind of transitions.
3422 for (const Use &U : ToBePromoted->operands()) {
3423 const Value *Val = U.get();
3424 if (Val == getEndOfTransition()) {
3425 // If the use is a division and the transition is on the rhs,
3426 // we cannot promote the operation, otherwise we may create a
3427 // division by zero.
3428 if (canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()))
3429 return false;
3430 continue;
3431 }
3432 if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) &&
3433 !isa<ConstantFP>(Val))
3434 return false;
3435 }
3436 // Check that the resulting operation is legal.
3437 int ISDOpcode = TLI.InstructionOpcodeToISD(ToBePromoted->getOpcode());
3438 if (!ISDOpcode)
3439 return false;
3440 return StressStoreExtract ||
Ahmed Bougacha026600d2014-11-12 23:05:03 +00003441 TLI.isOperationLegalOrCustom(
3442 ISDOpcode, TLI.getValueType(getTransitionType(), true));
Quentin Colombetc32615d2014-10-31 17:52:53 +00003443 }
3444
3445 /// \brief Check whether or not \p Use can be combined
3446 /// with the transition.
3447 /// I.e., is it possible to do Use(Transition) => AnotherUse?
3448 bool canCombine(const Instruction *Use) { return isa<StoreInst>(Use); }
3449
3450 /// \brief Record \p ToBePromoted as part of the chain to be promoted.
3451 void enqueueForPromotion(Instruction *ToBePromoted) {
3452 InstsToBePromoted.push_back(ToBePromoted);
3453 }
3454
3455 /// \brief Set the instruction that will be combined with the transition.
3456 void recordCombineInstruction(Instruction *ToBeCombined) {
3457 assert(canCombine(ToBeCombined) && "Unsupported instruction to combine");
3458 CombineInst = ToBeCombined;
3459 }
3460
3461 /// \brief Promote all the instructions enqueued for promotion if it is
3462 /// is profitable.
3463 /// \return True if the promotion happened, false otherwise.
3464 bool promote() {
3465 // Check if there is something to promote.
3466 // Right now, if we do not have anything to combine with,
3467 // we assume the promotion is not profitable.
3468 if (InstsToBePromoted.empty() || !CombineInst)
3469 return false;
3470
3471 // Check cost.
3472 if (!StressStoreExtract && !isProfitableToPromote())
3473 return false;
3474
3475 // Promote.
3476 for (auto &ToBePromoted : InstsToBePromoted)
3477 promoteImpl(ToBePromoted);
3478 InstsToBePromoted.clear();
3479 return true;
3480 }
3481};
3482} // End of anonymous namespace.
3483
3484void VectorPromoteHelper::promoteImpl(Instruction *ToBePromoted) {
3485 // At this point, we know that all the operands of ToBePromoted but Def
3486 // can be statically promoted.
3487 // For Def, we need to use its parameter in ToBePromoted:
3488 // b = ToBePromoted ty1 a
3489 // Def = Transition ty1 b to ty2
3490 // Move the transition down.
3491 // 1. Replace all uses of the promoted operation by the transition.
3492 // = ... b => = ... Def.
3493 assert(ToBePromoted->getType() == Transition->getType() &&
3494 "The type of the result of the transition does not match "
3495 "the final type");
3496 ToBePromoted->replaceAllUsesWith(Transition);
3497 // 2. Update the type of the uses.
3498 // b = ToBePromoted ty2 Def => b = ToBePromoted ty1 Def.
3499 Type *TransitionTy = getTransitionType();
3500 ToBePromoted->mutateType(TransitionTy);
3501 // 3. Update all the operands of the promoted operation with promoted
3502 // operands.
3503 // b = ToBePromoted ty1 Def => b = ToBePromoted ty1 a.
3504 for (Use &U : ToBePromoted->operands()) {
3505 Value *Val = U.get();
3506 Value *NewVal = nullptr;
3507 if (Val == Transition)
3508 NewVal = Transition->getOperand(getTransitionOriginalValueIdx());
3509 else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) ||
3510 isa<ConstantFP>(Val)) {
3511 // Use a splat constant if it is not safe to use undef.
3512 NewVal = getConstantVector(
3513 cast<Constant>(Val),
3514 isa<UndefValue>(Val) ||
3515 canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()));
3516 } else
3517 assert(0 && "Did you modified shouldPromote and forgot to update this?");
3518 ToBePromoted->setOperand(U.getOperandNo(), NewVal);
3519 }
3520 Transition->removeFromParent();
3521 Transition->insertAfter(ToBePromoted);
3522 Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted);
3523}
3524
3525/// Some targets can do store(extractelement) with one instruction.
3526/// Try to push the extractelement towards the stores when the target
3527/// has this feature and this is profitable.
3528bool CodeGenPrepare::OptimizeExtractElementInst(Instruction *Inst) {
3529 unsigned CombineCost = UINT_MAX;
3530 if (DisableStoreExtract || !TLI ||
3531 (!StressStoreExtract &&
3532 !TLI->canCombineStoreAndExtract(Inst->getOperand(0)->getType(),
3533 Inst->getOperand(1), CombineCost)))
3534 return false;
3535
3536 // At this point we know that Inst is a vector to scalar transition.
3537 // Try to move it down the def-use chain, until:
3538 // - We can combine the transition with its single use
3539 // => we got rid of the transition.
3540 // - We escape the current basic block
3541 // => we would need to check that we are moving it at a cheaper place and
3542 // we do not do that for now.
3543 BasicBlock *Parent = Inst->getParent();
3544 DEBUG(dbgs() << "Found an interesting transition: " << *Inst << '\n');
3545 VectorPromoteHelper VPH(*TLI, *TTI, Inst, CombineCost);
3546 // If the transition has more than one use, assume this is not going to be
3547 // beneficial.
3548 while (Inst->hasOneUse()) {
3549 Instruction *ToBePromoted = cast<Instruction>(*Inst->user_begin());
3550 DEBUG(dbgs() << "Use: " << *ToBePromoted << '\n');
3551
3552 if (ToBePromoted->getParent() != Parent) {
3553 DEBUG(dbgs() << "Instruction to promote is in a different block ("
3554 << ToBePromoted->getParent()->getName()
3555 << ") than the transition (" << Parent->getName() << ").\n");
3556 return false;
3557 }
3558
3559 if (VPH.canCombine(ToBePromoted)) {
3560 DEBUG(dbgs() << "Assume " << *Inst << '\n'
3561 << "will be combined with: " << *ToBePromoted << '\n');
3562 VPH.recordCombineInstruction(ToBePromoted);
3563 bool Changed = VPH.promote();
3564 NumStoreExtractExposed += Changed;
3565 return Changed;
3566 }
3567
3568 DEBUG(dbgs() << "Try promoting.\n");
3569 if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted))
3570 return false;
3571
3572 DEBUG(dbgs() << "Promoting is possible... Enqueue for promotion!\n");
3573
3574 VPH.enqueueForPromotion(ToBePromoted);
3575 Inst = ToBePromoted;
3576 }
3577 return false;
3578}
3579
Cameron Zwarich14ac8652011-01-06 02:37:26 +00003580bool CodeGenPrepare::OptimizeInst(Instruction *I) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00003581 if (PHINode *P = dyn_cast<PHINode>(I)) {
3582 // It is possible for very late stage optimizations (such as SimplifyCFG)
3583 // to introduce PHI nodes too late to be cleaned up. If we detect such a
3584 // trivial PHI, go ahead and zap it here.
Craig Topperc0196b12014-04-14 00:51:57 +00003585 if (Value *V = SimplifyInstruction(P, TLI ? TLI->getDataLayout() : nullptr,
Benjamin Kramer30d249a2013-09-24 16:37:40 +00003586 TLInfo, DT)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00003587 P->replaceAllUsesWith(V);
3588 P->eraseFromParent();
3589 ++NumPHIsElim;
Chris Lattneree588de2011-01-15 07:29:01 +00003590 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00003591 }
Chris Lattneree588de2011-01-15 07:29:01 +00003592 return false;
3593 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003594
Chris Lattneree588de2011-01-15 07:29:01 +00003595 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00003596 // If the source of the cast is a constant, then this should have
3597 // already been constant folded. The only reason NOT to constant fold
3598 // it is if something (e.g. LSR) was careful to place the constant
3599 // evaluation in a block other than then one that uses it (e.g. to hoist
3600 // the address of globals out of a loop). If this is the case, we don't
3601 // want to forward-subst the cast.
3602 if (isa<Constant>(CI->getOperand(0)))
3603 return false;
3604
Chris Lattneree588de2011-01-15 07:29:01 +00003605 if (TLI && OptimizeNoopCopyExpression(CI, *TLI))
3606 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00003607
Chris Lattneree588de2011-01-15 07:29:01 +00003608 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +00003609 /// Sink a zext or sext into its user blocks if the target type doesn't
3610 /// fit in one register
3611 if (TLI && TLI->getTypeAction(CI->getContext(),
3612 TLI->getValueType(CI->getType())) ==
3613 TargetLowering::TypeExpandInteger) {
3614 return SinkCast(CI);
3615 } else {
3616 bool MadeChange = MoveExtToFormExtLoad(I);
3617 return MadeChange | OptimizeExtUses(I);
3618 }
Cameron Zwarich14ac8652011-01-06 02:37:26 +00003619 }
Chris Lattneree588de2011-01-15 07:29:01 +00003620 return false;
3621 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003622
Chris Lattneree588de2011-01-15 07:29:01 +00003623 if (CmpInst *CI = dyn_cast<CmpInst>(I))
Hal Finkeldecb0242014-01-02 21:13:43 +00003624 if (!TLI || !TLI->hasMultipleConditionRegisters())
3625 return OptimizeCmpExpression(CI);
Nadav Rotem465834c2012-07-24 10:51:42 +00003626
Chris Lattneree588de2011-01-15 07:29:01 +00003627 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00003628 if (TLI)
Hans Wennborgf3254832012-10-30 11:23:25 +00003629 return OptimizeMemoryInst(I, I->getOperand(0), LI->getType());
3630 return false;
Chris Lattneree588de2011-01-15 07:29:01 +00003631 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003632
Chris Lattneree588de2011-01-15 07:29:01 +00003633 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00003634 if (TLI)
Chris Lattneree588de2011-01-15 07:29:01 +00003635 return OptimizeMemoryInst(I, SI->getOperand(1),
3636 SI->getOperand(0)->getType());
3637 return false;
3638 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003639
Yi Jiangd069f632014-04-21 19:34:27 +00003640 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I);
3641
3642 if (BinOp && (BinOp->getOpcode() == Instruction::AShr ||
3643 BinOp->getOpcode() == Instruction::LShr)) {
3644 ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1));
3645 if (TLI && CI && TLI->hasExtractBitsInsn())
3646 return OptimizeExtractBits(BinOp, CI, *TLI);
3647
3648 return false;
3649 }
3650
Chris Lattneree588de2011-01-15 07:29:01 +00003651 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00003652 if (GEPI->hasAllZeroIndices()) {
3653 /// The GEP operand must be a pointer, so must its result -> BitCast
3654 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
3655 GEPI->getName(), GEPI);
3656 GEPI->replaceAllUsesWith(NC);
3657 GEPI->eraseFromParent();
3658 ++NumGEPsElim;
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00003659 OptimizeInst(NC);
Chris Lattneree588de2011-01-15 07:29:01 +00003660 return true;
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00003661 }
Chris Lattneree588de2011-01-15 07:29:01 +00003662 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00003663 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003664
Chris Lattneree588de2011-01-15 07:29:01 +00003665 if (CallInst *CI = dyn_cast<CallInst>(I))
3666 return OptimizeCallInst(CI);
Cameron Zwarich14ac8652011-01-06 02:37:26 +00003667
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00003668 if (SelectInst *SI = dyn_cast<SelectInst>(I))
3669 return OptimizeSelectInst(SI);
3670
Tim Northoveraeb8e062014-02-19 10:02:43 +00003671 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I))
3672 return OptimizeShuffleVectorInst(SVI);
3673
Quentin Colombetc32615d2014-10-31 17:52:53 +00003674 if (isa<ExtractElementInst>(I))
3675 return OptimizeExtractElementInst(I);
3676
Chris Lattneree588de2011-01-15 07:29:01 +00003677 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00003678}
3679
Chris Lattnerf2836d12007-03-31 04:06:36 +00003680// In this pass we look for GEP and cast instructions that are used
3681// across basic blocks and rewrite them to improve basic-block-at-a-time
3682// selection.
3683bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
Cameron Zwarichce3b9302011-01-06 00:42:50 +00003684 SunkAddrs.clear();
Cameron Zwarich5dd2aa22011-03-02 03:31:46 +00003685 bool MadeChange = false;
Eric Christopherc1ea1492008-09-24 05:32:41 +00003686
Chris Lattner7a277142011-01-15 07:14:54 +00003687 CurInstIterator = BB.begin();
Hans Wennborg02fbc712012-09-19 07:48:16 +00003688 while (CurInstIterator != BB.end())
Chris Lattner1b93be52011-01-15 07:25:29 +00003689 MadeChange |= OptimizeInst(CurInstIterator++);
Eric Christopherc1ea1492008-09-24 05:32:41 +00003690
Benjamin Kramer455fa352012-11-23 19:17:06 +00003691 MadeChange |= DupRetToEnableTailCallOpts(&BB);
3692
Chris Lattnerf2836d12007-03-31 04:06:36 +00003693 return MadeChange;
3694}
Devang Patel53771ba2011-08-18 00:50:51 +00003695
3696// llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotem465834c2012-07-24 10:51:42 +00003697// handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patel53771ba2011-08-18 00:50:51 +00003698// find a node corresponding to the value.
3699bool CodeGenPrepare::PlaceDbgValues(Function &F) {
3700 bool MadeChange = false;
3701 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
Craig Topperc0196b12014-04-14 00:51:57 +00003702 Instruction *PrevNonDbgInst = nullptr;
Devang Patel53771ba2011-08-18 00:50:51 +00003703 for (BasicBlock::iterator BI = I->begin(), BE = I->end(); BI != BE;) {
3704 Instruction *Insn = BI; ++BI;
3705 DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
Adrian Prantl32da8892014-04-25 20:49:25 +00003706 // Leave dbg.values that refer to an alloca alone. These
3707 // instrinsics describe the address of a variable (= the alloca)
3708 // being taken. They should not be moved next to the alloca
3709 // (and to the beginning of the scope), but rather stay close to
3710 // where said address is used.
3711 if (!DVI || (DVI->getValue() && isa<AllocaInst>(DVI->getValue()))) {
Devang Patel53771ba2011-08-18 00:50:51 +00003712 PrevNonDbgInst = Insn;
3713 continue;
3714 }
3715
3716 Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
3717 if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
3718 DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
3719 DVI->removeFromParent();
3720 if (isa<PHINode>(VI))
3721 DVI->insertBefore(VI->getParent()->getFirstInsertionPt());
3722 else
3723 DVI->insertAfter(VI);
3724 MadeChange = true;
3725 ++NumDbgValueMoved;
3726 }
3727 }
3728 }
3729 return MadeChange;
3730}
Tim Northovercea0abb2014-03-29 08:22:29 +00003731
3732// If there is a sequence that branches based on comparing a single bit
3733// against zero that can be combined into a single instruction, and the
3734// target supports folding these into a single instruction, sink the
3735// mask and compare into the branch uses. Do this before OptimizeBlock ->
3736// OptimizeInst -> OptimizeCmpExpression, which perturbs the pattern being
3737// searched for.
3738bool CodeGenPrepare::sinkAndCmp(Function &F) {
3739 if (!EnableAndCmpSinking)
3740 return false;
3741 if (!TLI || !TLI->isMaskAndBranchFoldingLegal())
3742 return false;
3743 bool MadeChange = false;
3744 for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
3745 BasicBlock *BB = I++;
3746
3747 // Does this BB end with the following?
3748 // %andVal = and %val, #single-bit-set
3749 // %icmpVal = icmp %andResult, 0
3750 // br i1 %cmpVal label %dest1, label %dest2"
3751 BranchInst *Brcc = dyn_cast<BranchInst>(BB->getTerminator());
3752 if (!Brcc || !Brcc->isConditional())
3753 continue;
3754 ICmpInst *Cmp = dyn_cast<ICmpInst>(Brcc->getOperand(0));
3755 if (!Cmp || Cmp->getParent() != BB)
3756 continue;
3757 ConstantInt *Zero = dyn_cast<ConstantInt>(Cmp->getOperand(1));
3758 if (!Zero || !Zero->isZero())
3759 continue;
3760 Instruction *And = dyn_cast<Instruction>(Cmp->getOperand(0));
3761 if (!And || And->getOpcode() != Instruction::And || And->getParent() != BB)
3762 continue;
3763 ConstantInt* Mask = dyn_cast<ConstantInt>(And->getOperand(1));
3764 if (!Mask || !Mask->getUniqueInteger().isPowerOf2())
3765 continue;
3766 DEBUG(dbgs() << "found and; icmp ?,0; brcc\n"); DEBUG(BB->dump());
3767
3768 // Push the "and; icmp" for any users that are conditional branches.
3769 // Since there can only be one branch use per BB, we don't need to keep
3770 // track of which BBs we insert into.
3771 for (Value::use_iterator UI = Cmp->use_begin(), E = Cmp->use_end();
3772 UI != E; ) {
3773 Use &TheUse = *UI;
3774 // Find brcc use.
3775 BranchInst *BrccUser = dyn_cast<BranchInst>(*UI);
3776 ++UI;
3777 if (!BrccUser || !BrccUser->isConditional())
3778 continue;
3779 BasicBlock *UserBB = BrccUser->getParent();
3780 if (UserBB == BB) continue;
3781 DEBUG(dbgs() << "found Brcc use\n");
3782
3783 // Sink the "and; icmp" to use.
3784 MadeChange = true;
3785 BinaryOperator *NewAnd =
3786 BinaryOperator::CreateAnd(And->getOperand(0), And->getOperand(1), "",
3787 BrccUser);
3788 CmpInst *NewCmp =
3789 CmpInst::Create(Cmp->getOpcode(), Cmp->getPredicate(), NewAnd, Zero,
3790 "", BrccUser);
3791 TheUse = NewCmp;
3792 ++NumAndCmpsMoved;
3793 DEBUG(BrccUser->getParent()->dump());
3794 }
3795 }
3796 return MadeChange;
3797}