blob: 7e60c3b467929bc8f52ddd26df1516df337a6ff5 [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"
Chandler Carruth62d42152015-01-15 02:16:27 +000021#include "llvm/Analysis/TargetLibraryInfo.h"
Quentin Colombetc32615d2014-10-31 17:52:53 +000022#include "llvm/Analysis/TargetTransformInfo.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000023#include "llvm/IR/CallSite.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000024#include "llvm/IR/Constants.h"
25#include "llvm/IR/DataLayout.h"
26#include "llvm/IR/DerivedTypes.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000027#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000028#include "llvm/IR/Function.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000029#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000030#include "llvm/IR/IRBuilder.h"
31#include "llvm/IR/InlineAsm.h"
32#include "llvm/IR/Instructions.h"
33#include "llvm/IR/IntrinsicInst.h"
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +000034#include "llvm/IR/MDBuilder.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000035#include "llvm/IR/PatternMatch.h"
Ramkumar Ramachandradba73292015-01-14 23:27:07 +000036#include "llvm/IR/Statepoint.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +000037#include "llvm/IR/ValueHandle.h"
Chandler Carrutha4ea2692014-03-04 11:26:31 +000038#include "llvm/IR/ValueMap.h"
Chris Lattnerf2836d12007-03-31 04:06:36 +000039#include "llvm/Pass.h"
Evan Cheng8b637b12010-08-17 01:34:49 +000040#include "llvm/Support/CommandLine.h"
Evan Chengd3d80172007-12-05 23:58:20 +000041#include "llvm/Support/Debug.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000042#include "llvm/Support/raw_ostream.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000043#include "llvm/Target/TargetLowering.h"
Hal Finkelc3998302014-04-12 00:59:48 +000044#include "llvm/Target/TargetSubtargetInfo.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000045#include "llvm/Transforms/Utils/BasicBlockUtils.h"
46#include "llvm/Transforms/Utils/BuildLibCalls.h"
Preston Gurdcdf540d2012-09-04 18:22:17 +000047#include "llvm/Transforms/Utils/BypassSlowDivision.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000048#include "llvm/Transforms/Utils/Local.h"
Ahmed Bougachae03bef72015-01-12 17:22:43 +000049#include "llvm/Transforms/Utils/SimplifyLibCalls.h"
Chris Lattnerf2836d12007-03-31 04:06:36 +000050using namespace llvm;
Chris Lattnerd616ef52008-11-25 04:42:10 +000051using namespace llvm::PatternMatch;
Chris Lattnerf2836d12007-03-31 04:06:36 +000052
Chandler Carruth1b9dde02014-04-22 02:02:50 +000053#define DEBUG_TYPE "codegenprepare"
54
Cameron Zwarichced753f2011-01-05 17:27:27 +000055STATISTIC(NumBlocksElim, "Number of blocks eliminated");
Evan Cheng0663f232011-03-21 01:19:09 +000056STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated");
57STATISTIC(NumGEPsElim, "Number of GEPs converted to casts");
Cameron Zwarichced753f2011-01-05 17:27:27 +000058STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "
59 "sunken Cmps");
60STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
61 "of sunken Casts");
62STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "
63 "computations were sunk");
Evan Cheng0663f232011-03-21 01:19:09 +000064STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads");
65STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized");
66STATISTIC(NumRetsDup, "Number of return instructions duplicated");
Devang Patel53771ba2011-08-18 00:50:51 +000067STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved");
Benjamin Kramer047d7ca2012-05-05 12:49:22 +000068STATISTIC(NumSelectsExpanded, "Number of selects turned into branches");
Tim Northovercea0abb2014-03-29 08:22:29 +000069STATISTIC(NumAndCmpsMoved, "Number of and/cmp's pushed into branches");
Quentin Colombetc32615d2014-10-31 17:52:53 +000070STATISTIC(NumStoreExtractExposed, "Number of store(extractelement) exposed");
Jakob Stoklund Oleseneb12f492010-09-30 20:51:52 +000071
Cameron Zwarich338d3622011-03-11 21:52:04 +000072static cl::opt<bool> DisableBranchOpts(
73 "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
74 cl::desc("Disable branch optimizations in CodeGenPrepare"));
75
Ramkumar Ramachandradba73292015-01-14 23:27:07 +000076static cl::opt<bool>
77 DisableGCOpts("disable-cgp-gc-opts", cl::Hidden, cl::init(false),
78 cl::desc("Disable GC optimizations in CodeGenPrepare"));
79
Benjamin Kramer3d38c172012-05-06 14:25:16 +000080static cl::opt<bool> DisableSelectToBranch(
81 "disable-cgp-select2branch", cl::Hidden, cl::init(false),
82 cl::desc("Disable select to branch conversion."));
Benjamin Kramer047d7ca2012-05-05 12:49:22 +000083
Hal Finkelc3998302014-04-12 00:59:48 +000084static cl::opt<bool> AddrSinkUsingGEPs(
85 "addr-sink-using-gep", cl::Hidden, cl::init(false),
86 cl::desc("Address sinking in CGP using GEPs."));
87
Tim Northovercea0abb2014-03-29 08:22:29 +000088static cl::opt<bool> EnableAndCmpSinking(
89 "enable-andcmp-sinking", cl::Hidden, cl::init(true),
90 cl::desc("Enable sinkinig and/cmp into branches."));
91
Quentin Colombetc32615d2014-10-31 17:52:53 +000092static cl::opt<bool> DisableStoreExtract(
93 "disable-cgp-store-extract", cl::Hidden, cl::init(false),
94 cl::desc("Disable store(extract) optimizations in CodeGenPrepare"));
95
96static cl::opt<bool> StressStoreExtract(
97 "stress-cgp-store-extract", cl::Hidden, cl::init(false),
98 cl::desc("Stress test store(extract) optimizations in CodeGenPrepare"));
99
Quentin Colombetfc2201e2014-12-17 01:36:17 +0000100static cl::opt<bool> DisableExtLdPromotion(
101 "disable-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
102 cl::desc("Disable ext(promotable(ld)) -> promoted(ext(ld)) optimization in "
103 "CodeGenPrepare"));
104
105static cl::opt<bool> StressExtLdPromotion(
106 "stress-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
107 cl::desc("Stress test ext(promotable(ld)) -> promoted(ext(ld)) "
108 "optimization in CodeGenPrepare"));
109
Eric Christopherc1ea1492008-09-24 05:32:41 +0000110namespace {
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000111typedef SmallPtrSet<Instruction *, 16> SetOfInstrs;
Quentin Colombetf5485bb2014-11-13 01:44:51 +0000112struct TypeIsSExt {
113 Type *Ty;
114 bool IsSExt;
115 TypeIsSExt(Type *Ty, bool IsSExt) : Ty(Ty), IsSExt(IsSExt) {}
116};
117typedef DenseMap<Instruction *, TypeIsSExt> InstrToOrigTy;
Quentin Colombetfc2201e2014-12-17 01:36:17 +0000118class TypePromotionTransaction;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000119
Chris Lattner2dd09db2009-09-02 06:11:42 +0000120 class CodeGenPrepare : public FunctionPass {
Chris Lattnerf2836d12007-03-31 04:06:36 +0000121 /// TLI - Keep a pointer of a TargetLowering to consult for determining
122 /// transformation profitability.
Bill Wendling7a639ea2013-06-19 21:07:11 +0000123 const TargetMachine *TM;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000124 const TargetLowering *TLI;
Quentin Colombetc32615d2014-10-31 17:52:53 +0000125 const TargetTransformInfo *TTI;
Chad Rosierc24b86f2011-12-01 03:08:23 +0000126 const TargetLibraryInfo *TLInfo;
Cameron Zwarich84986b22011-01-08 17:01:52 +0000127 DominatorTree *DT;
Nadav Rotem465834c2012-07-24 10:51:42 +0000128
Chris Lattner7a277142011-01-15 07:14:54 +0000129 /// CurInstIterator - As we scan instructions optimizing them, this is the
130 /// next instruction to optimize. Xforms that can invalidate this should
131 /// update it.
132 BasicBlock::iterator CurInstIterator;
Evan Cheng3b3de7c2008-12-19 18:03:11 +0000133
Evan Cheng0663f232011-03-21 01:19:09 +0000134 /// Keeps track of non-local addresses that have been sunk into a block.
135 /// This allows us to avoid inserting duplicate code for blocks with
136 /// multiple load/stores of the same address.
Nick Lewycky5fb19632013-05-08 09:00:10 +0000137 ValueMap<Value*, Value*> SunkAddrs;
Cameron Zwarichce3b9302011-01-06 00:42:50 +0000138
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000139 /// Keeps track of all truncates inserted for the current function.
140 SetOfInstrs InsertedTruncsSet;
141 /// Keeps track of the type of the related instruction before their
142 /// promotion for the current function.
143 InstrToOrigTy PromotedInsts;
144
Devang Patel8f606d72011-03-24 15:35:25 +0000145 /// ModifiedDT - If CFG is modified in anyway, dominator tree may need to
Evan Cheng0663f232011-03-21 01:19:09 +0000146 /// be updated.
Devang Patel8f606d72011-03-24 15:35:25 +0000147 bool ModifiedDT;
Evan Cheng0663f232011-03-21 01:19:09 +0000148
Benjamin Kramer047d7ca2012-05-05 12:49:22 +0000149 /// OptSize - True if optimizing for size.
150 bool OptSize;
151
Chris Lattnerf2836d12007-03-31 04:06:36 +0000152 public:
Nick Lewyckye7da2d62007-05-06 13:37:16 +0000153 static char ID; // Pass identification, replacement for typeid
Craig Topperc0196b12014-04-14 00:51:57 +0000154 explicit CodeGenPrepare(const TargetMachine *TM = nullptr)
Quentin Colombetc32615d2014-10-31 17:52:53 +0000155 : FunctionPass(ID), TM(TM), TLI(nullptr), TTI(nullptr) {
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000156 initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
157 }
Craig Topper4584cd52014-03-07 09:26:03 +0000158 bool runOnFunction(Function &F) override;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000159
Craig Topper4584cd52014-03-07 09:26:03 +0000160 const char *getPassName() const override { return "CodeGen Prepare"; }
Evan Cheng99cafb12012-12-21 01:48:14 +0000161
Craig Topper4584cd52014-03-07 09:26:03 +0000162 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruth73523022014-01-13 13:07:17 +0000163 AU.addPreserved<DominatorTreeWrapperPass>();
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000164 AU.addRequired<TargetLibraryInfoWrapperPass>();
Chandler Carruth705b1852015-01-31 03:43:40 +0000165 AU.addRequired<TargetTransformInfoWrapperPass>();
Andreas Neustifterf8cb7582009-09-16 09:26:52 +0000166 }
167
Chris Lattnerf2836d12007-03-31 04:06:36 +0000168 private:
Nadav Rotem70409992012-08-14 05:19:07 +0000169 bool EliminateFallThrough(Function &F);
Chris Lattnerc3748562007-04-02 01:35:34 +0000170 bool EliminateMostlyEmptyBlocks(Function &F);
171 bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
172 void EliminateMostlyEmptyBlock(BasicBlock *BB);
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000173 bool OptimizeBlock(BasicBlock &BB, bool& ModifiedDT);
174 bool OptimizeInst(Instruction *I, bool& ModifiedDT);
Chris Lattner229907c2011-07-18 04:54:35 +0000175 bool OptimizeMemoryInst(Instruction *I, Value *Addr, Type *AccessTy);
Chris Lattner7a277142011-01-15 07:14:54 +0000176 bool OptimizeInlineAsmInst(CallInst *CS);
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000177 bool OptimizeCallInst(CallInst *CI, bool& ModifiedDT);
Quentin Colombetfc2201e2014-12-17 01:36:17 +0000178 bool MoveExtToFormExtLoad(Instruction *&I);
Evan Chengd3d80172007-12-05 23:58:20 +0000179 bool OptimizeExtUses(Instruction *I);
Benjamin Kramer047d7ca2012-05-05 12:49:22 +0000180 bool OptimizeSelectInst(SelectInst *SI);
Tim Northoveraeb8e062014-02-19 10:02:43 +0000181 bool OptimizeShuffleVectorInst(ShuffleVectorInst *SI);
Quentin Colombetc32615d2014-10-31 17:52:53 +0000182 bool OptimizeExtractElementInst(Instruction *Inst);
Benjamin Kramer455fa352012-11-23 19:17:06 +0000183 bool DupRetToEnableTailCallOpts(BasicBlock *BB);
Devang Patel53771ba2011-08-18 00:50:51 +0000184 bool PlaceDbgValues(Function &F);
Tim Northovercea0abb2014-03-29 08:22:29 +0000185 bool sinkAndCmp(Function &F);
Quentin Colombetfc2201e2014-12-17 01:36:17 +0000186 bool ExtLdPromotion(TypePromotionTransaction &TPT, LoadInst *&LI,
187 Instruction *&Inst,
188 const SmallVectorImpl<Instruction *> &Exts,
189 unsigned CreatedInst);
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +0000190 bool splitBranchCondition(Function &F);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000191 bool simplifyOffsetableRelocate(Instruction &I);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000192 };
193}
Devang Patel09f162c2007-05-01 21:15:47 +0000194
Devang Patel8c78a0b2007-05-03 01:11:54 +0000195char CodeGenPrepare::ID = 0;
Jiangning Liud623c522014-06-11 07:04:37 +0000196INITIALIZE_TM_PASS(CodeGenPrepare, "codegenprepare",
197 "Optimize for code generation", false, false)
Chris Lattnerf2836d12007-03-31 04:06:36 +0000198
Bill Wendling7a639ea2013-06-19 21:07:11 +0000199FunctionPass *llvm::createCodeGenPreparePass(const TargetMachine *TM) {
200 return new CodeGenPrepare(TM);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000201}
202
Chris Lattnerf2836d12007-03-31 04:06:36 +0000203bool CodeGenPrepare::runOnFunction(Function &F) {
Paul Robinson7c99ec52014-03-31 17:43:35 +0000204 if (skipOptnoneFunction(F))
205 return false;
206
Chris Lattnerf2836d12007-03-31 04:06:36 +0000207 bool EverMadeChange = false;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000208 // Clear per function information.
209 InsertedTruncsSet.clear();
210 PromotedInsts.clear();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000211
Devang Patel8f606d72011-03-24 15:35:25 +0000212 ModifiedDT = false;
Eric Christopherd9134482014-08-04 21:25:23 +0000213 if (TM)
Eric Christopherfccff372015-01-27 01:01:38 +0000214 TLI = TM->getSubtargetImpl(F)->getTargetLowering();
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000215 TLInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Chandler Carruthfdb9c572015-02-01 12:01:35 +0000216 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
Chandler Carruth73523022014-01-13 13:07:17 +0000217 DominatorTreeWrapperPass *DTWP =
218 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
Craig Topperc0196b12014-04-14 00:51:57 +0000219 DT = DTWP ? &DTWP->getDomTree() : nullptr;
Duncan P. N. Exon Smith70eb9c52015-02-14 01:44:41 +0000220 OptSize = F.hasFnAttribute(Attribute::OptimizeForSize);
Evan Cheng0663f232011-03-21 01:19:09 +0000221
Preston Gurdcdf540d2012-09-04 18:22:17 +0000222 /// This optimization identifies DIV instructions that can be
223 /// profitably bypassed and carried out with a shorter, faster divide.
Preston Gurd485296d2013-03-04 18:13:57 +0000224 if (!OptSize && TLI && TLI->isSlowDivBypassed()) {
Preston Gurd0d67f512012-10-04 21:33:40 +0000225 const DenseMap<unsigned int, unsigned int> &BypassWidths =
226 TLI->getBypassSlowDivWidths();
Evan Cheng71be12b2012-09-14 21:25:34 +0000227 for (Function::iterator I = F.begin(); I != F.end(); I++)
Preston Gurd0d67f512012-10-04 21:33:40 +0000228 EverMadeChange |= bypassSlowDivision(F, I, BypassWidths);
Preston Gurdcdf540d2012-09-04 18:22:17 +0000229 }
230
231 // Eliminate blocks that contain only PHI nodes and an
Chris Lattnerc3748562007-04-02 01:35:34 +0000232 // unconditional branch.
233 EverMadeChange |= EliminateMostlyEmptyBlocks(F);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000234
Devang Patel53771ba2011-08-18 00:50:51 +0000235 // llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotem465834c2012-07-24 10:51:42 +0000236 // handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patel53771ba2011-08-18 00:50:51 +0000237 // find a node corresponding to the value.
238 EverMadeChange |= PlaceDbgValues(F);
239
Tim Northovercea0abb2014-03-29 08:22:29 +0000240 // If there is a mask, compare against zero, and branch that can be combined
241 // into a single target instruction, push the mask and compare into branch
242 // users. Do this before OptimizeBlock -> OptimizeInst ->
243 // OptimizeCmpExpression, which perturbs the pattern being searched for.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +0000244 if (!DisableBranchOpts) {
Tim Northovercea0abb2014-03-29 08:22:29 +0000245 EverMadeChange |= sinkAndCmp(F);
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +0000246 EverMadeChange |= splitBranchCondition(F);
247 }
Tim Northovercea0abb2014-03-29 08:22:29 +0000248
Chris Lattnerc3748562007-04-02 01:35:34 +0000249 bool MadeChange = true;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000250 while (MadeChange) {
251 MadeChange = false;
Hans Wennborg02fbc712012-09-19 07:48:16 +0000252 for (Function::iterator I = F.begin(); I != F.end(); ) {
Evan Cheng0663f232011-03-21 01:19:09 +0000253 BasicBlock *BB = I++;
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000254 bool ModifiedDTOnIteration = false;
255 MadeChange |= OptimizeBlock(*BB, ModifiedDTOnIteration);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000256
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000257 // Restart BB iteration if the dominator tree of the Function was changed
258 ModifiedDT |= ModifiedDTOnIteration;
259 if (ModifiedDTOnIteration)
260 break;
Evan Cheng0663f232011-03-21 01:19:09 +0000261 }
Chris Lattnerf2836d12007-03-31 04:06:36 +0000262 EverMadeChange |= MadeChange;
263 }
Cameron Zwarichce3b9302011-01-06 00:42:50 +0000264
265 SunkAddrs.clear();
266
Cameron Zwarich338d3622011-03-11 21:52:04 +0000267 if (!DisableBranchOpts) {
268 MadeChange = false;
Bill Wendling97b93592012-03-04 10:46:01 +0000269 SmallPtrSet<BasicBlock*, 8> WorkList;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +0000270 for (BasicBlock &BB : F) {
271 SmallVector<BasicBlock *, 2> Successors(succ_begin(&BB), succ_end(&BB));
272 MadeChange |= ConstantFoldTerminator(&BB, true);
Bill Wendling97b93592012-03-04 10:46:01 +0000273 if (!MadeChange) continue;
274
275 for (SmallVectorImpl<BasicBlock*>::iterator
276 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
277 if (pred_begin(*II) == pred_end(*II))
278 WorkList.insert(*II);
279 }
280
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000281 // Delete the dead blocks and any of their dead successors.
Bill Wendlingab417b62012-12-06 00:30:20 +0000282 MadeChange |= !WorkList.empty();
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000283 while (!WorkList.empty()) {
284 BasicBlock *BB = *WorkList.begin();
285 WorkList.erase(BB);
286 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
287
288 DeleteDeadBlock(BB);
Stephen Lin837bba12013-07-15 17:55:02 +0000289
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000290 for (SmallVectorImpl<BasicBlock*>::iterator
291 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
292 if (pred_begin(*II) == pred_end(*II))
293 WorkList.insert(*II);
294 }
Cameron Zwarich338d3622011-03-11 21:52:04 +0000295
Nadav Rotem70409992012-08-14 05:19:07 +0000296 // Merge pairs of basic blocks with unconditional branches, connected by
297 // a single edge.
298 if (EverMadeChange || MadeChange)
299 MadeChange |= EliminateFallThrough(F);
300
Evan Cheng0663f232011-03-21 01:19:09 +0000301 if (MadeChange)
Devang Patel8f606d72011-03-24 15:35:25 +0000302 ModifiedDT = true;
Cameron Zwarich338d3622011-03-11 21:52:04 +0000303 EverMadeChange |= MadeChange;
304 }
305
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000306 if (!DisableGCOpts) {
307 SmallVector<Instruction *, 2> Statepoints;
308 for (BasicBlock &BB : F)
309 for (Instruction &I : BB)
310 if (isStatepoint(I))
311 Statepoints.push_back(&I);
312 for (auto &I : Statepoints)
313 EverMadeChange |= simplifyOffsetableRelocate(*I);
314 }
315
Devang Patel8f606d72011-03-24 15:35:25 +0000316 if (ModifiedDT && DT)
Chandler Carruth73523022014-01-13 13:07:17 +0000317 DT->recalculate(F);
Evan Cheng0663f232011-03-21 01:19:09 +0000318
Chris Lattnerf2836d12007-03-31 04:06:36 +0000319 return EverMadeChange;
320}
321
Nadav Rotem70409992012-08-14 05:19:07 +0000322/// EliminateFallThrough - Merge basic blocks which are connected
323/// by a single edge, where one of the basic blocks has a single successor
324/// pointing to the other basic block, which has a single predecessor.
325bool CodeGenPrepare::EliminateFallThrough(Function &F) {
326 bool Changed = false;
327 // Scan all of the blocks in the function, except for the entry block.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000328 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
Nadav Rotem70409992012-08-14 05:19:07 +0000329 BasicBlock *BB = I++;
330 // If the destination block has a single pred, then this is a trivial
331 // edge, just collapse it.
332 BasicBlock *SinglePred = BB->getSinglePredecessor();
333
Evan Cheng64a223a2012-09-28 23:58:57 +0000334 // Don't merge if BB's address is taken.
335 if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue;
Nadav Rotem70409992012-08-14 05:19:07 +0000336
337 BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
338 if (Term && !Term->isConditional()) {
339 Changed = true;
Michael Liao6e12d122012-08-21 05:55:22 +0000340 DEBUG(dbgs() << "To merge:\n"<< *SinglePred << "\n\n\n");
Nadav Rotem70409992012-08-14 05:19:07 +0000341 // Remember if SinglePred was the entry block of the function.
342 // If so, we will need to move BB back to the entry position.
343 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Chandler Carruth10f28f22015-01-20 01:37:09 +0000344 MergeBasicBlockIntoOnlyPred(BB, DT);
Nadav Rotem70409992012-08-14 05:19:07 +0000345
346 if (isEntry && BB != &BB->getParent()->getEntryBlock())
347 BB->moveBefore(&BB->getParent()->getEntryBlock());
348
349 // We have erased a block. Update the iterator.
350 I = BB;
Nadav Rotem70409992012-08-14 05:19:07 +0000351 }
352 }
353 return Changed;
354}
355
Dale Johannesen4026b042009-03-27 01:13:37 +0000356/// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes,
357/// debug info directives, and an unconditional branch. Passes before isel
358/// (e.g. LSR/loopsimplify) often split edges in ways that are non-optimal for
359/// isel. Start by eliminating these blocks so we can split them the way we
360/// want them.
Chris Lattnerc3748562007-04-02 01:35:34 +0000361bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
362 bool MadeChange = false;
363 // Note that this intentionally skips the entry block.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000364 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
Chris Lattnerc3748562007-04-02 01:35:34 +0000365 BasicBlock *BB = I++;
366
367 // If this block doesn't end with an uncond branch, ignore it.
368 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
369 if (!BI || !BI->isUnconditional())
370 continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000371
Dale Johannesen4026b042009-03-27 01:13:37 +0000372 // If the instruction before the branch (skipping debug info) isn't a phi
373 // node, then other stuff is happening here.
Chris Lattnerc3748562007-04-02 01:35:34 +0000374 BasicBlock::iterator BBI = BI;
375 if (BBI != BB->begin()) {
376 --BBI;
Dale Johannesen4026b042009-03-27 01:13:37 +0000377 while (isa<DbgInfoIntrinsic>(BBI)) {
378 if (BBI == BB->begin())
379 break;
380 --BBI;
381 }
382 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
383 continue;
Chris Lattnerc3748562007-04-02 01:35:34 +0000384 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000385
Chris Lattnerc3748562007-04-02 01:35:34 +0000386 // Do not break infinite loops.
387 BasicBlock *DestBB = BI->getSuccessor(0);
388 if (DestBB == BB)
389 continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000390
Chris Lattnerc3748562007-04-02 01:35:34 +0000391 if (!CanMergeBlocks(BB, DestBB))
392 continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000393
Chris Lattnerc3748562007-04-02 01:35:34 +0000394 EliminateMostlyEmptyBlock(BB);
395 MadeChange = true;
396 }
397 return MadeChange;
398}
399
400/// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
401/// single uncond branch between them, and BB contains no other non-phi
402/// instructions.
403bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
404 const BasicBlock *DestBB) const {
405 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
406 // the successor. If there are more complex condition (e.g. preheaders),
407 // don't mess around with them.
408 BasicBlock::const_iterator BBI = BB->begin();
409 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000410 for (const User *U : PN->users()) {
411 const Instruction *UI = cast<Instruction>(U);
412 if (UI->getParent() != DestBB || !isa<PHINode>(UI))
Chris Lattnerc3748562007-04-02 01:35:34 +0000413 return false;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000414 // If User is inside DestBB block and it is a PHINode then check
415 // incoming value. If incoming value is not from BB then this is
Devang Pateld3208522007-04-25 00:37:04 +0000416 // a complex condition (e.g. preheaders) we want to avoid here.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000417 if (UI->getParent() == DestBB) {
418 if (const PHINode *UPN = dyn_cast<PHINode>(UI))
Devang Pateld3208522007-04-25 00:37:04 +0000419 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
420 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
421 if (Insn && Insn->getParent() == BB &&
422 Insn->getParent() != UPN->getIncomingBlock(I))
423 return false;
424 }
425 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000426 }
427 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000428
Chris Lattnerc3748562007-04-02 01:35:34 +0000429 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
430 // and DestBB may have conflicting incoming values for the block. If so, we
431 // can't merge the block.
432 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
433 if (!DestBBPN) return true; // no conflict.
Eric Christopherc1ea1492008-09-24 05:32:41 +0000434
Chris Lattnerc3748562007-04-02 01:35:34 +0000435 // Collect the preds of BB.
Chris Lattner8201a9b2007-11-06 22:07:40 +0000436 SmallPtrSet<const BasicBlock*, 16> BBPreds;
Chris Lattnerc3748562007-04-02 01:35:34 +0000437 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
438 // It is faster to get preds from a PHI than with pred_iterator.
439 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
440 BBPreds.insert(BBPN->getIncomingBlock(i));
441 } else {
442 BBPreds.insert(pred_begin(BB), pred_end(BB));
443 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000444
Chris Lattnerc3748562007-04-02 01:35:34 +0000445 // Walk the preds of DestBB.
446 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
447 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
448 if (BBPreds.count(Pred)) { // Common predecessor?
449 BBI = DestBB->begin();
450 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
451 const Value *V1 = PN->getIncomingValueForBlock(Pred);
452 const Value *V2 = PN->getIncomingValueForBlock(BB);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000453
Chris Lattnerc3748562007-04-02 01:35:34 +0000454 // If V2 is a phi node in BB, look up what the mapped value will be.
455 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
456 if (V2PN->getParent() == BB)
457 V2 = V2PN->getIncomingValueForBlock(Pred);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000458
Chris Lattnerc3748562007-04-02 01:35:34 +0000459 // If there is a conflict, bail out.
460 if (V1 != V2) return false;
461 }
462 }
463 }
464
465 return true;
466}
467
468
469/// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
470/// an unconditional branch in it.
471void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
472 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
473 BasicBlock *DestBB = BI->getSuccessor(0);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000474
David Greene74e2d492010-01-05 01:27:11 +0000475 DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000476
Chris Lattnerc3748562007-04-02 01:35:34 +0000477 // If the destination block has a single pred, then this is a trivial edge,
478 // just collapse it.
Chris Lattner4059f432008-11-27 19:29:14 +0000479 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
Chris Lattner8a172da2008-11-28 19:54:49 +0000480 if (SinglePred != DestBB) {
481 // Remember if SinglePred was the entry block of the function. If so, we
482 // will need to move BB back to the entry position.
483 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Chandler Carruth10f28f22015-01-20 01:37:09 +0000484 MergeBasicBlockIntoOnlyPred(DestBB, DT);
Chris Lattner4059f432008-11-27 19:29:14 +0000485
Chris Lattner8a172da2008-11-28 19:54:49 +0000486 if (isEntry && BB != &BB->getParent()->getEntryBlock())
487 BB->moveBefore(&BB->getParent()->getEntryBlock());
Nadav Rotem465834c2012-07-24 10:51:42 +0000488
David Greene74e2d492010-01-05 01:27:11 +0000489 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattner8a172da2008-11-28 19:54:49 +0000490 return;
491 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000492 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000493
Chris Lattnerc3748562007-04-02 01:35:34 +0000494 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
495 // to handle the new incoming edges it is about to have.
496 PHINode *PN;
497 for (BasicBlock::iterator BBI = DestBB->begin();
498 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
499 // Remove the incoming value for BB, and remember it.
500 Value *InVal = PN->removeIncomingValue(BB, false);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000501
Chris Lattnerc3748562007-04-02 01:35:34 +0000502 // Two options: either the InVal is a phi node defined in BB or it is some
503 // value that dominates BB.
504 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
505 if (InValPhi && InValPhi->getParent() == BB) {
506 // Add all of the input values of the input PHI as inputs of this phi.
507 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
508 PN->addIncoming(InValPhi->getIncomingValue(i),
509 InValPhi->getIncomingBlock(i));
510 } else {
511 // Otherwise, add one instance of the dominating value for each edge that
512 // we will be adding.
513 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
514 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
515 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
516 } else {
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000517 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
518 PN->addIncoming(InVal, *PI);
Chris Lattnerc3748562007-04-02 01:35:34 +0000519 }
520 }
521 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000522
Chris Lattnerc3748562007-04-02 01:35:34 +0000523 // The PHIs are now updated, change everything that refers to BB to use
524 // DestBB and remove BB.
525 BB->replaceAllUsesWith(DestBB);
Devang Patel8f606d72011-03-24 15:35:25 +0000526 if (DT && !ModifiedDT) {
Cameron Zwarich84986b22011-01-08 17:01:52 +0000527 BasicBlock *BBIDom = DT->getNode(BB)->getIDom()->getBlock();
528 BasicBlock *DestBBIDom = DT->getNode(DestBB)->getIDom()->getBlock();
529 BasicBlock *NewIDom = DT->findNearestCommonDominator(BBIDom, DestBBIDom);
530 DT->changeImmediateDominator(DestBB, NewIDom);
531 DT->eraseNode(BB);
532 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000533 BB->eraseFromParent();
Cameron Zwarichced753f2011-01-05 17:27:27 +0000534 ++NumBlocksElim;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000535
David Greene74e2d492010-01-05 01:27:11 +0000536 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerc3748562007-04-02 01:35:34 +0000537}
538
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000539// Computes a map of base pointer relocation instructions to corresponding
540// derived pointer relocation instructions given a vector of all relocate calls
541static void computeBaseDerivedRelocateMap(
542 const SmallVectorImpl<User *> &AllRelocateCalls,
543 DenseMap<IntrinsicInst *, SmallVector<IntrinsicInst *, 2>> &
544 RelocateInstMap) {
545 // Collect information in two maps: one primarily for locating the base object
546 // while filling the second map; the second map is the final structure holding
547 // a mapping between Base and corresponding Derived relocate calls
548 DenseMap<std::pair<unsigned, unsigned>, IntrinsicInst *> RelocateIdxMap;
549 for (auto &U : AllRelocateCalls) {
550 GCRelocateOperands ThisRelocate(U);
551 IntrinsicInst *I = cast<IntrinsicInst>(U);
552 auto K = std::make_pair(ThisRelocate.basePtrIndex(),
553 ThisRelocate.derivedPtrIndex());
554 RelocateIdxMap.insert(std::make_pair(K, I));
555 }
556 for (auto &Item : RelocateIdxMap) {
557 std::pair<unsigned, unsigned> Key = Item.first;
558 if (Key.first == Key.second)
559 // Base relocation: nothing to insert
560 continue;
561
562 IntrinsicInst *I = Item.second;
563 auto BaseKey = std::make_pair(Key.first, Key.first);
564 IntrinsicInst *Base = RelocateIdxMap[BaseKey];
565 if (!Base)
566 // TODO: We might want to insert a new base object relocate and gep off
567 // that, if there are enough derived object relocates.
568 continue;
569 RelocateInstMap[Base].push_back(I);
570 }
571}
572
573// Accepts a GEP and extracts the operands into a vector provided they're all
574// small integer constants
575static bool getGEPSmallConstantIntOffsetV(GetElementPtrInst *GEP,
576 SmallVectorImpl<Value *> &OffsetV) {
577 for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
578 // Only accept small constant integer operands
579 auto Op = dyn_cast<ConstantInt>(GEP->getOperand(i));
580 if (!Op || Op->getZExtValue() > 20)
581 return false;
582 }
583
584 for (unsigned i = 1; i < GEP->getNumOperands(); i++)
585 OffsetV.push_back(GEP->getOperand(i));
586 return true;
587}
588
589// Takes a RelocatedBase (base pointer relocation instruction) and Targets to
590// replace, computes a replacement, and affects it.
591static bool
592simplifyRelocatesOffABase(IntrinsicInst *RelocatedBase,
593 const SmallVectorImpl<IntrinsicInst *> &Targets) {
594 bool MadeChange = false;
595 for (auto &ToReplace : Targets) {
596 GCRelocateOperands MasterRelocate(RelocatedBase);
597 GCRelocateOperands ThisRelocate(ToReplace);
598
599 assert(ThisRelocate.basePtrIndex() == MasterRelocate.basePtrIndex() &&
600 "Not relocating a derived object of the original base object");
601 if (ThisRelocate.basePtrIndex() == ThisRelocate.derivedPtrIndex()) {
602 // A duplicate relocate call. TODO: coalesce duplicates.
603 continue;
604 }
605
606 Value *Base = ThisRelocate.basePtr();
607 auto Derived = dyn_cast<GetElementPtrInst>(ThisRelocate.derivedPtr());
608 if (!Derived || Derived->getPointerOperand() != Base)
609 continue;
610
611 SmallVector<Value *, 2> OffsetV;
612 if (!getGEPSmallConstantIntOffsetV(Derived, OffsetV))
613 continue;
614
615 // Create a Builder and replace the target callsite with a gep
616 IRBuilder<> Builder(ToReplace);
617 Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc());
618 Value *Replacement =
619 Builder.CreateGEP(RelocatedBase, makeArrayRef(OffsetV));
620 Instruction *ReplacementInst = cast<Instruction>(Replacement);
621 ReplacementInst->removeFromParent();
622 ReplacementInst->insertAfter(RelocatedBase);
623 Replacement->takeName(ToReplace);
624 ToReplace->replaceAllUsesWith(Replacement);
625 ToReplace->eraseFromParent();
626
627 MadeChange = true;
628 }
629 return MadeChange;
630}
631
632// Turns this:
633//
634// %base = ...
635// %ptr = gep %base + 15
636// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
637// %base' = relocate(%tok, i32 4, i32 4)
638// %ptr' = relocate(%tok, i32 4, i32 5)
639// %val = load %ptr'
640//
641// into this:
642//
643// %base = ...
644// %ptr = gep %base + 15
645// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
646// %base' = gc.relocate(%tok, i32 4, i32 4)
647// %ptr' = gep %base' + 15
648// %val = load %ptr'
649bool CodeGenPrepare::simplifyOffsetableRelocate(Instruction &I) {
650 bool MadeChange = false;
651 SmallVector<User *, 2> AllRelocateCalls;
652
653 for (auto *U : I.users())
654 if (isGCRelocate(dyn_cast<Instruction>(U)))
655 // Collect all the relocate calls associated with a statepoint
656 AllRelocateCalls.push_back(U);
657
658 // We need atleast one base pointer relocation + one derived pointer
659 // relocation to mangle
660 if (AllRelocateCalls.size() < 2)
661 return false;
662
663 // RelocateInstMap is a mapping from the base relocate instruction to the
664 // corresponding derived relocate instructions
665 DenseMap<IntrinsicInst *, SmallVector<IntrinsicInst *, 2>> RelocateInstMap;
666 computeBaseDerivedRelocateMap(AllRelocateCalls, RelocateInstMap);
667 if (RelocateInstMap.empty())
668 return false;
669
670 for (auto &Item : RelocateInstMap)
671 // Item.first is the RelocatedBase to offset against
672 // Item.second is the vector of Targets to replace
673 MadeChange = simplifyRelocatesOffABase(Item.first, Item.second);
674 return MadeChange;
675}
676
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000677/// SinkCast - Sink the specified cast instruction into its user blocks
678static bool SinkCast(CastInst *CI) {
Chris Lattnerf2836d12007-03-31 04:06:36 +0000679 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000680
Chris Lattnerf2836d12007-03-31 04:06:36 +0000681 /// InsertedCasts - Only insert a cast in each block once.
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000682 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000683
Chris Lattnerf2836d12007-03-31 04:06:36 +0000684 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000685 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
Chris Lattnerf2836d12007-03-31 04:06:36 +0000686 UI != E; ) {
687 Use &TheUse = UI.getUse();
688 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000689
Chris Lattnerf2836d12007-03-31 04:06:36 +0000690 // Figure out which BB this cast is used in. For PHI's this is the
691 // appropriate predecessor block.
692 BasicBlock *UserBB = User->getParent();
693 if (PHINode *PN = dyn_cast<PHINode>(User)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000694 UserBB = PN->getIncomingBlock(TheUse);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000695 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000696
Chris Lattnerf2836d12007-03-31 04:06:36 +0000697 // Preincrement use iterator so we don't invalidate it.
698 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000699
Chris Lattnerf2836d12007-03-31 04:06:36 +0000700 // If this user is in the same block as the cast, don't change the cast.
701 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000702
Chris Lattnerf2836d12007-03-31 04:06:36 +0000703 // If we have already inserted a cast into this block, use it.
704 CastInst *&InsertedCast = InsertedCasts[UserBB];
705
706 if (!InsertedCast) {
Bill Wendling8ddfc092011-08-16 20:45:24 +0000707 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000708 InsertedCast =
709 CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
Chris Lattnerf2836d12007-03-31 04:06:36 +0000710 InsertPt);
711 MadeChange = true;
712 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000713
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000714 // Replace a use of the cast with a use of the new cast.
Chris Lattnerf2836d12007-03-31 04:06:36 +0000715 TheUse = InsertedCast;
Cameron Zwarichced753f2011-01-05 17:27:27 +0000716 ++NumCastUses;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000717 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000718
Chris Lattnerf2836d12007-03-31 04:06:36 +0000719 // If we removed all uses, nuke the cast.
Duncan Sandsafa84da42008-01-20 16:51:46 +0000720 if (CI->use_empty()) {
Chris Lattnerf2836d12007-03-31 04:06:36 +0000721 CI->eraseFromParent();
Duncan Sandsafa84da42008-01-20 16:51:46 +0000722 MadeChange = true;
723 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000724
Chris Lattnerf2836d12007-03-31 04:06:36 +0000725 return MadeChange;
726}
727
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000728/// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
729/// copy (e.g. it's casting from one pointer type to another, i32->i8 on PPC),
730/// sink it into user blocks to reduce the number of virtual
731/// registers that must be created and coalesced.
732///
733/// Return true if any changes are made.
734///
735static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
736 // If this is a noop copy,
737 EVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
738 EVT DstVT = TLI.getValueType(CI->getType());
739
740 // This is an fp<->int conversion?
741 if (SrcVT.isInteger() != DstVT.isInteger())
742 return false;
743
744 // If this is an extension, it will be a zero or sign extension, which
745 // isn't a noop.
746 if (SrcVT.bitsLT(DstVT)) return false;
747
748 // If these values will be promoted, find out what they will be promoted
749 // to. This helps us consider truncates on PPC as noop copies when they
750 // are.
751 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
752 TargetLowering::TypePromoteInteger)
753 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
754 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
755 TargetLowering::TypePromoteInteger)
756 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
757
758 // If, after promotion, these are the same types, this is a noop copy.
759 if (SrcVT != DstVT)
760 return false;
761
762 return SinkCast(CI);
763}
764
Eric Christopherc1ea1492008-09-24 05:32:41 +0000765/// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000766/// the number of virtual registers that must be created and coalesced. This is
Chris Lattner27406942007-08-02 16:53:43 +0000767/// a clear win except on targets with multiple condition code registers
768/// (PowerPC), where it might lose; some adjustment may be wanted there.
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000769///
770/// Return true if any changes are made.
Chris Lattner6416a6b2008-11-24 22:44:16 +0000771static bool OptimizeCmpExpression(CmpInst *CI) {
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000772 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000773
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000774 /// InsertedCmp - Only insert a cmp in each block once.
775 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000776
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000777 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000778 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000779 UI != E; ) {
780 Use &TheUse = UI.getUse();
781 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000782
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000783 // Preincrement use iterator so we don't invalidate it.
784 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000785
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000786 // Don't bother for PHI nodes.
787 if (isa<PHINode>(User))
788 continue;
789
790 // Figure out which BB this cmp is used in.
791 BasicBlock *UserBB = User->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000792
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000793 // If this user is in the same block as the cmp, don't change the cmp.
794 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000795
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000796 // If we have already inserted a cmp into this block, use it.
797 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
798
799 if (!InsertedCmp) {
Bill Wendling8ddfc092011-08-16 20:45:24 +0000800 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000801 InsertedCmp =
Dan Gohmanad1f0a12009-08-25 23:17:54 +0000802 CmpInst::Create(CI->getOpcode(),
Owen Anderson1e5f00e2009-07-09 23:48:35 +0000803 CI->getPredicate(), CI->getOperand(0),
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000804 CI->getOperand(1), "", InsertPt);
805 MadeChange = true;
806 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000807
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000808 // Replace a use of the cmp with a use of the new cmp.
809 TheUse = InsertedCmp;
Cameron Zwarichced753f2011-01-05 17:27:27 +0000810 ++NumCmpUses;
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000811 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000812
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000813 // If we removed all uses, nuke the cmp.
814 if (CI->use_empty())
815 CI->eraseFromParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000816
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000817 return MadeChange;
818}
819
Yi Jiangd069f632014-04-21 19:34:27 +0000820/// isExtractBitsCandidateUse - Check if the candidates could
821/// be combined with shift instruction, which includes:
822/// 1. Truncate instruction
823/// 2. And instruction and the imm is a mask of the low bits:
824/// imm & (imm+1) == 0
Benjamin Kramer322053c2014-04-27 14:54:59 +0000825static bool isExtractBitsCandidateUse(Instruction *User) {
Yi Jiangd069f632014-04-21 19:34:27 +0000826 if (!isa<TruncInst>(User)) {
827 if (User->getOpcode() != Instruction::And ||
828 !isa<ConstantInt>(User->getOperand(1)))
829 return false;
830
Quentin Colombetd4f44692014-04-22 01:20:34 +0000831 const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue();
Yi Jiangd069f632014-04-21 19:34:27 +0000832
Quentin Colombetd4f44692014-04-22 01:20:34 +0000833 if ((Cimm & (Cimm + 1)).getBoolValue())
Yi Jiangd069f632014-04-21 19:34:27 +0000834 return false;
835 }
836 return true;
837}
838
839/// SinkShiftAndTruncate - sink both shift and truncate instruction
840/// to the use of truncate's BB.
Benjamin Kramer322053c2014-04-27 14:54:59 +0000841static bool
Yi Jiangd069f632014-04-21 19:34:27 +0000842SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI,
843 DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts,
844 const TargetLowering &TLI) {
845 BasicBlock *UserBB = User->getParent();
846 DenseMap<BasicBlock *, CastInst *> InsertedTruncs;
847 TruncInst *TruncI = dyn_cast<TruncInst>(User);
848 bool MadeChange = false;
849
850 for (Value::user_iterator TruncUI = TruncI->user_begin(),
851 TruncE = TruncI->user_end();
852 TruncUI != TruncE;) {
853
854 Use &TruncTheUse = TruncUI.getUse();
855 Instruction *TruncUser = cast<Instruction>(*TruncUI);
856 // Preincrement use iterator so we don't invalidate it.
857
858 ++TruncUI;
859
860 int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode());
861 if (!ISDOpcode)
862 continue;
863
Tim Northovere2239ff2014-07-29 10:20:22 +0000864 // If the use is actually a legal node, there will not be an
865 // implicit truncate.
866 // FIXME: always querying the result type is just an
867 // approximation; some nodes' legality is determined by the
868 // operand or other means. There's no good way to find out though.
Ahmed Bougacha0788d492014-11-12 22:16:55 +0000869 if (TLI.isOperationLegalOrCustom(
870 ISDOpcode, TLI.getValueType(TruncUser->getType(), true)))
Yi Jiangd069f632014-04-21 19:34:27 +0000871 continue;
872
873 // Don't bother for PHI nodes.
874 if (isa<PHINode>(TruncUser))
875 continue;
876
877 BasicBlock *TruncUserBB = TruncUser->getParent();
878
879 if (UserBB == TruncUserBB)
880 continue;
881
882 BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB];
883 CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB];
884
885 if (!InsertedShift && !InsertedTrunc) {
886 BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt();
887 // Sink the shift
888 if (ShiftI->getOpcode() == Instruction::AShr)
889 InsertedShift =
890 BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, "", InsertPt);
891 else
892 InsertedShift =
893 BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, "", InsertPt);
894
895 // Sink the trunc
896 BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt();
897 TruncInsertPt++;
898
899 InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift,
900 TruncI->getType(), "", TruncInsertPt);
901
902 MadeChange = true;
903
904 TruncTheUse = InsertedTrunc;
905 }
906 }
907 return MadeChange;
908}
909
910/// OptimizeExtractBits - sink the shift *right* instruction into user blocks if
911/// the uses could potentially be combined with this shift instruction and
912/// generate BitExtract instruction. It will only be applied if the architecture
913/// supports BitExtract instruction. Here is an example:
914/// BB1:
915/// %x.extract.shift = lshr i64 %arg1, 32
916/// BB2:
917/// %x.extract.trunc = trunc i64 %x.extract.shift to i16
918/// ==>
919///
920/// BB2:
921/// %x.extract.shift.1 = lshr i64 %arg1, 32
922/// %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16
923///
924/// CodeGen will recoginze the pattern in BB2 and generate BitExtract
925/// instruction.
926/// Return true if any changes are made.
927static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI,
928 const TargetLowering &TLI) {
929 BasicBlock *DefBB = ShiftI->getParent();
930
931 /// Only insert instructions in each block once.
932 DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts;
933
934 bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(ShiftI->getType()));
935
936 bool MadeChange = false;
937 for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end();
938 UI != E;) {
939 Use &TheUse = UI.getUse();
940 Instruction *User = cast<Instruction>(*UI);
941 // Preincrement use iterator so we don't invalidate it.
942 ++UI;
943
944 // Don't bother for PHI nodes.
945 if (isa<PHINode>(User))
946 continue;
947
948 if (!isExtractBitsCandidateUse(User))
949 continue;
950
951 BasicBlock *UserBB = User->getParent();
952
953 if (UserBB == DefBB) {
954 // If the shift and truncate instruction are in the same BB. The use of
955 // the truncate(TruncUse) may still introduce another truncate if not
956 // legal. In this case, we would like to sink both shift and truncate
957 // instruction to the BB of TruncUse.
958 // for example:
959 // BB1:
960 // i64 shift.result = lshr i64 opnd, imm
961 // trunc.result = trunc shift.result to i16
962 //
963 // BB2:
964 // ----> We will have an implicit truncate here if the architecture does
965 // not have i16 compare.
966 // cmp i16 trunc.result, opnd2
967 //
968 if (isa<TruncInst>(User) && shiftIsLegal
969 // If the type of the truncate is legal, no trucate will be
970 // introduced in other basic blocks.
971 && (!TLI.isTypeLegal(TLI.getValueType(User->getType()))))
972 MadeChange =
973 SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI);
974
975 continue;
976 }
977 // If we have already inserted a shift into this block, use it.
978 BinaryOperator *&InsertedShift = InsertedShifts[UserBB];
979
980 if (!InsertedShift) {
981 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
982
983 if (ShiftI->getOpcode() == Instruction::AShr)
984 InsertedShift =
985 BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, "", InsertPt);
986 else
987 InsertedShift =
988 BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, "", InsertPt);
989
990 MadeChange = true;
991 }
992
993 // Replace a use of the shift with a use of the new shift.
994 TheUse = InsertedShift;
995 }
996
997 // If we removed all uses, nuke the shift.
998 if (ShiftI->use_empty())
999 ShiftI->eraseFromParent();
1000
1001 return MadeChange;
1002}
1003
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001004// ScalarizeMaskedLoad() translates masked load intrinsic, like
1005// <16 x i32 > @llvm.masked.load( <16 x i32>* %addr, i32 align,
1006// <16 x i1> %mask, <16 x i32> %passthru)
1007// to a chain of basic blocks, whith loading element one-by-one if
1008// the appropriate mask bit is set
1009//
1010// %1 = bitcast i8* %addr to i32*
1011// %2 = extractelement <16 x i1> %mask, i32 0
1012// %3 = icmp eq i1 %2, true
1013// br i1 %3, label %cond.load, label %else
1014//
1015//cond.load: ; preds = %0
1016// %4 = getelementptr i32* %1, i32 0
1017// %5 = load i32* %4
1018// %6 = insertelement <16 x i32> undef, i32 %5, i32 0
1019// br label %else
1020//
1021//else: ; preds = %0, %cond.load
1022// %res.phi.else = phi <16 x i32> [ %6, %cond.load ], [ undef, %0 ]
1023// %7 = extractelement <16 x i1> %mask, i32 1
1024// %8 = icmp eq i1 %7, true
1025// br i1 %8, label %cond.load1, label %else2
1026//
1027//cond.load1: ; preds = %else
1028// %9 = getelementptr i32* %1, i32 1
1029// %10 = load i32* %9
1030// %11 = insertelement <16 x i32> %res.phi.else, i32 %10, i32 1
1031// br label %else2
1032//
1033//else2: ; preds = %else, %cond.load1
1034// %res.phi.else3 = phi <16 x i32> [ %11, %cond.load1 ], [ %res.phi.else, %else ]
1035// %12 = extractelement <16 x i1> %mask, i32 2
1036// %13 = icmp eq i1 %12, true
1037// br i1 %13, label %cond.load4, label %else5
1038//
1039static void ScalarizeMaskedLoad(CallInst *CI) {
1040 Value *Ptr = CI->getArgOperand(0);
1041 Value *Src0 = CI->getArgOperand(3);
1042 Value *Mask = CI->getArgOperand(2);
1043 VectorType *VecType = dyn_cast<VectorType>(CI->getType());
1044 Type *EltTy = VecType->getElementType();
1045
1046 assert(VecType && "Unexpected return type of masked load intrinsic");
1047
1048 IRBuilder<> Builder(CI->getContext());
1049 Instruction *InsertPt = CI;
1050 BasicBlock *IfBlock = CI->getParent();
1051 BasicBlock *CondBlock = nullptr;
1052 BasicBlock *PrevIfBlock = CI->getParent();
1053 Builder.SetInsertPoint(InsertPt);
1054
1055 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1056
1057 // Bitcast %addr fron i8* to EltTy*
1058 Type *NewPtrType =
1059 EltTy->getPointerTo(cast<PointerType>(Ptr->getType())->getAddressSpace());
1060 Value *FirstEltPtr = Builder.CreateBitCast(Ptr, NewPtrType);
1061 Value *UndefVal = UndefValue::get(VecType);
1062
1063 // The result vector
1064 Value *VResult = UndefVal;
1065
1066 PHINode *Phi = nullptr;
1067 Value *PrevPhi = UndefVal;
1068
1069 unsigned VectorWidth = VecType->getNumElements();
1070 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1071
1072 // Fill the "else" block, created in the previous iteration
1073 //
1074 // %res.phi.else3 = phi <16 x i32> [ %11, %cond.load1 ], [ %res.phi.else, %else ]
1075 // %mask_1 = extractelement <16 x i1> %mask, i32 Idx
1076 // %to_load = icmp eq i1 %mask_1, true
1077 // br i1 %to_load, label %cond.load, label %else
1078 //
1079 if (Idx > 0) {
1080 Phi = Builder.CreatePHI(VecType, 2, "res.phi.else");
1081 Phi->addIncoming(VResult, CondBlock);
1082 Phi->addIncoming(PrevPhi, PrevIfBlock);
1083 PrevPhi = Phi;
1084 VResult = Phi;
1085 }
1086
1087 Value *Predicate = Builder.CreateExtractElement(Mask, Builder.getInt32(Idx));
1088 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
1089 ConstantInt::get(Predicate->getType(), 1));
1090
1091 // Create "cond" block
1092 //
1093 // %EltAddr = getelementptr i32* %1, i32 0
1094 // %Elt = load i32* %EltAddr
1095 // VResult = insertelement <16 x i32> VResult, i32 %Elt, i32 Idx
1096 //
1097 CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.load");
1098 Builder.SetInsertPoint(InsertPt);
1099
1100 Value* Gep = Builder.CreateInBoundsGEP(FirstEltPtr, Builder.getInt32(Idx));
1101 LoadInst* Load = Builder.CreateLoad(Gep, false);
1102 VResult = Builder.CreateInsertElement(VResult, Load, Builder.getInt32(Idx));
1103
1104 // Create "else" block, fill it in the next iteration
1105 BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
1106 Builder.SetInsertPoint(InsertPt);
1107 Instruction *OldBr = IfBlock->getTerminator();
1108 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1109 OldBr->eraseFromParent();
1110 PrevIfBlock = IfBlock;
1111 IfBlock = NewIfBlock;
1112 }
1113
1114 Phi = Builder.CreatePHI(VecType, 2, "res.phi.select");
1115 Phi->addIncoming(VResult, CondBlock);
1116 Phi->addIncoming(PrevPhi, PrevIfBlock);
1117 Value *NewI = Builder.CreateSelect(Mask, Phi, Src0);
1118 CI->replaceAllUsesWith(NewI);
1119 CI->eraseFromParent();
1120}
1121
1122// ScalarizeMaskedStore() translates masked store intrinsic, like
1123// void @llvm.masked.store(<16 x i32> %src, <16 x i32>* %addr, i32 align,
1124// <16 x i1> %mask)
1125// to a chain of basic blocks, that stores element one-by-one if
1126// the appropriate mask bit is set
1127//
1128// %1 = bitcast i8* %addr to i32*
1129// %2 = extractelement <16 x i1> %mask, i32 0
1130// %3 = icmp eq i1 %2, true
1131// br i1 %3, label %cond.store, label %else
1132//
1133// cond.store: ; preds = %0
1134// %4 = extractelement <16 x i32> %val, i32 0
1135// %5 = getelementptr i32* %1, i32 0
1136// store i32 %4, i32* %5
1137// br label %else
1138//
1139// else: ; preds = %0, %cond.store
1140// %6 = extractelement <16 x i1> %mask, i32 1
1141// %7 = icmp eq i1 %6, true
1142// br i1 %7, label %cond.store1, label %else2
1143//
1144// cond.store1: ; preds = %else
1145// %8 = extractelement <16 x i32> %val, i32 1
1146// %9 = getelementptr i32* %1, i32 1
1147// store i32 %8, i32* %9
1148// br label %else2
1149// . . .
1150static void ScalarizeMaskedStore(CallInst *CI) {
1151 Value *Ptr = CI->getArgOperand(1);
1152 Value *Src = CI->getArgOperand(0);
1153 Value *Mask = CI->getArgOperand(3);
1154
1155 VectorType *VecType = dyn_cast<VectorType>(Src->getType());
1156 Type *EltTy = VecType->getElementType();
1157
1158 assert(VecType && "Unexpected data type in masked store intrinsic");
1159
1160 IRBuilder<> Builder(CI->getContext());
1161 Instruction *InsertPt = CI;
1162 BasicBlock *IfBlock = CI->getParent();
1163 Builder.SetInsertPoint(InsertPt);
1164 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1165
1166 // Bitcast %addr fron i8* to EltTy*
1167 Type *NewPtrType =
1168 EltTy->getPointerTo(cast<PointerType>(Ptr->getType())->getAddressSpace());
1169 Value *FirstEltPtr = Builder.CreateBitCast(Ptr, NewPtrType);
1170
1171 unsigned VectorWidth = VecType->getNumElements();
1172 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1173
1174 // Fill the "else" block, created in the previous iteration
1175 //
1176 // %mask_1 = extractelement <16 x i1> %mask, i32 Idx
1177 // %to_store = icmp eq i1 %mask_1, true
1178 // br i1 %to_load, label %cond.store, label %else
1179 //
1180 Value *Predicate = Builder.CreateExtractElement(Mask, Builder.getInt32(Idx));
1181 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
1182 ConstantInt::get(Predicate->getType(), 1));
1183
1184 // Create "cond" block
1185 //
1186 // %OneElt = extractelement <16 x i32> %Src, i32 Idx
1187 // %EltAddr = getelementptr i32* %1, i32 0
1188 // %store i32 %OneElt, i32* %EltAddr
1189 //
1190 BasicBlock *CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store");
1191 Builder.SetInsertPoint(InsertPt);
1192
1193 Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx));
1194 Value* Gep = Builder.CreateInBoundsGEP(FirstEltPtr, Builder.getInt32(Idx));
1195 Builder.CreateStore(OneElt, Gep);
1196
1197 // Create "else" block, fill it in the next iteration
1198 BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
1199 Builder.SetInsertPoint(InsertPt);
1200 Instruction *OldBr = IfBlock->getTerminator();
1201 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1202 OldBr->eraseFromParent();
1203 IfBlock = NewIfBlock;
1204 }
1205 CI->eraseFromParent();
1206}
1207
1208bool CodeGenPrepare::OptimizeCallInst(CallInst *CI, bool& ModifiedDT) {
Chris Lattner7a277142011-01-15 07:14:54 +00001209 BasicBlock *BB = CI->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +00001210
Chris Lattner7a277142011-01-15 07:14:54 +00001211 // Lower inline assembly if we can.
1212 // If we found an inline asm expession, and if the target knows how to
1213 // lower it to normal LLVM code, do so now.
1214 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
1215 if (TLI->ExpandInlineAsm(CI)) {
1216 // Avoid invalidating the iterator.
1217 CurInstIterator = BB->begin();
1218 // Avoid processing instructions out of order, which could cause
1219 // reuse before a value is defined.
1220 SunkAddrs.clear();
1221 return true;
1222 }
1223 // Sink address computing for memory operands into the block.
1224 if (OptimizeInlineAsmInst(CI))
1225 return true;
1226 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001227
Eric Christopher4b7948e2010-03-11 02:41:03 +00001228 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001229 if (II) {
1230 switch (II->getIntrinsicID()) {
1231 default: break;
1232 case Intrinsic::objectsize: {
1233 // Lower all uses of llvm.objectsize.*
1234 bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
1235 Type *ReturnTy = CI->getType();
1236 Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
Nadav Rotem465834c2012-07-24 10:51:42 +00001237
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001238 // Substituting this can cause recursive simplifications, which can
1239 // invalidate our iterator. Use a WeakVH to hold onto it in case this
1240 // happens.
1241 WeakVH IterHandle(CurInstIterator);
Nadav Rotem465834c2012-07-24 10:51:42 +00001242
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001243 replaceAndRecursivelySimplify(CI, RetVal,
1244 TLI ? TLI->getDataLayout() : nullptr,
1245 TLInfo, ModifiedDT ? nullptr : DT);
Chris Lattner1b93be52011-01-15 07:25:29 +00001246
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001247 // If the iterator instruction was recursively deleted, start over at the
1248 // start of the block.
1249 if (IterHandle != CurInstIterator) {
1250 CurInstIterator = BB->begin();
1251 SunkAddrs.clear();
1252 }
1253 return true;
Chris Lattner86d56c62011-01-18 20:53:04 +00001254 }
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001255 case Intrinsic::masked_load: {
1256 // Scalarize unsupported vector masked load
1257 if (!TTI->isLegalMaskedLoad(CI->getType(), 1)) {
1258 ScalarizeMaskedLoad(CI);
1259 ModifiedDT = true;
1260 return true;
1261 }
1262 return false;
1263 }
1264 case Intrinsic::masked_store: {
1265 if (!TTI->isLegalMaskedStore(CI->getArgOperand(0)->getType(), 1)) {
1266 ScalarizeMaskedStore(CI);
1267 ModifiedDT = true;
1268 return true;
1269 }
1270 return false;
1271 }
1272 }
Eric Christopher4b7948e2010-03-11 02:41:03 +00001273
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001274 if (TLI) {
1275 SmallVector<Value*, 2> PtrOps;
1276 Type *AccessTy;
1277 if (TLI->GetAddrModeArguments(II, PtrOps, AccessTy))
1278 while (!PtrOps.empty())
1279 if (OptimizeMemoryInst(II, PtrOps.pop_back_val(), AccessTy))
1280 return true;
1281 }
Pete Cooper615fd892012-03-13 20:59:56 +00001282 }
1283
Eric Christopher4b7948e2010-03-11 02:41:03 +00001284 // From here on out we're working with named functions.
Craig Topperc0196b12014-04-14 00:51:57 +00001285 if (!CI->getCalledFunction()) return false;
Devang Patel0da52502011-05-26 21:51:06 +00001286
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001287 // We'll need DataLayout from here on out.
Craig Topperc0196b12014-04-14 00:51:57 +00001288 const DataLayout *TD = TLI ? TLI->getDataLayout() : nullptr;
Eric Christopher4b7948e2010-03-11 02:41:03 +00001289 if (!TD) return false;
Nadav Rotem465834c2012-07-24 10:51:42 +00001290
Benjamin Kramer7b88a492010-03-12 09:27:41 +00001291 // Lower all default uses of _chk calls. This is very similar
1292 // to what InstCombineCalls does, but here we are only lowering calls
Ahmed Bougachae03bef72015-01-12 17:22:43 +00001293 // to fortified library functions (e.g. __memcpy_chk) that have the default
1294 // "don't know" as the objectsize. Anything else should be left alone.
1295 FortifiedLibCallSimplifier Simplifier(TD, TLInfo, true);
1296 if (Value *V = Simplifier.optimizeCall(CI)) {
1297 CI->replaceAllUsesWith(V);
1298 CI->eraseFromParent();
1299 return true;
1300 }
1301 return false;
Eric Christopher4b7948e2010-03-11 02:41:03 +00001302}
Chris Lattner1b93be52011-01-15 07:25:29 +00001303
Evan Cheng0663f232011-03-21 01:19:09 +00001304/// DupRetToEnableTailCallOpts - Look for opportunities to duplicate return
1305/// instructions to the predecessor to enable tail call optimizations. The
1306/// case it is currently looking for is:
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001307/// @code
Evan Cheng0663f232011-03-21 01:19:09 +00001308/// bb0:
1309/// %tmp0 = tail call i32 @f0()
1310/// br label %return
1311/// bb1:
1312/// %tmp1 = tail call i32 @f1()
1313/// br label %return
1314/// bb2:
1315/// %tmp2 = tail call i32 @f2()
1316/// br label %return
1317/// return:
1318/// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
1319/// ret i32 %retval
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001320/// @endcode
Evan Cheng0663f232011-03-21 01:19:09 +00001321///
1322/// =>
1323///
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001324/// @code
Evan Cheng0663f232011-03-21 01:19:09 +00001325/// bb0:
1326/// %tmp0 = tail call i32 @f0()
1327/// ret i32 %tmp0
1328/// bb1:
1329/// %tmp1 = tail call i32 @f1()
1330/// ret i32 %tmp1
1331/// bb2:
1332/// %tmp2 = tail call i32 @f2()
1333/// ret i32 %tmp2
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001334/// @endcode
Benjamin Kramer455fa352012-11-23 19:17:06 +00001335bool CodeGenPrepare::DupRetToEnableTailCallOpts(BasicBlock *BB) {
Cameron Zwarich47e71752011-03-24 04:51:51 +00001336 if (!TLI)
1337 return false;
1338
Benjamin Kramer455fa352012-11-23 19:17:06 +00001339 ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
1340 if (!RI)
1341 return false;
1342
Craig Topperc0196b12014-04-14 00:51:57 +00001343 PHINode *PN = nullptr;
1344 BitCastInst *BCI = nullptr;
Evan Cheng0663f232011-03-21 01:19:09 +00001345 Value *V = RI->getReturnValue();
Evan Cheng249716e2012-07-27 21:21:26 +00001346 if (V) {
1347 BCI = dyn_cast<BitCastInst>(V);
1348 if (BCI)
1349 V = BCI->getOperand(0);
1350
1351 PN = dyn_cast<PHINode>(V);
1352 if (!PN)
1353 return false;
1354 }
Evan Cheng0663f232011-03-21 01:19:09 +00001355
Cameron Zwarich4649f172011-03-24 04:52:10 +00001356 if (PN && PN->getParent() != BB)
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001357 return false;
Evan Cheng0663f232011-03-21 01:19:09 +00001358
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001359 // It's not safe to eliminate the sign / zero extension of the return value.
1360 // See llvm::isInTailCallPosition().
1361 const Function *F = BB->getParent();
Bill Wendling658d24d2013-01-18 21:53:16 +00001362 AttributeSet CallerAttrs = F->getAttributes();
1363 if (CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::ZExt) ||
1364 CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::SExt))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001365 return false;
Evan Cheng0663f232011-03-21 01:19:09 +00001366
Cameron Zwarich4649f172011-03-24 04:52:10 +00001367 // Make sure there are no instructions between the PHI and return, or that the
1368 // return is the first instruction in the block.
1369 if (PN) {
1370 BasicBlock::iterator BI = BB->begin();
1371 do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
Evan Cheng249716e2012-07-27 21:21:26 +00001372 if (&*BI == BCI)
1373 // Also skip over the bitcast.
1374 ++BI;
Cameron Zwarich4649f172011-03-24 04:52:10 +00001375 if (&*BI != RI)
1376 return false;
1377 } else {
Cameron Zwarich74157ab2011-03-24 16:34:59 +00001378 BasicBlock::iterator BI = BB->begin();
1379 while (isa<DbgInfoIntrinsic>(BI)) ++BI;
1380 if (&*BI != RI)
Cameron Zwarich4649f172011-03-24 04:52:10 +00001381 return false;
1382 }
Evan Cheng0663f232011-03-21 01:19:09 +00001383
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001384 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
1385 /// call.
1386 SmallVector<CallInst*, 4> TailCalls;
Cameron Zwarich4649f172011-03-24 04:52:10 +00001387 if (PN) {
1388 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
1389 CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
1390 // Make sure the phi value is indeed produced by the tail call.
1391 if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
1392 TLI->mayBeEmittedAsTailCall(CI))
1393 TailCalls.push_back(CI);
1394 }
1395 } else {
1396 SmallPtrSet<BasicBlock*, 4> VisitedBBs;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001397 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
David Blaikie70573dc2014-11-19 07:49:26 +00001398 if (!VisitedBBs.insert(*PI).second)
Cameron Zwarich4649f172011-03-24 04:52:10 +00001399 continue;
1400
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001401 BasicBlock::InstListType &InstList = (*PI)->getInstList();
Cameron Zwarich4649f172011-03-24 04:52:10 +00001402 BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
1403 BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
Cameron Zwarich74157ab2011-03-24 16:34:59 +00001404 do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
1405 if (RI == RE)
Cameron Zwarich4649f172011-03-24 04:52:10 +00001406 continue;
Cameron Zwarich74157ab2011-03-24 16:34:59 +00001407
Cameron Zwarich4649f172011-03-24 04:52:10 +00001408 CallInst *CI = dyn_cast<CallInst>(&*RI);
Cameron Zwarich2edfe772011-03-24 15:54:11 +00001409 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI))
Cameron Zwarich4649f172011-03-24 04:52:10 +00001410 TailCalls.push_back(CI);
1411 }
Evan Cheng0663f232011-03-21 01:19:09 +00001412 }
1413
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001414 bool Changed = false;
1415 for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
1416 CallInst *CI = TailCalls[i];
1417 CallSite CS(CI);
1418
1419 // Conservatively require the attributes of the call to match those of the
1420 // return. Ignore noalias because it doesn't affect the call sequence.
Bill Wendling658d24d2013-01-18 21:53:16 +00001421 AttributeSet CalleeAttrs = CS.getAttributes();
1422 if (AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001423 removeAttribute(Attribute::NoAlias) !=
Bill Wendling658d24d2013-01-18 21:53:16 +00001424 AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001425 removeAttribute(Attribute::NoAlias))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001426 continue;
1427
1428 // Make sure the call instruction is followed by an unconditional branch to
1429 // the return block.
1430 BasicBlock *CallBB = CI->getParent();
1431 BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
1432 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
1433 continue;
1434
1435 // Duplicate the return into CallBB.
1436 (void)FoldReturnIntoUncondBranch(RI, BB, CallBB);
Devang Patel8f606d72011-03-24 15:35:25 +00001437 ModifiedDT = Changed = true;
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001438 ++NumRetsDup;
1439 }
1440
1441 // If we eliminated all predecessors of the block, delete the block now.
Evan Cheng64a223a2012-09-28 23:58:57 +00001442 if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001443 BB->eraseFromParent();
1444
1445 return Changed;
Evan Cheng0663f232011-03-21 01:19:09 +00001446}
1447
Chris Lattner728f9022008-11-25 07:09:13 +00001448//===----------------------------------------------------------------------===//
Chris Lattner728f9022008-11-25 07:09:13 +00001449// Memory Optimization
1450//===----------------------------------------------------------------------===//
1451
Chandler Carruthc8925912013-01-05 02:09:22 +00001452namespace {
1453
1454/// ExtAddrMode - This is an extended version of TargetLowering::AddrMode
1455/// which holds actual Value*'s for register values.
Chandler Carruth95f83e02013-01-07 15:14:13 +00001456struct ExtAddrMode : public TargetLowering::AddrMode {
Chandler Carruthc8925912013-01-05 02:09:22 +00001457 Value *BaseReg;
1458 Value *ScaledReg;
Craig Topperc0196b12014-04-14 00:51:57 +00001459 ExtAddrMode() : BaseReg(nullptr), ScaledReg(nullptr) {}
Chandler Carruthc8925912013-01-05 02:09:22 +00001460 void print(raw_ostream &OS) const;
1461 void dump() const;
Stephen Lin837bba12013-07-15 17:55:02 +00001462
Chandler Carruthc8925912013-01-05 02:09:22 +00001463 bool operator==(const ExtAddrMode& O) const {
1464 return (BaseReg == O.BaseReg) && (ScaledReg == O.ScaledReg) &&
1465 (BaseGV == O.BaseGV) && (BaseOffs == O.BaseOffs) &&
1466 (HasBaseReg == O.HasBaseReg) && (Scale == O.Scale);
1467 }
1468};
1469
Eli Friedmanc1f1f852013-09-10 23:09:24 +00001470#ifndef NDEBUG
1471static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
1472 AM.print(OS);
1473 return OS;
1474}
1475#endif
1476
Chandler Carruthc8925912013-01-05 02:09:22 +00001477void ExtAddrMode::print(raw_ostream &OS) const {
1478 bool NeedPlus = false;
1479 OS << "[";
1480 if (BaseGV) {
1481 OS << (NeedPlus ? " + " : "")
1482 << "GV:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00001483 BaseGV->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00001484 NeedPlus = true;
1485 }
1486
Richard Trieuc0f91212014-05-30 03:15:17 +00001487 if (BaseOffs) {
1488 OS << (NeedPlus ? " + " : "")
1489 << BaseOffs;
1490 NeedPlus = true;
1491 }
Chandler Carruthc8925912013-01-05 02:09:22 +00001492
1493 if (BaseReg) {
1494 OS << (NeedPlus ? " + " : "")
1495 << "Base:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00001496 BaseReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00001497 NeedPlus = true;
1498 }
1499 if (Scale) {
1500 OS << (NeedPlus ? " + " : "")
1501 << Scale << "*";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00001502 ScaledReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00001503 }
1504
1505 OS << ']';
1506}
1507
1508#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1509void ExtAddrMode::dump() const {
1510 print(dbgs());
1511 dbgs() << '\n';
1512}
1513#endif
1514
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001515/// \brief This class provides transaction based operation on the IR.
1516/// Every change made through this class is recorded in the internal state and
1517/// can be undone (rollback) until commit is called.
1518class TypePromotionTransaction {
1519
1520 /// \brief This represents the common interface of the individual transaction.
1521 /// Each class implements the logic for doing one specific modification on
1522 /// the IR via the TypePromotionTransaction.
1523 class TypePromotionAction {
1524 protected:
1525 /// The Instruction modified.
1526 Instruction *Inst;
1527
1528 public:
1529 /// \brief Constructor of the action.
1530 /// The constructor performs the related action on the IR.
1531 TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
1532
1533 virtual ~TypePromotionAction() {}
1534
1535 /// \brief Undo the modification done by this action.
1536 /// When this method is called, the IR must be in the same state as it was
1537 /// before this action was applied.
1538 /// \pre Undoing the action works if and only if the IR is in the exact same
1539 /// state as it was directly after this action was applied.
1540 virtual void undo() = 0;
1541
1542 /// \brief Advocate every change made by this action.
1543 /// When the results on the IR of the action are to be kept, it is important
1544 /// to call this function, otherwise hidden information may be kept forever.
1545 virtual void commit() {
1546 // Nothing to be done, this action is not doing anything.
1547 }
1548 };
1549
1550 /// \brief Utility to remember the position of an instruction.
1551 class InsertionHandler {
1552 /// Position of an instruction.
1553 /// Either an instruction:
1554 /// - Is the first in a basic block: BB is used.
1555 /// - Has a previous instructon: PrevInst is used.
1556 union {
1557 Instruction *PrevInst;
1558 BasicBlock *BB;
1559 } Point;
1560 /// Remember whether or not the instruction had a previous instruction.
1561 bool HasPrevInstruction;
1562
1563 public:
1564 /// \brief Record the position of \p Inst.
1565 InsertionHandler(Instruction *Inst) {
1566 BasicBlock::iterator It = Inst;
1567 HasPrevInstruction = (It != (Inst->getParent()->begin()));
1568 if (HasPrevInstruction)
1569 Point.PrevInst = --It;
1570 else
1571 Point.BB = Inst->getParent();
1572 }
1573
1574 /// \brief Insert \p Inst at the recorded position.
1575 void insert(Instruction *Inst) {
1576 if (HasPrevInstruction) {
1577 if (Inst->getParent())
1578 Inst->removeFromParent();
1579 Inst->insertAfter(Point.PrevInst);
1580 } else {
1581 Instruction *Position = Point.BB->getFirstInsertionPt();
1582 if (Inst->getParent())
1583 Inst->moveBefore(Position);
1584 else
1585 Inst->insertBefore(Position);
1586 }
1587 }
1588 };
1589
1590 /// \brief Move an instruction before another.
1591 class InstructionMoveBefore : public TypePromotionAction {
1592 /// Original position of the instruction.
1593 InsertionHandler Position;
1594
1595 public:
1596 /// \brief Move \p Inst before \p Before.
1597 InstructionMoveBefore(Instruction *Inst, Instruction *Before)
1598 : TypePromotionAction(Inst), Position(Inst) {
1599 DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before << "\n");
1600 Inst->moveBefore(Before);
1601 }
1602
1603 /// \brief Move the instruction back to its original position.
Craig Topper4584cd52014-03-07 09:26:03 +00001604 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001605 DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n");
1606 Position.insert(Inst);
1607 }
1608 };
1609
1610 /// \brief Set the operand of an instruction with a new value.
1611 class OperandSetter : public TypePromotionAction {
1612 /// Original operand of the instruction.
1613 Value *Origin;
1614 /// Index of the modified instruction.
1615 unsigned Idx;
1616
1617 public:
1618 /// \brief Set \p Idx operand of \p Inst with \p NewVal.
1619 OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
1620 : TypePromotionAction(Inst), Idx(Idx) {
1621 DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"
1622 << "for:" << *Inst << "\n"
1623 << "with:" << *NewVal << "\n");
1624 Origin = Inst->getOperand(Idx);
1625 Inst->setOperand(Idx, NewVal);
1626 }
1627
1628 /// \brief Restore the original value of the instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00001629 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001630 DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"
1631 << "for: " << *Inst << "\n"
1632 << "with: " << *Origin << "\n");
1633 Inst->setOperand(Idx, Origin);
1634 }
1635 };
1636
1637 /// \brief Hide the operands of an instruction.
1638 /// Do as if this instruction was not using any of its operands.
1639 class OperandsHider : public TypePromotionAction {
1640 /// The list of original operands.
1641 SmallVector<Value *, 4> OriginalValues;
1642
1643 public:
1644 /// \brief Remove \p Inst from the uses of the operands of \p Inst.
1645 OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
1646 DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n");
1647 unsigned NumOpnds = Inst->getNumOperands();
1648 OriginalValues.reserve(NumOpnds);
1649 for (unsigned It = 0; It < NumOpnds; ++It) {
1650 // Save the current operand.
1651 Value *Val = Inst->getOperand(It);
1652 OriginalValues.push_back(Val);
1653 // Set a dummy one.
1654 // We could use OperandSetter here, but that would implied an overhead
1655 // that we are not willing to pay.
1656 Inst->setOperand(It, UndefValue::get(Val->getType()));
1657 }
1658 }
1659
1660 /// \brief Restore the original list of uses.
Craig Topper4584cd52014-03-07 09:26:03 +00001661 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001662 DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n");
1663 for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
1664 Inst->setOperand(It, OriginalValues[It]);
1665 }
1666 };
1667
1668 /// \brief Build a truncate instruction.
1669 class TruncBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00001670 Value *Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001671 public:
1672 /// \brief Build a truncate instruction of \p Opnd producing a \p Ty
1673 /// result.
1674 /// trunc Opnd to Ty.
1675 TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
1676 IRBuilder<> Builder(Opnd);
Quentin Colombetac55b152014-09-16 22:36:07 +00001677 Val = Builder.CreateTrunc(Opnd, Ty, "promoted");
1678 DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001679 }
1680
Quentin Colombetac55b152014-09-16 22:36:07 +00001681 /// \brief Get the built value.
1682 Value *getBuiltValue() { return Val; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001683
1684 /// \brief Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00001685 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00001686 DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n");
1687 if (Instruction *IVal = dyn_cast<Instruction>(Val))
1688 IVal->eraseFromParent();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001689 }
1690 };
1691
1692 /// \brief Build a sign extension instruction.
1693 class SExtBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00001694 Value *Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001695 public:
1696 /// \brief Build a sign extension instruction of \p Opnd producing a \p Ty
1697 /// result.
1698 /// sext Opnd to Ty.
1699 SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
Quentin Colombetac55b152014-09-16 22:36:07 +00001700 : TypePromotionAction(InsertPt) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001701 IRBuilder<> Builder(InsertPt);
Quentin Colombetac55b152014-09-16 22:36:07 +00001702 Val = Builder.CreateSExt(Opnd, Ty, "promoted");
1703 DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001704 }
1705
Quentin Colombetac55b152014-09-16 22:36:07 +00001706 /// \brief Get the built value.
1707 Value *getBuiltValue() { return Val; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001708
1709 /// \brief Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00001710 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00001711 DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n");
1712 if (Instruction *IVal = dyn_cast<Instruction>(Val))
1713 IVal->eraseFromParent();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001714 }
1715 };
1716
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001717 /// \brief Build a zero extension instruction.
1718 class ZExtBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00001719 Value *Val;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001720 public:
1721 /// \brief Build a zero extension instruction of \p Opnd producing a \p Ty
1722 /// result.
1723 /// zext Opnd to Ty.
1724 ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
Quentin Colombetac55b152014-09-16 22:36:07 +00001725 : TypePromotionAction(InsertPt) {
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001726 IRBuilder<> Builder(InsertPt);
Quentin Colombetac55b152014-09-16 22:36:07 +00001727 Val = Builder.CreateZExt(Opnd, Ty, "promoted");
1728 DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n");
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001729 }
1730
Quentin Colombetac55b152014-09-16 22:36:07 +00001731 /// \brief Get the built value.
1732 Value *getBuiltValue() { return Val; }
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001733
1734 /// \brief Remove the built instruction.
1735 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00001736 DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n");
1737 if (Instruction *IVal = dyn_cast<Instruction>(Val))
1738 IVal->eraseFromParent();
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001739 }
1740 };
1741
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001742 /// \brief Mutate an instruction to another type.
1743 class TypeMutator : public TypePromotionAction {
1744 /// Record the original type.
1745 Type *OrigTy;
1746
1747 public:
1748 /// \brief Mutate the type of \p Inst into \p NewTy.
1749 TypeMutator(Instruction *Inst, Type *NewTy)
1750 : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
1751 DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy
1752 << "\n");
1753 Inst->mutateType(NewTy);
1754 }
1755
1756 /// \brief Mutate the instruction back to its original type.
Craig Topper4584cd52014-03-07 09:26:03 +00001757 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001758 DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy
1759 << "\n");
1760 Inst->mutateType(OrigTy);
1761 }
1762 };
1763
1764 /// \brief Replace the uses of an instruction by another instruction.
1765 class UsesReplacer : public TypePromotionAction {
1766 /// Helper structure to keep track of the replaced uses.
1767 struct InstructionAndIdx {
1768 /// The instruction using the instruction.
1769 Instruction *Inst;
1770 /// The index where this instruction is used for Inst.
1771 unsigned Idx;
1772 InstructionAndIdx(Instruction *Inst, unsigned Idx)
1773 : Inst(Inst), Idx(Idx) {}
1774 };
1775
1776 /// Keep track of the original uses (pair Instruction, Index).
1777 SmallVector<InstructionAndIdx, 4> OriginalUses;
1778 typedef SmallVectorImpl<InstructionAndIdx>::iterator use_iterator;
1779
1780 public:
1781 /// \brief Replace all the use of \p Inst by \p New.
1782 UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) {
1783 DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New
1784 << "\n");
1785 // Record the original uses.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001786 for (Use &U : Inst->uses()) {
1787 Instruction *UserI = cast<Instruction>(U.getUser());
1788 OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo()));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001789 }
1790 // Now, we can replace the uses.
1791 Inst->replaceAllUsesWith(New);
1792 }
1793
1794 /// \brief Reassign the original uses of Inst to Inst.
Craig Topper4584cd52014-03-07 09:26:03 +00001795 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001796 DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n");
1797 for (use_iterator UseIt = OriginalUses.begin(),
1798 EndIt = OriginalUses.end();
1799 UseIt != EndIt; ++UseIt) {
1800 UseIt->Inst->setOperand(UseIt->Idx, Inst);
1801 }
1802 }
1803 };
1804
1805 /// \brief Remove an instruction from the IR.
1806 class InstructionRemover : public TypePromotionAction {
1807 /// Original position of the instruction.
1808 InsertionHandler Inserter;
1809 /// Helper structure to hide all the link to the instruction. In other
1810 /// words, this helps to do as if the instruction was removed.
1811 OperandsHider Hider;
1812 /// Keep track of the uses replaced, if any.
1813 UsesReplacer *Replacer;
1814
1815 public:
1816 /// \brief Remove all reference of \p Inst and optinally replace all its
1817 /// uses with New.
Craig Topperc0196b12014-04-14 00:51:57 +00001818 /// \pre If !Inst->use_empty(), then New != nullptr
1819 InstructionRemover(Instruction *Inst, Value *New = nullptr)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001820 : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
Craig Topperc0196b12014-04-14 00:51:57 +00001821 Replacer(nullptr) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001822 if (New)
1823 Replacer = new UsesReplacer(Inst, New);
1824 DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n");
1825 Inst->removeFromParent();
1826 }
1827
1828 ~InstructionRemover() { delete Replacer; }
1829
1830 /// \brief Really remove the instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00001831 void commit() override { delete Inst; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001832
1833 /// \brief Resurrect the instruction and reassign it to the proper uses if
1834 /// new value was provided when build this action.
Craig Topper4584cd52014-03-07 09:26:03 +00001835 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001836 DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n");
1837 Inserter.insert(Inst);
1838 if (Replacer)
1839 Replacer->undo();
1840 Hider.undo();
1841 }
1842 };
1843
1844public:
1845 /// Restoration point.
1846 /// The restoration point is a pointer to an action instead of an iterator
1847 /// because the iterator may be invalidated but not the pointer.
1848 typedef const TypePromotionAction *ConstRestorationPt;
1849 /// Advocate every changes made in that transaction.
1850 void commit();
1851 /// Undo all the changes made after the given point.
1852 void rollback(ConstRestorationPt Point);
1853 /// Get the current restoration point.
1854 ConstRestorationPt getRestorationPoint() const;
1855
1856 /// \name API for IR modification with state keeping to support rollback.
1857 /// @{
1858 /// Same as Instruction::setOperand.
1859 void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
1860 /// Same as Instruction::eraseFromParent.
Craig Topperc0196b12014-04-14 00:51:57 +00001861 void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001862 /// Same as Value::replaceAllUsesWith.
1863 void replaceAllUsesWith(Instruction *Inst, Value *New);
1864 /// Same as Value::mutateType.
1865 void mutateType(Instruction *Inst, Type *NewTy);
1866 /// Same as IRBuilder::createTrunc.
Quentin Colombetac55b152014-09-16 22:36:07 +00001867 Value *createTrunc(Instruction *Opnd, Type *Ty);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001868 /// Same as IRBuilder::createSExt.
Quentin Colombetac55b152014-09-16 22:36:07 +00001869 Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001870 /// Same as IRBuilder::createZExt.
Quentin Colombetac55b152014-09-16 22:36:07 +00001871 Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001872 /// Same as Instruction::moveBefore.
1873 void moveBefore(Instruction *Inst, Instruction *Before);
1874 /// @}
1875
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001876private:
1877 /// The ordered list of actions made so far.
David Blaikie7620b312014-04-15 06:17:44 +00001878 SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions;
1879 typedef SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator CommitPt;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001880};
1881
1882void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
1883 Value *NewVal) {
1884 Actions.push_back(
David Blaikie7620b312014-04-15 06:17:44 +00001885 make_unique<TypePromotionTransaction::OperandSetter>(Inst, Idx, NewVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001886}
1887
1888void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
1889 Value *NewVal) {
1890 Actions.push_back(
David Blaikie7620b312014-04-15 06:17:44 +00001891 make_unique<TypePromotionTransaction::InstructionRemover>(Inst, NewVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001892}
1893
1894void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
1895 Value *New) {
David Blaikie7620b312014-04-15 06:17:44 +00001896 Actions.push_back(make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001897}
1898
1899void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
David Blaikie7620b312014-04-15 06:17:44 +00001900 Actions.push_back(make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001901}
1902
Quentin Colombetac55b152014-09-16 22:36:07 +00001903Value *TypePromotionTransaction::createTrunc(Instruction *Opnd,
1904 Type *Ty) {
David Blaikie7620b312014-04-15 06:17:44 +00001905 std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00001906 Value *Val = Ptr->getBuiltValue();
David Blaikie7620b312014-04-15 06:17:44 +00001907 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00001908 return Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001909}
1910
Quentin Colombetac55b152014-09-16 22:36:07 +00001911Value *TypePromotionTransaction::createSExt(Instruction *Inst,
1912 Value *Opnd, Type *Ty) {
David Blaikie7620b312014-04-15 06:17:44 +00001913 std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00001914 Value *Val = Ptr->getBuiltValue();
David Blaikie7620b312014-04-15 06:17:44 +00001915 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00001916 return Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001917}
1918
Quentin Colombetac55b152014-09-16 22:36:07 +00001919Value *TypePromotionTransaction::createZExt(Instruction *Inst,
1920 Value *Opnd, Type *Ty) {
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001921 std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00001922 Value *Val = Ptr->getBuiltValue();
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001923 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00001924 return Val;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001925}
1926
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001927void TypePromotionTransaction::moveBefore(Instruction *Inst,
1928 Instruction *Before) {
1929 Actions.push_back(
David Blaikie7620b312014-04-15 06:17:44 +00001930 make_unique<TypePromotionTransaction::InstructionMoveBefore>(Inst, Before));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001931}
1932
1933TypePromotionTransaction::ConstRestorationPt
1934TypePromotionTransaction::getRestorationPoint() const {
David Blaikie7620b312014-04-15 06:17:44 +00001935 return !Actions.empty() ? Actions.back().get() : nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001936}
1937
1938void TypePromotionTransaction::commit() {
1939 for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt;
David Blaikie7620b312014-04-15 06:17:44 +00001940 ++It)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001941 (*It)->commit();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001942 Actions.clear();
1943}
1944
1945void TypePromotionTransaction::rollback(
1946 TypePromotionTransaction::ConstRestorationPt Point) {
David Blaikie7620b312014-04-15 06:17:44 +00001947 while (!Actions.empty() && Point != Actions.back().get()) {
1948 std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001949 Curr->undo();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001950 }
1951}
1952
Chandler Carruthc8925912013-01-05 02:09:22 +00001953/// \brief A helper class for matching addressing modes.
1954///
1955/// This encapsulates the logic for matching the target-legal addressing modes.
1956class AddressingModeMatcher {
1957 SmallVectorImpl<Instruction*> &AddrModeInsts;
1958 const TargetLowering &TLI;
1959
1960 /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
1961 /// the memory instruction that we're computing this address for.
1962 Type *AccessTy;
1963 Instruction *MemoryInst;
Stephen Lin837bba12013-07-15 17:55:02 +00001964
Chandler Carruthc8925912013-01-05 02:09:22 +00001965 /// AddrMode - This is the addressing mode that we're building up. This is
1966 /// part of the return value of this addressing mode matching stuff.
1967 ExtAddrMode &AddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00001968
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001969 /// The truncate instruction inserted by other CodeGenPrepare optimizations.
1970 const SetOfInstrs &InsertedTruncs;
1971 /// A map from the instructions to their type before promotion.
1972 InstrToOrigTy &PromotedInsts;
1973 /// The ongoing transaction where every action should be registered.
1974 TypePromotionTransaction &TPT;
1975
Chandler Carruthc8925912013-01-05 02:09:22 +00001976 /// IgnoreProfitability - This is set to true when we should not do
1977 /// profitability checks. When true, IsProfitableToFoldIntoAddressingMode
1978 /// always returns true.
1979 bool IgnoreProfitability;
Stephen Lin837bba12013-07-15 17:55:02 +00001980
Chandler Carruthc8925912013-01-05 02:09:22 +00001981 AddressingModeMatcher(SmallVectorImpl<Instruction*> &AMI,
1982 const TargetLowering &T, Type *AT,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001983 Instruction *MI, ExtAddrMode &AM,
1984 const SetOfInstrs &InsertedTruncs,
1985 InstrToOrigTy &PromotedInsts,
1986 TypePromotionTransaction &TPT)
1987 : AddrModeInsts(AMI), TLI(T), AccessTy(AT), MemoryInst(MI), AddrMode(AM),
1988 InsertedTruncs(InsertedTruncs), PromotedInsts(PromotedInsts), TPT(TPT) {
Chandler Carruthc8925912013-01-05 02:09:22 +00001989 IgnoreProfitability = false;
1990 }
1991public:
Stephen Lin837bba12013-07-15 17:55:02 +00001992
Chandler Carruthc8925912013-01-05 02:09:22 +00001993 /// Match - Find the maximal addressing mode that a load/store of V can fold,
1994 /// give an access type of AccessTy. This returns a list of involved
1995 /// instructions in AddrModeInsts.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001996 /// \p InsertedTruncs The truncate instruction inserted by other
1997 /// CodeGenPrepare
1998 /// optimizations.
1999 /// \p PromotedInsts maps the instructions to their type before promotion.
2000 /// \p The ongoing transaction where every action should be registered.
Chandler Carruthc8925912013-01-05 02:09:22 +00002001 static ExtAddrMode Match(Value *V, Type *AccessTy,
2002 Instruction *MemoryInst,
2003 SmallVectorImpl<Instruction*> &AddrModeInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002004 const TargetLowering &TLI,
2005 const SetOfInstrs &InsertedTruncs,
2006 InstrToOrigTy &PromotedInsts,
2007 TypePromotionTransaction &TPT) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002008 ExtAddrMode Result;
2009
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002010 bool Success = AddressingModeMatcher(AddrModeInsts, TLI, AccessTy,
2011 MemoryInst, Result, InsertedTruncs,
2012 PromotedInsts, TPT).MatchAddr(V, 0);
Chandler Carruthc8925912013-01-05 02:09:22 +00002013 (void)Success; assert(Success && "Couldn't select *anything*?");
2014 return Result;
2015 }
2016private:
2017 bool MatchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
2018 bool MatchAddr(Value *V, unsigned Depth);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002019 bool MatchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth,
Craig Topperc0196b12014-04-14 00:51:57 +00002020 bool *MovedAway = nullptr);
Chandler Carruthc8925912013-01-05 02:09:22 +00002021 bool IsProfitableToFoldIntoAddressingMode(Instruction *I,
2022 ExtAddrMode &AMBefore,
2023 ExtAddrMode &AMAfter);
2024 bool ValueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
Quentin Colombet867c5502014-02-14 22:23:22 +00002025 bool IsPromotionProfitable(unsigned MatchedSize, unsigned SizeWithPromotion,
2026 Value *PromotedOperand) const;
Chandler Carruthc8925912013-01-05 02:09:22 +00002027};
2028
2029/// MatchScaledValue - Try adding ScaleReg*Scale to the current addressing mode.
2030/// Return true and update AddrMode if this addr mode is legal for the target,
2031/// false if not.
2032bool AddressingModeMatcher::MatchScaledValue(Value *ScaleReg, int64_t Scale,
2033 unsigned Depth) {
2034 // If Scale is 1, then this is the same as adding ScaleReg to the addressing
2035 // mode. Just process that directly.
2036 if (Scale == 1)
2037 return MatchAddr(ScaleReg, Depth);
Stephen Lin837bba12013-07-15 17:55:02 +00002038
Chandler Carruthc8925912013-01-05 02:09:22 +00002039 // If the scale is 0, it takes nothing to add this.
2040 if (Scale == 0)
2041 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002042
Chandler Carruthc8925912013-01-05 02:09:22 +00002043 // If we already have a scale of this value, we can add to it, otherwise, we
2044 // need an available scale field.
2045 if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
2046 return false;
2047
2048 ExtAddrMode TestAddrMode = AddrMode;
2049
2050 // Add scale to turn X*4+X*3 -> X*7. This could also do things like
2051 // [A+B + A*7] -> [B+A*8].
2052 TestAddrMode.Scale += Scale;
2053 TestAddrMode.ScaledReg = ScaleReg;
2054
2055 // If the new address isn't legal, bail out.
2056 if (!TLI.isLegalAddressingMode(TestAddrMode, AccessTy))
2057 return false;
2058
2059 // It was legal, so commit it.
2060 AddrMode = TestAddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00002061
Chandler Carruthc8925912013-01-05 02:09:22 +00002062 // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
2063 // to see if ScaleReg is actually X+C. If so, we can turn this into adding
2064 // X*Scale + C*Scale to addr mode.
Craig Topperc0196b12014-04-14 00:51:57 +00002065 ConstantInt *CI = nullptr; Value *AddLHS = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00002066 if (isa<Instruction>(ScaleReg) && // not a constant expr.
2067 match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
2068 TestAddrMode.ScaledReg = AddLHS;
2069 TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00002070
Chandler Carruthc8925912013-01-05 02:09:22 +00002071 // If this addressing mode is legal, commit it and remember that we folded
2072 // this instruction.
2073 if (TLI.isLegalAddressingMode(TestAddrMode, AccessTy)) {
2074 AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
2075 AddrMode = TestAddrMode;
2076 return true;
2077 }
2078 }
2079
2080 // Otherwise, not (x+c)*scale, just return what we have.
2081 return true;
2082}
2083
2084/// MightBeFoldableInst - This is a little filter, which returns true if an
2085/// addressing computation involving I might be folded into a load/store
2086/// accessing it. This doesn't need to be perfect, but needs to accept at least
2087/// the set of instructions that MatchOperationAddr can.
2088static bool MightBeFoldableInst(Instruction *I) {
2089 switch (I->getOpcode()) {
2090 case Instruction::BitCast:
Eli Benderskyf13a0562014-05-22 00:02:52 +00002091 case Instruction::AddrSpaceCast:
Chandler Carruthc8925912013-01-05 02:09:22 +00002092 // Don't touch identity bitcasts.
2093 if (I->getType() == I->getOperand(0)->getType())
2094 return false;
2095 return I->getType()->isPointerTy() || I->getType()->isIntegerTy();
2096 case Instruction::PtrToInt:
2097 // PtrToInt is always a noop, as we know that the int type is pointer sized.
2098 return true;
2099 case Instruction::IntToPtr:
2100 // We know the input is intptr_t, so this is foldable.
2101 return true;
2102 case Instruction::Add:
2103 return true;
2104 case Instruction::Mul:
2105 case Instruction::Shl:
2106 // Can only handle X*C and X << C.
2107 return isa<ConstantInt>(I->getOperand(1));
2108 case Instruction::GetElementPtr:
2109 return true;
2110 default:
2111 return false;
2112 }
2113}
2114
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002115/// \brief Check whether or not \p Val is a legal instruction for \p TLI.
2116/// \note \p Val is assumed to be the product of some type promotion.
2117/// Therefore if \p Val has an undefined state in \p TLI, this is assumed
2118/// to be legal, as the non-promoted value would have had the same state.
2119static bool isPromotedInstructionLegal(const TargetLowering &TLI, Value *Val) {
2120 Instruction *PromotedInst = dyn_cast<Instruction>(Val);
2121 if (!PromotedInst)
2122 return false;
2123 int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode());
2124 // If the ISDOpcode is undefined, it was undefined before the promotion.
2125 if (!ISDOpcode)
2126 return true;
2127 // Otherwise, check if the promoted instruction is legal or not.
2128 return TLI.isOperationLegalOrCustom(
2129 ISDOpcode, TLI.getValueType(PromotedInst->getType()));
2130}
2131
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002132/// \brief Hepler class to perform type promotion.
2133class TypePromotionHelper {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002134 /// \brief Utility function to check whether or not a sign or zero extension
2135 /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by
2136 /// either using the operands of \p Inst or promoting \p Inst.
2137 /// The type of the extension is defined by \p IsSExt.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002138 /// In other words, check if:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002139 /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002140 /// #1 Promotion applies:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002141 /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...).
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002142 /// #2 Operand reuses:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002143 /// ext opnd1 to ConsideredExtType.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002144 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002145 static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType,
2146 const InstrToOrigTy &PromotedInsts, bool IsSExt);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002147
2148 /// \brief Utility function to determine if \p OpIdx should be promoted when
2149 /// promoting \p Inst.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002150 static bool shouldExtOperand(const Instruction *Inst, int OpIdx) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002151 if (isa<SelectInst>(Inst) && OpIdx == 0)
2152 return false;
2153 return true;
2154 }
2155
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002156 /// \brief Utility function to promote the operand of \p Ext when this
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002157 /// operand is a promotable trunc or sext or zext.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002158 /// \p PromotedInsts maps the instructions to their type before promotion.
2159 /// \p CreatedInsts[out] contains how many non-free instructions have been
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002160 /// created to promote the operand of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002161 /// Newly added extensions are inserted in \p Exts.
2162 /// Newly added truncates are inserted in \p Truncs.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002163 /// Should never be called directly.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002164 /// \return The promoted value which is used instead of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002165 static Value *promoteOperandForTruncAndAnyExt(
2166 Instruction *Ext, TypePromotionTransaction &TPT,
2167 InstrToOrigTy &PromotedInsts, unsigned &CreatedInsts,
2168 SmallVectorImpl<Instruction *> *Exts,
2169 SmallVectorImpl<Instruction *> *Truncs);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002170
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002171 /// \brief Utility function to promote the operand of \p Ext when this
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002172 /// operand is promotable and is not a supported trunc or sext.
2173 /// \p PromotedInsts maps the instructions to their type before promotion.
2174 /// \p CreatedInsts[out] contains how many non-free instructions have been
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002175 /// created to promote the operand of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002176 /// Newly added extensions are inserted in \p Exts.
2177 /// Newly added truncates are inserted in \p Truncs.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002178 /// Should never be called directly.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002179 /// \return The promoted value which is used instead of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002180 static Value *
2181 promoteOperandForOther(Instruction *Ext, TypePromotionTransaction &TPT,
2182 InstrToOrigTy &PromotedInsts, unsigned &CreatedInsts,
2183 SmallVectorImpl<Instruction *> *Exts,
2184 SmallVectorImpl<Instruction *> *Truncs, bool IsSExt);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002185
2186 /// \see promoteOperandForOther.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002187 static Value *
2188 signExtendOperandForOther(Instruction *Ext, TypePromotionTransaction &TPT,
2189 InstrToOrigTy &PromotedInsts,
2190 unsigned &CreatedInsts,
2191 SmallVectorImpl<Instruction *> *Exts,
2192 SmallVectorImpl<Instruction *> *Truncs) {
2193 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInsts, Exts,
2194 Truncs, true);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002195 }
2196
2197 /// \see promoteOperandForOther.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002198 static Value *
2199 zeroExtendOperandForOther(Instruction *Ext, TypePromotionTransaction &TPT,
2200 InstrToOrigTy &PromotedInsts,
2201 unsigned &CreatedInsts,
2202 SmallVectorImpl<Instruction *> *Exts,
2203 SmallVectorImpl<Instruction *> *Truncs) {
2204 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInsts, Exts,
2205 Truncs, false);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002206 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002207
2208public:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002209 /// Type for the utility function that promotes the operand of Ext.
2210 typedef Value *(*Action)(Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002211 InstrToOrigTy &PromotedInsts, unsigned &CreatedInsts,
2212 SmallVectorImpl<Instruction *> *Exts,
2213 SmallVectorImpl<Instruction *> *Truncs);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002214 /// \brief Given a sign/zero extend instruction \p Ext, return the approriate
2215 /// action to promote the operand of \p Ext instead of using Ext.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002216 /// \return NULL if no promotable action is possible with the current
2217 /// sign extension.
2218 /// \p InsertedTruncs keeps track of all the truncate instructions inserted by
2219 /// the others CodeGenPrepare optimizations. This information is important
2220 /// because we do not want to promote these instructions as CodeGenPrepare
2221 /// will reinsert them later. Thus creating an infinite loop: create/remove.
2222 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002223 static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedTruncs,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002224 const TargetLowering &TLI,
2225 const InstrToOrigTy &PromotedInsts);
2226};
2227
2228bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002229 Type *ConsideredExtType,
2230 const InstrToOrigTy &PromotedInsts,
2231 bool IsSExt) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002232 // The promotion helper does not know how to deal with vector types yet.
2233 // To be able to fix that, we would need to fix the places where we
2234 // statically extend, e.g., constants and such.
2235 if (Inst->getType()->isVectorTy())
2236 return false;
2237
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002238 // We can always get through zext.
2239 if (isa<ZExtInst>(Inst))
2240 return true;
2241
2242 // sext(sext) is ok too.
2243 if (IsSExt && isa<SExtInst>(Inst))
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002244 return true;
2245
2246 // We can get through binary operator, if it is legal. In other words, the
2247 // binary operator must have a nuw or nsw flag.
2248 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
2249 if (BinOp && isa<OverflowingBinaryOperator>(BinOp) &&
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002250 ((!IsSExt && BinOp->hasNoUnsignedWrap()) ||
2251 (IsSExt && BinOp->hasNoSignedWrap())))
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002252 return true;
2253
2254 // Check if we can do the following simplification.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002255 // ext(trunc(opnd)) --> ext(opnd)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002256 if (!isa<TruncInst>(Inst))
2257 return false;
2258
2259 Value *OpndVal = Inst->getOperand(0);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002260 // Check if we can use this operand in the extension.
2261 // If the type is larger than the result type of the extension,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002262 // we cannot.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002263 if (!OpndVal->getType()->isIntegerTy() ||
2264 OpndVal->getType()->getIntegerBitWidth() >
2265 ConsideredExtType->getIntegerBitWidth())
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002266 return false;
2267
2268 // If the operand of the truncate is not an instruction, we will not have
2269 // any information on the dropped bits.
2270 // (Actually we could for constant but it is not worth the extra logic).
2271 Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
2272 if (!Opnd)
2273 return false;
2274
2275 // Check if the source of the type is narrow enough.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002276 // I.e., check that trunc just drops extended bits of the same kind of
2277 // the extension.
2278 // #1 get the type of the operand and check the kind of the extended bits.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002279 const Type *OpndType;
2280 InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002281 if (It != PromotedInsts.end() && It->second.IsSExt == IsSExt)
2282 OpndType = It->second.Ty;
2283 else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd)))
2284 OpndType = Opnd->getOperand(0)->getType();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002285 else
2286 return false;
2287
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002288 // #2 check that the truncate just drop extended bits.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002289 if (Inst->getType()->getIntegerBitWidth() >= OpndType->getIntegerBitWidth())
2290 return true;
2291
2292 return false;
2293}
2294
2295TypePromotionHelper::Action TypePromotionHelper::getAction(
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002296 Instruction *Ext, const SetOfInstrs &InsertedTruncs,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002297 const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002298 assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
2299 "Unexpected instruction type");
2300 Instruction *ExtOpnd = dyn_cast<Instruction>(Ext->getOperand(0));
2301 Type *ExtTy = Ext->getType();
2302 bool IsSExt = isa<SExtInst>(Ext);
2303 // If the operand of the extension is not an instruction, we cannot
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002304 // get through.
2305 // If it, check we can get through.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002306 if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt))
Craig Topperc0196b12014-04-14 00:51:57 +00002307 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002308
2309 // Do not promote if the operand has been added by codegenprepare.
2310 // Otherwise, it means we are undoing an optimization that is likely to be
2311 // redone, thus causing potential infinite loop.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002312 if (isa<TruncInst>(ExtOpnd) && InsertedTruncs.count(ExtOpnd))
Craig Topperc0196b12014-04-14 00:51:57 +00002313 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002314
2315 // SExt or Trunc instructions.
2316 // Return the related handler.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002317 if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) ||
2318 isa<ZExtInst>(ExtOpnd))
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002319 return promoteOperandForTruncAndAnyExt;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002320
2321 // Regular instruction.
2322 // Abort early if we will have to insert non-free instructions.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002323 if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(ExtTy, ExtOpnd->getType()))
Craig Topperc0196b12014-04-14 00:51:57 +00002324 return nullptr;
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002325 return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002326}
2327
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002328Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt(
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002329 llvm::Instruction *SExt, TypePromotionTransaction &TPT,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002330 InstrToOrigTy &PromotedInsts, unsigned &CreatedInsts,
2331 SmallVectorImpl<Instruction *> *Exts,
2332 SmallVectorImpl<Instruction *> *Truncs) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002333 // By construction, the operand of SExt is an instruction. Otherwise we cannot
2334 // get through it and this method should not be called.
2335 Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
Quentin Colombetac55b152014-09-16 22:36:07 +00002336 Value *ExtVal = SExt;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002337 if (isa<ZExtInst>(SExtOpnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002338 // Replace s|zext(zext(opnd))
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002339 // => zext(opnd).
Quentin Colombetac55b152014-09-16 22:36:07 +00002340 Value *ZExt =
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002341 TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType());
2342 TPT.replaceAllUsesWith(SExt, ZExt);
2343 TPT.eraseInstruction(SExt);
Quentin Colombetac55b152014-09-16 22:36:07 +00002344 ExtVal = ZExt;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002345 } else {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002346 // Replace z|sext(trunc(opnd)) or sext(sext(opnd))
2347 // => z|sext(opnd).
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002348 TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
2349 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002350 CreatedInsts = 0;
2351
2352 // Remove dead code.
2353 if (SExtOpnd->use_empty())
2354 TPT.eraseInstruction(SExtOpnd);
2355
Quentin Colombet9dcb7242014-09-15 18:26:58 +00002356 // Check if the extension is still needed.
Quentin Colombetac55b152014-09-16 22:36:07 +00002357 Instruction *ExtInst = dyn_cast<Instruction>(ExtVal);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002358 if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType()) {
2359 if (ExtInst && Exts)
2360 Exts->push_back(ExtInst);
Quentin Colombetac55b152014-09-16 22:36:07 +00002361 return ExtVal;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002362 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002363
Quentin Colombet9dcb7242014-09-15 18:26:58 +00002364 // At this point we have: ext ty opnd to ty.
2365 // Reassign the uses of ExtInst to the opnd and remove ExtInst.
2366 Value *NextVal = ExtInst->getOperand(0);
2367 TPT.eraseInstruction(ExtInst, NextVal);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002368 return NextVal;
2369}
2370
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002371Value *TypePromotionHelper::promoteOperandForOther(
2372 Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002373 InstrToOrigTy &PromotedInsts, unsigned &CreatedInsts,
2374 SmallVectorImpl<Instruction *> *Exts,
2375 SmallVectorImpl<Instruction *> *Truncs, bool IsSExt) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002376 // By construction, the operand of Ext is an instruction. Otherwise we cannot
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002377 // get through it and this method should not be called.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002378 Instruction *ExtOpnd = cast<Instruction>(Ext->getOperand(0));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002379 CreatedInsts = 0;
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002380 if (!ExtOpnd->hasOneUse()) {
2381 // ExtOpnd will be promoted.
2382 // All its uses, but Ext, will need to use a truncated value of the
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002383 // promoted version.
2384 // Create the truncate now.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002385 Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->getType());
Quentin Colombetac55b152014-09-16 22:36:07 +00002386 if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) {
2387 ITrunc->removeFromParent();
2388 // Insert it just after the definition.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002389 ITrunc->insertAfter(ExtOpnd);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002390 if (Truncs)
2391 Truncs->push_back(ITrunc);
Quentin Colombetac55b152014-09-16 22:36:07 +00002392 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002393
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002394 TPT.replaceAllUsesWith(ExtOpnd, Trunc);
2395 // Restore the operand of Ext (which has been replace by the previous call
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002396 // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002397 TPT.setOperand(Ext, 0, ExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002398 }
2399
2400 // Get through the Instruction:
2401 // 1. Update its type.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002402 // 2. Replace the uses of Ext by Inst.
2403 // 3. Extend each operand that needs to be extended.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002404
2405 // Remember the original type of the instruction before promotion.
2406 // This is useful to know that the high bits are sign extended bits.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002407 PromotedInsts.insert(std::pair<Instruction *, TypeIsSExt>(
2408 ExtOpnd, TypeIsSExt(ExtOpnd->getType(), IsSExt)));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002409 // Step #1.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002410 TPT.mutateType(ExtOpnd, Ext->getType());
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002411 // Step #2.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002412 TPT.replaceAllUsesWith(Ext, ExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002413 // Step #3.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002414 Instruction *ExtForOpnd = Ext;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002415
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002416 DEBUG(dbgs() << "Propagate Ext to operands\n");
2417 for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002418 ++OpIdx) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002419 DEBUG(dbgs() << "Operand:\n" << *(ExtOpnd->getOperand(OpIdx)) << '\n');
2420 if (ExtOpnd->getOperand(OpIdx)->getType() == Ext->getType() ||
2421 !shouldExtOperand(ExtOpnd, OpIdx)) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002422 DEBUG(dbgs() << "No need to propagate\n");
2423 continue;
2424 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002425 // Check if we can statically extend the operand.
2426 Value *Opnd = ExtOpnd->getOperand(OpIdx);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002427 if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002428 DEBUG(dbgs() << "Statically extend\n");
2429 unsigned BitWidth = Ext->getType()->getIntegerBitWidth();
2430 APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth)
2431 : Cst->getValue().zext(BitWidth);
2432 TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->getType(), CstVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002433 continue;
2434 }
2435 // UndefValue are typed, so we have to statically sign extend them.
2436 if (isa<UndefValue>(Opnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002437 DEBUG(dbgs() << "Statically extend\n");
2438 TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->getType()));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002439 continue;
2440 }
2441
2442 // Otherwise we have to explicity sign extend the operand.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002443 // Check if Ext was reused to extend an operand.
2444 if (!ExtForOpnd) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002445 // If yes, create a new one.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002446 DEBUG(dbgs() << "More operands to ext\n");
Quentin Colombet84f89cc2014-12-22 18:11:52 +00002447 Value *ValForExtOpnd = IsSExt ? TPT.createSExt(Ext, Opnd, Ext->getType())
2448 : TPT.createZExt(Ext, Opnd, Ext->getType());
2449 if (!isa<Instruction>(ValForExtOpnd)) {
2450 TPT.setOperand(ExtOpnd, OpIdx, ValForExtOpnd);
2451 continue;
2452 }
2453 ExtForOpnd = cast<Instruction>(ValForExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002454 ++CreatedInsts;
2455 }
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002456 if (Exts)
2457 Exts->push_back(ExtForOpnd);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002458 TPT.setOperand(ExtForOpnd, 0, Opnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002459
2460 // Move the sign extension before the insertion point.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002461 TPT.moveBefore(ExtForOpnd, ExtOpnd);
2462 TPT.setOperand(ExtOpnd, OpIdx, ExtForOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002463 // If more sext are required, new instructions will have to be created.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002464 ExtForOpnd = nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002465 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002466 if (ExtForOpnd == Ext) {
2467 DEBUG(dbgs() << "Extension is useless now\n");
2468 TPT.eraseInstruction(Ext);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002469 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002470 return ExtOpnd;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002471}
2472
Quentin Colombet867c5502014-02-14 22:23:22 +00002473/// IsPromotionProfitable - Check whether or not promoting an instruction
2474/// to a wider type was profitable.
2475/// \p MatchedSize gives the number of instructions that have been matched
2476/// in the addressing mode after the promotion was applied.
2477/// \p SizeWithPromotion gives the number of created instructions for
2478/// the promotion plus the number of instructions that have been
2479/// matched in the addressing mode before the promotion.
2480/// \p PromotedOperand is the value that has been promoted.
2481/// \return True if the promotion is profitable, false otherwise.
2482bool
2483AddressingModeMatcher::IsPromotionProfitable(unsigned MatchedSize,
2484 unsigned SizeWithPromotion,
2485 Value *PromotedOperand) const {
2486 // We folded less instructions than what we created to promote the operand.
2487 // This is not profitable.
2488 if (MatchedSize < SizeWithPromotion)
2489 return false;
2490 if (MatchedSize > SizeWithPromotion)
2491 return true;
2492 // The promotion is neutral but it may help folding the sign extension in
2493 // loads for instance.
2494 // Check that we did not create an illegal instruction.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002495 return isPromotedInstructionLegal(TLI, PromotedOperand);
Quentin Colombet867c5502014-02-14 22:23:22 +00002496}
2497
Chandler Carruthc8925912013-01-05 02:09:22 +00002498/// MatchOperationAddr - Given an instruction or constant expr, see if we can
2499/// fold the operation into the addressing mode. If so, update the addressing
2500/// mode and return true, otherwise return false without modifying AddrMode.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002501/// If \p MovedAway is not NULL, it contains the information of whether or
2502/// not AddrInst has to be folded into the addressing mode on success.
2503/// If \p MovedAway == true, \p AddrInst will not be part of the addressing
2504/// because it has been moved away.
2505/// Thus AddrInst must not be added in the matched instructions.
2506/// This state can happen when AddrInst is a sext, since it may be moved away.
2507/// Therefore, AddrInst may not be valid when MovedAway is true and it must
2508/// not be referenced anymore.
Chandler Carruthc8925912013-01-05 02:09:22 +00002509bool AddressingModeMatcher::MatchOperationAddr(User *AddrInst, unsigned Opcode,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002510 unsigned Depth,
2511 bool *MovedAway) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002512 // Avoid exponential behavior on extremely deep expression trees.
2513 if (Depth >= 5) return false;
Stephen Lin837bba12013-07-15 17:55:02 +00002514
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002515 // By default, all matched instructions stay in place.
2516 if (MovedAway)
2517 *MovedAway = false;
2518
Chandler Carruthc8925912013-01-05 02:09:22 +00002519 switch (Opcode) {
2520 case Instruction::PtrToInt:
2521 // PtrToInt is always a noop, as we know that the int type is pointer sized.
2522 return MatchAddr(AddrInst->getOperand(0), Depth);
2523 case Instruction::IntToPtr:
2524 // This inttoptr is a no-op if the integer type is pointer sized.
2525 if (TLI.getValueType(AddrInst->getOperand(0)->getType()) ==
Matt Arsenault37d42ec2013-09-06 00:18:43 +00002526 TLI.getPointerTy(AddrInst->getType()->getPointerAddressSpace()))
Chandler Carruthc8925912013-01-05 02:09:22 +00002527 return MatchAddr(AddrInst->getOperand(0), Depth);
2528 return false;
2529 case Instruction::BitCast:
Eli Benderskyf13a0562014-05-22 00:02:52 +00002530 case Instruction::AddrSpaceCast:
Chandler Carruthc8925912013-01-05 02:09:22 +00002531 // BitCast is always a noop, and we can handle it as long as it is
2532 // int->int or pointer->pointer (we don't want int<->fp or something).
2533 if ((AddrInst->getOperand(0)->getType()->isPointerTy() ||
2534 AddrInst->getOperand(0)->getType()->isIntegerTy()) &&
2535 // Don't touch identity bitcasts. These were probably put here by LSR,
2536 // and we don't want to mess around with them. Assume it knows what it
2537 // is doing.
2538 AddrInst->getOperand(0)->getType() != AddrInst->getType())
2539 return MatchAddr(AddrInst->getOperand(0), Depth);
2540 return false;
2541 case Instruction::Add: {
2542 // Check to see if we can merge in the RHS then the LHS. If so, we win.
2543 ExtAddrMode BackupAddrMode = AddrMode;
2544 unsigned OldSize = AddrModeInsts.size();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002545 // Start a transaction at this point.
2546 // The LHS may match but not the RHS.
2547 // Therefore, we need a higher level restoration point to undo partially
2548 // matched operation.
2549 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2550 TPT.getRestorationPoint();
2551
Chandler Carruthc8925912013-01-05 02:09:22 +00002552 if (MatchAddr(AddrInst->getOperand(1), Depth+1) &&
2553 MatchAddr(AddrInst->getOperand(0), Depth+1))
2554 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002555
Chandler Carruthc8925912013-01-05 02:09:22 +00002556 // Restore the old addr mode info.
2557 AddrMode = BackupAddrMode;
2558 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002559 TPT.rollback(LastKnownGood);
Stephen Lin837bba12013-07-15 17:55:02 +00002560
Chandler Carruthc8925912013-01-05 02:09:22 +00002561 // Otherwise this was over-aggressive. Try merging in the LHS then the RHS.
2562 if (MatchAddr(AddrInst->getOperand(0), Depth+1) &&
2563 MatchAddr(AddrInst->getOperand(1), Depth+1))
2564 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002565
Chandler Carruthc8925912013-01-05 02:09:22 +00002566 // Otherwise we definitely can't merge the ADD in.
2567 AddrMode = BackupAddrMode;
2568 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002569 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00002570 break;
2571 }
2572 //case Instruction::Or:
2573 // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
2574 //break;
2575 case Instruction::Mul:
2576 case Instruction::Shl: {
2577 // Can only handle X*C and X << C.
2578 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
Sanjay Pateld3bbfa12014-07-16 22:40:28 +00002579 if (!RHS)
2580 return false;
Chandler Carruthc8925912013-01-05 02:09:22 +00002581 int64_t Scale = RHS->getSExtValue();
2582 if (Opcode == Instruction::Shl)
2583 Scale = 1LL << Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00002584
Chandler Carruthc8925912013-01-05 02:09:22 +00002585 return MatchScaledValue(AddrInst->getOperand(0), Scale, Depth);
2586 }
2587 case Instruction::GetElementPtr: {
2588 // Scan the GEP. We check it if it contains constant offsets and at most
2589 // one variable offset.
2590 int VariableOperand = -1;
2591 unsigned VariableScale = 0;
Stephen Lin837bba12013-07-15 17:55:02 +00002592
Chandler Carruthc8925912013-01-05 02:09:22 +00002593 int64_t ConstantOffset = 0;
2594 const DataLayout *TD = TLI.getDataLayout();
2595 gep_type_iterator GTI = gep_type_begin(AddrInst);
2596 for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
2597 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
2598 const StructLayout *SL = TD->getStructLayout(STy);
2599 unsigned Idx =
2600 cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
2601 ConstantOffset += SL->getElementOffset(Idx);
2602 } else {
2603 uint64_t TypeSize = TD->getTypeAllocSize(GTI.getIndexedType());
2604 if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
2605 ConstantOffset += CI->getSExtValue()*TypeSize;
2606 } else if (TypeSize) { // Scales of zero don't do anything.
2607 // We only allow one variable index at the moment.
2608 if (VariableOperand != -1)
2609 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00002610
Chandler Carruthc8925912013-01-05 02:09:22 +00002611 // Remember the variable index.
2612 VariableOperand = i;
2613 VariableScale = TypeSize;
2614 }
2615 }
2616 }
Stephen Lin837bba12013-07-15 17:55:02 +00002617
Chandler Carruthc8925912013-01-05 02:09:22 +00002618 // A common case is for the GEP to only do a constant offset. In this case,
2619 // just add it to the disp field and check validity.
2620 if (VariableOperand == -1) {
2621 AddrMode.BaseOffs += ConstantOffset;
2622 if (ConstantOffset == 0 || TLI.isLegalAddressingMode(AddrMode, AccessTy)){
2623 // Check to see if we can fold the base pointer in too.
2624 if (MatchAddr(AddrInst->getOperand(0), Depth+1))
2625 return true;
2626 }
2627 AddrMode.BaseOffs -= ConstantOffset;
2628 return false;
2629 }
2630
2631 // Save the valid addressing mode in case we can't match.
2632 ExtAddrMode BackupAddrMode = AddrMode;
2633 unsigned OldSize = AddrModeInsts.size();
2634
2635 // See if the scale and offset amount is valid for this target.
2636 AddrMode.BaseOffs += ConstantOffset;
2637
2638 // Match the base operand of the GEP.
2639 if (!MatchAddr(AddrInst->getOperand(0), Depth+1)) {
2640 // If it couldn't be matched, just stuff the value in a register.
2641 if (AddrMode.HasBaseReg) {
2642 AddrMode = BackupAddrMode;
2643 AddrModeInsts.resize(OldSize);
2644 return false;
2645 }
2646 AddrMode.HasBaseReg = true;
2647 AddrMode.BaseReg = AddrInst->getOperand(0);
2648 }
2649
2650 // Match the remaining variable portion of the GEP.
2651 if (!MatchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
2652 Depth)) {
2653 // If it couldn't be matched, try stuffing the base into a register
2654 // instead of matching it, and retrying the match of the scale.
2655 AddrMode = BackupAddrMode;
2656 AddrModeInsts.resize(OldSize);
2657 if (AddrMode.HasBaseReg)
2658 return false;
2659 AddrMode.HasBaseReg = true;
2660 AddrMode.BaseReg = AddrInst->getOperand(0);
2661 AddrMode.BaseOffs += ConstantOffset;
2662 if (!MatchScaledValue(AddrInst->getOperand(VariableOperand),
2663 VariableScale, Depth)) {
2664 // If even that didn't work, bail.
2665 AddrMode = BackupAddrMode;
2666 AddrModeInsts.resize(OldSize);
2667 return false;
2668 }
2669 }
2670
2671 return true;
2672 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002673 case Instruction::SExt:
2674 case Instruction::ZExt: {
2675 Instruction *Ext = dyn_cast<Instruction>(AddrInst);
2676 if (!Ext)
Sanjay Pateld3bbfa12014-07-16 22:40:28 +00002677 return false;
Sanjay Patelab60d042014-07-16 21:08:10 +00002678
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002679 // Try to move this ext out of the way of the addressing mode.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002680 // Ask for a method for doing so.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002681 TypePromotionHelper::Action TPH =
2682 TypePromotionHelper::getAction(Ext, InsertedTruncs, TLI, PromotedInsts);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002683 if (!TPH)
2684 return false;
2685
2686 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2687 TPT.getRestorationPoint();
2688 unsigned CreatedInsts = 0;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002689 Value *PromotedOperand =
2690 TPH(Ext, TPT, PromotedInsts, CreatedInsts, nullptr, nullptr);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002691 // SExt has been moved away.
2692 // Thus either it will be rematched later in the recursive calls or it is
2693 // gone. Anyway, we must not fold it into the addressing mode at this point.
2694 // E.g.,
2695 // op = add opnd, 1
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002696 // idx = ext op
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002697 // addr = gep base, idx
2698 // is now:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002699 // promotedOpnd = ext opnd <- no match here
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002700 // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls)
2701 // addr = gep base, op <- match
2702 if (MovedAway)
2703 *MovedAway = true;
2704
2705 assert(PromotedOperand &&
2706 "TypePromotionHelper should have filtered out those cases");
2707
2708 ExtAddrMode BackupAddrMode = AddrMode;
2709 unsigned OldSize = AddrModeInsts.size();
2710
2711 if (!MatchAddr(PromotedOperand, Depth) ||
Quentin Colombet867c5502014-02-14 22:23:22 +00002712 !IsPromotionProfitable(AddrModeInsts.size(), OldSize + CreatedInsts,
2713 PromotedOperand)) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002714 AddrMode = BackupAddrMode;
2715 AddrModeInsts.resize(OldSize);
2716 DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
2717 TPT.rollback(LastKnownGood);
2718 return false;
2719 }
2720 return true;
2721 }
Chandler Carruthc8925912013-01-05 02:09:22 +00002722 }
2723 return false;
2724}
2725
2726/// MatchAddr - If we can, try to add the value of 'Addr' into the current
2727/// addressing mode. If Addr can't be added to AddrMode this returns false and
2728/// leaves AddrMode unmodified. This assumes that Addr is either a pointer type
2729/// or intptr_t for the target.
2730///
2731bool AddressingModeMatcher::MatchAddr(Value *Addr, unsigned Depth) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002732 // Start a transaction at this point that we will rollback if the matching
2733 // fails.
2734 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2735 TPT.getRestorationPoint();
Chandler Carruthc8925912013-01-05 02:09:22 +00002736 if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
2737 // Fold in immediates if legal for the target.
2738 AddrMode.BaseOffs += CI->getSExtValue();
2739 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2740 return true;
2741 AddrMode.BaseOffs -= CI->getSExtValue();
2742 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
2743 // If this is a global variable, try to fold it into the addressing mode.
Craig Topperc0196b12014-04-14 00:51:57 +00002744 if (!AddrMode.BaseGV) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002745 AddrMode.BaseGV = GV;
2746 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2747 return true;
Craig Topperc0196b12014-04-14 00:51:57 +00002748 AddrMode.BaseGV = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00002749 }
2750 } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
2751 ExtAddrMode BackupAddrMode = AddrMode;
2752 unsigned OldSize = AddrModeInsts.size();
2753
2754 // Check to see if it is possible to fold this operation.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002755 bool MovedAway = false;
2756 if (MatchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
2757 // This instruction may have been move away. If so, there is nothing
2758 // to check here.
2759 if (MovedAway)
2760 return true;
Chandler Carruthc8925912013-01-05 02:09:22 +00002761 // Okay, it's possible to fold this. Check to see if it is actually
2762 // *profitable* to do so. We use a simple cost model to avoid increasing
2763 // register pressure too much.
2764 if (I->hasOneUse() ||
2765 IsProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
2766 AddrModeInsts.push_back(I);
2767 return true;
2768 }
Stephen Lin837bba12013-07-15 17:55:02 +00002769
Chandler Carruthc8925912013-01-05 02:09:22 +00002770 // It isn't profitable to do this, roll back.
2771 //cerr << "NOT FOLDING: " << *I;
2772 AddrMode = BackupAddrMode;
2773 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002774 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00002775 }
2776 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
2777 if (MatchOperationAddr(CE, CE->getOpcode(), Depth))
2778 return true;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002779 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00002780 } else if (isa<ConstantPointerNull>(Addr)) {
2781 // Null pointer gets folded without affecting the addressing mode.
2782 return true;
2783 }
2784
2785 // Worse case, the target should support [reg] addressing modes. :)
2786 if (!AddrMode.HasBaseReg) {
2787 AddrMode.HasBaseReg = true;
2788 AddrMode.BaseReg = Addr;
2789 // Still check for legality in case the target supports [imm] but not [i+r].
2790 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2791 return true;
2792 AddrMode.HasBaseReg = false;
Craig Topperc0196b12014-04-14 00:51:57 +00002793 AddrMode.BaseReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00002794 }
2795
2796 // If the base register is already taken, see if we can do [r+r].
2797 if (AddrMode.Scale == 0) {
2798 AddrMode.Scale = 1;
2799 AddrMode.ScaledReg = Addr;
2800 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2801 return true;
2802 AddrMode.Scale = 0;
Craig Topperc0196b12014-04-14 00:51:57 +00002803 AddrMode.ScaledReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00002804 }
2805 // Couldn't match.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002806 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00002807 return false;
2808}
2809
2810/// IsOperandAMemoryOperand - Check to see if all uses of OpVal by the specified
2811/// inline asm call are due to memory operands. If so, return true, otherwise
2812/// return false.
2813static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
2814 const TargetLowering &TLI) {
2815 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(ImmutableCallSite(CI));
2816 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
2817 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Stephen Lin837bba12013-07-15 17:55:02 +00002818
Chandler Carruthc8925912013-01-05 02:09:22 +00002819 // Compute the constraint code and ConstraintType to use.
2820 TLI.ComputeConstraintToUse(OpInfo, SDValue());
2821
2822 // If this asm operand is our Value*, and if it isn't an indirect memory
2823 // operand, we can't fold it!
2824 if (OpInfo.CallOperandVal == OpVal &&
2825 (OpInfo.ConstraintType != TargetLowering::C_Memory ||
2826 !OpInfo.isIndirect))
2827 return false;
2828 }
2829
2830 return true;
2831}
2832
2833/// FindAllMemoryUses - Recursively walk all the uses of I until we find a
2834/// memory use. If we find an obviously non-foldable instruction, return true.
2835/// Add the ultimately found memory instructions to MemoryUses.
2836static bool FindAllMemoryUses(Instruction *I,
2837 SmallVectorImpl<std::pair<Instruction*,unsigned> > &MemoryUses,
Craig Topper71b7b682014-08-21 05:55:13 +00002838 SmallPtrSetImpl<Instruction*> &ConsideredInsts,
Chandler Carruthc8925912013-01-05 02:09:22 +00002839 const TargetLowering &TLI) {
2840 // If we already considered this instruction, we're done.
David Blaikie70573dc2014-11-19 07:49:26 +00002841 if (!ConsideredInsts.insert(I).second)
Chandler Carruthc8925912013-01-05 02:09:22 +00002842 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00002843
Chandler Carruthc8925912013-01-05 02:09:22 +00002844 // If this is an obviously unfoldable instruction, bail out.
2845 if (!MightBeFoldableInst(I))
2846 return true;
2847
2848 // Loop over all the uses, recursively processing them.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002849 for (Use &U : I->uses()) {
2850 Instruction *UserI = cast<Instruction>(U.getUser());
Chandler Carruthc8925912013-01-05 02:09:22 +00002851
Chandler Carruthcdf47882014-03-09 03:16:01 +00002852 if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
2853 MemoryUses.push_back(std::make_pair(LI, U.getOperandNo()));
Chandler Carruthc8925912013-01-05 02:09:22 +00002854 continue;
2855 }
Stephen Lin837bba12013-07-15 17:55:02 +00002856
Chandler Carruthcdf47882014-03-09 03:16:01 +00002857 if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
2858 unsigned opNo = U.getOperandNo();
Chandler Carruthc8925912013-01-05 02:09:22 +00002859 if (opNo == 0) return true; // Storing addr, not into addr.
2860 MemoryUses.push_back(std::make_pair(SI, opNo));
2861 continue;
2862 }
Stephen Lin837bba12013-07-15 17:55:02 +00002863
Chandler Carruthcdf47882014-03-09 03:16:01 +00002864 if (CallInst *CI = dyn_cast<CallInst>(UserI)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002865 InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
2866 if (!IA) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002867
Chandler Carruthc8925912013-01-05 02:09:22 +00002868 // If this is a memory operand, we're cool, otherwise bail out.
2869 if (!IsOperandAMemoryOperand(CI, IA, I, TLI))
2870 return true;
2871 continue;
2872 }
Stephen Lin837bba12013-07-15 17:55:02 +00002873
Chandler Carruthcdf47882014-03-09 03:16:01 +00002874 if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TLI))
Chandler Carruthc8925912013-01-05 02:09:22 +00002875 return true;
2876 }
2877
2878 return false;
2879}
2880
2881/// ValueAlreadyLiveAtInst - Retrn true if Val is already known to be live at
2882/// the use site that we're folding it into. If so, there is no cost to
2883/// include it in the addressing mode. KnownLive1 and KnownLive2 are two values
2884/// that we know are live at the instruction already.
2885bool AddressingModeMatcher::ValueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
2886 Value *KnownLive2) {
2887 // If Val is either of the known-live values, we know it is live!
Craig Topperc0196b12014-04-14 00:51:57 +00002888 if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2)
Chandler Carruthc8925912013-01-05 02:09:22 +00002889 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002890
Chandler Carruthc8925912013-01-05 02:09:22 +00002891 // All values other than instructions and arguments (e.g. constants) are live.
2892 if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002893
Chandler Carruthc8925912013-01-05 02:09:22 +00002894 // If Val is a constant sized alloca in the entry block, it is live, this is
2895 // true because it is just a reference to the stack/frame pointer, which is
2896 // live for the whole function.
2897 if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
2898 if (AI->isStaticAlloca())
2899 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002900
Chandler Carruthc8925912013-01-05 02:09:22 +00002901 // Check to see if this value is already used in the memory instruction's
2902 // block. If so, it's already live into the block at the very least, so we
2903 // can reasonably fold it.
2904 return Val->isUsedInBasicBlock(MemoryInst->getParent());
2905}
2906
2907/// IsProfitableToFoldIntoAddressingMode - It is possible for the addressing
2908/// mode of the machine to fold the specified instruction into a load or store
2909/// that ultimately uses it. However, the specified instruction has multiple
2910/// uses. Given this, it may actually increase register pressure to fold it
2911/// into the load. For example, consider this code:
2912///
2913/// X = ...
2914/// Y = X+1
2915/// use(Y) -> nonload/store
2916/// Z = Y+1
2917/// load Z
2918///
2919/// In this case, Y has multiple uses, and can be folded into the load of Z
2920/// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to
2921/// be live at the use(Y) line. If we don't fold Y into load Z, we use one
2922/// fewer register. Since Y can't be folded into "use(Y)" we don't increase the
2923/// number of computations either.
2924///
2925/// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If
2926/// X was live across 'load Z' for other reasons, we actually *would* want to
2927/// fold the addressing mode in the Z case. This would make Y die earlier.
2928bool AddressingModeMatcher::
2929IsProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
2930 ExtAddrMode &AMAfter) {
2931 if (IgnoreProfitability) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002932
Chandler Carruthc8925912013-01-05 02:09:22 +00002933 // AMBefore is the addressing mode before this instruction was folded into it,
2934 // and AMAfter is the addressing mode after the instruction was folded. Get
2935 // the set of registers referenced by AMAfter and subtract out those
2936 // referenced by AMBefore: this is the set of values which folding in this
2937 // address extends the lifetime of.
2938 //
2939 // Note that there are only two potential values being referenced here,
2940 // BaseReg and ScaleReg (global addresses are always available, as are any
2941 // folded immediates).
2942 Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
Stephen Lin837bba12013-07-15 17:55:02 +00002943
Chandler Carruthc8925912013-01-05 02:09:22 +00002944 // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
2945 // lifetime wasn't extended by adding this instruction.
2946 if (ValueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
Craig Topperc0196b12014-04-14 00:51:57 +00002947 BaseReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00002948 if (ValueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
Craig Topperc0196b12014-04-14 00:51:57 +00002949 ScaledReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00002950
2951 // If folding this instruction (and it's subexprs) didn't extend any live
2952 // ranges, we're ok with it.
Craig Topperc0196b12014-04-14 00:51:57 +00002953 if (!BaseReg && !ScaledReg)
Chandler Carruthc8925912013-01-05 02:09:22 +00002954 return true;
2955
2956 // If all uses of this instruction are ultimately load/store/inlineasm's,
2957 // check to see if their addressing modes will include this instruction. If
2958 // so, we can fold it into all uses, so it doesn't matter if it has multiple
2959 // uses.
2960 SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
2961 SmallPtrSet<Instruction*, 16> ConsideredInsts;
2962 if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TLI))
2963 return false; // Has a non-memory, non-foldable use!
Stephen Lin837bba12013-07-15 17:55:02 +00002964
Chandler Carruthc8925912013-01-05 02:09:22 +00002965 // Now that we know that all uses of this instruction are part of a chain of
2966 // computation involving only operations that could theoretically be folded
2967 // into a memory use, loop over each of these uses and see if they could
2968 // *actually* fold the instruction.
2969 SmallVector<Instruction*, 32> MatchedAddrModeInsts;
2970 for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
2971 Instruction *User = MemoryUses[i].first;
2972 unsigned OpNo = MemoryUses[i].second;
Stephen Lin837bba12013-07-15 17:55:02 +00002973
Chandler Carruthc8925912013-01-05 02:09:22 +00002974 // Get the access type of this use. If the use isn't a pointer, we don't
2975 // know what it accesses.
2976 Value *Address = User->getOperand(OpNo);
2977 if (!Address->getType()->isPointerTy())
2978 return false;
Matt Arsenault8227b9f2013-09-06 00:37:24 +00002979 Type *AddressAccessTy = Address->getType()->getPointerElementType();
Stephen Lin837bba12013-07-15 17:55:02 +00002980
Chandler Carruthc8925912013-01-05 02:09:22 +00002981 // Do a match against the root of this address, ignoring profitability. This
2982 // will tell us if the addressing mode for the memory operation will
2983 // *actually* cover the shared instruction.
2984 ExtAddrMode Result;
Quentin Colombet5a69dda2014-02-11 01:59:02 +00002985 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2986 TPT.getRestorationPoint();
Chandler Carruthc8925912013-01-05 02:09:22 +00002987 AddressingModeMatcher Matcher(MatchedAddrModeInsts, TLI, AddressAccessTy,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002988 MemoryInst, Result, InsertedTruncs,
2989 PromotedInsts, TPT);
Chandler Carruthc8925912013-01-05 02:09:22 +00002990 Matcher.IgnoreProfitability = true;
2991 bool Success = Matcher.MatchAddr(Address, 0);
2992 (void)Success; assert(Success && "Couldn't select *anything*?");
2993
Quentin Colombet5a69dda2014-02-11 01:59:02 +00002994 // The match was to check the profitability, the changes made are not
2995 // part of the original matcher. Therefore, they should be dropped
2996 // otherwise the original matcher will not present the right state.
2997 TPT.rollback(LastKnownGood);
2998
Chandler Carruthc8925912013-01-05 02:09:22 +00002999 // If the match didn't cover I, then it won't be shared by it.
3000 if (std::find(MatchedAddrModeInsts.begin(), MatchedAddrModeInsts.end(),
3001 I) == MatchedAddrModeInsts.end())
3002 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003003
Chandler Carruthc8925912013-01-05 02:09:22 +00003004 MatchedAddrModeInsts.clear();
3005 }
Stephen Lin837bba12013-07-15 17:55:02 +00003006
Chandler Carruthc8925912013-01-05 02:09:22 +00003007 return true;
3008}
3009
3010} // end anonymous namespace
3011
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003012/// IsNonLocalValue - Return true if the specified values are defined in a
3013/// different basic block than BB.
3014static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
3015 if (Instruction *I = dyn_cast<Instruction>(V))
3016 return I->getParent() != BB;
3017 return false;
3018}
3019
Bob Wilson53bdae32009-12-03 21:47:07 +00003020/// OptimizeMemoryInst - Load and Store Instructions often have
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003021/// addressing modes that can do significant amounts of computation. As such,
3022/// instruction selection will try to get the load or store to do as much
3023/// computation as possible for the program. The problem is that isel can only
3024/// see within a single block. As such, we sink as much legal addressing mode
3025/// stuff into the block as possible.
Chris Lattner728f9022008-11-25 07:09:13 +00003026///
3027/// This method is used to optimize both load/store and inline asms with memory
3028/// operands.
Chris Lattner6d71b7f2008-11-26 03:20:37 +00003029bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
Chris Lattner229907c2011-07-18 04:54:35 +00003030 Type *AccessTy) {
Owen Anderson8ba5f392010-11-27 08:15:55 +00003031 Value *Repl = Addr;
Nadav Rotem465834c2012-07-24 10:51:42 +00003032
3033 // Try to collapse single-value PHI nodes. This is necessary to undo
Owen Andersondfb8c3b2010-11-19 22:15:03 +00003034 // unprofitable PRE transformations.
Cameron Zwarich43cecb12011-01-03 06:33:01 +00003035 SmallVector<Value*, 8> worklist;
3036 SmallPtrSet<Value*, 16> Visited;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003037 worklist.push_back(Addr);
Nadav Rotem465834c2012-07-24 10:51:42 +00003038
Owen Anderson8ba5f392010-11-27 08:15:55 +00003039 // Use a worklist to iteratively look through PHI nodes, and ensure that
3040 // the addressing mode obtained from the non-PHI roots of the graph
3041 // are equivalent.
Craig Topperc0196b12014-04-14 00:51:57 +00003042 Value *Consensus = nullptr;
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00003043 unsigned NumUsesConsensus = 0;
Cameron Zwarich13c885d2011-03-05 08:12:26 +00003044 bool IsNumUsesConsensusValid = false;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003045 SmallVector<Instruction*, 16> AddrModeInsts;
3046 ExtAddrMode AddrMode;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003047 TypePromotionTransaction TPT;
3048 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3049 TPT.getRestorationPoint();
Owen Anderson8ba5f392010-11-27 08:15:55 +00003050 while (!worklist.empty()) {
3051 Value *V = worklist.back();
3052 worklist.pop_back();
Nadav Rotem465834c2012-07-24 10:51:42 +00003053
Owen Anderson8ba5f392010-11-27 08:15:55 +00003054 // Break use-def graph loops.
David Blaikie70573dc2014-11-19 07:49:26 +00003055 if (!Visited.insert(V).second) {
Craig Topperc0196b12014-04-14 00:51:57 +00003056 Consensus = nullptr;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003057 break;
Owen Andersondfb8c3b2010-11-19 22:15:03 +00003058 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003059
Owen Anderson8ba5f392010-11-27 08:15:55 +00003060 // For a PHI node, push all of its incoming values.
3061 if (PHINode *P = dyn_cast<PHINode>(V)) {
3062 for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i)
3063 worklist.push_back(P->getIncomingValue(i));
3064 continue;
3065 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003066
Owen Anderson8ba5f392010-11-27 08:15:55 +00003067 // For non-PHIs, determine the addressing mode being computed.
3068 SmallVector<Instruction*, 16> NewAddrModeInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003069 ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
3070 V, AccessTy, MemoryInst, NewAddrModeInsts, *TLI, InsertedTruncsSet,
3071 PromotedInsts, TPT);
Cameron Zwarich13c885d2011-03-05 08:12:26 +00003072
3073 // This check is broken into two cases with very similar code to avoid using
3074 // getNumUses() as much as possible. Some values have a lot of uses, so
3075 // calling getNumUses() unconditionally caused a significant compile-time
3076 // regression.
3077 if (!Consensus) {
3078 Consensus = V;
3079 AddrMode = NewAddrMode;
3080 AddrModeInsts = NewAddrModeInsts;
3081 continue;
3082 } else if (NewAddrMode == AddrMode) {
3083 if (!IsNumUsesConsensusValid) {
3084 NumUsesConsensus = Consensus->getNumUses();
3085 IsNumUsesConsensusValid = true;
3086 }
3087
3088 // Ensure that the obtained addressing mode is equivalent to that obtained
3089 // for all other roots of the PHI traversal. Also, when choosing one
3090 // such root as representative, select the one with the most uses in order
3091 // to keep the cost modeling heuristics in AddressingModeMatcher
3092 // applicable.
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00003093 unsigned NumUses = V->getNumUses();
3094 if (NumUses > NumUsesConsensus) {
Owen Anderson8ba5f392010-11-27 08:15:55 +00003095 Consensus = V;
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00003096 NumUsesConsensus = NumUses;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003097 AddrModeInsts = NewAddrModeInsts;
3098 }
3099 continue;
3100 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003101
Craig Topperc0196b12014-04-14 00:51:57 +00003102 Consensus = nullptr;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003103 break;
Owen Andersondfb8c3b2010-11-19 22:15:03 +00003104 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003105
Owen Anderson8ba5f392010-11-27 08:15:55 +00003106 // If the addressing mode couldn't be determined, or if multiple different
3107 // ones were determined, bail out now.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003108 if (!Consensus) {
3109 TPT.rollback(LastKnownGood);
3110 return false;
3111 }
3112 TPT.commit();
Nadav Rotem465834c2012-07-24 10:51:42 +00003113
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003114 // Check to see if any of the instructions supersumed by this addr mode are
3115 // non-local to I's BB.
3116 bool AnyNonLocal = false;
3117 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
Chris Lattner6d71b7f2008-11-26 03:20:37 +00003118 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003119 AnyNonLocal = true;
3120 break;
3121 }
3122 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00003123
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003124 // If all the instructions matched are already in this BB, don't do anything.
3125 if (!AnyNonLocal) {
David Greene74e2d492010-01-05 01:27:11 +00003126 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003127 return false;
3128 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00003129
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003130 // Insert this computation right after this user. Since our caller is
3131 // scanning from the top of the BB to the bottom, reuse of the expr are
3132 // guaranteed to happen later.
Devang Patelc10e52a2011-09-06 18:49:53 +00003133 IRBuilder<> Builder(MemoryInst);
Eric Christopherc1ea1492008-09-24 05:32:41 +00003134
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003135 // Now that we determined the addressing expression we want to use and know
3136 // that we have to sink it into this block. Check to see if we have already
3137 // done this for some other load/store instr in this block. If so, reuse the
3138 // computation.
3139 Value *&SunkAddr = SunkAddrs[Addr];
3140 if (SunkAddr) {
David Greene74e2d492010-01-05 01:27:11 +00003141 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00003142 << *MemoryInst << "\n");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003143 if (SunkAddr->getType() != Addr->getType())
Benjamin Kramer547b6c52011-09-27 20:39:19 +00003144 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
Eric Christopherfccff372015-01-27 01:01:38 +00003145 } else if (AddrSinkUsingGEPs ||
3146 (!AddrSinkUsingGEPs.getNumOccurrences() && TM &&
Eric Christopher2c635492015-01-27 07:54:39 +00003147 TM->getSubtargetImpl(*MemoryInst->getParent()->getParent())
3148 ->useAA())) {
Hal Finkelc3998302014-04-12 00:59:48 +00003149 // By default, we use the GEP-based method when AA is used later. This
3150 // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities.
3151 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00003152 << *MemoryInst << "\n");
Hal Finkelc3998302014-04-12 00:59:48 +00003153 Type *IntPtrTy = TLI->getDataLayout()->getIntPtrType(Addr->getType());
Craig Topperc0196b12014-04-14 00:51:57 +00003154 Value *ResultPtr = nullptr, *ResultIndex = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00003155
3156 // First, find the pointer.
3157 if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) {
3158 ResultPtr = AddrMode.BaseReg;
Craig Topperc0196b12014-04-14 00:51:57 +00003159 AddrMode.BaseReg = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00003160 }
3161
3162 if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) {
3163 // We can't add more than one pointer together, nor can we scale a
3164 // pointer (both of which seem meaningless).
3165 if (ResultPtr || AddrMode.Scale != 1)
3166 return false;
3167
3168 ResultPtr = AddrMode.ScaledReg;
3169 AddrMode.Scale = 0;
3170 }
3171
3172 if (AddrMode.BaseGV) {
3173 if (ResultPtr)
3174 return false;
3175
3176 ResultPtr = AddrMode.BaseGV;
3177 }
3178
3179 // If the real base value actually came from an inttoptr, then the matcher
3180 // will look through it and provide only the integer value. In that case,
3181 // use it here.
3182 if (!ResultPtr && AddrMode.BaseReg) {
3183 ResultPtr =
3184 Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(), "sunkaddr");
Craig Topperc0196b12014-04-14 00:51:57 +00003185 AddrMode.BaseReg = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00003186 } else if (!ResultPtr && AddrMode.Scale == 1) {
3187 ResultPtr =
3188 Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(), "sunkaddr");
3189 AddrMode.Scale = 0;
3190 }
3191
3192 if (!ResultPtr &&
3193 !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) {
3194 SunkAddr = Constant::getNullValue(Addr->getType());
3195 } else if (!ResultPtr) {
3196 return false;
3197 } else {
3198 Type *I8PtrTy =
3199 Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace());
3200
3201 // Start with the base register. Do this first so that subsequent address
3202 // matching finds it last, which will prevent it from trying to match it
3203 // as the scaled value in case it happens to be a mul. That would be
3204 // problematic if we've sunk a different mul for the scale, because then
3205 // we'd end up sinking both muls.
3206 if (AddrMode.BaseReg) {
3207 Value *V = AddrMode.BaseReg;
3208 if (V->getType() != IntPtrTy)
3209 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
3210
3211 ResultIndex = V;
3212 }
3213
3214 // Add the scale value.
3215 if (AddrMode.Scale) {
3216 Value *V = AddrMode.ScaledReg;
3217 if (V->getType() == IntPtrTy) {
3218 // done.
3219 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
3220 cast<IntegerType>(V->getType())->getBitWidth()) {
3221 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
3222 } else {
3223 // It is only safe to sign extend the BaseReg if we know that the math
3224 // required to create it did not overflow before we extend it. Since
3225 // the original IR value was tossed in favor of a constant back when
3226 // the AddrMode was created we need to bail out gracefully if widths
3227 // do not match instead of extending it.
3228 Instruction *I = dyn_cast_or_null<Instruction>(ResultIndex);
3229 if (I && (ResultIndex != AddrMode.BaseReg))
3230 I->eraseFromParent();
3231 return false;
3232 }
3233
3234 if (AddrMode.Scale != 1)
3235 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
3236 "sunkaddr");
3237 if (ResultIndex)
3238 ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr");
3239 else
3240 ResultIndex = V;
3241 }
3242
3243 // Add in the Base Offset if present.
3244 if (AddrMode.BaseOffs) {
3245 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
3246 if (ResultIndex) {
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00003247 // We need to add this separately from the scale above to help with
3248 // SDAG consecutive load/store merging.
Hal Finkelc3998302014-04-12 00:59:48 +00003249 if (ResultPtr->getType() != I8PtrTy)
3250 ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
3251 ResultPtr = Builder.CreateGEP(ResultPtr, ResultIndex, "sunkaddr");
3252 }
3253
3254 ResultIndex = V;
3255 }
3256
3257 if (!ResultIndex) {
3258 SunkAddr = ResultPtr;
3259 } else {
3260 if (ResultPtr->getType() != I8PtrTy)
3261 ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
3262 SunkAddr = Builder.CreateGEP(ResultPtr, ResultIndex, "sunkaddr");
3263 }
3264
3265 if (SunkAddr->getType() != Addr->getType())
3266 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
3267 }
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003268 } else {
David Greene74e2d492010-01-05 01:27:11 +00003269 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00003270 << *MemoryInst << "\n");
Matt Arsenault37d42ec2013-09-06 00:18:43 +00003271 Type *IntPtrTy = TLI->getDataLayout()->getIntPtrType(Addr->getType());
Craig Topperc0196b12014-04-14 00:51:57 +00003272 Value *Result = nullptr;
Dan Gohmanca194452010-01-19 22:45:06 +00003273
3274 // Start with the base register. Do this first so that subsequent address
3275 // matching finds it last, which will prevent it from trying to match it
3276 // as the scaled value in case it happens to be a mul. That would be
3277 // problematic if we've sunk a different mul for the scale, because then
3278 // we'd end up sinking both muls.
3279 if (AddrMode.BaseReg) {
3280 Value *V = AddrMode.BaseReg;
Duncan Sands19d0b472010-02-16 11:11:14 +00003281 if (V->getType()->isPointerTy())
Devang Patelc10e52a2011-09-06 18:49:53 +00003282 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00003283 if (V->getType() != IntPtrTy)
Devang Patelc10e52a2011-09-06 18:49:53 +00003284 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00003285 Result = V;
3286 }
3287
3288 // Add the scale value.
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003289 if (AddrMode.Scale) {
3290 Value *V = AddrMode.ScaledReg;
3291 if (V->getType() == IntPtrTy) {
3292 // done.
Duncan Sands19d0b472010-02-16 11:11:14 +00003293 } else if (V->getType()->isPointerTy()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00003294 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003295 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
3296 cast<IntegerType>(V->getType())->getBitWidth()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00003297 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003298 } else {
Jim Grosbached2cd392014-03-26 17:27:01 +00003299 // It is only safe to sign extend the BaseReg if we know that the math
3300 // required to create it did not overflow before we extend it. Since
3301 // the original IR value was tossed in favor of a constant back when
3302 // the AddrMode was created we need to bail out gracefully if widths
3303 // do not match instead of extending it.
Joey Gouly12a8bf02014-05-13 15:42:45 +00003304 Instruction *I = dyn_cast_or_null<Instruction>(Result);
Jim Grosbach83b44e12014-04-10 00:27:45 +00003305 if (I && (Result != AddrMode.BaseReg))
3306 I->eraseFromParent();
Jim Grosbached2cd392014-03-26 17:27:01 +00003307 return false;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003308 }
3309 if (AddrMode.Scale != 1)
Devang Patelc10e52a2011-09-06 18:49:53 +00003310 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
3311 "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003312 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00003313 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003314 else
3315 Result = V;
3316 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00003317
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003318 // Add in the BaseGV if present.
3319 if (AddrMode.BaseGV) {
Devang Patelc10e52a2011-09-06 18:49:53 +00003320 Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003321 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00003322 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003323 else
3324 Result = V;
3325 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00003326
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003327 // Add in the Base Offset if present.
3328 if (AddrMode.BaseOffs) {
Owen Andersonedb4a702009-07-24 23:12:02 +00003329 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003330 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00003331 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003332 else
3333 Result = V;
3334 }
3335
Craig Topperc0196b12014-04-14 00:51:57 +00003336 if (!Result)
Owen Anderson5a1acd92009-07-31 20:28:14 +00003337 SunkAddr = Constant::getNullValue(Addr->getType());
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003338 else
Devang Patelc10e52a2011-09-06 18:49:53 +00003339 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003340 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00003341
Owen Andersondfb8c3b2010-11-19 22:15:03 +00003342 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
Eric Christopherc1ea1492008-09-24 05:32:41 +00003343
Chris Lattneraf1bcce2011-04-09 07:05:44 +00003344 // If we have no uses, recursively delete the value and all dead instructions
3345 // using it.
Owen Andersondfb8c3b2010-11-19 22:15:03 +00003346 if (Repl->use_empty()) {
Chris Lattneraf1bcce2011-04-09 07:05:44 +00003347 // This can cause recursive deletion, which can invalidate our iterator.
3348 // Use a WeakVH to hold onto it in case this happens.
3349 WeakVH IterHandle(CurInstIterator);
3350 BasicBlock *BB = CurInstIterator->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +00003351
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00003352 RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
Chris Lattneraf1bcce2011-04-09 07:05:44 +00003353
3354 if (IterHandle != CurInstIterator) {
3355 // If the iterator instruction was recursively deleted, start over at the
3356 // start of the block.
3357 CurInstIterator = BB->begin();
3358 SunkAddrs.clear();
Nadav Rotem465834c2012-07-24 10:51:42 +00003359 }
Dale Johannesenb67a6e662010-03-31 20:37:15 +00003360 }
Cameron Zwarichced753f2011-01-05 17:27:27 +00003361 ++NumMemoryInsts;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003362 return true;
3363}
3364
Evan Cheng1da25002008-02-26 02:42:37 +00003365/// OptimizeInlineAsmInst - If there are any memory operands, use
Chris Lattner728f9022008-11-25 07:09:13 +00003366/// OptimizeMemoryInst to sink their address computing into the block when
Evan Cheng1da25002008-02-26 02:42:37 +00003367/// possible / profitable.
Chris Lattner7a277142011-01-15 07:14:54 +00003368bool CodeGenPrepare::OptimizeInlineAsmInst(CallInst *CS) {
Evan Cheng1da25002008-02-26 02:42:37 +00003369 bool MadeChange = false;
Evan Cheng1da25002008-02-26 02:42:37 +00003370
Nadav Rotem465834c2012-07-24 10:51:42 +00003371 TargetLowering::AsmOperandInfoVector
Chris Lattner7a277142011-01-15 07:14:54 +00003372 TargetConstraints = TLI->ParseConstraints(CS);
Dale Johannesenf95f59a2010-09-16 18:30:55 +00003373 unsigned ArgNo = 0;
John Thompson1094c802010-09-13 18:15:37 +00003374 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
3375 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Nadav Rotem465834c2012-07-24 10:51:42 +00003376
Evan Cheng1da25002008-02-26 02:42:37 +00003377 // Compute the constraint code and ConstraintType to use.
Dale Johannesence97d552010-06-25 21:55:36 +00003378 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Evan Cheng1da25002008-02-26 02:42:37 +00003379
Eli Friedman666bbe32008-02-26 18:37:49 +00003380 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
3381 OpInfo.isIndirect) {
Chris Lattner7a277142011-01-15 07:14:54 +00003382 Value *OpVal = CS->getArgOperand(ArgNo++);
Chris Lattneree588de2011-01-15 07:29:01 +00003383 MadeChange |= OptimizeMemoryInst(CS, OpVal, OpVal->getType());
Dale Johannesenf95f59a2010-09-16 18:30:55 +00003384 } else if (OpInfo.Type == InlineAsm::isInput)
3385 ArgNo++;
Evan Cheng1da25002008-02-26 02:42:37 +00003386 }
3387
3388 return MadeChange;
3389}
3390
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003391/// \brief Check if all the uses of \p Inst are equivalent (or free) zero or
3392/// sign extensions.
3393static bool hasSameExtUse(Instruction *Inst, const TargetLowering &TLI) {
3394 assert(!Inst->use_empty() && "Input must have at least one use");
3395 const Instruction *FirstUser = cast<Instruction>(*Inst->user_begin());
3396 bool IsSExt = isa<SExtInst>(FirstUser);
3397 Type *ExtTy = FirstUser->getType();
3398 for (const User *U : Inst->users()) {
3399 const Instruction *UI = cast<Instruction>(U);
3400 if ((IsSExt && !isa<SExtInst>(UI)) || (!IsSExt && !isa<ZExtInst>(UI)))
3401 return false;
3402 Type *CurTy = UI->getType();
3403 // Same input and output types: Same instruction after CSE.
3404 if (CurTy == ExtTy)
3405 continue;
3406
3407 // If IsSExt is true, we are in this situation:
3408 // a = Inst
3409 // b = sext ty1 a to ty2
3410 // c = sext ty1 a to ty3
3411 // Assuming ty2 is shorter than ty3, this could be turned into:
3412 // a = Inst
3413 // b = sext ty1 a to ty2
3414 // c = sext ty2 b to ty3
3415 // However, the last sext is not free.
3416 if (IsSExt)
3417 return false;
3418
3419 // This is a ZExt, maybe this is free to extend from one type to another.
3420 // In that case, we would not account for a different use.
3421 Type *NarrowTy;
3422 Type *LargeTy;
3423 if (ExtTy->getScalarType()->getIntegerBitWidth() >
3424 CurTy->getScalarType()->getIntegerBitWidth()) {
3425 NarrowTy = CurTy;
3426 LargeTy = ExtTy;
3427 } else {
3428 NarrowTy = ExtTy;
3429 LargeTy = CurTy;
3430 }
3431
3432 if (!TLI.isZExtFree(NarrowTy, LargeTy))
3433 return false;
3434 }
3435 // All uses are the same or can be derived from one another for free.
3436 return true;
3437}
3438
3439/// \brief Try to form ExtLd by promoting \p Exts until they reach a
3440/// load instruction.
3441/// If an ext(load) can be formed, it is returned via \p LI for the load
3442/// and \p Inst for the extension.
3443/// Otherwise LI == nullptr and Inst == nullptr.
3444/// When some promotion happened, \p TPT contains the proper state to
3445/// revert them.
3446///
3447/// \return true when promoting was necessary to expose the ext(load)
3448/// opportunity, false otherwise.
3449///
3450/// Example:
3451/// \code
3452/// %ld = load i32* %addr
3453/// %add = add nuw i32 %ld, 4
3454/// %zext = zext i32 %add to i64
3455/// \endcode
3456/// =>
3457/// \code
3458/// %ld = load i32* %addr
3459/// %zext = zext i32 %ld to i64
3460/// %add = add nuw i64 %zext, 4
3461/// \encode
3462/// Thanks to the promotion, we can match zext(load i32*) to i64.
3463bool CodeGenPrepare::ExtLdPromotion(TypePromotionTransaction &TPT,
3464 LoadInst *&LI, Instruction *&Inst,
3465 const SmallVectorImpl<Instruction *> &Exts,
3466 unsigned CreatedInsts = 0) {
3467 // Iterate over all the extensions to see if one form an ext(load).
3468 for (auto I : Exts) {
3469 // Check if we directly have ext(load).
3470 if ((LI = dyn_cast<LoadInst>(I->getOperand(0)))) {
3471 Inst = I;
3472 // No promotion happened here.
3473 return false;
3474 }
3475 // Check whether or not we want to do any promotion.
3476 if (!TLI || !TLI->enableExtLdPromotion() || DisableExtLdPromotion)
3477 continue;
3478 // Get the action to perform the promotion.
3479 TypePromotionHelper::Action TPH = TypePromotionHelper::getAction(
3480 I, InsertedTruncsSet, *TLI, PromotedInsts);
3481 // Check if we can promote.
3482 if (!TPH)
3483 continue;
3484 // Save the current state.
3485 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3486 TPT.getRestorationPoint();
3487 SmallVector<Instruction *, 4> NewExts;
3488 unsigned NewCreatedInsts = 0;
3489 // Promote.
3490 Value *PromotedVal =
3491 TPH(I, TPT, PromotedInsts, NewCreatedInsts, &NewExts, nullptr);
3492 assert(PromotedVal &&
3493 "TypePromotionHelper should have filtered out those cases");
3494
3495 // We would be able to merge only one extension in a load.
3496 // Therefore, if we have more than 1 new extension we heuristically
3497 // cut this search path, because it means we degrade the code quality.
3498 // With exactly 2, the transformation is neutral, because we will merge
3499 // one extension but leave one. However, we optimistically keep going,
3500 // because the new extension may be removed too.
3501 unsigned TotalCreatedInsts = CreatedInsts + NewCreatedInsts;
3502 if (!StressExtLdPromotion &&
3503 (TotalCreatedInsts > 1 ||
3504 !isPromotedInstructionLegal(*TLI, PromotedVal))) {
3505 // The promotion is not profitable, rollback to the previous state.
3506 TPT.rollback(LastKnownGood);
3507 continue;
3508 }
3509 // The promotion is profitable.
3510 // Check if it exposes an ext(load).
3511 (void)ExtLdPromotion(TPT, LI, Inst, NewExts, TotalCreatedInsts);
3512 if (LI && (StressExtLdPromotion || NewCreatedInsts == 0 ||
3513 // If we have created a new extension, i.e., now we have two
3514 // extensions. We must make sure one of them is merged with
3515 // the load, otherwise we may degrade the code quality.
3516 (LI->hasOneUse() || hasSameExtUse(LI, *TLI))))
3517 // Promotion happened.
3518 return true;
3519 // If this does not help to expose an ext(load) then, rollback.
3520 TPT.rollback(LastKnownGood);
3521 }
3522 // None of the extension can form an ext(load).
3523 LI = nullptr;
3524 Inst = nullptr;
3525 return false;
3526}
3527
Dan Gohman99429a02009-10-16 20:59:35 +00003528/// MoveExtToFormExtLoad - Move a zext or sext fed by a load into the same
3529/// basic block as the load, unless conditions are unfavorable. This allows
3530/// SelectionDAG to fold the extend into the load.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003531/// \p I[in/out] the extension may be modified during the process if some
3532/// promotions apply.
Dan Gohman99429a02009-10-16 20:59:35 +00003533///
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003534bool CodeGenPrepare::MoveExtToFormExtLoad(Instruction *&I) {
3535 // Try to promote a chain of computation if it allows to form
3536 // an extended load.
3537 TypePromotionTransaction TPT;
3538 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3539 TPT.getRestorationPoint();
3540 SmallVector<Instruction *, 1> Exts;
3541 Exts.push_back(I);
Dan Gohman99429a02009-10-16 20:59:35 +00003542 // Look for a load being extended.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003543 LoadInst *LI = nullptr;
3544 Instruction *OldExt = I;
3545 bool HasPromoted = ExtLdPromotion(TPT, LI, I, Exts);
3546 if (!LI || !I) {
3547 assert(!HasPromoted && !LI && "If we did not match any load instruction "
3548 "the code must remain the same");
3549 I = OldExt;
3550 return false;
3551 }
Dan Gohman99429a02009-10-16 20:59:35 +00003552
3553 // If they're already in the same block, there's nothing to do.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003554 // Make the cheap checks first if we did not promote.
3555 // If we promoted, we need to check if it is indeed profitable.
3556 if (!HasPromoted && LI->getParent() == I->getParent())
Dan Gohman99429a02009-10-16 20:59:35 +00003557 return false;
3558
Ahmed Bougacha55e3c2d2014-12-05 18:04:40 +00003559 EVT VT = TLI->getValueType(I->getType());
3560 EVT LoadVT = TLI->getValueType(LI->getType());
3561
Dan Gohman99429a02009-10-16 20:59:35 +00003562 // If the load has other users and the truncate is not free, this probably
3563 // isn't worthwhile.
Ahmed Bougacha55e3c2d2014-12-05 18:04:40 +00003564 if (!LI->hasOneUse() && TLI &&
3565 (TLI->isTypeLegal(LoadVT) || !TLI->isTypeLegal(VT)) &&
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003566 !TLI->isTruncateFree(I->getType(), LI->getType())) {
3567 I = OldExt;
3568 TPT.rollback(LastKnownGood);
Dan Gohman99429a02009-10-16 20:59:35 +00003569 return false;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003570 }
Dan Gohman99429a02009-10-16 20:59:35 +00003571
3572 // Check whether the target supports casts folded into loads.
3573 unsigned LType;
3574 if (isa<ZExtInst>(I))
3575 LType = ISD::ZEXTLOAD;
3576 else {
3577 assert(isa<SExtInst>(I) && "Unexpected ext type!");
3578 LType = ISD::SEXTLOAD;
3579 }
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00003580 if (TLI && !TLI->isLoadExtLegal(LType, VT, LoadVT)) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003581 I = OldExt;
3582 TPT.rollback(LastKnownGood);
Dan Gohman99429a02009-10-16 20:59:35 +00003583 return false;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003584 }
Dan Gohman99429a02009-10-16 20:59:35 +00003585
3586 // Move the extend into the same block as the load, so that SelectionDAG
3587 // can fold it.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003588 TPT.commit();
Dan Gohman99429a02009-10-16 20:59:35 +00003589 I->removeFromParent();
3590 I->insertAfter(LI);
Cameron Zwarichced753f2011-01-05 17:27:27 +00003591 ++NumExtsMoved;
Dan Gohman99429a02009-10-16 20:59:35 +00003592 return true;
3593}
3594
Evan Chengd3d80172007-12-05 23:58:20 +00003595bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
3596 BasicBlock *DefBB = I->getParent();
3597
Bob Wilsonff714f92010-09-21 21:44:14 +00003598 // If the result of a {s|z}ext and its source are both live out, rewrite all
Evan Chengd3d80172007-12-05 23:58:20 +00003599 // other uses of the source with result of extension.
3600 Value *Src = I->getOperand(0);
3601 if (Src->hasOneUse())
3602 return false;
3603
Evan Cheng2011df42007-12-13 07:50:36 +00003604 // Only do this xform if truncating is free.
Gabor Greifaa261722008-02-26 19:13:21 +00003605 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
Evan Cheng37c36ed2007-12-13 03:32:53 +00003606 return false;
3607
Evan Cheng7bc89422007-12-12 00:51:06 +00003608 // Only safe to perform the optimization if the source is also defined in
Evan Cheng63d33cf2007-12-12 02:53:41 +00003609 // this block.
3610 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
Evan Cheng7bc89422007-12-12 00:51:06 +00003611 return false;
3612
Evan Chengd3d80172007-12-05 23:58:20 +00003613 bool DefIsLiveOut = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00003614 for (User *U : I->users()) {
3615 Instruction *UI = cast<Instruction>(U);
Evan Chengd3d80172007-12-05 23:58:20 +00003616
3617 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003618 BasicBlock *UserBB = UI->getParent();
Evan Chengd3d80172007-12-05 23:58:20 +00003619 if (UserBB == DefBB) continue;
3620 DefIsLiveOut = true;
3621 break;
3622 }
3623 if (!DefIsLiveOut)
3624 return false;
3625
Jim Grosbach0f38c1e2013-04-15 17:40:48 +00003626 // Make sure none of the uses are PHI nodes.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003627 for (User *U : Src->users()) {
3628 Instruction *UI = cast<Instruction>(U);
3629 BasicBlock *UserBB = UI->getParent();
Evan Cheng37c36ed2007-12-13 03:32:53 +00003630 if (UserBB == DefBB) continue;
3631 // Be conservative. We don't want this xform to end up introducing
3632 // reloads just before load / store instructions.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003633 if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI))
Evan Cheng63d33cf2007-12-12 02:53:41 +00003634 return false;
3635 }
3636
Evan Chengd3d80172007-12-05 23:58:20 +00003637 // InsertedTruncs - Only insert one trunc in each block once.
3638 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
3639
3640 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00003641 for (Use &U : Src->uses()) {
3642 Instruction *User = cast<Instruction>(U.getUser());
Evan Chengd3d80172007-12-05 23:58:20 +00003643
3644 // Figure out which BB this ext is used in.
3645 BasicBlock *UserBB = User->getParent();
3646 if (UserBB == DefBB) continue;
3647
3648 // Both src and def are live in this block. Rewrite the use.
3649 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
3650
3651 if (!InsertedTrunc) {
Bill Wendling8ddfc092011-08-16 20:45:24 +00003652 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Evan Chengd3d80172007-12-05 23:58:20 +00003653 InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003654 InsertedTruncsSet.insert(InsertedTrunc);
Evan Chengd3d80172007-12-05 23:58:20 +00003655 }
3656
3657 // Replace a use of the {s|z}ext source with a use of the result.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003658 U = InsertedTrunc;
Cameron Zwarichced753f2011-01-05 17:27:27 +00003659 ++NumExtUses;
Evan Chengd3d80172007-12-05 23:58:20 +00003660 MadeChange = true;
3661 }
3662
3663 return MadeChange;
3664}
3665
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00003666/// isFormingBranchFromSelectProfitable - Returns true if a SelectInst should be
3667/// turned into an explicit branch.
3668static bool isFormingBranchFromSelectProfitable(SelectInst *SI) {
3669 // FIXME: This should use the same heuristics as IfConversion to determine
3670 // whether a select is better represented as a branch. This requires that
3671 // branch probability metadata is preserved for the select, which is not the
3672 // case currently.
3673
3674 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
3675
3676 // If the branch is predicted right, an out of order CPU can avoid blocking on
3677 // the compare. Emit cmovs on compares with a memory operand as branches to
3678 // avoid stalls on the load from memory. If the compare has more than one use
3679 // there's probably another cmov or setcc around so it's not worth emitting a
3680 // branch.
3681 if (!Cmp)
3682 return false;
3683
3684 Value *CmpOp0 = Cmp->getOperand(0);
3685 Value *CmpOp1 = Cmp->getOperand(1);
3686
3687 // We check that the memory operand has one use to avoid uses of the loaded
3688 // value directly after the compare, making branches unprofitable.
3689 return Cmp->hasOneUse() &&
3690 ((isa<LoadInst>(CmpOp0) && CmpOp0->hasOneUse()) ||
3691 (isa<LoadInst>(CmpOp1) && CmpOp1->hasOneUse()));
3692}
3693
3694
Nadav Rotem9d832022012-09-02 12:10:19 +00003695/// If we have a SelectInst that will likely profit from branch prediction,
3696/// turn it into a branch.
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00003697bool CodeGenPrepare::OptimizeSelectInst(SelectInst *SI) {
Nadav Rotem9d832022012-09-02 12:10:19 +00003698 bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
3699
3700 // Can we convert the 'select' to CF ?
3701 if (DisableSelectToBranch || OptSize || !TLI || VectorCond)
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00003702 return false;
3703
Nadav Rotem9d832022012-09-02 12:10:19 +00003704 TargetLowering::SelectSupportKind SelectKind;
3705 if (VectorCond)
3706 SelectKind = TargetLowering::VectorMaskSelect;
3707 else if (SI->getType()->isVectorTy())
3708 SelectKind = TargetLowering::ScalarCondVectorVal;
3709 else
3710 SelectKind = TargetLowering::ScalarValSelect;
3711
3712 // Do we have efficient codegen support for this kind of 'selects' ?
3713 if (TLI->isSelectSupported(SelectKind)) {
3714 // We have efficient codegen support for the select instruction.
3715 // Check if it is profitable to keep this 'select'.
3716 if (!TLI->isPredictableSelectExpensive() ||
3717 !isFormingBranchFromSelectProfitable(SI))
3718 return false;
3719 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00003720
3721 ModifiedDT = true;
3722
3723 // First, we split the block containing the select into 2 blocks.
3724 BasicBlock *StartBlock = SI->getParent();
3725 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(SI));
3726 BasicBlock *NextBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
3727
3728 // Create a new block serving as the landing pad for the branch.
3729 BasicBlock *SmallBlock = BasicBlock::Create(SI->getContext(), "select.mid",
3730 NextBlock->getParent(), NextBlock);
3731
3732 // Move the unconditional branch from the block with the select in it into our
3733 // landing pad block.
3734 StartBlock->getTerminator()->eraseFromParent();
3735 BranchInst::Create(NextBlock, SmallBlock);
3736
3737 // Insert the real conditional branch based on the original condition.
3738 BranchInst::Create(NextBlock, SmallBlock, SI->getCondition(), SI);
3739
3740 // The select itself is replaced with a PHI Node.
3741 PHINode *PN = PHINode::Create(SI->getType(), 2, "", NextBlock->begin());
3742 PN->takeName(SI);
3743 PN->addIncoming(SI->getTrueValue(), StartBlock);
3744 PN->addIncoming(SI->getFalseValue(), SmallBlock);
3745 SI->replaceAllUsesWith(PN);
3746 SI->eraseFromParent();
3747
3748 // Instruct OptimizeBlock to skip to the next block.
3749 CurInstIterator = StartBlock->end();
3750 ++NumSelectsExpanded;
3751 return true;
3752}
3753
Benjamin Kramer573ff362014-03-01 17:24:40 +00003754static bool isBroadcastShuffle(ShuffleVectorInst *SVI) {
Tim Northoveraeb8e062014-02-19 10:02:43 +00003755 SmallVector<int, 16> Mask(SVI->getShuffleMask());
3756 int SplatElem = -1;
3757 for (unsigned i = 0; i < Mask.size(); ++i) {
3758 if (SplatElem != -1 && Mask[i] != -1 && Mask[i] != SplatElem)
3759 return false;
3760 SplatElem = Mask[i];
3761 }
3762
3763 return true;
3764}
3765
3766/// Some targets have expensive vector shifts if the lanes aren't all the same
3767/// (e.g. x86 only introduced "vpsllvd" and friends with AVX2). In these cases
3768/// it's often worth sinking a shufflevector splat down to its use so that
3769/// codegen can spot all lanes are identical.
3770bool CodeGenPrepare::OptimizeShuffleVectorInst(ShuffleVectorInst *SVI) {
3771 BasicBlock *DefBB = SVI->getParent();
3772
3773 // Only do this xform if variable vector shifts are particularly expensive.
3774 if (!TLI || !TLI->isVectorShiftByScalarCheap(SVI->getType()))
3775 return false;
3776
3777 // We only expect better codegen by sinking a shuffle if we can recognise a
3778 // constant splat.
3779 if (!isBroadcastShuffle(SVI))
3780 return false;
3781
3782 // InsertedShuffles - Only insert a shuffle in each block once.
3783 DenseMap<BasicBlock*, Instruction*> InsertedShuffles;
3784
3785 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00003786 for (User *U : SVI->users()) {
3787 Instruction *UI = cast<Instruction>(U);
Tim Northoveraeb8e062014-02-19 10:02:43 +00003788
3789 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003790 BasicBlock *UserBB = UI->getParent();
Tim Northoveraeb8e062014-02-19 10:02:43 +00003791 if (UserBB == DefBB) continue;
3792
3793 // For now only apply this when the splat is used by a shift instruction.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003794 if (!UI->isShift()) continue;
Tim Northoveraeb8e062014-02-19 10:02:43 +00003795
3796 // Everything checks out, sink the shuffle if the user's block doesn't
3797 // already have a copy.
3798 Instruction *&InsertedShuffle = InsertedShuffles[UserBB];
3799
3800 if (!InsertedShuffle) {
3801 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
3802 InsertedShuffle = new ShuffleVectorInst(SVI->getOperand(0),
3803 SVI->getOperand(1),
3804 SVI->getOperand(2), "", InsertPt);
3805 }
3806
Chandler Carruthcdf47882014-03-09 03:16:01 +00003807 UI->replaceUsesOfWith(SVI, InsertedShuffle);
Tim Northoveraeb8e062014-02-19 10:02:43 +00003808 MadeChange = true;
3809 }
3810
3811 // If we removed all uses, nuke the shuffle.
3812 if (SVI->use_empty()) {
3813 SVI->eraseFromParent();
3814 MadeChange = true;
3815 }
3816
3817 return MadeChange;
3818}
3819
Quentin Colombetc32615d2014-10-31 17:52:53 +00003820namespace {
3821/// \brief Helper class to promote a scalar operation to a vector one.
3822/// This class is used to move downward extractelement transition.
3823/// E.g.,
3824/// a = vector_op <2 x i32>
3825/// b = extractelement <2 x i32> a, i32 0
3826/// c = scalar_op b
3827/// store c
3828///
3829/// =>
3830/// a = vector_op <2 x i32>
3831/// c = vector_op a (equivalent to scalar_op on the related lane)
3832/// * d = extractelement <2 x i32> c, i32 0
3833/// * store d
3834/// Assuming both extractelement and store can be combine, we get rid of the
3835/// transition.
3836class VectorPromoteHelper {
3837 /// Used to perform some checks on the legality of vector operations.
3838 const TargetLowering &TLI;
3839
3840 /// Used to estimated the cost of the promoted chain.
3841 const TargetTransformInfo &TTI;
3842
3843 /// The transition being moved downwards.
3844 Instruction *Transition;
3845 /// The sequence of instructions to be promoted.
3846 SmallVector<Instruction *, 4> InstsToBePromoted;
3847 /// Cost of combining a store and an extract.
3848 unsigned StoreExtractCombineCost;
3849 /// Instruction that will be combined with the transition.
3850 Instruction *CombineInst;
3851
3852 /// \brief The instruction that represents the current end of the transition.
3853 /// Since we are faking the promotion until we reach the end of the chain
3854 /// of computation, we need a way to get the current end of the transition.
3855 Instruction *getEndOfTransition() const {
3856 if (InstsToBePromoted.empty())
3857 return Transition;
3858 return InstsToBePromoted.back();
3859 }
3860
3861 /// \brief Return the index of the original value in the transition.
3862 /// E.g., for "extractelement <2 x i32> c, i32 1" the original value,
3863 /// c, is at index 0.
3864 unsigned getTransitionOriginalValueIdx() const {
3865 assert(isa<ExtractElementInst>(Transition) &&
3866 "Other kind of transitions are not supported yet");
3867 return 0;
3868 }
3869
3870 /// \brief Return the index of the index in the transition.
3871 /// E.g., for "extractelement <2 x i32> c, i32 0" the index
3872 /// is at index 1.
3873 unsigned getTransitionIdx() const {
3874 assert(isa<ExtractElementInst>(Transition) &&
3875 "Other kind of transitions are not supported yet");
3876 return 1;
3877 }
3878
3879 /// \brief Get the type of the transition.
3880 /// This is the type of the original value.
3881 /// E.g., for "extractelement <2 x i32> c, i32 1" the type of the
3882 /// transition is <2 x i32>.
3883 Type *getTransitionType() const {
3884 return Transition->getOperand(getTransitionOriginalValueIdx())->getType();
3885 }
3886
3887 /// \brief Promote \p ToBePromoted by moving \p Def downward through.
3888 /// I.e., we have the following sequence:
3889 /// Def = Transition <ty1> a to <ty2>
3890 /// b = ToBePromoted <ty2> Def, ...
3891 /// =>
3892 /// b = ToBePromoted <ty1> a, ...
3893 /// Def = Transition <ty1> ToBePromoted to <ty2>
3894 void promoteImpl(Instruction *ToBePromoted);
3895
3896 /// \brief Check whether or not it is profitable to promote all the
3897 /// instructions enqueued to be promoted.
3898 bool isProfitableToPromote() {
3899 Value *ValIdx = Transition->getOperand(getTransitionOriginalValueIdx());
3900 unsigned Index = isa<ConstantInt>(ValIdx)
3901 ? cast<ConstantInt>(ValIdx)->getZExtValue()
3902 : -1;
3903 Type *PromotedType = getTransitionType();
3904
3905 StoreInst *ST = cast<StoreInst>(CombineInst);
3906 unsigned AS = ST->getPointerAddressSpace();
3907 unsigned Align = ST->getAlignment();
3908 // Check if this store is supported.
3909 if (!TLI.allowsMisalignedMemoryAccesses(
Ahmed Bougacha026600d2014-11-12 23:05:03 +00003910 TLI.getValueType(ST->getValueOperand()->getType()), AS, Align)) {
Quentin Colombetc32615d2014-10-31 17:52:53 +00003911 // If this is not supported, there is no way we can combine
3912 // the extract with the store.
3913 return false;
3914 }
3915
3916 // The scalar chain of computation has to pay for the transition
3917 // scalar to vector.
3918 // The vector chain has to account for the combining cost.
3919 uint64_t ScalarCost =
3920 TTI.getVectorInstrCost(Transition->getOpcode(), PromotedType, Index);
3921 uint64_t VectorCost = StoreExtractCombineCost;
3922 for (const auto &Inst : InstsToBePromoted) {
3923 // Compute the cost.
3924 // By construction, all instructions being promoted are arithmetic ones.
3925 // Moreover, one argument is a constant that can be viewed as a splat
3926 // constant.
3927 Value *Arg0 = Inst->getOperand(0);
3928 bool IsArg0Constant = isa<UndefValue>(Arg0) || isa<ConstantInt>(Arg0) ||
3929 isa<ConstantFP>(Arg0);
3930 TargetTransformInfo::OperandValueKind Arg0OVK =
3931 IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
3932 : TargetTransformInfo::OK_AnyValue;
3933 TargetTransformInfo::OperandValueKind Arg1OVK =
3934 !IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
3935 : TargetTransformInfo::OK_AnyValue;
3936 ScalarCost += TTI.getArithmeticInstrCost(
3937 Inst->getOpcode(), Inst->getType(), Arg0OVK, Arg1OVK);
3938 VectorCost += TTI.getArithmeticInstrCost(Inst->getOpcode(), PromotedType,
3939 Arg0OVK, Arg1OVK);
3940 }
3941 DEBUG(dbgs() << "Estimated cost of computation to be promoted:\nScalar: "
3942 << ScalarCost << "\nVector: " << VectorCost << '\n');
3943 return ScalarCost > VectorCost;
3944 }
3945
3946 /// \brief Generate a constant vector with \p Val with the same
3947 /// number of elements as the transition.
3948 /// \p UseSplat defines whether or not \p Val should be replicated
3949 /// accross the whole vector.
3950 /// In other words, if UseSplat == true, we generate <Val, Val, ..., Val>,
3951 /// otherwise we generate a vector with as many undef as possible:
3952 /// <undef, ..., undef, Val, undef, ..., undef> where \p Val is only
3953 /// used at the index of the extract.
3954 Value *getConstantVector(Constant *Val, bool UseSplat) const {
3955 unsigned ExtractIdx = UINT_MAX;
3956 if (!UseSplat) {
3957 // If we cannot determine where the constant must be, we have to
3958 // use a splat constant.
3959 Value *ValExtractIdx = Transition->getOperand(getTransitionIdx());
3960 if (ConstantInt *CstVal = dyn_cast<ConstantInt>(ValExtractIdx))
3961 ExtractIdx = CstVal->getSExtValue();
3962 else
3963 UseSplat = true;
3964 }
3965
3966 unsigned End = getTransitionType()->getVectorNumElements();
3967 if (UseSplat)
3968 return ConstantVector::getSplat(End, Val);
3969
3970 SmallVector<Constant *, 4> ConstVec;
3971 UndefValue *UndefVal = UndefValue::get(Val->getType());
3972 for (unsigned Idx = 0; Idx != End; ++Idx) {
3973 if (Idx == ExtractIdx)
3974 ConstVec.push_back(Val);
3975 else
3976 ConstVec.push_back(UndefVal);
3977 }
3978 return ConstantVector::get(ConstVec);
3979 }
3980
3981 /// \brief Check if promoting to a vector type an operand at \p OperandIdx
3982 /// in \p Use can trigger undefined behavior.
3983 static bool canCauseUndefinedBehavior(const Instruction *Use,
3984 unsigned OperandIdx) {
3985 // This is not safe to introduce undef when the operand is on
3986 // the right hand side of a division-like instruction.
3987 if (OperandIdx != 1)
3988 return false;
3989 switch (Use->getOpcode()) {
3990 default:
3991 return false;
3992 case Instruction::SDiv:
3993 case Instruction::UDiv:
3994 case Instruction::SRem:
3995 case Instruction::URem:
3996 return true;
3997 case Instruction::FDiv:
3998 case Instruction::FRem:
3999 return !Use->hasNoNaNs();
4000 }
4001 llvm_unreachable(nullptr);
4002 }
4003
4004public:
4005 VectorPromoteHelper(const TargetLowering &TLI, const TargetTransformInfo &TTI,
4006 Instruction *Transition, unsigned CombineCost)
4007 : TLI(TLI), TTI(TTI), Transition(Transition),
4008 StoreExtractCombineCost(CombineCost), CombineInst(nullptr) {
4009 assert(Transition && "Do not know how to promote null");
4010 }
4011
4012 /// \brief Check if we can promote \p ToBePromoted to \p Type.
4013 bool canPromote(const Instruction *ToBePromoted) const {
4014 // We could support CastInst too.
4015 return isa<BinaryOperator>(ToBePromoted);
4016 }
4017
4018 /// \brief Check if it is profitable to promote \p ToBePromoted
4019 /// by moving downward the transition through.
4020 bool shouldPromote(const Instruction *ToBePromoted) const {
4021 // Promote only if all the operands can be statically expanded.
4022 // Indeed, we do not want to introduce any new kind of transitions.
4023 for (const Use &U : ToBePromoted->operands()) {
4024 const Value *Val = U.get();
4025 if (Val == getEndOfTransition()) {
4026 // If the use is a division and the transition is on the rhs,
4027 // we cannot promote the operation, otherwise we may create a
4028 // division by zero.
4029 if (canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()))
4030 return false;
4031 continue;
4032 }
4033 if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) &&
4034 !isa<ConstantFP>(Val))
4035 return false;
4036 }
4037 // Check that the resulting operation is legal.
4038 int ISDOpcode = TLI.InstructionOpcodeToISD(ToBePromoted->getOpcode());
4039 if (!ISDOpcode)
4040 return false;
4041 return StressStoreExtract ||
Ahmed Bougacha026600d2014-11-12 23:05:03 +00004042 TLI.isOperationLegalOrCustom(
4043 ISDOpcode, TLI.getValueType(getTransitionType(), true));
Quentin Colombetc32615d2014-10-31 17:52:53 +00004044 }
4045
4046 /// \brief Check whether or not \p Use can be combined
4047 /// with the transition.
4048 /// I.e., is it possible to do Use(Transition) => AnotherUse?
4049 bool canCombine(const Instruction *Use) { return isa<StoreInst>(Use); }
4050
4051 /// \brief Record \p ToBePromoted as part of the chain to be promoted.
4052 void enqueueForPromotion(Instruction *ToBePromoted) {
4053 InstsToBePromoted.push_back(ToBePromoted);
4054 }
4055
4056 /// \brief Set the instruction that will be combined with the transition.
4057 void recordCombineInstruction(Instruction *ToBeCombined) {
4058 assert(canCombine(ToBeCombined) && "Unsupported instruction to combine");
4059 CombineInst = ToBeCombined;
4060 }
4061
4062 /// \brief Promote all the instructions enqueued for promotion if it is
4063 /// is profitable.
4064 /// \return True if the promotion happened, false otherwise.
4065 bool promote() {
4066 // Check if there is something to promote.
4067 // Right now, if we do not have anything to combine with,
4068 // we assume the promotion is not profitable.
4069 if (InstsToBePromoted.empty() || !CombineInst)
4070 return false;
4071
4072 // Check cost.
4073 if (!StressStoreExtract && !isProfitableToPromote())
4074 return false;
4075
4076 // Promote.
4077 for (auto &ToBePromoted : InstsToBePromoted)
4078 promoteImpl(ToBePromoted);
4079 InstsToBePromoted.clear();
4080 return true;
4081 }
4082};
4083} // End of anonymous namespace.
4084
4085void VectorPromoteHelper::promoteImpl(Instruction *ToBePromoted) {
4086 // At this point, we know that all the operands of ToBePromoted but Def
4087 // can be statically promoted.
4088 // For Def, we need to use its parameter in ToBePromoted:
4089 // b = ToBePromoted ty1 a
4090 // Def = Transition ty1 b to ty2
4091 // Move the transition down.
4092 // 1. Replace all uses of the promoted operation by the transition.
4093 // = ... b => = ... Def.
4094 assert(ToBePromoted->getType() == Transition->getType() &&
4095 "The type of the result of the transition does not match "
4096 "the final type");
4097 ToBePromoted->replaceAllUsesWith(Transition);
4098 // 2. Update the type of the uses.
4099 // b = ToBePromoted ty2 Def => b = ToBePromoted ty1 Def.
4100 Type *TransitionTy = getTransitionType();
4101 ToBePromoted->mutateType(TransitionTy);
4102 // 3. Update all the operands of the promoted operation with promoted
4103 // operands.
4104 // b = ToBePromoted ty1 Def => b = ToBePromoted ty1 a.
4105 for (Use &U : ToBePromoted->operands()) {
4106 Value *Val = U.get();
4107 Value *NewVal = nullptr;
4108 if (Val == Transition)
4109 NewVal = Transition->getOperand(getTransitionOriginalValueIdx());
4110 else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) ||
4111 isa<ConstantFP>(Val)) {
4112 // Use a splat constant if it is not safe to use undef.
4113 NewVal = getConstantVector(
4114 cast<Constant>(Val),
4115 isa<UndefValue>(Val) ||
4116 canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()));
4117 } else
Craig Topperd3c02f12015-01-05 10:15:49 +00004118 llvm_unreachable("Did you modified shouldPromote and forgot to update "
4119 "this?");
Quentin Colombetc32615d2014-10-31 17:52:53 +00004120 ToBePromoted->setOperand(U.getOperandNo(), NewVal);
4121 }
4122 Transition->removeFromParent();
4123 Transition->insertAfter(ToBePromoted);
4124 Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted);
4125}
4126
4127/// Some targets can do store(extractelement) with one instruction.
4128/// Try to push the extractelement towards the stores when the target
4129/// has this feature and this is profitable.
4130bool CodeGenPrepare::OptimizeExtractElementInst(Instruction *Inst) {
4131 unsigned CombineCost = UINT_MAX;
4132 if (DisableStoreExtract || !TLI ||
4133 (!StressStoreExtract &&
4134 !TLI->canCombineStoreAndExtract(Inst->getOperand(0)->getType(),
4135 Inst->getOperand(1), CombineCost)))
4136 return false;
4137
4138 // At this point we know that Inst is a vector to scalar transition.
4139 // Try to move it down the def-use chain, until:
4140 // - We can combine the transition with its single use
4141 // => we got rid of the transition.
4142 // - We escape the current basic block
4143 // => we would need to check that we are moving it at a cheaper place and
4144 // we do not do that for now.
4145 BasicBlock *Parent = Inst->getParent();
4146 DEBUG(dbgs() << "Found an interesting transition: " << *Inst << '\n');
4147 VectorPromoteHelper VPH(*TLI, *TTI, Inst, CombineCost);
4148 // If the transition has more than one use, assume this is not going to be
4149 // beneficial.
4150 while (Inst->hasOneUse()) {
4151 Instruction *ToBePromoted = cast<Instruction>(*Inst->user_begin());
4152 DEBUG(dbgs() << "Use: " << *ToBePromoted << '\n');
4153
4154 if (ToBePromoted->getParent() != Parent) {
4155 DEBUG(dbgs() << "Instruction to promote is in a different block ("
4156 << ToBePromoted->getParent()->getName()
4157 << ") than the transition (" << Parent->getName() << ").\n");
4158 return false;
4159 }
4160
4161 if (VPH.canCombine(ToBePromoted)) {
4162 DEBUG(dbgs() << "Assume " << *Inst << '\n'
4163 << "will be combined with: " << *ToBePromoted << '\n');
4164 VPH.recordCombineInstruction(ToBePromoted);
4165 bool Changed = VPH.promote();
4166 NumStoreExtractExposed += Changed;
4167 return Changed;
4168 }
4169
4170 DEBUG(dbgs() << "Try promoting.\n");
4171 if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted))
4172 return false;
4173
4174 DEBUG(dbgs() << "Promoting is possible... Enqueue for promotion!\n");
4175
4176 VPH.enqueueForPromotion(ToBePromoted);
4177 Inst = ToBePromoted;
4178 }
4179 return false;
4180}
4181
Elena Demikhovsky87700a72014-12-28 08:54:45 +00004182bool CodeGenPrepare::OptimizeInst(Instruction *I, bool& ModifiedDT) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00004183 if (PHINode *P = dyn_cast<PHINode>(I)) {
4184 // It is possible for very late stage optimizations (such as SimplifyCFG)
4185 // to introduce PHI nodes too late to be cleaned up. If we detect such a
4186 // trivial PHI, go ahead and zap it here.
Craig Topperc0196b12014-04-14 00:51:57 +00004187 if (Value *V = SimplifyInstruction(P, TLI ? TLI->getDataLayout() : nullptr,
Benjamin Kramer30d249a2013-09-24 16:37:40 +00004188 TLInfo, DT)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00004189 P->replaceAllUsesWith(V);
4190 P->eraseFromParent();
4191 ++NumPHIsElim;
Chris Lattneree588de2011-01-15 07:29:01 +00004192 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00004193 }
Chris Lattneree588de2011-01-15 07:29:01 +00004194 return false;
4195 }
Nadav Rotem465834c2012-07-24 10:51:42 +00004196
Chris Lattneree588de2011-01-15 07:29:01 +00004197 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00004198 // If the source of the cast is a constant, then this should have
4199 // already been constant folded. The only reason NOT to constant fold
4200 // it is if something (e.g. LSR) was careful to place the constant
4201 // evaluation in a block other than then one that uses it (e.g. to hoist
4202 // the address of globals out of a loop). If this is the case, we don't
4203 // want to forward-subst the cast.
4204 if (isa<Constant>(CI->getOperand(0)))
4205 return false;
4206
Chris Lattneree588de2011-01-15 07:29:01 +00004207 if (TLI && OptimizeNoopCopyExpression(CI, *TLI))
4208 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00004209
Chris Lattneree588de2011-01-15 07:29:01 +00004210 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +00004211 /// Sink a zext or sext into its user blocks if the target type doesn't
4212 /// fit in one register
4213 if (TLI && TLI->getTypeAction(CI->getContext(),
4214 TLI->getValueType(CI->getType())) ==
4215 TargetLowering::TypeExpandInteger) {
4216 return SinkCast(CI);
4217 } else {
4218 bool MadeChange = MoveExtToFormExtLoad(I);
4219 return MadeChange | OptimizeExtUses(I);
4220 }
Cameron Zwarich14ac8652011-01-06 02:37:26 +00004221 }
Chris Lattneree588de2011-01-15 07:29:01 +00004222 return false;
4223 }
Nadav Rotem465834c2012-07-24 10:51:42 +00004224
Chris Lattneree588de2011-01-15 07:29:01 +00004225 if (CmpInst *CI = dyn_cast<CmpInst>(I))
Hal Finkeldecb0242014-01-02 21:13:43 +00004226 if (!TLI || !TLI->hasMultipleConditionRegisters())
4227 return OptimizeCmpExpression(CI);
Nadav Rotem465834c2012-07-24 10:51:42 +00004228
Chris Lattneree588de2011-01-15 07:29:01 +00004229 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00004230 if (TLI)
Hans Wennborgf3254832012-10-30 11:23:25 +00004231 return OptimizeMemoryInst(I, I->getOperand(0), LI->getType());
4232 return false;
Chris Lattneree588de2011-01-15 07:29:01 +00004233 }
Nadav Rotem465834c2012-07-24 10:51:42 +00004234
Chris Lattneree588de2011-01-15 07:29:01 +00004235 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00004236 if (TLI)
Chris Lattneree588de2011-01-15 07:29:01 +00004237 return OptimizeMemoryInst(I, SI->getOperand(1),
4238 SI->getOperand(0)->getType());
4239 return false;
4240 }
Nadav Rotem465834c2012-07-24 10:51:42 +00004241
Yi Jiangd069f632014-04-21 19:34:27 +00004242 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I);
4243
4244 if (BinOp && (BinOp->getOpcode() == Instruction::AShr ||
4245 BinOp->getOpcode() == Instruction::LShr)) {
4246 ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1));
4247 if (TLI && CI && TLI->hasExtractBitsInsn())
4248 return OptimizeExtractBits(BinOp, CI, *TLI);
4249
4250 return false;
4251 }
4252
Chris Lattneree588de2011-01-15 07:29:01 +00004253 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00004254 if (GEPI->hasAllZeroIndices()) {
4255 /// The GEP operand must be a pointer, so must its result -> BitCast
4256 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
4257 GEPI->getName(), GEPI);
4258 GEPI->replaceAllUsesWith(NC);
4259 GEPI->eraseFromParent();
4260 ++NumGEPsElim;
Elena Demikhovsky87700a72014-12-28 08:54:45 +00004261 OptimizeInst(NC, ModifiedDT);
Chris Lattneree588de2011-01-15 07:29:01 +00004262 return true;
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00004263 }
Chris Lattneree588de2011-01-15 07:29:01 +00004264 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00004265 }
Nadav Rotem465834c2012-07-24 10:51:42 +00004266
Chris Lattneree588de2011-01-15 07:29:01 +00004267 if (CallInst *CI = dyn_cast<CallInst>(I))
Elena Demikhovsky87700a72014-12-28 08:54:45 +00004268 return OptimizeCallInst(CI, ModifiedDT);
Cameron Zwarich14ac8652011-01-06 02:37:26 +00004269
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004270 if (SelectInst *SI = dyn_cast<SelectInst>(I))
4271 return OptimizeSelectInst(SI);
4272
Tim Northoveraeb8e062014-02-19 10:02:43 +00004273 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I))
4274 return OptimizeShuffleVectorInst(SVI);
4275
Quentin Colombetc32615d2014-10-31 17:52:53 +00004276 if (isa<ExtractElementInst>(I))
4277 return OptimizeExtractElementInst(I);
4278
Chris Lattneree588de2011-01-15 07:29:01 +00004279 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00004280}
4281
Chris Lattnerf2836d12007-03-31 04:06:36 +00004282// In this pass we look for GEP and cast instructions that are used
4283// across basic blocks and rewrite them to improve basic-block-at-a-time
4284// selection.
Elena Demikhovsky87700a72014-12-28 08:54:45 +00004285bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB, bool& ModifiedDT) {
Cameron Zwarichce3b9302011-01-06 00:42:50 +00004286 SunkAddrs.clear();
Cameron Zwarich5dd2aa22011-03-02 03:31:46 +00004287 bool MadeChange = false;
Eric Christopherc1ea1492008-09-24 05:32:41 +00004288
Chris Lattner7a277142011-01-15 07:14:54 +00004289 CurInstIterator = BB.begin();
Elena Demikhovsky87700a72014-12-28 08:54:45 +00004290 while (CurInstIterator != BB.end()) {
4291 MadeChange |= OptimizeInst(CurInstIterator++, ModifiedDT);
4292 if (ModifiedDT)
4293 return true;
4294 }
Benjamin Kramer455fa352012-11-23 19:17:06 +00004295 MadeChange |= DupRetToEnableTailCallOpts(&BB);
4296
Chris Lattnerf2836d12007-03-31 04:06:36 +00004297 return MadeChange;
4298}
Devang Patel53771ba2011-08-18 00:50:51 +00004299
4300// llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotem465834c2012-07-24 10:51:42 +00004301// handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patel53771ba2011-08-18 00:50:51 +00004302// find a node corresponding to the value.
4303bool CodeGenPrepare::PlaceDbgValues(Function &F) {
4304 bool MadeChange = false;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +00004305 for (BasicBlock &BB : F) {
Craig Topperc0196b12014-04-14 00:51:57 +00004306 Instruction *PrevNonDbgInst = nullptr;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +00004307 for (BasicBlock::iterator BI = BB.begin(), BE = BB.end(); BI != BE;) {
Duncan P. N. Exon Smithe90f1162015-01-08 21:07:55 +00004308 Instruction *Insn = BI++;
Devang Patel53771ba2011-08-18 00:50:51 +00004309 DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
Adrian Prantl32da8892014-04-25 20:49:25 +00004310 // Leave dbg.values that refer to an alloca alone. These
4311 // instrinsics describe the address of a variable (= the alloca)
4312 // being taken. They should not be moved next to the alloca
4313 // (and to the beginning of the scope), but rather stay close to
4314 // where said address is used.
4315 if (!DVI || (DVI->getValue() && isa<AllocaInst>(DVI->getValue()))) {
Devang Patel53771ba2011-08-18 00:50:51 +00004316 PrevNonDbgInst = Insn;
4317 continue;
4318 }
4319
4320 Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
4321 if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
4322 DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
4323 DVI->removeFromParent();
4324 if (isa<PHINode>(VI))
4325 DVI->insertBefore(VI->getParent()->getFirstInsertionPt());
4326 else
4327 DVI->insertAfter(VI);
4328 MadeChange = true;
4329 ++NumDbgValueMoved;
4330 }
4331 }
4332 }
4333 return MadeChange;
4334}
Tim Northovercea0abb2014-03-29 08:22:29 +00004335
4336// If there is a sequence that branches based on comparing a single bit
4337// against zero that can be combined into a single instruction, and the
4338// target supports folding these into a single instruction, sink the
4339// mask and compare into the branch uses. Do this before OptimizeBlock ->
4340// OptimizeInst -> OptimizeCmpExpression, which perturbs the pattern being
4341// searched for.
4342bool CodeGenPrepare::sinkAndCmp(Function &F) {
4343 if (!EnableAndCmpSinking)
4344 return false;
4345 if (!TLI || !TLI->isMaskAndBranchFoldingLegal())
4346 return false;
4347 bool MadeChange = false;
4348 for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
4349 BasicBlock *BB = I++;
4350
4351 // Does this BB end with the following?
4352 // %andVal = and %val, #single-bit-set
4353 // %icmpVal = icmp %andResult, 0
4354 // br i1 %cmpVal label %dest1, label %dest2"
4355 BranchInst *Brcc = dyn_cast<BranchInst>(BB->getTerminator());
4356 if (!Brcc || !Brcc->isConditional())
4357 continue;
4358 ICmpInst *Cmp = dyn_cast<ICmpInst>(Brcc->getOperand(0));
4359 if (!Cmp || Cmp->getParent() != BB)
4360 continue;
4361 ConstantInt *Zero = dyn_cast<ConstantInt>(Cmp->getOperand(1));
4362 if (!Zero || !Zero->isZero())
4363 continue;
4364 Instruction *And = dyn_cast<Instruction>(Cmp->getOperand(0));
4365 if (!And || And->getOpcode() != Instruction::And || And->getParent() != BB)
4366 continue;
4367 ConstantInt* Mask = dyn_cast<ConstantInt>(And->getOperand(1));
4368 if (!Mask || !Mask->getUniqueInteger().isPowerOf2())
4369 continue;
4370 DEBUG(dbgs() << "found and; icmp ?,0; brcc\n"); DEBUG(BB->dump());
4371
4372 // Push the "and; icmp" for any users that are conditional branches.
4373 // Since there can only be one branch use per BB, we don't need to keep
4374 // track of which BBs we insert into.
4375 for (Value::use_iterator UI = Cmp->use_begin(), E = Cmp->use_end();
4376 UI != E; ) {
4377 Use &TheUse = *UI;
4378 // Find brcc use.
4379 BranchInst *BrccUser = dyn_cast<BranchInst>(*UI);
4380 ++UI;
4381 if (!BrccUser || !BrccUser->isConditional())
4382 continue;
4383 BasicBlock *UserBB = BrccUser->getParent();
4384 if (UserBB == BB) continue;
4385 DEBUG(dbgs() << "found Brcc use\n");
4386
4387 // Sink the "and; icmp" to use.
4388 MadeChange = true;
4389 BinaryOperator *NewAnd =
4390 BinaryOperator::CreateAnd(And->getOperand(0), And->getOperand(1), "",
4391 BrccUser);
4392 CmpInst *NewCmp =
4393 CmpInst::Create(Cmp->getOpcode(), Cmp->getPredicate(), NewAnd, Zero,
4394 "", BrccUser);
4395 TheUse = NewCmp;
4396 ++NumAndCmpsMoved;
4397 DEBUG(BrccUser->getParent()->dump());
4398 }
4399 }
4400 return MadeChange;
4401}
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00004402
Juergen Ributzka194350a2014-12-09 17:32:12 +00004403/// \brief Retrieve the probabilities of a conditional branch. Returns true on
4404/// success, or returns false if no or invalid metadata was found.
4405static bool extractBranchMetadata(BranchInst *BI,
4406 uint64_t &ProbTrue, uint64_t &ProbFalse) {
4407 assert(BI->isConditional() &&
4408 "Looking for probabilities on unconditional branch?");
4409 auto *ProfileData = BI->getMetadata(LLVMContext::MD_prof);
4410 if (!ProfileData || ProfileData->getNumOperands() != 3)
4411 return false;
4412
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004413 const auto *CITrue =
4414 mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(1));
4415 const auto *CIFalse =
4416 mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(2));
Juergen Ributzka194350a2014-12-09 17:32:12 +00004417 if (!CITrue || !CIFalse)
4418 return false;
4419
4420 ProbTrue = CITrue->getValue().getZExtValue();
4421 ProbFalse = CIFalse->getValue().getZExtValue();
4422
4423 return true;
4424}
4425
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00004426/// \brief Scale down both weights to fit into uint32_t.
4427static void scaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) {
4428 uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
4429 uint32_t Scale = (NewMax / UINT32_MAX) + 1;
4430 NewTrue = NewTrue / Scale;
4431 NewFalse = NewFalse / Scale;
4432}
4433
4434/// \brief Some targets prefer to split a conditional branch like:
4435/// \code
4436/// %0 = icmp ne i32 %a, 0
4437/// %1 = icmp ne i32 %b, 0
4438/// %or.cond = or i1 %0, %1
4439/// br i1 %or.cond, label %TrueBB, label %FalseBB
4440/// \endcode
4441/// into multiple branch instructions like:
4442/// \code
4443/// bb1:
4444/// %0 = icmp ne i32 %a, 0
4445/// br i1 %0, label %TrueBB, label %bb2
4446/// bb2:
4447/// %1 = icmp ne i32 %b, 0
4448/// br i1 %1, label %TrueBB, label %FalseBB
4449/// \endcode
4450/// This usually allows instruction selection to do even further optimizations
4451/// and combine the compare with the branch instruction. Currently this is
4452/// applied for targets which have "cheap" jump instructions.
4453///
4454/// FIXME: Remove the (equivalent?) implementation in SelectionDAG.
4455///
4456bool CodeGenPrepare::splitBranchCondition(Function &F) {
4457 if (!TM || TM->Options.EnableFastISel != true ||
4458 !TLI || TLI->isJumpExpensive())
4459 return false;
4460
4461 bool MadeChange = false;
4462 for (auto &BB : F) {
4463 // Does this BB end with the following?
4464 // %cond1 = icmp|fcmp|binary instruction ...
4465 // %cond2 = icmp|fcmp|binary instruction ...
4466 // %cond.or = or|and i1 %cond1, cond2
4467 // br i1 %cond.or label %dest1, label %dest2"
4468 BinaryOperator *LogicOp;
4469 BasicBlock *TBB, *FBB;
4470 if (!match(BB.getTerminator(), m_Br(m_OneUse(m_BinOp(LogicOp)), TBB, FBB)))
4471 continue;
4472
4473 unsigned Opc;
Juergen Ributzka8bda7382014-12-09 17:50:10 +00004474 Value *Cond1, *Cond2;
4475 if (match(LogicOp, m_And(m_OneUse(m_Value(Cond1)),
4476 m_OneUse(m_Value(Cond2)))))
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00004477 Opc = Instruction::And;
Juergen Ributzka8bda7382014-12-09 17:50:10 +00004478 else if (match(LogicOp, m_Or(m_OneUse(m_Value(Cond1)),
4479 m_OneUse(m_Value(Cond2)))))
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00004480 Opc = Instruction::Or;
4481 else
4482 continue;
4483
4484 if (!match(Cond1, m_CombineOr(m_Cmp(), m_BinOp())) ||
4485 !match(Cond2, m_CombineOr(m_Cmp(), m_BinOp())) )
4486 continue;
4487
4488 DEBUG(dbgs() << "Before branch condition splitting\n"; BB.dump());
4489
4490 // Create a new BB.
4491 auto *InsertBefore = std::next(Function::iterator(BB))
4492 .getNodePtrUnchecked();
4493 auto TmpBB = BasicBlock::Create(BB.getContext(),
4494 BB.getName() + ".cond.split",
4495 BB.getParent(), InsertBefore);
4496
4497 // Update original basic block by using the first condition directly by the
4498 // branch instruction and removing the no longer needed and/or instruction.
4499 auto *Br1 = cast<BranchInst>(BB.getTerminator());
4500 Br1->setCondition(Cond1);
4501 LogicOp->eraseFromParent();
Juergen Ributzka8bda7382014-12-09 17:50:10 +00004502
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00004503 // Depending on the conditon we have to either replace the true or the false
4504 // successor of the original branch instruction.
4505 if (Opc == Instruction::And)
4506 Br1->setSuccessor(0, TmpBB);
4507 else
4508 Br1->setSuccessor(1, TmpBB);
4509
4510 // Fill in the new basic block.
4511 auto *Br2 = IRBuilder<>(TmpBB).CreateCondBr(Cond2, TBB, FBB);
Juergen Ributzka8bda7382014-12-09 17:50:10 +00004512 if (auto *I = dyn_cast<Instruction>(Cond2)) {
4513 I->removeFromParent();
4514 I->insertBefore(Br2);
4515 }
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00004516
4517 // Update PHI nodes in both successors. The original BB needs to be
4518 // replaced in one succesor's PHI nodes, because the branch comes now from
4519 // the newly generated BB (NewBB). In the other successor we need to add one
4520 // incoming edge to the PHI nodes, because both branch instructions target
4521 // now the same successor. Depending on the original branch condition
4522 // (and/or) we have to swap the successors (TrueDest, FalseDest), so that
4523 // we perfrom the correct update for the PHI nodes.
4524 // This doesn't change the successor order of the just created branch
4525 // instruction (or any other instruction).
4526 if (Opc == Instruction::Or)
4527 std::swap(TBB, FBB);
4528
4529 // Replace the old BB with the new BB.
4530 for (auto &I : *TBB) {
4531 PHINode *PN = dyn_cast<PHINode>(&I);
4532 if (!PN)
4533 break;
4534 int i;
4535 while ((i = PN->getBasicBlockIndex(&BB)) >= 0)
4536 PN->setIncomingBlock(i, TmpBB);
4537 }
4538
4539 // Add another incoming edge form the new BB.
4540 for (auto &I : *FBB) {
4541 PHINode *PN = dyn_cast<PHINode>(&I);
4542 if (!PN)
4543 break;
4544 auto *Val = PN->getIncomingValueForBlock(&BB);
4545 PN->addIncoming(Val, TmpBB);
4546 }
4547
4548 // Update the branch weights (from SelectionDAGBuilder::
4549 // FindMergedConditions).
4550 if (Opc == Instruction::Or) {
4551 // Codegen X | Y as:
4552 // BB1:
4553 // jmp_if_X TBB
4554 // jmp TmpBB
4555 // TmpBB:
4556 // jmp_if_Y TBB
4557 // jmp FBB
4558 //
4559
4560 // We have flexibility in setting Prob for BB1 and Prob for NewBB.
4561 // The requirement is that
4562 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
4563 // = TrueProb for orignal BB.
4564 // Assuming the orignal weights are A and B, one choice is to set BB1's
4565 // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice
4566 // assumes that
4567 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
4568 // Another choice is to assume TrueProb for BB1 equals to TrueProb for
4569 // TmpBB, but the math is more complicated.
4570 uint64_t TrueWeight, FalseWeight;
Juergen Ributzka194350a2014-12-09 17:32:12 +00004571 if (extractBranchMetadata(Br1, TrueWeight, FalseWeight)) {
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00004572 uint64_t NewTrueWeight = TrueWeight;
4573 uint64_t NewFalseWeight = TrueWeight + 2 * FalseWeight;
4574 scaleWeights(NewTrueWeight, NewFalseWeight);
4575 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
4576 .createBranchWeights(TrueWeight, FalseWeight));
4577
4578 NewTrueWeight = TrueWeight;
4579 NewFalseWeight = 2 * FalseWeight;
4580 scaleWeights(NewTrueWeight, NewFalseWeight);
4581 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
4582 .createBranchWeights(TrueWeight, FalseWeight));
4583 }
4584 } else {
4585 // Codegen X & Y as:
4586 // BB1:
4587 // jmp_if_X TmpBB
4588 // jmp FBB
4589 // TmpBB:
4590 // jmp_if_Y TBB
4591 // jmp FBB
4592 //
4593 // This requires creation of TmpBB after CurBB.
4594
4595 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
4596 // The requirement is that
4597 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
4598 // = FalseProb for orignal BB.
4599 // Assuming the orignal weights are A and B, one choice is to set BB1's
4600 // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice
4601 // assumes that
4602 // FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB.
4603 uint64_t TrueWeight, FalseWeight;
Juergen Ributzka194350a2014-12-09 17:32:12 +00004604 if (extractBranchMetadata(Br1, TrueWeight, FalseWeight)) {
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00004605 uint64_t NewTrueWeight = 2 * TrueWeight + FalseWeight;
4606 uint64_t NewFalseWeight = FalseWeight;
4607 scaleWeights(NewTrueWeight, NewFalseWeight);
4608 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
4609 .createBranchWeights(TrueWeight, FalseWeight));
4610
4611 NewTrueWeight = 2 * TrueWeight;
4612 NewFalseWeight = FalseWeight;
4613 scaleWeights(NewTrueWeight, NewFalseWeight);
4614 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
4615 .createBranchWeights(TrueWeight, FalseWeight));
4616 }
4617 }
4618
4619 // Request DOM Tree update.
4620 // Note: No point in getting fancy here, since the DT info is never
4621 // available to CodeGenPrepare and the existing update code is broken
4622 // anyways.
4623 ModifiedDT = true;
4624
4625 MadeChange = true;
4626
4627 DEBUG(dbgs() << "After branch condition splitting\n"; BB.dump();
4628 TmpBB->dump());
4629 }
4630 return MadeChange;
4631}