blob: 367cff217346c76c0dde52ad4767ac5fb7dda802 [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);
Sanjoy Dasb8186762015-02-27 02:24:16 +0000564
565 // We're iterating over RelocateIdxMap so we cannot modify it.
566 auto MaybeBase = RelocateIdxMap.find(BaseKey);
567 if (MaybeBase == RelocateIdxMap.end())
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000568 // TODO: We might want to insert a new base object relocate and gep off
569 // that, if there are enough derived object relocates.
570 continue;
Sanjoy Dasb8186762015-02-27 02:24:16 +0000571
572 RelocateInstMap[MaybeBase->second].push_back(I);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000573 }
574}
575
576// Accepts a GEP and extracts the operands into a vector provided they're all
577// small integer constants
578static bool getGEPSmallConstantIntOffsetV(GetElementPtrInst *GEP,
579 SmallVectorImpl<Value *> &OffsetV) {
580 for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
581 // Only accept small constant integer operands
582 auto Op = dyn_cast<ConstantInt>(GEP->getOperand(i));
583 if (!Op || Op->getZExtValue() > 20)
584 return false;
585 }
586
587 for (unsigned i = 1; i < GEP->getNumOperands(); i++)
588 OffsetV.push_back(GEP->getOperand(i));
589 return true;
590}
591
592// Takes a RelocatedBase (base pointer relocation instruction) and Targets to
593// replace, computes a replacement, and affects it.
594static bool
595simplifyRelocatesOffABase(IntrinsicInst *RelocatedBase,
596 const SmallVectorImpl<IntrinsicInst *> &Targets) {
597 bool MadeChange = false;
598 for (auto &ToReplace : Targets) {
599 GCRelocateOperands MasterRelocate(RelocatedBase);
600 GCRelocateOperands ThisRelocate(ToReplace);
601
602 assert(ThisRelocate.basePtrIndex() == MasterRelocate.basePtrIndex() &&
603 "Not relocating a derived object of the original base object");
604 if (ThisRelocate.basePtrIndex() == ThisRelocate.derivedPtrIndex()) {
605 // A duplicate relocate call. TODO: coalesce duplicates.
606 continue;
607 }
608
609 Value *Base = ThisRelocate.basePtr();
610 auto Derived = dyn_cast<GetElementPtrInst>(ThisRelocate.derivedPtr());
611 if (!Derived || Derived->getPointerOperand() != Base)
612 continue;
613
614 SmallVector<Value *, 2> OffsetV;
615 if (!getGEPSmallConstantIntOffsetV(Derived, OffsetV))
616 continue;
617
618 // Create a Builder and replace the target callsite with a gep
619 IRBuilder<> Builder(ToReplace);
620 Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc());
621 Value *Replacement =
622 Builder.CreateGEP(RelocatedBase, makeArrayRef(OffsetV));
623 Instruction *ReplacementInst = cast<Instruction>(Replacement);
624 ReplacementInst->removeFromParent();
625 ReplacementInst->insertAfter(RelocatedBase);
626 Replacement->takeName(ToReplace);
627 ToReplace->replaceAllUsesWith(Replacement);
628 ToReplace->eraseFromParent();
629
630 MadeChange = true;
631 }
632 return MadeChange;
633}
634
635// Turns this:
636//
637// %base = ...
638// %ptr = gep %base + 15
639// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
640// %base' = relocate(%tok, i32 4, i32 4)
641// %ptr' = relocate(%tok, i32 4, i32 5)
642// %val = load %ptr'
643//
644// into this:
645//
646// %base = ...
647// %ptr = gep %base + 15
648// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
649// %base' = gc.relocate(%tok, i32 4, i32 4)
650// %ptr' = gep %base' + 15
651// %val = load %ptr'
652bool CodeGenPrepare::simplifyOffsetableRelocate(Instruction &I) {
653 bool MadeChange = false;
654 SmallVector<User *, 2> AllRelocateCalls;
655
656 for (auto *U : I.users())
657 if (isGCRelocate(dyn_cast<Instruction>(U)))
658 // Collect all the relocate calls associated with a statepoint
659 AllRelocateCalls.push_back(U);
660
661 // We need atleast one base pointer relocation + one derived pointer
662 // relocation to mangle
663 if (AllRelocateCalls.size() < 2)
664 return false;
665
666 // RelocateInstMap is a mapping from the base relocate instruction to the
667 // corresponding derived relocate instructions
668 DenseMap<IntrinsicInst *, SmallVector<IntrinsicInst *, 2>> RelocateInstMap;
669 computeBaseDerivedRelocateMap(AllRelocateCalls, RelocateInstMap);
670 if (RelocateInstMap.empty())
671 return false;
672
673 for (auto &Item : RelocateInstMap)
674 // Item.first is the RelocatedBase to offset against
675 // Item.second is the vector of Targets to replace
676 MadeChange = simplifyRelocatesOffABase(Item.first, Item.second);
677 return MadeChange;
678}
679
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000680/// SinkCast - Sink the specified cast instruction into its user blocks
681static bool SinkCast(CastInst *CI) {
Chris Lattnerf2836d12007-03-31 04:06:36 +0000682 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000683
Chris Lattnerf2836d12007-03-31 04:06:36 +0000684 /// InsertedCasts - Only insert a cast in each block once.
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000685 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000686
Chris Lattnerf2836d12007-03-31 04:06:36 +0000687 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000688 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
Chris Lattnerf2836d12007-03-31 04:06:36 +0000689 UI != E; ) {
690 Use &TheUse = UI.getUse();
691 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000692
Chris Lattnerf2836d12007-03-31 04:06:36 +0000693 // Figure out which BB this cast is used in. For PHI's this is the
694 // appropriate predecessor block.
695 BasicBlock *UserBB = User->getParent();
696 if (PHINode *PN = dyn_cast<PHINode>(User)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000697 UserBB = PN->getIncomingBlock(TheUse);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000698 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000699
Chris Lattnerf2836d12007-03-31 04:06:36 +0000700 // Preincrement use iterator so we don't invalidate it.
701 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000702
Chris Lattnerf2836d12007-03-31 04:06:36 +0000703 // If this user is in the same block as the cast, don't change the cast.
704 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000705
Chris Lattnerf2836d12007-03-31 04:06:36 +0000706 // If we have already inserted a cast into this block, use it.
707 CastInst *&InsertedCast = InsertedCasts[UserBB];
708
709 if (!InsertedCast) {
Bill Wendling8ddfc092011-08-16 20:45:24 +0000710 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000711 InsertedCast =
712 CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
Chris Lattnerf2836d12007-03-31 04:06:36 +0000713 InsertPt);
714 MadeChange = true;
715 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000716
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000717 // Replace a use of the cast with a use of the new cast.
Chris Lattnerf2836d12007-03-31 04:06:36 +0000718 TheUse = InsertedCast;
Cameron Zwarichced753f2011-01-05 17:27:27 +0000719 ++NumCastUses;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000720 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000721
Chris Lattnerf2836d12007-03-31 04:06:36 +0000722 // If we removed all uses, nuke the cast.
Duncan Sandsafa84da42008-01-20 16:51:46 +0000723 if (CI->use_empty()) {
Chris Lattnerf2836d12007-03-31 04:06:36 +0000724 CI->eraseFromParent();
Duncan Sandsafa84da42008-01-20 16:51:46 +0000725 MadeChange = true;
726 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000727
Chris Lattnerf2836d12007-03-31 04:06:36 +0000728 return MadeChange;
729}
730
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000731/// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
732/// copy (e.g. it's casting from one pointer type to another, i32->i8 on PPC),
733/// sink it into user blocks to reduce the number of virtual
734/// registers that must be created and coalesced.
735///
736/// Return true if any changes are made.
737///
738static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
739 // If this is a noop copy,
740 EVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
741 EVT DstVT = TLI.getValueType(CI->getType());
742
743 // This is an fp<->int conversion?
744 if (SrcVT.isInteger() != DstVT.isInteger())
745 return false;
746
747 // If this is an extension, it will be a zero or sign extension, which
748 // isn't a noop.
749 if (SrcVT.bitsLT(DstVT)) return false;
750
751 // If these values will be promoted, find out what they will be promoted
752 // to. This helps us consider truncates on PPC as noop copies when they
753 // are.
754 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
755 TargetLowering::TypePromoteInteger)
756 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
757 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
758 TargetLowering::TypePromoteInteger)
759 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
760
761 // If, after promotion, these are the same types, this is a noop copy.
762 if (SrcVT != DstVT)
763 return false;
764
765 return SinkCast(CI);
766}
767
Eric Christopherc1ea1492008-09-24 05:32:41 +0000768/// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000769/// the number of virtual registers that must be created and coalesced. This is
Chris Lattner27406942007-08-02 16:53:43 +0000770/// a clear win except on targets with multiple condition code registers
771/// (PowerPC), where it might lose; some adjustment may be wanted there.
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000772///
773/// Return true if any changes are made.
Chris Lattner6416a6b2008-11-24 22:44:16 +0000774static bool OptimizeCmpExpression(CmpInst *CI) {
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000775 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000776
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000777 /// InsertedCmp - Only insert a cmp in each block once.
778 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000779
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000780 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000781 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000782 UI != E; ) {
783 Use &TheUse = UI.getUse();
784 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000785
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000786 // Preincrement use iterator so we don't invalidate it.
787 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000788
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000789 // Don't bother for PHI nodes.
790 if (isa<PHINode>(User))
791 continue;
792
793 // Figure out which BB this cmp is used in.
794 BasicBlock *UserBB = User->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000795
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000796 // If this user is in the same block as the cmp, don't change the cmp.
797 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000798
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000799 // If we have already inserted a cmp into this block, use it.
800 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
801
802 if (!InsertedCmp) {
Bill Wendling8ddfc092011-08-16 20:45:24 +0000803 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000804 InsertedCmp =
Dan Gohmanad1f0a12009-08-25 23:17:54 +0000805 CmpInst::Create(CI->getOpcode(),
Owen Anderson1e5f00e2009-07-09 23:48:35 +0000806 CI->getPredicate(), CI->getOperand(0),
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000807 CI->getOperand(1), "", InsertPt);
808 MadeChange = true;
809 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000810
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000811 // Replace a use of the cmp with a use of the new cmp.
812 TheUse = InsertedCmp;
Cameron Zwarichced753f2011-01-05 17:27:27 +0000813 ++NumCmpUses;
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000814 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000815
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000816 // If we removed all uses, nuke the cmp.
817 if (CI->use_empty())
818 CI->eraseFromParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000819
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000820 return MadeChange;
821}
822
Yi Jiangd069f632014-04-21 19:34:27 +0000823/// isExtractBitsCandidateUse - Check if the candidates could
824/// be combined with shift instruction, which includes:
825/// 1. Truncate instruction
826/// 2. And instruction and the imm is a mask of the low bits:
827/// imm & (imm+1) == 0
Benjamin Kramer322053c2014-04-27 14:54:59 +0000828static bool isExtractBitsCandidateUse(Instruction *User) {
Yi Jiangd069f632014-04-21 19:34:27 +0000829 if (!isa<TruncInst>(User)) {
830 if (User->getOpcode() != Instruction::And ||
831 !isa<ConstantInt>(User->getOperand(1)))
832 return false;
833
Quentin Colombetd4f44692014-04-22 01:20:34 +0000834 const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue();
Yi Jiangd069f632014-04-21 19:34:27 +0000835
Quentin Colombetd4f44692014-04-22 01:20:34 +0000836 if ((Cimm & (Cimm + 1)).getBoolValue())
Yi Jiangd069f632014-04-21 19:34:27 +0000837 return false;
838 }
839 return true;
840}
841
842/// SinkShiftAndTruncate - sink both shift and truncate instruction
843/// to the use of truncate's BB.
Benjamin Kramer322053c2014-04-27 14:54:59 +0000844static bool
Yi Jiangd069f632014-04-21 19:34:27 +0000845SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI,
846 DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts,
847 const TargetLowering &TLI) {
848 BasicBlock *UserBB = User->getParent();
849 DenseMap<BasicBlock *, CastInst *> InsertedTruncs;
850 TruncInst *TruncI = dyn_cast<TruncInst>(User);
851 bool MadeChange = false;
852
853 for (Value::user_iterator TruncUI = TruncI->user_begin(),
854 TruncE = TruncI->user_end();
855 TruncUI != TruncE;) {
856
857 Use &TruncTheUse = TruncUI.getUse();
858 Instruction *TruncUser = cast<Instruction>(*TruncUI);
859 // Preincrement use iterator so we don't invalidate it.
860
861 ++TruncUI;
862
863 int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode());
864 if (!ISDOpcode)
865 continue;
866
Tim Northovere2239ff2014-07-29 10:20:22 +0000867 // If the use is actually a legal node, there will not be an
868 // implicit truncate.
869 // FIXME: always querying the result type is just an
870 // approximation; some nodes' legality is determined by the
871 // operand or other means. There's no good way to find out though.
Ahmed Bougacha0788d492014-11-12 22:16:55 +0000872 if (TLI.isOperationLegalOrCustom(
873 ISDOpcode, TLI.getValueType(TruncUser->getType(), true)))
Yi Jiangd069f632014-04-21 19:34:27 +0000874 continue;
875
876 // Don't bother for PHI nodes.
877 if (isa<PHINode>(TruncUser))
878 continue;
879
880 BasicBlock *TruncUserBB = TruncUser->getParent();
881
882 if (UserBB == TruncUserBB)
883 continue;
884
885 BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB];
886 CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB];
887
888 if (!InsertedShift && !InsertedTrunc) {
889 BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt();
890 // Sink the shift
891 if (ShiftI->getOpcode() == Instruction::AShr)
892 InsertedShift =
893 BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, "", InsertPt);
894 else
895 InsertedShift =
896 BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, "", InsertPt);
897
898 // Sink the trunc
899 BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt();
900 TruncInsertPt++;
901
902 InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift,
903 TruncI->getType(), "", TruncInsertPt);
904
905 MadeChange = true;
906
907 TruncTheUse = InsertedTrunc;
908 }
909 }
910 return MadeChange;
911}
912
913/// OptimizeExtractBits - sink the shift *right* instruction into user blocks if
914/// the uses could potentially be combined with this shift instruction and
915/// generate BitExtract instruction. It will only be applied if the architecture
916/// supports BitExtract instruction. Here is an example:
917/// BB1:
918/// %x.extract.shift = lshr i64 %arg1, 32
919/// BB2:
920/// %x.extract.trunc = trunc i64 %x.extract.shift to i16
921/// ==>
922///
923/// BB2:
924/// %x.extract.shift.1 = lshr i64 %arg1, 32
925/// %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16
926///
927/// CodeGen will recoginze the pattern in BB2 and generate BitExtract
928/// instruction.
929/// Return true if any changes are made.
930static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI,
931 const TargetLowering &TLI) {
932 BasicBlock *DefBB = ShiftI->getParent();
933
934 /// Only insert instructions in each block once.
935 DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts;
936
937 bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(ShiftI->getType()));
938
939 bool MadeChange = false;
940 for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end();
941 UI != E;) {
942 Use &TheUse = UI.getUse();
943 Instruction *User = cast<Instruction>(*UI);
944 // Preincrement use iterator so we don't invalidate it.
945 ++UI;
946
947 // Don't bother for PHI nodes.
948 if (isa<PHINode>(User))
949 continue;
950
951 if (!isExtractBitsCandidateUse(User))
952 continue;
953
954 BasicBlock *UserBB = User->getParent();
955
956 if (UserBB == DefBB) {
957 // If the shift and truncate instruction are in the same BB. The use of
958 // the truncate(TruncUse) may still introduce another truncate if not
959 // legal. In this case, we would like to sink both shift and truncate
960 // instruction to the BB of TruncUse.
961 // for example:
962 // BB1:
963 // i64 shift.result = lshr i64 opnd, imm
964 // trunc.result = trunc shift.result to i16
965 //
966 // BB2:
967 // ----> We will have an implicit truncate here if the architecture does
968 // not have i16 compare.
969 // cmp i16 trunc.result, opnd2
970 //
971 if (isa<TruncInst>(User) && shiftIsLegal
972 // If the type of the truncate is legal, no trucate will be
973 // introduced in other basic blocks.
974 && (!TLI.isTypeLegal(TLI.getValueType(User->getType()))))
975 MadeChange =
976 SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI);
977
978 continue;
979 }
980 // If we have already inserted a shift into this block, use it.
981 BinaryOperator *&InsertedShift = InsertedShifts[UserBB];
982
983 if (!InsertedShift) {
984 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
985
986 if (ShiftI->getOpcode() == Instruction::AShr)
987 InsertedShift =
988 BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, "", InsertPt);
989 else
990 InsertedShift =
991 BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, "", InsertPt);
992
993 MadeChange = true;
994 }
995
996 // Replace a use of the shift with a use of the new shift.
997 TheUse = InsertedShift;
998 }
999
1000 // If we removed all uses, nuke the shift.
1001 if (ShiftI->use_empty())
1002 ShiftI->eraseFromParent();
1003
1004 return MadeChange;
1005}
1006
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001007// ScalarizeMaskedLoad() translates masked load intrinsic, like
1008// <16 x i32 > @llvm.masked.load( <16 x i32>* %addr, i32 align,
1009// <16 x i1> %mask, <16 x i32> %passthru)
1010// to a chain of basic blocks, whith loading element one-by-one if
1011// the appropriate mask bit is set
1012//
1013// %1 = bitcast i8* %addr to i32*
1014// %2 = extractelement <16 x i1> %mask, i32 0
1015// %3 = icmp eq i1 %2, true
1016// br i1 %3, label %cond.load, label %else
1017//
1018//cond.load: ; preds = %0
1019// %4 = getelementptr i32* %1, i32 0
1020// %5 = load i32* %4
1021// %6 = insertelement <16 x i32> undef, i32 %5, i32 0
1022// br label %else
1023//
1024//else: ; preds = %0, %cond.load
1025// %res.phi.else = phi <16 x i32> [ %6, %cond.load ], [ undef, %0 ]
1026// %7 = extractelement <16 x i1> %mask, i32 1
1027// %8 = icmp eq i1 %7, true
1028// br i1 %8, label %cond.load1, label %else2
1029//
1030//cond.load1: ; preds = %else
1031// %9 = getelementptr i32* %1, i32 1
1032// %10 = load i32* %9
1033// %11 = insertelement <16 x i32> %res.phi.else, i32 %10, i32 1
1034// br label %else2
1035//
1036//else2: ; preds = %else, %cond.load1
1037// %res.phi.else3 = phi <16 x i32> [ %11, %cond.load1 ], [ %res.phi.else, %else ]
1038// %12 = extractelement <16 x i1> %mask, i32 2
1039// %13 = icmp eq i1 %12, true
1040// br i1 %13, label %cond.load4, label %else5
1041//
1042static void ScalarizeMaskedLoad(CallInst *CI) {
1043 Value *Ptr = CI->getArgOperand(0);
1044 Value *Src0 = CI->getArgOperand(3);
1045 Value *Mask = CI->getArgOperand(2);
1046 VectorType *VecType = dyn_cast<VectorType>(CI->getType());
1047 Type *EltTy = VecType->getElementType();
1048
1049 assert(VecType && "Unexpected return type of masked load intrinsic");
1050
1051 IRBuilder<> Builder(CI->getContext());
1052 Instruction *InsertPt = CI;
1053 BasicBlock *IfBlock = CI->getParent();
1054 BasicBlock *CondBlock = nullptr;
1055 BasicBlock *PrevIfBlock = CI->getParent();
1056 Builder.SetInsertPoint(InsertPt);
1057
1058 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1059
1060 // Bitcast %addr fron i8* to EltTy*
1061 Type *NewPtrType =
1062 EltTy->getPointerTo(cast<PointerType>(Ptr->getType())->getAddressSpace());
1063 Value *FirstEltPtr = Builder.CreateBitCast(Ptr, NewPtrType);
1064 Value *UndefVal = UndefValue::get(VecType);
1065
1066 // The result vector
1067 Value *VResult = UndefVal;
1068
1069 PHINode *Phi = nullptr;
1070 Value *PrevPhi = UndefVal;
1071
1072 unsigned VectorWidth = VecType->getNumElements();
1073 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1074
1075 // Fill the "else" block, created in the previous iteration
1076 //
1077 // %res.phi.else3 = phi <16 x i32> [ %11, %cond.load1 ], [ %res.phi.else, %else ]
1078 // %mask_1 = extractelement <16 x i1> %mask, i32 Idx
1079 // %to_load = icmp eq i1 %mask_1, true
1080 // br i1 %to_load, label %cond.load, label %else
1081 //
1082 if (Idx > 0) {
1083 Phi = Builder.CreatePHI(VecType, 2, "res.phi.else");
1084 Phi->addIncoming(VResult, CondBlock);
1085 Phi->addIncoming(PrevPhi, PrevIfBlock);
1086 PrevPhi = Phi;
1087 VResult = Phi;
1088 }
1089
1090 Value *Predicate = Builder.CreateExtractElement(Mask, Builder.getInt32(Idx));
1091 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
1092 ConstantInt::get(Predicate->getType(), 1));
1093
1094 // Create "cond" block
1095 //
1096 // %EltAddr = getelementptr i32* %1, i32 0
1097 // %Elt = load i32* %EltAddr
1098 // VResult = insertelement <16 x i32> VResult, i32 %Elt, i32 Idx
1099 //
1100 CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.load");
1101 Builder.SetInsertPoint(InsertPt);
1102
1103 Value* Gep = Builder.CreateInBoundsGEP(FirstEltPtr, Builder.getInt32(Idx));
1104 LoadInst* Load = Builder.CreateLoad(Gep, false);
1105 VResult = Builder.CreateInsertElement(VResult, Load, Builder.getInt32(Idx));
1106
1107 // Create "else" block, fill it in the next iteration
1108 BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
1109 Builder.SetInsertPoint(InsertPt);
1110 Instruction *OldBr = IfBlock->getTerminator();
1111 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1112 OldBr->eraseFromParent();
1113 PrevIfBlock = IfBlock;
1114 IfBlock = NewIfBlock;
1115 }
1116
1117 Phi = Builder.CreatePHI(VecType, 2, "res.phi.select");
1118 Phi->addIncoming(VResult, CondBlock);
1119 Phi->addIncoming(PrevPhi, PrevIfBlock);
1120 Value *NewI = Builder.CreateSelect(Mask, Phi, Src0);
1121 CI->replaceAllUsesWith(NewI);
1122 CI->eraseFromParent();
1123}
1124
1125// ScalarizeMaskedStore() translates masked store intrinsic, like
1126// void @llvm.masked.store(<16 x i32> %src, <16 x i32>* %addr, i32 align,
1127// <16 x i1> %mask)
1128// to a chain of basic blocks, that stores element one-by-one if
1129// the appropriate mask bit is set
1130//
1131// %1 = bitcast i8* %addr to i32*
1132// %2 = extractelement <16 x i1> %mask, i32 0
1133// %3 = icmp eq i1 %2, true
1134// br i1 %3, label %cond.store, label %else
1135//
1136// cond.store: ; preds = %0
1137// %4 = extractelement <16 x i32> %val, i32 0
1138// %5 = getelementptr i32* %1, i32 0
1139// store i32 %4, i32* %5
1140// br label %else
1141//
1142// else: ; preds = %0, %cond.store
1143// %6 = extractelement <16 x i1> %mask, i32 1
1144// %7 = icmp eq i1 %6, true
1145// br i1 %7, label %cond.store1, label %else2
1146//
1147// cond.store1: ; preds = %else
1148// %8 = extractelement <16 x i32> %val, i32 1
1149// %9 = getelementptr i32* %1, i32 1
1150// store i32 %8, i32* %9
1151// br label %else2
1152// . . .
1153static void ScalarizeMaskedStore(CallInst *CI) {
1154 Value *Ptr = CI->getArgOperand(1);
1155 Value *Src = CI->getArgOperand(0);
1156 Value *Mask = CI->getArgOperand(3);
1157
1158 VectorType *VecType = dyn_cast<VectorType>(Src->getType());
1159 Type *EltTy = VecType->getElementType();
1160
1161 assert(VecType && "Unexpected data type in masked store intrinsic");
1162
1163 IRBuilder<> Builder(CI->getContext());
1164 Instruction *InsertPt = CI;
1165 BasicBlock *IfBlock = CI->getParent();
1166 Builder.SetInsertPoint(InsertPt);
1167 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1168
1169 // Bitcast %addr fron i8* to EltTy*
1170 Type *NewPtrType =
1171 EltTy->getPointerTo(cast<PointerType>(Ptr->getType())->getAddressSpace());
1172 Value *FirstEltPtr = Builder.CreateBitCast(Ptr, NewPtrType);
1173
1174 unsigned VectorWidth = VecType->getNumElements();
1175 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1176
1177 // Fill the "else" block, created in the previous iteration
1178 //
1179 // %mask_1 = extractelement <16 x i1> %mask, i32 Idx
1180 // %to_store = icmp eq i1 %mask_1, true
1181 // br i1 %to_load, label %cond.store, label %else
1182 //
1183 Value *Predicate = Builder.CreateExtractElement(Mask, Builder.getInt32(Idx));
1184 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
1185 ConstantInt::get(Predicate->getType(), 1));
1186
1187 // Create "cond" block
1188 //
1189 // %OneElt = extractelement <16 x i32> %Src, i32 Idx
1190 // %EltAddr = getelementptr i32* %1, i32 0
1191 // %store i32 %OneElt, i32* %EltAddr
1192 //
1193 BasicBlock *CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store");
1194 Builder.SetInsertPoint(InsertPt);
1195
1196 Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx));
1197 Value* Gep = Builder.CreateInBoundsGEP(FirstEltPtr, Builder.getInt32(Idx));
1198 Builder.CreateStore(OneElt, Gep);
1199
1200 // Create "else" block, fill it in the next iteration
1201 BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
1202 Builder.SetInsertPoint(InsertPt);
1203 Instruction *OldBr = IfBlock->getTerminator();
1204 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1205 OldBr->eraseFromParent();
1206 IfBlock = NewIfBlock;
1207 }
1208 CI->eraseFromParent();
1209}
1210
1211bool CodeGenPrepare::OptimizeCallInst(CallInst *CI, bool& ModifiedDT) {
Chris Lattner7a277142011-01-15 07:14:54 +00001212 BasicBlock *BB = CI->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +00001213
Chris Lattner7a277142011-01-15 07:14:54 +00001214 // Lower inline assembly if we can.
1215 // If we found an inline asm expession, and if the target knows how to
1216 // lower it to normal LLVM code, do so now.
1217 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
1218 if (TLI->ExpandInlineAsm(CI)) {
1219 // Avoid invalidating the iterator.
1220 CurInstIterator = BB->begin();
1221 // Avoid processing instructions out of order, which could cause
1222 // reuse before a value is defined.
1223 SunkAddrs.clear();
1224 return true;
1225 }
1226 // Sink address computing for memory operands into the block.
1227 if (OptimizeInlineAsmInst(CI))
1228 return true;
1229 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001230
Eric Christopher4b7948e2010-03-11 02:41:03 +00001231 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001232 if (II) {
1233 switch (II->getIntrinsicID()) {
1234 default: break;
1235 case Intrinsic::objectsize: {
1236 // Lower all uses of llvm.objectsize.*
1237 bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
1238 Type *ReturnTy = CI->getType();
1239 Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
Nadav Rotem465834c2012-07-24 10:51:42 +00001240
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001241 // Substituting this can cause recursive simplifications, which can
1242 // invalidate our iterator. Use a WeakVH to hold onto it in case this
1243 // happens.
1244 WeakVH IterHandle(CurInstIterator);
Nadav Rotem465834c2012-07-24 10:51:42 +00001245
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001246 replaceAndRecursivelySimplify(CI, RetVal,
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001247 TLInfo, ModifiedDT ? nullptr : DT);
Chris Lattner1b93be52011-01-15 07:25:29 +00001248
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001249 // If the iterator instruction was recursively deleted, start over at the
1250 // start of the block.
1251 if (IterHandle != CurInstIterator) {
1252 CurInstIterator = BB->begin();
1253 SunkAddrs.clear();
1254 }
1255 return true;
Chris Lattner86d56c62011-01-18 20:53:04 +00001256 }
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001257 case Intrinsic::masked_load: {
1258 // Scalarize unsupported vector masked load
1259 if (!TTI->isLegalMaskedLoad(CI->getType(), 1)) {
1260 ScalarizeMaskedLoad(CI);
1261 ModifiedDT = true;
1262 return true;
1263 }
1264 return false;
1265 }
1266 case Intrinsic::masked_store: {
1267 if (!TTI->isLegalMaskedStore(CI->getArgOperand(0)->getType(), 1)) {
1268 ScalarizeMaskedStore(CI);
1269 ModifiedDT = true;
1270 return true;
1271 }
1272 return false;
1273 }
1274 }
Eric Christopher4b7948e2010-03-11 02:41:03 +00001275
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001276 if (TLI) {
1277 SmallVector<Value*, 2> PtrOps;
1278 Type *AccessTy;
1279 if (TLI->GetAddrModeArguments(II, PtrOps, AccessTy))
1280 while (!PtrOps.empty())
1281 if (OptimizeMemoryInst(II, PtrOps.pop_back_val(), AccessTy))
1282 return true;
1283 }
Pete Cooper615fd892012-03-13 20:59:56 +00001284 }
1285
Eric Christopher4b7948e2010-03-11 02:41:03 +00001286 // From here on out we're working with named functions.
Craig Topperc0196b12014-04-14 00:51:57 +00001287 if (!CI->getCalledFunction()) return false;
Devang Patel0da52502011-05-26 21:51:06 +00001288
Benjamin Kramer7b88a492010-03-12 09:27:41 +00001289 // Lower all default uses of _chk calls. This is very similar
1290 // to what InstCombineCalls does, but here we are only lowering calls
Ahmed Bougachae03bef72015-01-12 17:22:43 +00001291 // to fortified library functions (e.g. __memcpy_chk) that have the default
1292 // "don't know" as the objectsize. Anything else should be left alone.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001293 FortifiedLibCallSimplifier Simplifier(TLInfo, true);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00001294 if (Value *V = Simplifier.optimizeCall(CI)) {
1295 CI->replaceAllUsesWith(V);
1296 CI->eraseFromParent();
1297 return true;
1298 }
1299 return false;
Eric Christopher4b7948e2010-03-11 02:41:03 +00001300}
Chris Lattner1b93be52011-01-15 07:25:29 +00001301
Evan Cheng0663f232011-03-21 01:19:09 +00001302/// DupRetToEnableTailCallOpts - Look for opportunities to duplicate return
1303/// instructions to the predecessor to enable tail call optimizations. The
1304/// case it is currently looking for is:
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001305/// @code
Evan Cheng0663f232011-03-21 01:19:09 +00001306/// bb0:
1307/// %tmp0 = tail call i32 @f0()
1308/// br label %return
1309/// bb1:
1310/// %tmp1 = tail call i32 @f1()
1311/// br label %return
1312/// bb2:
1313/// %tmp2 = tail call i32 @f2()
1314/// br label %return
1315/// return:
1316/// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
1317/// ret i32 %retval
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001318/// @endcode
Evan Cheng0663f232011-03-21 01:19:09 +00001319///
1320/// =>
1321///
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001322/// @code
Evan Cheng0663f232011-03-21 01:19:09 +00001323/// bb0:
1324/// %tmp0 = tail call i32 @f0()
1325/// ret i32 %tmp0
1326/// bb1:
1327/// %tmp1 = tail call i32 @f1()
1328/// ret i32 %tmp1
1329/// bb2:
1330/// %tmp2 = tail call i32 @f2()
1331/// ret i32 %tmp2
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001332/// @endcode
Benjamin Kramer455fa352012-11-23 19:17:06 +00001333bool CodeGenPrepare::DupRetToEnableTailCallOpts(BasicBlock *BB) {
Cameron Zwarich47e71752011-03-24 04:51:51 +00001334 if (!TLI)
1335 return false;
1336
Benjamin Kramer455fa352012-11-23 19:17:06 +00001337 ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
1338 if (!RI)
1339 return false;
1340
Craig Topperc0196b12014-04-14 00:51:57 +00001341 PHINode *PN = nullptr;
1342 BitCastInst *BCI = nullptr;
Evan Cheng0663f232011-03-21 01:19:09 +00001343 Value *V = RI->getReturnValue();
Evan Cheng249716e2012-07-27 21:21:26 +00001344 if (V) {
1345 BCI = dyn_cast<BitCastInst>(V);
1346 if (BCI)
1347 V = BCI->getOperand(0);
1348
1349 PN = dyn_cast<PHINode>(V);
1350 if (!PN)
1351 return false;
1352 }
Evan Cheng0663f232011-03-21 01:19:09 +00001353
Cameron Zwarich4649f172011-03-24 04:52:10 +00001354 if (PN && PN->getParent() != BB)
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001355 return false;
Evan Cheng0663f232011-03-21 01:19:09 +00001356
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001357 // It's not safe to eliminate the sign / zero extension of the return value.
1358 // See llvm::isInTailCallPosition().
1359 const Function *F = BB->getParent();
Bill Wendling658d24d2013-01-18 21:53:16 +00001360 AttributeSet CallerAttrs = F->getAttributes();
1361 if (CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::ZExt) ||
1362 CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::SExt))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001363 return false;
Evan Cheng0663f232011-03-21 01:19:09 +00001364
Cameron Zwarich4649f172011-03-24 04:52:10 +00001365 // Make sure there are no instructions between the PHI and return, or that the
1366 // return is the first instruction in the block.
1367 if (PN) {
1368 BasicBlock::iterator BI = BB->begin();
1369 do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
Evan Cheng249716e2012-07-27 21:21:26 +00001370 if (&*BI == BCI)
1371 // Also skip over the bitcast.
1372 ++BI;
Cameron Zwarich4649f172011-03-24 04:52:10 +00001373 if (&*BI != RI)
1374 return false;
1375 } else {
Cameron Zwarich74157ab2011-03-24 16:34:59 +00001376 BasicBlock::iterator BI = BB->begin();
1377 while (isa<DbgInfoIntrinsic>(BI)) ++BI;
1378 if (&*BI != RI)
Cameron Zwarich4649f172011-03-24 04:52:10 +00001379 return false;
1380 }
Evan Cheng0663f232011-03-21 01:19:09 +00001381
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001382 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
1383 /// call.
1384 SmallVector<CallInst*, 4> TailCalls;
Cameron Zwarich4649f172011-03-24 04:52:10 +00001385 if (PN) {
1386 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
1387 CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
1388 // Make sure the phi value is indeed produced by the tail call.
1389 if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
1390 TLI->mayBeEmittedAsTailCall(CI))
1391 TailCalls.push_back(CI);
1392 }
1393 } else {
1394 SmallPtrSet<BasicBlock*, 4> VisitedBBs;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001395 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
David Blaikie70573dc2014-11-19 07:49:26 +00001396 if (!VisitedBBs.insert(*PI).second)
Cameron Zwarich4649f172011-03-24 04:52:10 +00001397 continue;
1398
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001399 BasicBlock::InstListType &InstList = (*PI)->getInstList();
Cameron Zwarich4649f172011-03-24 04:52:10 +00001400 BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
1401 BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
Cameron Zwarich74157ab2011-03-24 16:34:59 +00001402 do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
1403 if (RI == RE)
Cameron Zwarich4649f172011-03-24 04:52:10 +00001404 continue;
Cameron Zwarich74157ab2011-03-24 16:34:59 +00001405
Cameron Zwarich4649f172011-03-24 04:52:10 +00001406 CallInst *CI = dyn_cast<CallInst>(&*RI);
Cameron Zwarich2edfe772011-03-24 15:54:11 +00001407 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI))
Cameron Zwarich4649f172011-03-24 04:52:10 +00001408 TailCalls.push_back(CI);
1409 }
Evan Cheng0663f232011-03-21 01:19:09 +00001410 }
1411
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001412 bool Changed = false;
1413 for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
1414 CallInst *CI = TailCalls[i];
1415 CallSite CS(CI);
1416
1417 // Conservatively require the attributes of the call to match those of the
1418 // return. Ignore noalias because it doesn't affect the call sequence.
Bill Wendling658d24d2013-01-18 21:53:16 +00001419 AttributeSet CalleeAttrs = CS.getAttributes();
1420 if (AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001421 removeAttribute(Attribute::NoAlias) !=
Bill Wendling658d24d2013-01-18 21:53:16 +00001422 AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001423 removeAttribute(Attribute::NoAlias))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001424 continue;
1425
1426 // Make sure the call instruction is followed by an unconditional branch to
1427 // the return block.
1428 BasicBlock *CallBB = CI->getParent();
1429 BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
1430 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
1431 continue;
1432
1433 // Duplicate the return into CallBB.
1434 (void)FoldReturnIntoUncondBranch(RI, BB, CallBB);
Devang Patel8f606d72011-03-24 15:35:25 +00001435 ModifiedDT = Changed = true;
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001436 ++NumRetsDup;
1437 }
1438
1439 // If we eliminated all predecessors of the block, delete the block now.
Evan Cheng64a223a2012-09-28 23:58:57 +00001440 if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001441 BB->eraseFromParent();
1442
1443 return Changed;
Evan Cheng0663f232011-03-21 01:19:09 +00001444}
1445
Chris Lattner728f9022008-11-25 07:09:13 +00001446//===----------------------------------------------------------------------===//
Chris Lattner728f9022008-11-25 07:09:13 +00001447// Memory Optimization
1448//===----------------------------------------------------------------------===//
1449
Chandler Carruthc8925912013-01-05 02:09:22 +00001450namespace {
1451
1452/// ExtAddrMode - This is an extended version of TargetLowering::AddrMode
1453/// which holds actual Value*'s for register values.
Chandler Carruth95f83e02013-01-07 15:14:13 +00001454struct ExtAddrMode : public TargetLowering::AddrMode {
Chandler Carruthc8925912013-01-05 02:09:22 +00001455 Value *BaseReg;
1456 Value *ScaledReg;
Craig Topperc0196b12014-04-14 00:51:57 +00001457 ExtAddrMode() : BaseReg(nullptr), ScaledReg(nullptr) {}
Chandler Carruthc8925912013-01-05 02:09:22 +00001458 void print(raw_ostream &OS) const;
1459 void dump() const;
Stephen Lin837bba12013-07-15 17:55:02 +00001460
Chandler Carruthc8925912013-01-05 02:09:22 +00001461 bool operator==(const ExtAddrMode& O) const {
1462 return (BaseReg == O.BaseReg) && (ScaledReg == O.ScaledReg) &&
1463 (BaseGV == O.BaseGV) && (BaseOffs == O.BaseOffs) &&
1464 (HasBaseReg == O.HasBaseReg) && (Scale == O.Scale);
1465 }
1466};
1467
Eli Friedmanc1f1f852013-09-10 23:09:24 +00001468#ifndef NDEBUG
1469static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
1470 AM.print(OS);
1471 return OS;
1472}
1473#endif
1474
Chandler Carruthc8925912013-01-05 02:09:22 +00001475void ExtAddrMode::print(raw_ostream &OS) const {
1476 bool NeedPlus = false;
1477 OS << "[";
1478 if (BaseGV) {
1479 OS << (NeedPlus ? " + " : "")
1480 << "GV:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00001481 BaseGV->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00001482 NeedPlus = true;
1483 }
1484
Richard Trieuc0f91212014-05-30 03:15:17 +00001485 if (BaseOffs) {
1486 OS << (NeedPlus ? " + " : "")
1487 << BaseOffs;
1488 NeedPlus = true;
1489 }
Chandler Carruthc8925912013-01-05 02:09:22 +00001490
1491 if (BaseReg) {
1492 OS << (NeedPlus ? " + " : "")
1493 << "Base:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00001494 BaseReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00001495 NeedPlus = true;
1496 }
1497 if (Scale) {
1498 OS << (NeedPlus ? " + " : "")
1499 << Scale << "*";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00001500 ScaledReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00001501 }
1502
1503 OS << ']';
1504}
1505
1506#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1507void ExtAddrMode::dump() const {
1508 print(dbgs());
1509 dbgs() << '\n';
1510}
1511#endif
1512
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001513/// \brief This class provides transaction based operation on the IR.
1514/// Every change made through this class is recorded in the internal state and
1515/// can be undone (rollback) until commit is called.
1516class TypePromotionTransaction {
1517
1518 /// \brief This represents the common interface of the individual transaction.
1519 /// Each class implements the logic for doing one specific modification on
1520 /// the IR via the TypePromotionTransaction.
1521 class TypePromotionAction {
1522 protected:
1523 /// The Instruction modified.
1524 Instruction *Inst;
1525
1526 public:
1527 /// \brief Constructor of the action.
1528 /// The constructor performs the related action on the IR.
1529 TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
1530
1531 virtual ~TypePromotionAction() {}
1532
1533 /// \brief Undo the modification done by this action.
1534 /// When this method is called, the IR must be in the same state as it was
1535 /// before this action was applied.
1536 /// \pre Undoing the action works if and only if the IR is in the exact same
1537 /// state as it was directly after this action was applied.
1538 virtual void undo() = 0;
1539
1540 /// \brief Advocate every change made by this action.
1541 /// When the results on the IR of the action are to be kept, it is important
1542 /// to call this function, otherwise hidden information may be kept forever.
1543 virtual void commit() {
1544 // Nothing to be done, this action is not doing anything.
1545 }
1546 };
1547
1548 /// \brief Utility to remember the position of an instruction.
1549 class InsertionHandler {
1550 /// Position of an instruction.
1551 /// Either an instruction:
1552 /// - Is the first in a basic block: BB is used.
1553 /// - Has a previous instructon: PrevInst is used.
1554 union {
1555 Instruction *PrevInst;
1556 BasicBlock *BB;
1557 } Point;
1558 /// Remember whether or not the instruction had a previous instruction.
1559 bool HasPrevInstruction;
1560
1561 public:
1562 /// \brief Record the position of \p Inst.
1563 InsertionHandler(Instruction *Inst) {
1564 BasicBlock::iterator It = Inst;
1565 HasPrevInstruction = (It != (Inst->getParent()->begin()));
1566 if (HasPrevInstruction)
1567 Point.PrevInst = --It;
1568 else
1569 Point.BB = Inst->getParent();
1570 }
1571
1572 /// \brief Insert \p Inst at the recorded position.
1573 void insert(Instruction *Inst) {
1574 if (HasPrevInstruction) {
1575 if (Inst->getParent())
1576 Inst->removeFromParent();
1577 Inst->insertAfter(Point.PrevInst);
1578 } else {
1579 Instruction *Position = Point.BB->getFirstInsertionPt();
1580 if (Inst->getParent())
1581 Inst->moveBefore(Position);
1582 else
1583 Inst->insertBefore(Position);
1584 }
1585 }
1586 };
1587
1588 /// \brief Move an instruction before another.
1589 class InstructionMoveBefore : public TypePromotionAction {
1590 /// Original position of the instruction.
1591 InsertionHandler Position;
1592
1593 public:
1594 /// \brief Move \p Inst before \p Before.
1595 InstructionMoveBefore(Instruction *Inst, Instruction *Before)
1596 : TypePromotionAction(Inst), Position(Inst) {
1597 DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before << "\n");
1598 Inst->moveBefore(Before);
1599 }
1600
1601 /// \brief Move the instruction back to its original position.
Craig Topper4584cd52014-03-07 09:26:03 +00001602 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001603 DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n");
1604 Position.insert(Inst);
1605 }
1606 };
1607
1608 /// \brief Set the operand of an instruction with a new value.
1609 class OperandSetter : public TypePromotionAction {
1610 /// Original operand of the instruction.
1611 Value *Origin;
1612 /// Index of the modified instruction.
1613 unsigned Idx;
1614
1615 public:
1616 /// \brief Set \p Idx operand of \p Inst with \p NewVal.
1617 OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
1618 : TypePromotionAction(Inst), Idx(Idx) {
1619 DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"
1620 << "for:" << *Inst << "\n"
1621 << "with:" << *NewVal << "\n");
1622 Origin = Inst->getOperand(Idx);
1623 Inst->setOperand(Idx, NewVal);
1624 }
1625
1626 /// \brief Restore the original value of the instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00001627 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001628 DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"
1629 << "for: " << *Inst << "\n"
1630 << "with: " << *Origin << "\n");
1631 Inst->setOperand(Idx, Origin);
1632 }
1633 };
1634
1635 /// \brief Hide the operands of an instruction.
1636 /// Do as if this instruction was not using any of its operands.
1637 class OperandsHider : public TypePromotionAction {
1638 /// The list of original operands.
1639 SmallVector<Value *, 4> OriginalValues;
1640
1641 public:
1642 /// \brief Remove \p Inst from the uses of the operands of \p Inst.
1643 OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
1644 DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n");
1645 unsigned NumOpnds = Inst->getNumOperands();
1646 OriginalValues.reserve(NumOpnds);
1647 for (unsigned It = 0; It < NumOpnds; ++It) {
1648 // Save the current operand.
1649 Value *Val = Inst->getOperand(It);
1650 OriginalValues.push_back(Val);
1651 // Set a dummy one.
1652 // We could use OperandSetter here, but that would implied an overhead
1653 // that we are not willing to pay.
1654 Inst->setOperand(It, UndefValue::get(Val->getType()));
1655 }
1656 }
1657
1658 /// \brief Restore the original list of uses.
Craig Topper4584cd52014-03-07 09:26:03 +00001659 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001660 DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n");
1661 for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
1662 Inst->setOperand(It, OriginalValues[It]);
1663 }
1664 };
1665
1666 /// \brief Build a truncate instruction.
1667 class TruncBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00001668 Value *Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001669 public:
1670 /// \brief Build a truncate instruction of \p Opnd producing a \p Ty
1671 /// result.
1672 /// trunc Opnd to Ty.
1673 TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
1674 IRBuilder<> Builder(Opnd);
Quentin Colombetac55b152014-09-16 22:36:07 +00001675 Val = Builder.CreateTrunc(Opnd, Ty, "promoted");
1676 DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001677 }
1678
Quentin Colombetac55b152014-09-16 22:36:07 +00001679 /// \brief Get the built value.
1680 Value *getBuiltValue() { return Val; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001681
1682 /// \brief Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00001683 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00001684 DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n");
1685 if (Instruction *IVal = dyn_cast<Instruction>(Val))
1686 IVal->eraseFromParent();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001687 }
1688 };
1689
1690 /// \brief Build a sign extension instruction.
1691 class SExtBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00001692 Value *Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001693 public:
1694 /// \brief Build a sign extension instruction of \p Opnd producing a \p Ty
1695 /// result.
1696 /// sext Opnd to Ty.
1697 SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
Quentin Colombetac55b152014-09-16 22:36:07 +00001698 : TypePromotionAction(InsertPt) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001699 IRBuilder<> Builder(InsertPt);
Quentin Colombetac55b152014-09-16 22:36:07 +00001700 Val = Builder.CreateSExt(Opnd, Ty, "promoted");
1701 DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001702 }
1703
Quentin Colombetac55b152014-09-16 22:36:07 +00001704 /// \brief Get the built value.
1705 Value *getBuiltValue() { return Val; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001706
1707 /// \brief Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00001708 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00001709 DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n");
1710 if (Instruction *IVal = dyn_cast<Instruction>(Val))
1711 IVal->eraseFromParent();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001712 }
1713 };
1714
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001715 /// \brief Build a zero extension instruction.
1716 class ZExtBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00001717 Value *Val;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001718 public:
1719 /// \brief Build a zero extension instruction of \p Opnd producing a \p Ty
1720 /// result.
1721 /// zext Opnd to Ty.
1722 ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
Quentin Colombetac55b152014-09-16 22:36:07 +00001723 : TypePromotionAction(InsertPt) {
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001724 IRBuilder<> Builder(InsertPt);
Quentin Colombetac55b152014-09-16 22:36:07 +00001725 Val = Builder.CreateZExt(Opnd, Ty, "promoted");
1726 DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n");
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001727 }
1728
Quentin Colombetac55b152014-09-16 22:36:07 +00001729 /// \brief Get the built value.
1730 Value *getBuiltValue() { return Val; }
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001731
1732 /// \brief Remove the built instruction.
1733 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00001734 DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n");
1735 if (Instruction *IVal = dyn_cast<Instruction>(Val))
1736 IVal->eraseFromParent();
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001737 }
1738 };
1739
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001740 /// \brief Mutate an instruction to another type.
1741 class TypeMutator : public TypePromotionAction {
1742 /// Record the original type.
1743 Type *OrigTy;
1744
1745 public:
1746 /// \brief Mutate the type of \p Inst into \p NewTy.
1747 TypeMutator(Instruction *Inst, Type *NewTy)
1748 : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
1749 DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy
1750 << "\n");
1751 Inst->mutateType(NewTy);
1752 }
1753
1754 /// \brief Mutate the instruction back to its original type.
Craig Topper4584cd52014-03-07 09:26:03 +00001755 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001756 DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy
1757 << "\n");
1758 Inst->mutateType(OrigTy);
1759 }
1760 };
1761
1762 /// \brief Replace the uses of an instruction by another instruction.
1763 class UsesReplacer : public TypePromotionAction {
1764 /// Helper structure to keep track of the replaced uses.
1765 struct InstructionAndIdx {
1766 /// The instruction using the instruction.
1767 Instruction *Inst;
1768 /// The index where this instruction is used for Inst.
1769 unsigned Idx;
1770 InstructionAndIdx(Instruction *Inst, unsigned Idx)
1771 : Inst(Inst), Idx(Idx) {}
1772 };
1773
1774 /// Keep track of the original uses (pair Instruction, Index).
1775 SmallVector<InstructionAndIdx, 4> OriginalUses;
1776 typedef SmallVectorImpl<InstructionAndIdx>::iterator use_iterator;
1777
1778 public:
1779 /// \brief Replace all the use of \p Inst by \p New.
1780 UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) {
1781 DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New
1782 << "\n");
1783 // Record the original uses.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001784 for (Use &U : Inst->uses()) {
1785 Instruction *UserI = cast<Instruction>(U.getUser());
1786 OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo()));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001787 }
1788 // Now, we can replace the uses.
1789 Inst->replaceAllUsesWith(New);
1790 }
1791
1792 /// \brief Reassign the original uses of Inst to Inst.
Craig Topper4584cd52014-03-07 09:26:03 +00001793 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001794 DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n");
1795 for (use_iterator UseIt = OriginalUses.begin(),
1796 EndIt = OriginalUses.end();
1797 UseIt != EndIt; ++UseIt) {
1798 UseIt->Inst->setOperand(UseIt->Idx, Inst);
1799 }
1800 }
1801 };
1802
1803 /// \brief Remove an instruction from the IR.
1804 class InstructionRemover : public TypePromotionAction {
1805 /// Original position of the instruction.
1806 InsertionHandler Inserter;
1807 /// Helper structure to hide all the link to the instruction. In other
1808 /// words, this helps to do as if the instruction was removed.
1809 OperandsHider Hider;
1810 /// Keep track of the uses replaced, if any.
1811 UsesReplacer *Replacer;
1812
1813 public:
1814 /// \brief Remove all reference of \p Inst and optinally replace all its
1815 /// uses with New.
Craig Topperc0196b12014-04-14 00:51:57 +00001816 /// \pre If !Inst->use_empty(), then New != nullptr
1817 InstructionRemover(Instruction *Inst, Value *New = nullptr)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001818 : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
Craig Topperc0196b12014-04-14 00:51:57 +00001819 Replacer(nullptr) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001820 if (New)
1821 Replacer = new UsesReplacer(Inst, New);
1822 DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n");
1823 Inst->removeFromParent();
1824 }
1825
1826 ~InstructionRemover() { delete Replacer; }
1827
1828 /// \brief Really remove the instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00001829 void commit() override { delete Inst; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001830
1831 /// \brief Resurrect the instruction and reassign it to the proper uses if
1832 /// new value was provided when build this action.
Craig Topper4584cd52014-03-07 09:26:03 +00001833 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001834 DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n");
1835 Inserter.insert(Inst);
1836 if (Replacer)
1837 Replacer->undo();
1838 Hider.undo();
1839 }
1840 };
1841
1842public:
1843 /// Restoration point.
1844 /// The restoration point is a pointer to an action instead of an iterator
1845 /// because the iterator may be invalidated but not the pointer.
1846 typedef const TypePromotionAction *ConstRestorationPt;
1847 /// Advocate every changes made in that transaction.
1848 void commit();
1849 /// Undo all the changes made after the given point.
1850 void rollback(ConstRestorationPt Point);
1851 /// Get the current restoration point.
1852 ConstRestorationPt getRestorationPoint() const;
1853
1854 /// \name API for IR modification with state keeping to support rollback.
1855 /// @{
1856 /// Same as Instruction::setOperand.
1857 void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
1858 /// Same as Instruction::eraseFromParent.
Craig Topperc0196b12014-04-14 00:51:57 +00001859 void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001860 /// Same as Value::replaceAllUsesWith.
1861 void replaceAllUsesWith(Instruction *Inst, Value *New);
1862 /// Same as Value::mutateType.
1863 void mutateType(Instruction *Inst, Type *NewTy);
1864 /// Same as IRBuilder::createTrunc.
Quentin Colombetac55b152014-09-16 22:36:07 +00001865 Value *createTrunc(Instruction *Opnd, Type *Ty);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001866 /// Same as IRBuilder::createSExt.
Quentin Colombetac55b152014-09-16 22:36:07 +00001867 Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001868 /// Same as IRBuilder::createZExt.
Quentin Colombetac55b152014-09-16 22:36:07 +00001869 Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001870 /// Same as Instruction::moveBefore.
1871 void moveBefore(Instruction *Inst, Instruction *Before);
1872 /// @}
1873
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001874private:
1875 /// The ordered list of actions made so far.
David Blaikie7620b312014-04-15 06:17:44 +00001876 SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions;
1877 typedef SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator CommitPt;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001878};
1879
1880void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
1881 Value *NewVal) {
1882 Actions.push_back(
David Blaikie7620b312014-04-15 06:17:44 +00001883 make_unique<TypePromotionTransaction::OperandSetter>(Inst, Idx, NewVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001884}
1885
1886void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
1887 Value *NewVal) {
1888 Actions.push_back(
David Blaikie7620b312014-04-15 06:17:44 +00001889 make_unique<TypePromotionTransaction::InstructionRemover>(Inst, NewVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001890}
1891
1892void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
1893 Value *New) {
David Blaikie7620b312014-04-15 06:17:44 +00001894 Actions.push_back(make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001895}
1896
1897void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
David Blaikie7620b312014-04-15 06:17:44 +00001898 Actions.push_back(make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001899}
1900
Quentin Colombetac55b152014-09-16 22:36:07 +00001901Value *TypePromotionTransaction::createTrunc(Instruction *Opnd,
1902 Type *Ty) {
David Blaikie7620b312014-04-15 06:17:44 +00001903 std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00001904 Value *Val = Ptr->getBuiltValue();
David Blaikie7620b312014-04-15 06:17:44 +00001905 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00001906 return Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001907}
1908
Quentin Colombetac55b152014-09-16 22:36:07 +00001909Value *TypePromotionTransaction::createSExt(Instruction *Inst,
1910 Value *Opnd, Type *Ty) {
David Blaikie7620b312014-04-15 06:17:44 +00001911 std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00001912 Value *Val = Ptr->getBuiltValue();
David Blaikie7620b312014-04-15 06:17:44 +00001913 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00001914 return Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001915}
1916
Quentin Colombetac55b152014-09-16 22:36:07 +00001917Value *TypePromotionTransaction::createZExt(Instruction *Inst,
1918 Value *Opnd, Type *Ty) {
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001919 std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00001920 Value *Val = Ptr->getBuiltValue();
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001921 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00001922 return Val;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001923}
1924
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001925void TypePromotionTransaction::moveBefore(Instruction *Inst,
1926 Instruction *Before) {
1927 Actions.push_back(
David Blaikie7620b312014-04-15 06:17:44 +00001928 make_unique<TypePromotionTransaction::InstructionMoveBefore>(Inst, Before));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001929}
1930
1931TypePromotionTransaction::ConstRestorationPt
1932TypePromotionTransaction::getRestorationPoint() const {
David Blaikie7620b312014-04-15 06:17:44 +00001933 return !Actions.empty() ? Actions.back().get() : nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001934}
1935
1936void TypePromotionTransaction::commit() {
1937 for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt;
David Blaikie7620b312014-04-15 06:17:44 +00001938 ++It)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001939 (*It)->commit();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001940 Actions.clear();
1941}
1942
1943void TypePromotionTransaction::rollback(
1944 TypePromotionTransaction::ConstRestorationPt Point) {
David Blaikie7620b312014-04-15 06:17:44 +00001945 while (!Actions.empty() && Point != Actions.back().get()) {
1946 std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001947 Curr->undo();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001948 }
1949}
1950
Chandler Carruthc8925912013-01-05 02:09:22 +00001951/// \brief A helper class for matching addressing modes.
1952///
1953/// This encapsulates the logic for matching the target-legal addressing modes.
1954class AddressingModeMatcher {
1955 SmallVectorImpl<Instruction*> &AddrModeInsts;
Eric Christopherd75c00c2015-02-26 22:38:34 +00001956 const TargetMachine &TM;
Chandler Carruthc8925912013-01-05 02:09:22 +00001957 const TargetLowering &TLI;
1958
1959 /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
1960 /// the memory instruction that we're computing this address for.
1961 Type *AccessTy;
1962 Instruction *MemoryInst;
Stephen Lin837bba12013-07-15 17:55:02 +00001963
Chandler Carruthc8925912013-01-05 02:09:22 +00001964 /// AddrMode - This is the addressing mode that we're building up. This is
1965 /// part of the return value of this addressing mode matching stuff.
1966 ExtAddrMode &AddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00001967
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001968 /// The truncate instruction inserted by other CodeGenPrepare optimizations.
1969 const SetOfInstrs &InsertedTruncs;
1970 /// A map from the instructions to their type before promotion.
1971 InstrToOrigTy &PromotedInsts;
1972 /// The ongoing transaction where every action should be registered.
1973 TypePromotionTransaction &TPT;
1974
Chandler Carruthc8925912013-01-05 02:09:22 +00001975 /// IgnoreProfitability - This is set to true when we should not do
1976 /// profitability checks. When true, IsProfitableToFoldIntoAddressingMode
1977 /// always returns true.
1978 bool IgnoreProfitability;
Stephen Lin837bba12013-07-15 17:55:02 +00001979
Eric Christopherd75c00c2015-02-26 22:38:34 +00001980 AddressingModeMatcher(SmallVectorImpl<Instruction *> &AMI,
1981 const TargetMachine &TM, Type *AT, Instruction *MI,
1982 ExtAddrMode &AM, const SetOfInstrs &InsertedTruncs,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001983 InstrToOrigTy &PromotedInsts,
1984 TypePromotionTransaction &TPT)
Eric Christopherd75c00c2015-02-26 22:38:34 +00001985 : AddrModeInsts(AMI), TM(TM),
1986 TLI(*TM.getSubtargetImpl(*MI->getParent()->getParent())
1987 ->getTargetLowering()),
1988 AccessTy(AT), MemoryInst(MI), AddrMode(AM),
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001989 InsertedTruncs(InsertedTruncs), PromotedInsts(PromotedInsts), TPT(TPT) {
Chandler Carruthc8925912013-01-05 02:09:22 +00001990 IgnoreProfitability = false;
1991 }
1992public:
Stephen Lin837bba12013-07-15 17:55:02 +00001993
Chandler Carruthc8925912013-01-05 02:09:22 +00001994 /// Match - Find the maximal addressing mode that a load/store of V can fold,
1995 /// give an access type of AccessTy. This returns a list of involved
1996 /// instructions in AddrModeInsts.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001997 /// \p InsertedTruncs The truncate instruction inserted by other
1998 /// CodeGenPrepare
1999 /// optimizations.
2000 /// \p PromotedInsts maps the instructions to their type before promotion.
2001 /// \p The ongoing transaction where every action should be registered.
Chandler Carruthc8925912013-01-05 02:09:22 +00002002 static ExtAddrMode Match(Value *V, Type *AccessTy,
2003 Instruction *MemoryInst,
2004 SmallVectorImpl<Instruction*> &AddrModeInsts,
Eric Christopherd75c00c2015-02-26 22:38:34 +00002005 const TargetMachine &TM,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002006 const SetOfInstrs &InsertedTruncs,
2007 InstrToOrigTy &PromotedInsts,
2008 TypePromotionTransaction &TPT) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002009 ExtAddrMode Result;
2010
Eric Christopherd75c00c2015-02-26 22:38:34 +00002011 bool Success = AddressingModeMatcher(AddrModeInsts, TM, AccessTy,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002012 MemoryInst, Result, InsertedTruncs,
2013 PromotedInsts, TPT).MatchAddr(V, 0);
Chandler Carruthc8925912013-01-05 02:09:22 +00002014 (void)Success; assert(Success && "Couldn't select *anything*?");
2015 return Result;
2016 }
2017private:
2018 bool MatchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
2019 bool MatchAddr(Value *V, unsigned Depth);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002020 bool MatchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth,
Craig Topperc0196b12014-04-14 00:51:57 +00002021 bool *MovedAway = nullptr);
Chandler Carruthc8925912013-01-05 02:09:22 +00002022 bool IsProfitableToFoldIntoAddressingMode(Instruction *I,
2023 ExtAddrMode &AMBefore,
2024 ExtAddrMode &AMAfter);
2025 bool ValueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
Quentin Colombet867c5502014-02-14 22:23:22 +00002026 bool IsPromotionProfitable(unsigned MatchedSize, unsigned SizeWithPromotion,
2027 Value *PromotedOperand) const;
Chandler Carruthc8925912013-01-05 02:09:22 +00002028};
2029
2030/// MatchScaledValue - Try adding ScaleReg*Scale to the current addressing mode.
2031/// Return true and update AddrMode if this addr mode is legal for the target,
2032/// false if not.
2033bool AddressingModeMatcher::MatchScaledValue(Value *ScaleReg, int64_t Scale,
2034 unsigned Depth) {
2035 // If Scale is 1, then this is the same as adding ScaleReg to the addressing
2036 // mode. Just process that directly.
2037 if (Scale == 1)
2038 return MatchAddr(ScaleReg, Depth);
Stephen Lin837bba12013-07-15 17:55:02 +00002039
Chandler Carruthc8925912013-01-05 02:09:22 +00002040 // If the scale is 0, it takes nothing to add this.
2041 if (Scale == 0)
2042 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002043
Chandler Carruthc8925912013-01-05 02:09:22 +00002044 // If we already have a scale of this value, we can add to it, otherwise, we
2045 // need an available scale field.
2046 if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
2047 return false;
2048
2049 ExtAddrMode TestAddrMode = AddrMode;
2050
2051 // Add scale to turn X*4+X*3 -> X*7. This could also do things like
2052 // [A+B + A*7] -> [B+A*8].
2053 TestAddrMode.Scale += Scale;
2054 TestAddrMode.ScaledReg = ScaleReg;
2055
2056 // If the new address isn't legal, bail out.
2057 if (!TLI.isLegalAddressingMode(TestAddrMode, AccessTy))
2058 return false;
2059
2060 // It was legal, so commit it.
2061 AddrMode = TestAddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00002062
Chandler Carruthc8925912013-01-05 02:09:22 +00002063 // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
2064 // to see if ScaleReg is actually X+C. If so, we can turn this into adding
2065 // X*Scale + C*Scale to addr mode.
Craig Topperc0196b12014-04-14 00:51:57 +00002066 ConstantInt *CI = nullptr; Value *AddLHS = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00002067 if (isa<Instruction>(ScaleReg) && // not a constant expr.
2068 match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
2069 TestAddrMode.ScaledReg = AddLHS;
2070 TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00002071
Chandler Carruthc8925912013-01-05 02:09:22 +00002072 // If this addressing mode is legal, commit it and remember that we folded
2073 // this instruction.
2074 if (TLI.isLegalAddressingMode(TestAddrMode, AccessTy)) {
2075 AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
2076 AddrMode = TestAddrMode;
2077 return true;
2078 }
2079 }
2080
2081 // Otherwise, not (x+c)*scale, just return what we have.
2082 return true;
2083}
2084
2085/// MightBeFoldableInst - This is a little filter, which returns true if an
2086/// addressing computation involving I might be folded into a load/store
2087/// accessing it. This doesn't need to be perfect, but needs to accept at least
2088/// the set of instructions that MatchOperationAddr can.
2089static bool MightBeFoldableInst(Instruction *I) {
2090 switch (I->getOpcode()) {
2091 case Instruction::BitCast:
Eli Benderskyf13a0562014-05-22 00:02:52 +00002092 case Instruction::AddrSpaceCast:
Chandler Carruthc8925912013-01-05 02:09:22 +00002093 // Don't touch identity bitcasts.
2094 if (I->getType() == I->getOperand(0)->getType())
2095 return false;
2096 return I->getType()->isPointerTy() || I->getType()->isIntegerTy();
2097 case Instruction::PtrToInt:
2098 // PtrToInt is always a noop, as we know that the int type is pointer sized.
2099 return true;
2100 case Instruction::IntToPtr:
2101 // We know the input is intptr_t, so this is foldable.
2102 return true;
2103 case Instruction::Add:
2104 return true;
2105 case Instruction::Mul:
2106 case Instruction::Shl:
2107 // Can only handle X*C and X << C.
2108 return isa<ConstantInt>(I->getOperand(1));
2109 case Instruction::GetElementPtr:
2110 return true;
2111 default:
2112 return false;
2113 }
2114}
2115
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002116/// \brief Check whether or not \p Val is a legal instruction for \p TLI.
2117/// \note \p Val is assumed to be the product of some type promotion.
2118/// Therefore if \p Val has an undefined state in \p TLI, this is assumed
2119/// to be legal, as the non-promoted value would have had the same state.
2120static bool isPromotedInstructionLegal(const TargetLowering &TLI, Value *Val) {
2121 Instruction *PromotedInst = dyn_cast<Instruction>(Val);
2122 if (!PromotedInst)
2123 return false;
2124 int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode());
2125 // If the ISDOpcode is undefined, it was undefined before the promotion.
2126 if (!ISDOpcode)
2127 return true;
2128 // Otherwise, check if the promoted instruction is legal or not.
2129 return TLI.isOperationLegalOrCustom(
2130 ISDOpcode, TLI.getValueType(PromotedInst->getType()));
2131}
2132
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002133/// \brief Hepler class to perform type promotion.
2134class TypePromotionHelper {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002135 /// \brief Utility function to check whether or not a sign or zero extension
2136 /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by
2137 /// either using the operands of \p Inst or promoting \p Inst.
2138 /// The type of the extension is defined by \p IsSExt.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002139 /// In other words, check if:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002140 /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002141 /// #1 Promotion applies:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002142 /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...).
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002143 /// #2 Operand reuses:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002144 /// ext opnd1 to ConsideredExtType.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002145 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002146 static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType,
2147 const InstrToOrigTy &PromotedInsts, bool IsSExt);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002148
2149 /// \brief Utility function to determine if \p OpIdx should be promoted when
2150 /// promoting \p Inst.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002151 static bool shouldExtOperand(const Instruction *Inst, int OpIdx) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002152 if (isa<SelectInst>(Inst) && OpIdx == 0)
2153 return false;
2154 return true;
2155 }
2156
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002157 /// \brief Utility function to promote the operand of \p Ext when this
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002158 /// operand is a promotable trunc or sext or zext.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002159 /// \p PromotedInsts maps the instructions to their type before promotion.
2160 /// \p CreatedInsts[out] contains how many non-free instructions have been
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002161 /// created to promote the operand of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002162 /// Newly added extensions are inserted in \p Exts.
2163 /// Newly added truncates are inserted in \p Truncs.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002164 /// Should never be called directly.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002165 /// \return The promoted value which is used instead of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002166 static Value *promoteOperandForTruncAndAnyExt(
2167 Instruction *Ext, TypePromotionTransaction &TPT,
2168 InstrToOrigTy &PromotedInsts, unsigned &CreatedInsts,
2169 SmallVectorImpl<Instruction *> *Exts,
2170 SmallVectorImpl<Instruction *> *Truncs);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002171
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002172 /// \brief Utility function to promote the operand of \p Ext when this
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002173 /// operand is promotable and is not a supported trunc or sext.
2174 /// \p PromotedInsts maps the instructions to their type before promotion.
2175 /// \p CreatedInsts[out] contains how many non-free instructions have been
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002176 /// created to promote the operand of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002177 /// Newly added extensions are inserted in \p Exts.
2178 /// Newly added truncates are inserted in \p Truncs.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002179 /// Should never be called directly.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002180 /// \return The promoted value which is used instead of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002181 static Value *
2182 promoteOperandForOther(Instruction *Ext, TypePromotionTransaction &TPT,
2183 InstrToOrigTy &PromotedInsts, unsigned &CreatedInsts,
2184 SmallVectorImpl<Instruction *> *Exts,
2185 SmallVectorImpl<Instruction *> *Truncs, bool IsSExt);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002186
2187 /// \see promoteOperandForOther.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002188 static Value *
2189 signExtendOperandForOther(Instruction *Ext, TypePromotionTransaction &TPT,
2190 InstrToOrigTy &PromotedInsts,
2191 unsigned &CreatedInsts,
2192 SmallVectorImpl<Instruction *> *Exts,
2193 SmallVectorImpl<Instruction *> *Truncs) {
2194 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInsts, Exts,
2195 Truncs, true);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002196 }
2197
2198 /// \see promoteOperandForOther.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002199 static Value *
2200 zeroExtendOperandForOther(Instruction *Ext, TypePromotionTransaction &TPT,
2201 InstrToOrigTy &PromotedInsts,
2202 unsigned &CreatedInsts,
2203 SmallVectorImpl<Instruction *> *Exts,
2204 SmallVectorImpl<Instruction *> *Truncs) {
2205 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInsts, Exts,
2206 Truncs, false);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002207 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002208
2209public:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002210 /// Type for the utility function that promotes the operand of Ext.
2211 typedef Value *(*Action)(Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002212 InstrToOrigTy &PromotedInsts, unsigned &CreatedInsts,
2213 SmallVectorImpl<Instruction *> *Exts,
2214 SmallVectorImpl<Instruction *> *Truncs);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002215 /// \brief Given a sign/zero extend instruction \p Ext, return the approriate
2216 /// action to promote the operand of \p Ext instead of using Ext.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002217 /// \return NULL if no promotable action is possible with the current
2218 /// sign extension.
2219 /// \p InsertedTruncs keeps track of all the truncate instructions inserted by
2220 /// the others CodeGenPrepare optimizations. This information is important
2221 /// because we do not want to promote these instructions as CodeGenPrepare
2222 /// will reinsert them later. Thus creating an infinite loop: create/remove.
2223 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002224 static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedTruncs,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002225 const TargetLowering &TLI,
2226 const InstrToOrigTy &PromotedInsts);
2227};
2228
2229bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002230 Type *ConsideredExtType,
2231 const InstrToOrigTy &PromotedInsts,
2232 bool IsSExt) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002233 // The promotion helper does not know how to deal with vector types yet.
2234 // To be able to fix that, we would need to fix the places where we
2235 // statically extend, e.g., constants and such.
2236 if (Inst->getType()->isVectorTy())
2237 return false;
2238
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002239 // We can always get through zext.
2240 if (isa<ZExtInst>(Inst))
2241 return true;
2242
2243 // sext(sext) is ok too.
2244 if (IsSExt && isa<SExtInst>(Inst))
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002245 return true;
2246
2247 // We can get through binary operator, if it is legal. In other words, the
2248 // binary operator must have a nuw or nsw flag.
2249 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
2250 if (BinOp && isa<OverflowingBinaryOperator>(BinOp) &&
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002251 ((!IsSExt && BinOp->hasNoUnsignedWrap()) ||
2252 (IsSExt && BinOp->hasNoSignedWrap())))
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002253 return true;
2254
2255 // Check if we can do the following simplification.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002256 // ext(trunc(opnd)) --> ext(opnd)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002257 if (!isa<TruncInst>(Inst))
2258 return false;
2259
2260 Value *OpndVal = Inst->getOperand(0);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002261 // Check if we can use this operand in the extension.
2262 // If the type is larger than the result type of the extension,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002263 // we cannot.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002264 if (!OpndVal->getType()->isIntegerTy() ||
2265 OpndVal->getType()->getIntegerBitWidth() >
2266 ConsideredExtType->getIntegerBitWidth())
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002267 return false;
2268
2269 // If the operand of the truncate is not an instruction, we will not have
2270 // any information on the dropped bits.
2271 // (Actually we could for constant but it is not worth the extra logic).
2272 Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
2273 if (!Opnd)
2274 return false;
2275
2276 // Check if the source of the type is narrow enough.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002277 // I.e., check that trunc just drops extended bits of the same kind of
2278 // the extension.
2279 // #1 get the type of the operand and check the kind of the extended bits.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002280 const Type *OpndType;
2281 InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002282 if (It != PromotedInsts.end() && It->second.IsSExt == IsSExt)
2283 OpndType = It->second.Ty;
2284 else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd)))
2285 OpndType = Opnd->getOperand(0)->getType();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002286 else
2287 return false;
2288
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002289 // #2 check that the truncate just drop extended bits.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002290 if (Inst->getType()->getIntegerBitWidth() >= OpndType->getIntegerBitWidth())
2291 return true;
2292
2293 return false;
2294}
2295
2296TypePromotionHelper::Action TypePromotionHelper::getAction(
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002297 Instruction *Ext, const SetOfInstrs &InsertedTruncs,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002298 const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002299 assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
2300 "Unexpected instruction type");
2301 Instruction *ExtOpnd = dyn_cast<Instruction>(Ext->getOperand(0));
2302 Type *ExtTy = Ext->getType();
2303 bool IsSExt = isa<SExtInst>(Ext);
2304 // If the operand of the extension is not an instruction, we cannot
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002305 // get through.
2306 // If it, check we can get through.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002307 if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt))
Craig Topperc0196b12014-04-14 00:51:57 +00002308 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002309
2310 // Do not promote if the operand has been added by codegenprepare.
2311 // Otherwise, it means we are undoing an optimization that is likely to be
2312 // redone, thus causing potential infinite loop.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002313 if (isa<TruncInst>(ExtOpnd) && InsertedTruncs.count(ExtOpnd))
Craig Topperc0196b12014-04-14 00:51:57 +00002314 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002315
2316 // SExt or Trunc instructions.
2317 // Return the related handler.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002318 if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) ||
2319 isa<ZExtInst>(ExtOpnd))
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002320 return promoteOperandForTruncAndAnyExt;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002321
2322 // Regular instruction.
2323 // Abort early if we will have to insert non-free instructions.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002324 if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(ExtTy, ExtOpnd->getType()))
Craig Topperc0196b12014-04-14 00:51:57 +00002325 return nullptr;
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002326 return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002327}
2328
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002329Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt(
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002330 llvm::Instruction *SExt, TypePromotionTransaction &TPT,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002331 InstrToOrigTy &PromotedInsts, unsigned &CreatedInsts,
2332 SmallVectorImpl<Instruction *> *Exts,
2333 SmallVectorImpl<Instruction *> *Truncs) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002334 // By construction, the operand of SExt is an instruction. Otherwise we cannot
2335 // get through it and this method should not be called.
2336 Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
Quentin Colombetac55b152014-09-16 22:36:07 +00002337 Value *ExtVal = SExt;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002338 if (isa<ZExtInst>(SExtOpnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002339 // Replace s|zext(zext(opnd))
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002340 // => zext(opnd).
Quentin Colombetac55b152014-09-16 22:36:07 +00002341 Value *ZExt =
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002342 TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType());
2343 TPT.replaceAllUsesWith(SExt, ZExt);
2344 TPT.eraseInstruction(SExt);
Quentin Colombetac55b152014-09-16 22:36:07 +00002345 ExtVal = ZExt;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002346 } else {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002347 // Replace z|sext(trunc(opnd)) or sext(sext(opnd))
2348 // => z|sext(opnd).
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002349 TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
2350 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002351 CreatedInsts = 0;
2352
2353 // Remove dead code.
2354 if (SExtOpnd->use_empty())
2355 TPT.eraseInstruction(SExtOpnd);
2356
Quentin Colombet9dcb7242014-09-15 18:26:58 +00002357 // Check if the extension is still needed.
Quentin Colombetac55b152014-09-16 22:36:07 +00002358 Instruction *ExtInst = dyn_cast<Instruction>(ExtVal);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002359 if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType()) {
2360 if (ExtInst && Exts)
2361 Exts->push_back(ExtInst);
Quentin Colombetac55b152014-09-16 22:36:07 +00002362 return ExtVal;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002363 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002364
Quentin Colombet9dcb7242014-09-15 18:26:58 +00002365 // At this point we have: ext ty opnd to ty.
2366 // Reassign the uses of ExtInst to the opnd and remove ExtInst.
2367 Value *NextVal = ExtInst->getOperand(0);
2368 TPT.eraseInstruction(ExtInst, NextVal);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002369 return NextVal;
2370}
2371
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002372Value *TypePromotionHelper::promoteOperandForOther(
2373 Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002374 InstrToOrigTy &PromotedInsts, unsigned &CreatedInsts,
2375 SmallVectorImpl<Instruction *> *Exts,
2376 SmallVectorImpl<Instruction *> *Truncs, bool IsSExt) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002377 // By construction, the operand of Ext is an instruction. Otherwise we cannot
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002378 // get through it and this method should not be called.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002379 Instruction *ExtOpnd = cast<Instruction>(Ext->getOperand(0));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002380 CreatedInsts = 0;
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002381 if (!ExtOpnd->hasOneUse()) {
2382 // ExtOpnd will be promoted.
2383 // All its uses, but Ext, will need to use a truncated value of the
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002384 // promoted version.
2385 // Create the truncate now.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002386 Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->getType());
Quentin Colombetac55b152014-09-16 22:36:07 +00002387 if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) {
2388 ITrunc->removeFromParent();
2389 // Insert it just after the definition.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002390 ITrunc->insertAfter(ExtOpnd);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002391 if (Truncs)
2392 Truncs->push_back(ITrunc);
Quentin Colombetac55b152014-09-16 22:36:07 +00002393 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002394
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002395 TPT.replaceAllUsesWith(ExtOpnd, Trunc);
2396 // Restore the operand of Ext (which has been replace by the previous call
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002397 // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002398 TPT.setOperand(Ext, 0, ExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002399 }
2400
2401 // Get through the Instruction:
2402 // 1. Update its type.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002403 // 2. Replace the uses of Ext by Inst.
2404 // 3. Extend each operand that needs to be extended.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002405
2406 // Remember the original type of the instruction before promotion.
2407 // This is useful to know that the high bits are sign extended bits.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002408 PromotedInsts.insert(std::pair<Instruction *, TypeIsSExt>(
2409 ExtOpnd, TypeIsSExt(ExtOpnd->getType(), IsSExt)));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002410 // Step #1.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002411 TPT.mutateType(ExtOpnd, Ext->getType());
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002412 // Step #2.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002413 TPT.replaceAllUsesWith(Ext, ExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002414 // Step #3.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002415 Instruction *ExtForOpnd = Ext;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002416
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002417 DEBUG(dbgs() << "Propagate Ext to operands\n");
2418 for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002419 ++OpIdx) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002420 DEBUG(dbgs() << "Operand:\n" << *(ExtOpnd->getOperand(OpIdx)) << '\n');
2421 if (ExtOpnd->getOperand(OpIdx)->getType() == Ext->getType() ||
2422 !shouldExtOperand(ExtOpnd, OpIdx)) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002423 DEBUG(dbgs() << "No need to propagate\n");
2424 continue;
2425 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002426 // Check if we can statically extend the operand.
2427 Value *Opnd = ExtOpnd->getOperand(OpIdx);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002428 if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002429 DEBUG(dbgs() << "Statically extend\n");
2430 unsigned BitWidth = Ext->getType()->getIntegerBitWidth();
2431 APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth)
2432 : Cst->getValue().zext(BitWidth);
2433 TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->getType(), CstVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002434 continue;
2435 }
2436 // UndefValue are typed, so we have to statically sign extend them.
2437 if (isa<UndefValue>(Opnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002438 DEBUG(dbgs() << "Statically extend\n");
2439 TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->getType()));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002440 continue;
2441 }
2442
2443 // Otherwise we have to explicity sign extend the operand.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002444 // Check if Ext was reused to extend an operand.
2445 if (!ExtForOpnd) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002446 // If yes, create a new one.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002447 DEBUG(dbgs() << "More operands to ext\n");
Quentin Colombet84f89cc2014-12-22 18:11:52 +00002448 Value *ValForExtOpnd = IsSExt ? TPT.createSExt(Ext, Opnd, Ext->getType())
2449 : TPT.createZExt(Ext, Opnd, Ext->getType());
2450 if (!isa<Instruction>(ValForExtOpnd)) {
2451 TPT.setOperand(ExtOpnd, OpIdx, ValForExtOpnd);
2452 continue;
2453 }
2454 ExtForOpnd = cast<Instruction>(ValForExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002455 ++CreatedInsts;
2456 }
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002457 if (Exts)
2458 Exts->push_back(ExtForOpnd);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002459 TPT.setOperand(ExtForOpnd, 0, Opnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002460
2461 // Move the sign extension before the insertion point.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002462 TPT.moveBefore(ExtForOpnd, ExtOpnd);
2463 TPT.setOperand(ExtOpnd, OpIdx, ExtForOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002464 // If more sext are required, new instructions will have to be created.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002465 ExtForOpnd = nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002466 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002467 if (ExtForOpnd == Ext) {
2468 DEBUG(dbgs() << "Extension is useless now\n");
2469 TPT.eraseInstruction(Ext);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002470 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002471 return ExtOpnd;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002472}
2473
Quentin Colombet867c5502014-02-14 22:23:22 +00002474/// IsPromotionProfitable - Check whether or not promoting an instruction
2475/// to a wider type was profitable.
2476/// \p MatchedSize gives the number of instructions that have been matched
2477/// in the addressing mode after the promotion was applied.
2478/// \p SizeWithPromotion gives the number of created instructions for
2479/// the promotion plus the number of instructions that have been
2480/// matched in the addressing mode before the promotion.
2481/// \p PromotedOperand is the value that has been promoted.
2482/// \return True if the promotion is profitable, false otherwise.
2483bool
2484AddressingModeMatcher::IsPromotionProfitable(unsigned MatchedSize,
2485 unsigned SizeWithPromotion,
2486 Value *PromotedOperand) const {
2487 // We folded less instructions than what we created to promote the operand.
2488 // This is not profitable.
2489 if (MatchedSize < SizeWithPromotion)
2490 return false;
2491 if (MatchedSize > SizeWithPromotion)
2492 return true;
2493 // The promotion is neutral but it may help folding the sign extension in
2494 // loads for instance.
2495 // Check that we did not create an illegal instruction.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002496 return isPromotedInstructionLegal(TLI, PromotedOperand);
Quentin Colombet867c5502014-02-14 22:23:22 +00002497}
2498
Chandler Carruthc8925912013-01-05 02:09:22 +00002499/// MatchOperationAddr - Given an instruction or constant expr, see if we can
2500/// fold the operation into the addressing mode. If so, update the addressing
2501/// mode and return true, otherwise return false without modifying AddrMode.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002502/// If \p MovedAway is not NULL, it contains the information of whether or
2503/// not AddrInst has to be folded into the addressing mode on success.
2504/// If \p MovedAway == true, \p AddrInst will not be part of the addressing
2505/// because it has been moved away.
2506/// Thus AddrInst must not be added in the matched instructions.
2507/// This state can happen when AddrInst is a sext, since it may be moved away.
2508/// Therefore, AddrInst may not be valid when MovedAway is true and it must
2509/// not be referenced anymore.
Chandler Carruthc8925912013-01-05 02:09:22 +00002510bool AddressingModeMatcher::MatchOperationAddr(User *AddrInst, unsigned Opcode,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002511 unsigned Depth,
2512 bool *MovedAway) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002513 // Avoid exponential behavior on extremely deep expression trees.
2514 if (Depth >= 5) return false;
Stephen Lin837bba12013-07-15 17:55:02 +00002515
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002516 // By default, all matched instructions stay in place.
2517 if (MovedAway)
2518 *MovedAway = false;
2519
Chandler Carruthc8925912013-01-05 02:09:22 +00002520 switch (Opcode) {
2521 case Instruction::PtrToInt:
2522 // PtrToInt is always a noop, as we know that the int type is pointer sized.
2523 return MatchAddr(AddrInst->getOperand(0), Depth);
2524 case Instruction::IntToPtr:
2525 // This inttoptr is a no-op if the integer type is pointer sized.
2526 if (TLI.getValueType(AddrInst->getOperand(0)->getType()) ==
Matt Arsenault37d42ec2013-09-06 00:18:43 +00002527 TLI.getPointerTy(AddrInst->getType()->getPointerAddressSpace()))
Chandler Carruthc8925912013-01-05 02:09:22 +00002528 return MatchAddr(AddrInst->getOperand(0), Depth);
2529 return false;
2530 case Instruction::BitCast:
Eli Benderskyf13a0562014-05-22 00:02:52 +00002531 case Instruction::AddrSpaceCast:
Chandler Carruthc8925912013-01-05 02:09:22 +00002532 // BitCast is always a noop, and we can handle it as long as it is
2533 // int->int or pointer->pointer (we don't want int<->fp or something).
2534 if ((AddrInst->getOperand(0)->getType()->isPointerTy() ||
2535 AddrInst->getOperand(0)->getType()->isIntegerTy()) &&
2536 // Don't touch identity bitcasts. These were probably put here by LSR,
2537 // and we don't want to mess around with them. Assume it knows what it
2538 // is doing.
2539 AddrInst->getOperand(0)->getType() != AddrInst->getType())
2540 return MatchAddr(AddrInst->getOperand(0), Depth);
2541 return false;
2542 case Instruction::Add: {
2543 // Check to see if we can merge in the RHS then the LHS. If so, we win.
2544 ExtAddrMode BackupAddrMode = AddrMode;
2545 unsigned OldSize = AddrModeInsts.size();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002546 // Start a transaction at this point.
2547 // The LHS may match but not the RHS.
2548 // Therefore, we need a higher level restoration point to undo partially
2549 // matched operation.
2550 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2551 TPT.getRestorationPoint();
2552
Chandler Carruthc8925912013-01-05 02:09:22 +00002553 if (MatchAddr(AddrInst->getOperand(1), Depth+1) &&
2554 MatchAddr(AddrInst->getOperand(0), Depth+1))
2555 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002556
Chandler Carruthc8925912013-01-05 02:09:22 +00002557 // Restore the old addr mode info.
2558 AddrMode = BackupAddrMode;
2559 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002560 TPT.rollback(LastKnownGood);
Stephen Lin837bba12013-07-15 17:55:02 +00002561
Chandler Carruthc8925912013-01-05 02:09:22 +00002562 // Otherwise this was over-aggressive. Try merging in the LHS then the RHS.
2563 if (MatchAddr(AddrInst->getOperand(0), Depth+1) &&
2564 MatchAddr(AddrInst->getOperand(1), Depth+1))
2565 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002566
Chandler Carruthc8925912013-01-05 02:09:22 +00002567 // Otherwise we definitely can't merge the ADD in.
2568 AddrMode = BackupAddrMode;
2569 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002570 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00002571 break;
2572 }
2573 //case Instruction::Or:
2574 // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
2575 //break;
2576 case Instruction::Mul:
2577 case Instruction::Shl: {
2578 // Can only handle X*C and X << C.
2579 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
Sanjay Pateld3bbfa12014-07-16 22:40:28 +00002580 if (!RHS)
2581 return false;
Chandler Carruthc8925912013-01-05 02:09:22 +00002582 int64_t Scale = RHS->getSExtValue();
2583 if (Opcode == Instruction::Shl)
2584 Scale = 1LL << Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00002585
Chandler Carruthc8925912013-01-05 02:09:22 +00002586 return MatchScaledValue(AddrInst->getOperand(0), Scale, Depth);
2587 }
2588 case Instruction::GetElementPtr: {
2589 // Scan the GEP. We check it if it contains constant offsets and at most
2590 // one variable offset.
2591 int VariableOperand = -1;
2592 unsigned VariableScale = 0;
Stephen Lin837bba12013-07-15 17:55:02 +00002593
Chandler Carruthc8925912013-01-05 02:09:22 +00002594 int64_t ConstantOffset = 0;
2595 const DataLayout *TD = TLI.getDataLayout();
2596 gep_type_iterator GTI = gep_type_begin(AddrInst);
2597 for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
2598 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
2599 const StructLayout *SL = TD->getStructLayout(STy);
2600 unsigned Idx =
2601 cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
2602 ConstantOffset += SL->getElementOffset(Idx);
2603 } else {
2604 uint64_t TypeSize = TD->getTypeAllocSize(GTI.getIndexedType());
2605 if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
2606 ConstantOffset += CI->getSExtValue()*TypeSize;
2607 } else if (TypeSize) { // Scales of zero don't do anything.
2608 // We only allow one variable index at the moment.
2609 if (VariableOperand != -1)
2610 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00002611
Chandler Carruthc8925912013-01-05 02:09:22 +00002612 // Remember the variable index.
2613 VariableOperand = i;
2614 VariableScale = TypeSize;
2615 }
2616 }
2617 }
Stephen Lin837bba12013-07-15 17:55:02 +00002618
Chandler Carruthc8925912013-01-05 02:09:22 +00002619 // A common case is for the GEP to only do a constant offset. In this case,
2620 // just add it to the disp field and check validity.
2621 if (VariableOperand == -1) {
2622 AddrMode.BaseOffs += ConstantOffset;
2623 if (ConstantOffset == 0 || TLI.isLegalAddressingMode(AddrMode, AccessTy)){
2624 // Check to see if we can fold the base pointer in too.
2625 if (MatchAddr(AddrInst->getOperand(0), Depth+1))
2626 return true;
2627 }
2628 AddrMode.BaseOffs -= ConstantOffset;
2629 return false;
2630 }
2631
2632 // Save the valid addressing mode in case we can't match.
2633 ExtAddrMode BackupAddrMode = AddrMode;
2634 unsigned OldSize = AddrModeInsts.size();
2635
2636 // See if the scale and offset amount is valid for this target.
2637 AddrMode.BaseOffs += ConstantOffset;
2638
2639 // Match the base operand of the GEP.
2640 if (!MatchAddr(AddrInst->getOperand(0), Depth+1)) {
2641 // If it couldn't be matched, just stuff the value in a register.
2642 if (AddrMode.HasBaseReg) {
2643 AddrMode = BackupAddrMode;
2644 AddrModeInsts.resize(OldSize);
2645 return false;
2646 }
2647 AddrMode.HasBaseReg = true;
2648 AddrMode.BaseReg = AddrInst->getOperand(0);
2649 }
2650
2651 // Match the remaining variable portion of the GEP.
2652 if (!MatchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
2653 Depth)) {
2654 // If it couldn't be matched, try stuffing the base into a register
2655 // instead of matching it, and retrying the match of the scale.
2656 AddrMode = BackupAddrMode;
2657 AddrModeInsts.resize(OldSize);
2658 if (AddrMode.HasBaseReg)
2659 return false;
2660 AddrMode.HasBaseReg = true;
2661 AddrMode.BaseReg = AddrInst->getOperand(0);
2662 AddrMode.BaseOffs += ConstantOffset;
2663 if (!MatchScaledValue(AddrInst->getOperand(VariableOperand),
2664 VariableScale, Depth)) {
2665 // If even that didn't work, bail.
2666 AddrMode = BackupAddrMode;
2667 AddrModeInsts.resize(OldSize);
2668 return false;
2669 }
2670 }
2671
2672 return true;
2673 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002674 case Instruction::SExt:
2675 case Instruction::ZExt: {
2676 Instruction *Ext = dyn_cast<Instruction>(AddrInst);
2677 if (!Ext)
Sanjay Pateld3bbfa12014-07-16 22:40:28 +00002678 return false;
Sanjay Patelab60d042014-07-16 21:08:10 +00002679
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002680 // Try to move this ext out of the way of the addressing mode.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002681 // Ask for a method for doing so.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002682 TypePromotionHelper::Action TPH =
2683 TypePromotionHelper::getAction(Ext, InsertedTruncs, TLI, PromotedInsts);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002684 if (!TPH)
2685 return false;
2686
2687 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2688 TPT.getRestorationPoint();
2689 unsigned CreatedInsts = 0;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002690 Value *PromotedOperand =
2691 TPH(Ext, TPT, PromotedInsts, CreatedInsts, nullptr, nullptr);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002692 // SExt has been moved away.
2693 // Thus either it will be rematched later in the recursive calls or it is
2694 // gone. Anyway, we must not fold it into the addressing mode at this point.
2695 // E.g.,
2696 // op = add opnd, 1
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002697 // idx = ext op
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002698 // addr = gep base, idx
2699 // is now:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002700 // promotedOpnd = ext opnd <- no match here
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002701 // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls)
2702 // addr = gep base, op <- match
2703 if (MovedAway)
2704 *MovedAway = true;
2705
2706 assert(PromotedOperand &&
2707 "TypePromotionHelper should have filtered out those cases");
2708
2709 ExtAddrMode BackupAddrMode = AddrMode;
2710 unsigned OldSize = AddrModeInsts.size();
2711
2712 if (!MatchAddr(PromotedOperand, Depth) ||
Quentin Colombet867c5502014-02-14 22:23:22 +00002713 !IsPromotionProfitable(AddrModeInsts.size(), OldSize + CreatedInsts,
2714 PromotedOperand)) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002715 AddrMode = BackupAddrMode;
2716 AddrModeInsts.resize(OldSize);
2717 DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
2718 TPT.rollback(LastKnownGood);
2719 return false;
2720 }
2721 return true;
2722 }
Chandler Carruthc8925912013-01-05 02:09:22 +00002723 }
2724 return false;
2725}
2726
2727/// MatchAddr - If we can, try to add the value of 'Addr' into the current
2728/// addressing mode. If Addr can't be added to AddrMode this returns false and
2729/// leaves AddrMode unmodified. This assumes that Addr is either a pointer type
2730/// or intptr_t for the target.
2731///
2732bool AddressingModeMatcher::MatchAddr(Value *Addr, unsigned Depth) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002733 // Start a transaction at this point that we will rollback if the matching
2734 // fails.
2735 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2736 TPT.getRestorationPoint();
Chandler Carruthc8925912013-01-05 02:09:22 +00002737 if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
2738 // Fold in immediates if legal for the target.
2739 AddrMode.BaseOffs += CI->getSExtValue();
2740 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2741 return true;
2742 AddrMode.BaseOffs -= CI->getSExtValue();
2743 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
2744 // If this is a global variable, try to fold it into the addressing mode.
Craig Topperc0196b12014-04-14 00:51:57 +00002745 if (!AddrMode.BaseGV) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002746 AddrMode.BaseGV = GV;
2747 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2748 return true;
Craig Topperc0196b12014-04-14 00:51:57 +00002749 AddrMode.BaseGV = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00002750 }
2751 } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
2752 ExtAddrMode BackupAddrMode = AddrMode;
2753 unsigned OldSize = AddrModeInsts.size();
2754
2755 // Check to see if it is possible to fold this operation.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002756 bool MovedAway = false;
2757 if (MatchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
2758 // This instruction may have been move away. If so, there is nothing
2759 // to check here.
2760 if (MovedAway)
2761 return true;
Chandler Carruthc8925912013-01-05 02:09:22 +00002762 // Okay, it's possible to fold this. Check to see if it is actually
2763 // *profitable* to do so. We use a simple cost model to avoid increasing
2764 // register pressure too much.
2765 if (I->hasOneUse() ||
2766 IsProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
2767 AddrModeInsts.push_back(I);
2768 return true;
2769 }
Stephen Lin837bba12013-07-15 17:55:02 +00002770
Chandler Carruthc8925912013-01-05 02:09:22 +00002771 // It isn't profitable to do this, roll back.
2772 //cerr << "NOT FOLDING: " << *I;
2773 AddrMode = BackupAddrMode;
2774 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002775 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00002776 }
2777 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
2778 if (MatchOperationAddr(CE, CE->getOpcode(), Depth))
2779 return true;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002780 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00002781 } else if (isa<ConstantPointerNull>(Addr)) {
2782 // Null pointer gets folded without affecting the addressing mode.
2783 return true;
2784 }
2785
2786 // Worse case, the target should support [reg] addressing modes. :)
2787 if (!AddrMode.HasBaseReg) {
2788 AddrMode.HasBaseReg = true;
2789 AddrMode.BaseReg = Addr;
2790 // Still check for legality in case the target supports [imm] but not [i+r].
2791 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2792 return true;
2793 AddrMode.HasBaseReg = false;
Craig Topperc0196b12014-04-14 00:51:57 +00002794 AddrMode.BaseReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00002795 }
2796
2797 // If the base register is already taken, see if we can do [r+r].
2798 if (AddrMode.Scale == 0) {
2799 AddrMode.Scale = 1;
2800 AddrMode.ScaledReg = Addr;
2801 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2802 return true;
2803 AddrMode.Scale = 0;
Craig Topperc0196b12014-04-14 00:51:57 +00002804 AddrMode.ScaledReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00002805 }
2806 // Couldn't match.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002807 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00002808 return false;
2809}
2810
2811/// IsOperandAMemoryOperand - Check to see if all uses of OpVal by the specified
2812/// inline asm call are due to memory operands. If so, return true, otherwise
2813/// return false.
2814static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
Eric Christopher11e4df72015-02-26 22:38:43 +00002815 const TargetMachine &TM) {
2816 const Function *F = CI->getParent()->getParent();
2817 const TargetLowering *TLI = TM.getSubtargetImpl(*F)->getTargetLowering();
2818 const TargetRegisterInfo *TRI = TM.getSubtargetImpl(*F)->getRegisterInfo();
Eric Christopherd75c00c2015-02-26 22:38:34 +00002819 TargetLowering::AsmOperandInfoVector TargetConstraints =
Eric Christopher11e4df72015-02-26 22:38:43 +00002820 TLI->ParseConstraints(TRI, ImmutableCallSite(CI));
Chandler Carruthc8925912013-01-05 02:09:22 +00002821 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
2822 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Stephen Lin837bba12013-07-15 17:55:02 +00002823
Chandler Carruthc8925912013-01-05 02:09:22 +00002824 // Compute the constraint code and ConstraintType to use.
Eric Christopher11e4df72015-02-26 22:38:43 +00002825 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Chandler Carruthc8925912013-01-05 02:09:22 +00002826
2827 // If this asm operand is our Value*, and if it isn't an indirect memory
2828 // operand, we can't fold it!
2829 if (OpInfo.CallOperandVal == OpVal &&
2830 (OpInfo.ConstraintType != TargetLowering::C_Memory ||
2831 !OpInfo.isIndirect))
2832 return false;
2833 }
2834
2835 return true;
2836}
2837
2838/// FindAllMemoryUses - Recursively walk all the uses of I until we find a
2839/// memory use. If we find an obviously non-foldable instruction, return true.
2840/// Add the ultimately found memory instructions to MemoryUses.
Eric Christopher11e4df72015-02-26 22:38:43 +00002841static bool FindAllMemoryUses(
2842 Instruction *I,
2843 SmallVectorImpl<std::pair<Instruction *, unsigned>> &MemoryUses,
2844 SmallPtrSetImpl<Instruction *> &ConsideredInsts, const TargetMachine &TM) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002845 // If we already considered this instruction, we're done.
David Blaikie70573dc2014-11-19 07:49:26 +00002846 if (!ConsideredInsts.insert(I).second)
Chandler Carruthc8925912013-01-05 02:09:22 +00002847 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00002848
Chandler Carruthc8925912013-01-05 02:09:22 +00002849 // If this is an obviously unfoldable instruction, bail out.
2850 if (!MightBeFoldableInst(I))
2851 return true;
2852
2853 // Loop over all the uses, recursively processing them.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002854 for (Use &U : I->uses()) {
2855 Instruction *UserI = cast<Instruction>(U.getUser());
Chandler Carruthc8925912013-01-05 02:09:22 +00002856
Chandler Carruthcdf47882014-03-09 03:16:01 +00002857 if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
2858 MemoryUses.push_back(std::make_pair(LI, U.getOperandNo()));
Chandler Carruthc8925912013-01-05 02:09:22 +00002859 continue;
2860 }
Stephen Lin837bba12013-07-15 17:55:02 +00002861
Chandler Carruthcdf47882014-03-09 03:16:01 +00002862 if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
2863 unsigned opNo = U.getOperandNo();
Chandler Carruthc8925912013-01-05 02:09:22 +00002864 if (opNo == 0) return true; // Storing addr, not into addr.
2865 MemoryUses.push_back(std::make_pair(SI, opNo));
2866 continue;
2867 }
Stephen Lin837bba12013-07-15 17:55:02 +00002868
Chandler Carruthcdf47882014-03-09 03:16:01 +00002869 if (CallInst *CI = dyn_cast<CallInst>(UserI)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002870 InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
2871 if (!IA) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002872
Chandler Carruthc8925912013-01-05 02:09:22 +00002873 // If this is a memory operand, we're cool, otherwise bail out.
Eric Christopher11e4df72015-02-26 22:38:43 +00002874 if (!IsOperandAMemoryOperand(CI, IA, I, TM))
Chandler Carruthc8925912013-01-05 02:09:22 +00002875 return true;
2876 continue;
2877 }
Stephen Lin837bba12013-07-15 17:55:02 +00002878
Eric Christopher11e4df72015-02-26 22:38:43 +00002879 if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TM))
Chandler Carruthc8925912013-01-05 02:09:22 +00002880 return true;
2881 }
2882
2883 return false;
2884}
2885
2886/// ValueAlreadyLiveAtInst - Retrn true if Val is already known to be live at
2887/// the use site that we're folding it into. If so, there is no cost to
2888/// include it in the addressing mode. KnownLive1 and KnownLive2 are two values
2889/// that we know are live at the instruction already.
2890bool AddressingModeMatcher::ValueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
2891 Value *KnownLive2) {
2892 // If Val is either of the known-live values, we know it is live!
Craig Topperc0196b12014-04-14 00:51:57 +00002893 if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2)
Chandler Carruthc8925912013-01-05 02:09:22 +00002894 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002895
Chandler Carruthc8925912013-01-05 02:09:22 +00002896 // All values other than instructions and arguments (e.g. constants) are live.
2897 if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002898
Chandler Carruthc8925912013-01-05 02:09:22 +00002899 // If Val is a constant sized alloca in the entry block, it is live, this is
2900 // true because it is just a reference to the stack/frame pointer, which is
2901 // live for the whole function.
2902 if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
2903 if (AI->isStaticAlloca())
2904 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002905
Chandler Carruthc8925912013-01-05 02:09:22 +00002906 // Check to see if this value is already used in the memory instruction's
2907 // block. If so, it's already live into the block at the very least, so we
2908 // can reasonably fold it.
2909 return Val->isUsedInBasicBlock(MemoryInst->getParent());
2910}
2911
2912/// IsProfitableToFoldIntoAddressingMode - It is possible for the addressing
2913/// mode of the machine to fold the specified instruction into a load or store
2914/// that ultimately uses it. However, the specified instruction has multiple
2915/// uses. Given this, it may actually increase register pressure to fold it
2916/// into the load. For example, consider this code:
2917///
2918/// X = ...
2919/// Y = X+1
2920/// use(Y) -> nonload/store
2921/// Z = Y+1
2922/// load Z
2923///
2924/// In this case, Y has multiple uses, and can be folded into the load of Z
2925/// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to
2926/// be live at the use(Y) line. If we don't fold Y into load Z, we use one
2927/// fewer register. Since Y can't be folded into "use(Y)" we don't increase the
2928/// number of computations either.
2929///
2930/// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If
2931/// X was live across 'load Z' for other reasons, we actually *would* want to
2932/// fold the addressing mode in the Z case. This would make Y die earlier.
2933bool AddressingModeMatcher::
2934IsProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
2935 ExtAddrMode &AMAfter) {
2936 if (IgnoreProfitability) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002937
Chandler Carruthc8925912013-01-05 02:09:22 +00002938 // AMBefore is the addressing mode before this instruction was folded into it,
2939 // and AMAfter is the addressing mode after the instruction was folded. Get
2940 // the set of registers referenced by AMAfter and subtract out those
2941 // referenced by AMBefore: this is the set of values which folding in this
2942 // address extends the lifetime of.
2943 //
2944 // Note that there are only two potential values being referenced here,
2945 // BaseReg and ScaleReg (global addresses are always available, as are any
2946 // folded immediates).
2947 Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
Stephen Lin837bba12013-07-15 17:55:02 +00002948
Chandler Carruthc8925912013-01-05 02:09:22 +00002949 // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
2950 // lifetime wasn't extended by adding this instruction.
2951 if (ValueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
Craig Topperc0196b12014-04-14 00:51:57 +00002952 BaseReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00002953 if (ValueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
Craig Topperc0196b12014-04-14 00:51:57 +00002954 ScaledReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00002955
2956 // If folding this instruction (and it's subexprs) didn't extend any live
2957 // ranges, we're ok with it.
Craig Topperc0196b12014-04-14 00:51:57 +00002958 if (!BaseReg && !ScaledReg)
Chandler Carruthc8925912013-01-05 02:09:22 +00002959 return true;
2960
2961 // If all uses of this instruction are ultimately load/store/inlineasm's,
2962 // check to see if their addressing modes will include this instruction. If
2963 // so, we can fold it into all uses, so it doesn't matter if it has multiple
2964 // uses.
2965 SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
2966 SmallPtrSet<Instruction*, 16> ConsideredInsts;
Eric Christopher11e4df72015-02-26 22:38:43 +00002967 if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TM))
Chandler Carruthc8925912013-01-05 02:09:22 +00002968 return false; // Has a non-memory, non-foldable use!
Stephen Lin837bba12013-07-15 17:55:02 +00002969
Chandler Carruthc8925912013-01-05 02:09:22 +00002970 // Now that we know that all uses of this instruction are part of a chain of
2971 // computation involving only operations that could theoretically be folded
2972 // into a memory use, loop over each of these uses and see if they could
2973 // *actually* fold the instruction.
2974 SmallVector<Instruction*, 32> MatchedAddrModeInsts;
2975 for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
2976 Instruction *User = MemoryUses[i].first;
2977 unsigned OpNo = MemoryUses[i].second;
Stephen Lin837bba12013-07-15 17:55:02 +00002978
Chandler Carruthc8925912013-01-05 02:09:22 +00002979 // Get the access type of this use. If the use isn't a pointer, we don't
2980 // know what it accesses.
2981 Value *Address = User->getOperand(OpNo);
2982 if (!Address->getType()->isPointerTy())
2983 return false;
Matt Arsenault8227b9f2013-09-06 00:37:24 +00002984 Type *AddressAccessTy = Address->getType()->getPointerElementType();
Stephen Lin837bba12013-07-15 17:55:02 +00002985
Chandler Carruthc8925912013-01-05 02:09:22 +00002986 // Do a match against the root of this address, ignoring profitability. This
2987 // will tell us if the addressing mode for the memory operation will
2988 // *actually* cover the shared instruction.
2989 ExtAddrMode Result;
Quentin Colombet5a69dda2014-02-11 01:59:02 +00002990 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2991 TPT.getRestorationPoint();
Eric Christopherd75c00c2015-02-26 22:38:34 +00002992 AddressingModeMatcher Matcher(MatchedAddrModeInsts, TM, AddressAccessTy,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002993 MemoryInst, Result, InsertedTruncs,
2994 PromotedInsts, TPT);
Chandler Carruthc8925912013-01-05 02:09:22 +00002995 Matcher.IgnoreProfitability = true;
2996 bool Success = Matcher.MatchAddr(Address, 0);
2997 (void)Success; assert(Success && "Couldn't select *anything*?");
2998
Quentin Colombet5a69dda2014-02-11 01:59:02 +00002999 // The match was to check the profitability, the changes made are not
3000 // part of the original matcher. Therefore, they should be dropped
3001 // otherwise the original matcher will not present the right state.
3002 TPT.rollback(LastKnownGood);
3003
Chandler Carruthc8925912013-01-05 02:09:22 +00003004 // If the match didn't cover I, then it won't be shared by it.
3005 if (std::find(MatchedAddrModeInsts.begin(), MatchedAddrModeInsts.end(),
3006 I) == MatchedAddrModeInsts.end())
3007 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003008
Chandler Carruthc8925912013-01-05 02:09:22 +00003009 MatchedAddrModeInsts.clear();
3010 }
Stephen Lin837bba12013-07-15 17:55:02 +00003011
Chandler Carruthc8925912013-01-05 02:09:22 +00003012 return true;
3013}
3014
3015} // end anonymous namespace
3016
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003017/// IsNonLocalValue - Return true if the specified values are defined in a
3018/// different basic block than BB.
3019static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
3020 if (Instruction *I = dyn_cast<Instruction>(V))
3021 return I->getParent() != BB;
3022 return false;
3023}
3024
Bob Wilson53bdae32009-12-03 21:47:07 +00003025/// OptimizeMemoryInst - Load and Store Instructions often have
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003026/// addressing modes that can do significant amounts of computation. As such,
3027/// instruction selection will try to get the load or store to do as much
3028/// computation as possible for the program. The problem is that isel can only
3029/// see within a single block. As such, we sink as much legal addressing mode
3030/// stuff into the block as possible.
Chris Lattner728f9022008-11-25 07:09:13 +00003031///
3032/// This method is used to optimize both load/store and inline asms with memory
3033/// operands.
Chris Lattner6d71b7f2008-11-26 03:20:37 +00003034bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
Chris Lattner229907c2011-07-18 04:54:35 +00003035 Type *AccessTy) {
Owen Anderson8ba5f392010-11-27 08:15:55 +00003036 Value *Repl = Addr;
Nadav Rotem465834c2012-07-24 10:51:42 +00003037
3038 // Try to collapse single-value PHI nodes. This is necessary to undo
Owen Andersondfb8c3b2010-11-19 22:15:03 +00003039 // unprofitable PRE transformations.
Cameron Zwarich43cecb12011-01-03 06:33:01 +00003040 SmallVector<Value*, 8> worklist;
3041 SmallPtrSet<Value*, 16> Visited;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003042 worklist.push_back(Addr);
Nadav Rotem465834c2012-07-24 10:51:42 +00003043
Owen Anderson8ba5f392010-11-27 08:15:55 +00003044 // Use a worklist to iteratively look through PHI nodes, and ensure that
3045 // the addressing mode obtained from the non-PHI roots of the graph
3046 // are equivalent.
Craig Topperc0196b12014-04-14 00:51:57 +00003047 Value *Consensus = nullptr;
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00003048 unsigned NumUsesConsensus = 0;
Cameron Zwarich13c885d2011-03-05 08:12:26 +00003049 bool IsNumUsesConsensusValid = false;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003050 SmallVector<Instruction*, 16> AddrModeInsts;
3051 ExtAddrMode AddrMode;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003052 TypePromotionTransaction TPT;
3053 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3054 TPT.getRestorationPoint();
Owen Anderson8ba5f392010-11-27 08:15:55 +00003055 while (!worklist.empty()) {
3056 Value *V = worklist.back();
3057 worklist.pop_back();
Nadav Rotem465834c2012-07-24 10:51:42 +00003058
Owen Anderson8ba5f392010-11-27 08:15:55 +00003059 // Break use-def graph loops.
David Blaikie70573dc2014-11-19 07:49:26 +00003060 if (!Visited.insert(V).second) {
Craig Topperc0196b12014-04-14 00:51:57 +00003061 Consensus = nullptr;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003062 break;
Owen Andersondfb8c3b2010-11-19 22:15:03 +00003063 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003064
Owen Anderson8ba5f392010-11-27 08:15:55 +00003065 // For a PHI node, push all of its incoming values.
3066 if (PHINode *P = dyn_cast<PHINode>(V)) {
3067 for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i)
3068 worklist.push_back(P->getIncomingValue(i));
3069 continue;
3070 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003071
Owen Anderson8ba5f392010-11-27 08:15:55 +00003072 // For non-PHIs, determine the addressing mode being computed.
3073 SmallVector<Instruction*, 16> NewAddrModeInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003074 ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
Eric Christopherd75c00c2015-02-26 22:38:34 +00003075 V, AccessTy, MemoryInst, NewAddrModeInsts, *TM, InsertedTruncsSet,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003076 PromotedInsts, TPT);
Cameron Zwarich13c885d2011-03-05 08:12:26 +00003077
3078 // This check is broken into two cases with very similar code to avoid using
3079 // getNumUses() as much as possible. Some values have a lot of uses, so
3080 // calling getNumUses() unconditionally caused a significant compile-time
3081 // regression.
3082 if (!Consensus) {
3083 Consensus = V;
3084 AddrMode = NewAddrMode;
3085 AddrModeInsts = NewAddrModeInsts;
3086 continue;
3087 } else if (NewAddrMode == AddrMode) {
3088 if (!IsNumUsesConsensusValid) {
3089 NumUsesConsensus = Consensus->getNumUses();
3090 IsNumUsesConsensusValid = true;
3091 }
3092
3093 // Ensure that the obtained addressing mode is equivalent to that obtained
3094 // for all other roots of the PHI traversal. Also, when choosing one
3095 // such root as representative, select the one with the most uses in order
3096 // to keep the cost modeling heuristics in AddressingModeMatcher
3097 // applicable.
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00003098 unsigned NumUses = V->getNumUses();
3099 if (NumUses > NumUsesConsensus) {
Owen Anderson8ba5f392010-11-27 08:15:55 +00003100 Consensus = V;
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00003101 NumUsesConsensus = NumUses;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003102 AddrModeInsts = NewAddrModeInsts;
3103 }
3104 continue;
3105 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003106
Craig Topperc0196b12014-04-14 00:51:57 +00003107 Consensus = nullptr;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003108 break;
Owen Andersondfb8c3b2010-11-19 22:15:03 +00003109 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003110
Owen Anderson8ba5f392010-11-27 08:15:55 +00003111 // If the addressing mode couldn't be determined, or if multiple different
3112 // ones were determined, bail out now.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003113 if (!Consensus) {
3114 TPT.rollback(LastKnownGood);
3115 return false;
3116 }
3117 TPT.commit();
Nadav Rotem465834c2012-07-24 10:51:42 +00003118
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003119 // Check to see if any of the instructions supersumed by this addr mode are
3120 // non-local to I's BB.
3121 bool AnyNonLocal = false;
3122 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
Chris Lattner6d71b7f2008-11-26 03:20:37 +00003123 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003124 AnyNonLocal = true;
3125 break;
3126 }
3127 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00003128
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003129 // If all the instructions matched are already in this BB, don't do anything.
3130 if (!AnyNonLocal) {
David Greene74e2d492010-01-05 01:27:11 +00003131 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003132 return false;
3133 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00003134
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003135 // Insert this computation right after this user. Since our caller is
3136 // scanning from the top of the BB to the bottom, reuse of the expr are
3137 // guaranteed to happen later.
Devang Patelc10e52a2011-09-06 18:49:53 +00003138 IRBuilder<> Builder(MemoryInst);
Eric Christopherc1ea1492008-09-24 05:32:41 +00003139
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003140 // Now that we determined the addressing expression we want to use and know
3141 // that we have to sink it into this block. Check to see if we have already
3142 // done this for some other load/store instr in this block. If so, reuse the
3143 // computation.
3144 Value *&SunkAddr = SunkAddrs[Addr];
3145 if (SunkAddr) {
David Greene74e2d492010-01-05 01:27:11 +00003146 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00003147 << *MemoryInst << "\n");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003148 if (SunkAddr->getType() != Addr->getType())
Benjamin Kramer547b6c52011-09-27 20:39:19 +00003149 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
Eric Christopherfccff372015-01-27 01:01:38 +00003150 } else if (AddrSinkUsingGEPs ||
3151 (!AddrSinkUsingGEPs.getNumOccurrences() && TM &&
Eric Christopher2c635492015-01-27 07:54:39 +00003152 TM->getSubtargetImpl(*MemoryInst->getParent()->getParent())
3153 ->useAA())) {
Hal Finkelc3998302014-04-12 00:59:48 +00003154 // By default, we use the GEP-based method when AA is used later. This
3155 // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities.
3156 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00003157 << *MemoryInst << "\n");
Hal Finkelc3998302014-04-12 00:59:48 +00003158 Type *IntPtrTy = TLI->getDataLayout()->getIntPtrType(Addr->getType());
Craig Topperc0196b12014-04-14 00:51:57 +00003159 Value *ResultPtr = nullptr, *ResultIndex = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00003160
3161 // First, find the pointer.
3162 if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) {
3163 ResultPtr = AddrMode.BaseReg;
Craig Topperc0196b12014-04-14 00:51:57 +00003164 AddrMode.BaseReg = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00003165 }
3166
3167 if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) {
3168 // We can't add more than one pointer together, nor can we scale a
3169 // pointer (both of which seem meaningless).
3170 if (ResultPtr || AddrMode.Scale != 1)
3171 return false;
3172
3173 ResultPtr = AddrMode.ScaledReg;
3174 AddrMode.Scale = 0;
3175 }
3176
3177 if (AddrMode.BaseGV) {
3178 if (ResultPtr)
3179 return false;
3180
3181 ResultPtr = AddrMode.BaseGV;
3182 }
3183
3184 // If the real base value actually came from an inttoptr, then the matcher
3185 // will look through it and provide only the integer value. In that case,
3186 // use it here.
3187 if (!ResultPtr && AddrMode.BaseReg) {
3188 ResultPtr =
3189 Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(), "sunkaddr");
Craig Topperc0196b12014-04-14 00:51:57 +00003190 AddrMode.BaseReg = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00003191 } else if (!ResultPtr && AddrMode.Scale == 1) {
3192 ResultPtr =
3193 Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(), "sunkaddr");
3194 AddrMode.Scale = 0;
3195 }
3196
3197 if (!ResultPtr &&
3198 !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) {
3199 SunkAddr = Constant::getNullValue(Addr->getType());
3200 } else if (!ResultPtr) {
3201 return false;
3202 } else {
3203 Type *I8PtrTy =
3204 Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace());
3205
3206 // Start with the base register. Do this first so that subsequent address
3207 // matching finds it last, which will prevent it from trying to match it
3208 // as the scaled value in case it happens to be a mul. That would be
3209 // problematic if we've sunk a different mul for the scale, because then
3210 // we'd end up sinking both muls.
3211 if (AddrMode.BaseReg) {
3212 Value *V = AddrMode.BaseReg;
3213 if (V->getType() != IntPtrTy)
3214 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
3215
3216 ResultIndex = V;
3217 }
3218
3219 // Add the scale value.
3220 if (AddrMode.Scale) {
3221 Value *V = AddrMode.ScaledReg;
3222 if (V->getType() == IntPtrTy) {
3223 // done.
3224 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
3225 cast<IntegerType>(V->getType())->getBitWidth()) {
3226 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
3227 } else {
3228 // It is only safe to sign extend the BaseReg if we know that the math
3229 // required to create it did not overflow before we extend it. Since
3230 // the original IR value was tossed in favor of a constant back when
3231 // the AddrMode was created we need to bail out gracefully if widths
3232 // do not match instead of extending it.
3233 Instruction *I = dyn_cast_or_null<Instruction>(ResultIndex);
3234 if (I && (ResultIndex != AddrMode.BaseReg))
3235 I->eraseFromParent();
3236 return false;
3237 }
3238
3239 if (AddrMode.Scale != 1)
3240 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
3241 "sunkaddr");
3242 if (ResultIndex)
3243 ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr");
3244 else
3245 ResultIndex = V;
3246 }
3247
3248 // Add in the Base Offset if present.
3249 if (AddrMode.BaseOffs) {
3250 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
3251 if (ResultIndex) {
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00003252 // We need to add this separately from the scale above to help with
3253 // SDAG consecutive load/store merging.
Hal Finkelc3998302014-04-12 00:59:48 +00003254 if (ResultPtr->getType() != I8PtrTy)
3255 ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
3256 ResultPtr = Builder.CreateGEP(ResultPtr, ResultIndex, "sunkaddr");
3257 }
3258
3259 ResultIndex = V;
3260 }
3261
3262 if (!ResultIndex) {
3263 SunkAddr = ResultPtr;
3264 } else {
3265 if (ResultPtr->getType() != I8PtrTy)
3266 ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
3267 SunkAddr = Builder.CreateGEP(ResultPtr, ResultIndex, "sunkaddr");
3268 }
3269
3270 if (SunkAddr->getType() != Addr->getType())
3271 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
3272 }
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003273 } else {
David Greene74e2d492010-01-05 01:27:11 +00003274 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00003275 << *MemoryInst << "\n");
Matt Arsenault37d42ec2013-09-06 00:18:43 +00003276 Type *IntPtrTy = TLI->getDataLayout()->getIntPtrType(Addr->getType());
Craig Topperc0196b12014-04-14 00:51:57 +00003277 Value *Result = nullptr;
Dan Gohmanca194452010-01-19 22:45:06 +00003278
3279 // Start with the base register. Do this first so that subsequent address
3280 // matching finds it last, which will prevent it from trying to match it
3281 // as the scaled value in case it happens to be a mul. That would be
3282 // problematic if we've sunk a different mul for the scale, because then
3283 // we'd end up sinking both muls.
3284 if (AddrMode.BaseReg) {
3285 Value *V = AddrMode.BaseReg;
Duncan Sands19d0b472010-02-16 11:11:14 +00003286 if (V->getType()->isPointerTy())
Devang Patelc10e52a2011-09-06 18:49:53 +00003287 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00003288 if (V->getType() != IntPtrTy)
Devang Patelc10e52a2011-09-06 18:49:53 +00003289 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00003290 Result = V;
3291 }
3292
3293 // Add the scale value.
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003294 if (AddrMode.Scale) {
3295 Value *V = AddrMode.ScaledReg;
3296 if (V->getType() == IntPtrTy) {
3297 // done.
Duncan Sands19d0b472010-02-16 11:11:14 +00003298 } else if (V->getType()->isPointerTy()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00003299 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003300 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
3301 cast<IntegerType>(V->getType())->getBitWidth()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00003302 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003303 } else {
Jim Grosbached2cd392014-03-26 17:27:01 +00003304 // It is only safe to sign extend the BaseReg if we know that the math
3305 // required to create it did not overflow before we extend it. Since
3306 // the original IR value was tossed in favor of a constant back when
3307 // the AddrMode was created we need to bail out gracefully if widths
3308 // do not match instead of extending it.
Joey Gouly12a8bf02014-05-13 15:42:45 +00003309 Instruction *I = dyn_cast_or_null<Instruction>(Result);
Jim Grosbach83b44e12014-04-10 00:27:45 +00003310 if (I && (Result != AddrMode.BaseReg))
3311 I->eraseFromParent();
Jim Grosbached2cd392014-03-26 17:27:01 +00003312 return false;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003313 }
3314 if (AddrMode.Scale != 1)
Devang Patelc10e52a2011-09-06 18:49:53 +00003315 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
3316 "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003317 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00003318 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003319 else
3320 Result = V;
3321 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00003322
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003323 // Add in the BaseGV if present.
3324 if (AddrMode.BaseGV) {
Devang Patelc10e52a2011-09-06 18:49:53 +00003325 Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003326 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00003327 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003328 else
3329 Result = V;
3330 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00003331
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003332 // Add in the Base Offset if present.
3333 if (AddrMode.BaseOffs) {
Owen Andersonedb4a702009-07-24 23:12:02 +00003334 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003335 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00003336 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003337 else
3338 Result = V;
3339 }
3340
Craig Topperc0196b12014-04-14 00:51:57 +00003341 if (!Result)
Owen Anderson5a1acd92009-07-31 20:28:14 +00003342 SunkAddr = Constant::getNullValue(Addr->getType());
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003343 else
Devang Patelc10e52a2011-09-06 18:49:53 +00003344 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003345 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00003346
Owen Andersondfb8c3b2010-11-19 22:15:03 +00003347 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
Eric Christopherc1ea1492008-09-24 05:32:41 +00003348
Chris Lattneraf1bcce2011-04-09 07:05:44 +00003349 // If we have no uses, recursively delete the value and all dead instructions
3350 // using it.
Owen Andersondfb8c3b2010-11-19 22:15:03 +00003351 if (Repl->use_empty()) {
Chris Lattneraf1bcce2011-04-09 07:05:44 +00003352 // This can cause recursive deletion, which can invalidate our iterator.
3353 // Use a WeakVH to hold onto it in case this happens.
3354 WeakVH IterHandle(CurInstIterator);
3355 BasicBlock *BB = CurInstIterator->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +00003356
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00003357 RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
Chris Lattneraf1bcce2011-04-09 07:05:44 +00003358
3359 if (IterHandle != CurInstIterator) {
3360 // If the iterator instruction was recursively deleted, start over at the
3361 // start of the block.
3362 CurInstIterator = BB->begin();
3363 SunkAddrs.clear();
Nadav Rotem465834c2012-07-24 10:51:42 +00003364 }
Dale Johannesenb67a6e662010-03-31 20:37:15 +00003365 }
Cameron Zwarichced753f2011-01-05 17:27:27 +00003366 ++NumMemoryInsts;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003367 return true;
3368}
3369
Evan Cheng1da25002008-02-26 02:42:37 +00003370/// OptimizeInlineAsmInst - If there are any memory operands, use
Chris Lattner728f9022008-11-25 07:09:13 +00003371/// OptimizeMemoryInst to sink their address computing into the block when
Evan Cheng1da25002008-02-26 02:42:37 +00003372/// possible / profitable.
Chris Lattner7a277142011-01-15 07:14:54 +00003373bool CodeGenPrepare::OptimizeInlineAsmInst(CallInst *CS) {
Evan Cheng1da25002008-02-26 02:42:37 +00003374 bool MadeChange = false;
Evan Cheng1da25002008-02-26 02:42:37 +00003375
Eric Christopher11e4df72015-02-26 22:38:43 +00003376 const TargetRegisterInfo *TRI =
3377 TM->getSubtargetImpl(*CS->getParent()->getParent())->getRegisterInfo();
Nadav Rotem465834c2012-07-24 10:51:42 +00003378 TargetLowering::AsmOperandInfoVector
Eric Christopher11e4df72015-02-26 22:38:43 +00003379 TargetConstraints = TLI->ParseConstraints(TRI, CS);
Dale Johannesenf95f59a2010-09-16 18:30:55 +00003380 unsigned ArgNo = 0;
John Thompson1094c802010-09-13 18:15:37 +00003381 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
3382 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Nadav Rotem465834c2012-07-24 10:51:42 +00003383
Evan Cheng1da25002008-02-26 02:42:37 +00003384 // Compute the constraint code and ConstraintType to use.
Dale Johannesence97d552010-06-25 21:55:36 +00003385 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Evan Cheng1da25002008-02-26 02:42:37 +00003386
Eli Friedman666bbe32008-02-26 18:37:49 +00003387 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
3388 OpInfo.isIndirect) {
Chris Lattner7a277142011-01-15 07:14:54 +00003389 Value *OpVal = CS->getArgOperand(ArgNo++);
Chris Lattneree588de2011-01-15 07:29:01 +00003390 MadeChange |= OptimizeMemoryInst(CS, OpVal, OpVal->getType());
Dale Johannesenf95f59a2010-09-16 18:30:55 +00003391 } else if (OpInfo.Type == InlineAsm::isInput)
3392 ArgNo++;
Evan Cheng1da25002008-02-26 02:42:37 +00003393 }
3394
3395 return MadeChange;
3396}
3397
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003398/// \brief Check if all the uses of \p Inst are equivalent (or free) zero or
3399/// sign extensions.
3400static bool hasSameExtUse(Instruction *Inst, const TargetLowering &TLI) {
3401 assert(!Inst->use_empty() && "Input must have at least one use");
3402 const Instruction *FirstUser = cast<Instruction>(*Inst->user_begin());
3403 bool IsSExt = isa<SExtInst>(FirstUser);
3404 Type *ExtTy = FirstUser->getType();
3405 for (const User *U : Inst->users()) {
3406 const Instruction *UI = cast<Instruction>(U);
3407 if ((IsSExt && !isa<SExtInst>(UI)) || (!IsSExt && !isa<ZExtInst>(UI)))
3408 return false;
3409 Type *CurTy = UI->getType();
3410 // Same input and output types: Same instruction after CSE.
3411 if (CurTy == ExtTy)
3412 continue;
3413
3414 // If IsSExt is true, we are in this situation:
3415 // a = Inst
3416 // b = sext ty1 a to ty2
3417 // c = sext ty1 a to ty3
3418 // Assuming ty2 is shorter than ty3, this could be turned into:
3419 // a = Inst
3420 // b = sext ty1 a to ty2
3421 // c = sext ty2 b to ty3
3422 // However, the last sext is not free.
3423 if (IsSExt)
3424 return false;
3425
3426 // This is a ZExt, maybe this is free to extend from one type to another.
3427 // In that case, we would not account for a different use.
3428 Type *NarrowTy;
3429 Type *LargeTy;
3430 if (ExtTy->getScalarType()->getIntegerBitWidth() >
3431 CurTy->getScalarType()->getIntegerBitWidth()) {
3432 NarrowTy = CurTy;
3433 LargeTy = ExtTy;
3434 } else {
3435 NarrowTy = ExtTy;
3436 LargeTy = CurTy;
3437 }
3438
3439 if (!TLI.isZExtFree(NarrowTy, LargeTy))
3440 return false;
3441 }
3442 // All uses are the same or can be derived from one another for free.
3443 return true;
3444}
3445
3446/// \brief Try to form ExtLd by promoting \p Exts until they reach a
3447/// load instruction.
3448/// If an ext(load) can be formed, it is returned via \p LI for the load
3449/// and \p Inst for the extension.
3450/// Otherwise LI == nullptr and Inst == nullptr.
3451/// When some promotion happened, \p TPT contains the proper state to
3452/// revert them.
3453///
3454/// \return true when promoting was necessary to expose the ext(load)
3455/// opportunity, false otherwise.
3456///
3457/// Example:
3458/// \code
3459/// %ld = load i32* %addr
3460/// %add = add nuw i32 %ld, 4
3461/// %zext = zext i32 %add to i64
3462/// \endcode
3463/// =>
3464/// \code
3465/// %ld = load i32* %addr
3466/// %zext = zext i32 %ld to i64
3467/// %add = add nuw i64 %zext, 4
3468/// \encode
3469/// Thanks to the promotion, we can match zext(load i32*) to i64.
3470bool CodeGenPrepare::ExtLdPromotion(TypePromotionTransaction &TPT,
3471 LoadInst *&LI, Instruction *&Inst,
3472 const SmallVectorImpl<Instruction *> &Exts,
3473 unsigned CreatedInsts = 0) {
3474 // Iterate over all the extensions to see if one form an ext(load).
3475 for (auto I : Exts) {
3476 // Check if we directly have ext(load).
3477 if ((LI = dyn_cast<LoadInst>(I->getOperand(0)))) {
3478 Inst = I;
3479 // No promotion happened here.
3480 return false;
3481 }
3482 // Check whether or not we want to do any promotion.
3483 if (!TLI || !TLI->enableExtLdPromotion() || DisableExtLdPromotion)
3484 continue;
3485 // Get the action to perform the promotion.
3486 TypePromotionHelper::Action TPH = TypePromotionHelper::getAction(
3487 I, InsertedTruncsSet, *TLI, PromotedInsts);
3488 // Check if we can promote.
3489 if (!TPH)
3490 continue;
3491 // Save the current state.
3492 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3493 TPT.getRestorationPoint();
3494 SmallVector<Instruction *, 4> NewExts;
3495 unsigned NewCreatedInsts = 0;
3496 // Promote.
3497 Value *PromotedVal =
3498 TPH(I, TPT, PromotedInsts, NewCreatedInsts, &NewExts, nullptr);
3499 assert(PromotedVal &&
3500 "TypePromotionHelper should have filtered out those cases");
3501
3502 // We would be able to merge only one extension in a load.
3503 // Therefore, if we have more than 1 new extension we heuristically
3504 // cut this search path, because it means we degrade the code quality.
3505 // With exactly 2, the transformation is neutral, because we will merge
3506 // one extension but leave one. However, we optimistically keep going,
3507 // because the new extension may be removed too.
3508 unsigned TotalCreatedInsts = CreatedInsts + NewCreatedInsts;
3509 if (!StressExtLdPromotion &&
3510 (TotalCreatedInsts > 1 ||
3511 !isPromotedInstructionLegal(*TLI, PromotedVal))) {
3512 // The promotion is not profitable, rollback to the previous state.
3513 TPT.rollback(LastKnownGood);
3514 continue;
3515 }
3516 // The promotion is profitable.
3517 // Check if it exposes an ext(load).
3518 (void)ExtLdPromotion(TPT, LI, Inst, NewExts, TotalCreatedInsts);
3519 if (LI && (StressExtLdPromotion || NewCreatedInsts == 0 ||
3520 // If we have created a new extension, i.e., now we have two
3521 // extensions. We must make sure one of them is merged with
3522 // the load, otherwise we may degrade the code quality.
3523 (LI->hasOneUse() || hasSameExtUse(LI, *TLI))))
3524 // Promotion happened.
3525 return true;
3526 // If this does not help to expose an ext(load) then, rollback.
3527 TPT.rollback(LastKnownGood);
3528 }
3529 // None of the extension can form an ext(load).
3530 LI = nullptr;
3531 Inst = nullptr;
3532 return false;
3533}
3534
Dan Gohman99429a02009-10-16 20:59:35 +00003535/// MoveExtToFormExtLoad - Move a zext or sext fed by a load into the same
3536/// basic block as the load, unless conditions are unfavorable. This allows
3537/// SelectionDAG to fold the extend into the load.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003538/// \p I[in/out] the extension may be modified during the process if some
3539/// promotions apply.
Dan Gohman99429a02009-10-16 20:59:35 +00003540///
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003541bool CodeGenPrepare::MoveExtToFormExtLoad(Instruction *&I) {
3542 // Try to promote a chain of computation if it allows to form
3543 // an extended load.
3544 TypePromotionTransaction TPT;
3545 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3546 TPT.getRestorationPoint();
3547 SmallVector<Instruction *, 1> Exts;
3548 Exts.push_back(I);
Dan Gohman99429a02009-10-16 20:59:35 +00003549 // Look for a load being extended.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003550 LoadInst *LI = nullptr;
3551 Instruction *OldExt = I;
3552 bool HasPromoted = ExtLdPromotion(TPT, LI, I, Exts);
3553 if (!LI || !I) {
3554 assert(!HasPromoted && !LI && "If we did not match any load instruction "
3555 "the code must remain the same");
3556 I = OldExt;
3557 return false;
3558 }
Dan Gohman99429a02009-10-16 20:59:35 +00003559
3560 // If they're already in the same block, there's nothing to do.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003561 // Make the cheap checks first if we did not promote.
3562 // If we promoted, we need to check if it is indeed profitable.
3563 if (!HasPromoted && LI->getParent() == I->getParent())
Dan Gohman99429a02009-10-16 20:59:35 +00003564 return false;
3565
Ahmed Bougacha55e3c2d2014-12-05 18:04:40 +00003566 EVT VT = TLI->getValueType(I->getType());
3567 EVT LoadVT = TLI->getValueType(LI->getType());
3568
Dan Gohman99429a02009-10-16 20:59:35 +00003569 // If the load has other users and the truncate is not free, this probably
3570 // isn't worthwhile.
Ahmed Bougacha55e3c2d2014-12-05 18:04:40 +00003571 if (!LI->hasOneUse() && TLI &&
3572 (TLI->isTypeLegal(LoadVT) || !TLI->isTypeLegal(VT)) &&
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003573 !TLI->isTruncateFree(I->getType(), LI->getType())) {
3574 I = OldExt;
3575 TPT.rollback(LastKnownGood);
Dan Gohman99429a02009-10-16 20:59:35 +00003576 return false;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003577 }
Dan Gohman99429a02009-10-16 20:59:35 +00003578
3579 // Check whether the target supports casts folded into loads.
3580 unsigned LType;
3581 if (isa<ZExtInst>(I))
3582 LType = ISD::ZEXTLOAD;
3583 else {
3584 assert(isa<SExtInst>(I) && "Unexpected ext type!");
3585 LType = ISD::SEXTLOAD;
3586 }
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00003587 if (TLI && !TLI->isLoadExtLegal(LType, VT, LoadVT)) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003588 I = OldExt;
3589 TPT.rollback(LastKnownGood);
Dan Gohman99429a02009-10-16 20:59:35 +00003590 return false;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003591 }
Dan Gohman99429a02009-10-16 20:59:35 +00003592
3593 // Move the extend into the same block as the load, so that SelectionDAG
3594 // can fold it.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003595 TPT.commit();
Dan Gohman99429a02009-10-16 20:59:35 +00003596 I->removeFromParent();
3597 I->insertAfter(LI);
Cameron Zwarichced753f2011-01-05 17:27:27 +00003598 ++NumExtsMoved;
Dan Gohman99429a02009-10-16 20:59:35 +00003599 return true;
3600}
3601
Evan Chengd3d80172007-12-05 23:58:20 +00003602bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
3603 BasicBlock *DefBB = I->getParent();
3604
Bob Wilsonff714f92010-09-21 21:44:14 +00003605 // If the result of a {s|z}ext and its source are both live out, rewrite all
Evan Chengd3d80172007-12-05 23:58:20 +00003606 // other uses of the source with result of extension.
3607 Value *Src = I->getOperand(0);
3608 if (Src->hasOneUse())
3609 return false;
3610
Evan Cheng2011df42007-12-13 07:50:36 +00003611 // Only do this xform if truncating is free.
Gabor Greifaa261722008-02-26 19:13:21 +00003612 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
Evan Cheng37c36ed2007-12-13 03:32:53 +00003613 return false;
3614
Evan Cheng7bc89422007-12-12 00:51:06 +00003615 // Only safe to perform the optimization if the source is also defined in
Evan Cheng63d33cf2007-12-12 02:53:41 +00003616 // this block.
3617 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
Evan Cheng7bc89422007-12-12 00:51:06 +00003618 return false;
3619
Evan Chengd3d80172007-12-05 23:58:20 +00003620 bool DefIsLiveOut = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00003621 for (User *U : I->users()) {
3622 Instruction *UI = cast<Instruction>(U);
Evan Chengd3d80172007-12-05 23:58:20 +00003623
3624 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003625 BasicBlock *UserBB = UI->getParent();
Evan Chengd3d80172007-12-05 23:58:20 +00003626 if (UserBB == DefBB) continue;
3627 DefIsLiveOut = true;
3628 break;
3629 }
3630 if (!DefIsLiveOut)
3631 return false;
3632
Jim Grosbach0f38c1e2013-04-15 17:40:48 +00003633 // Make sure none of the uses are PHI nodes.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003634 for (User *U : Src->users()) {
3635 Instruction *UI = cast<Instruction>(U);
3636 BasicBlock *UserBB = UI->getParent();
Evan Cheng37c36ed2007-12-13 03:32:53 +00003637 if (UserBB == DefBB) continue;
3638 // Be conservative. We don't want this xform to end up introducing
3639 // reloads just before load / store instructions.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003640 if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI))
Evan Cheng63d33cf2007-12-12 02:53:41 +00003641 return false;
3642 }
3643
Evan Chengd3d80172007-12-05 23:58:20 +00003644 // InsertedTruncs - Only insert one trunc in each block once.
3645 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
3646
3647 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00003648 for (Use &U : Src->uses()) {
3649 Instruction *User = cast<Instruction>(U.getUser());
Evan Chengd3d80172007-12-05 23:58:20 +00003650
3651 // Figure out which BB this ext is used in.
3652 BasicBlock *UserBB = User->getParent();
3653 if (UserBB == DefBB) continue;
3654
3655 // Both src and def are live in this block. Rewrite the use.
3656 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
3657
3658 if (!InsertedTrunc) {
Bill Wendling8ddfc092011-08-16 20:45:24 +00003659 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Evan Chengd3d80172007-12-05 23:58:20 +00003660 InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003661 InsertedTruncsSet.insert(InsertedTrunc);
Evan Chengd3d80172007-12-05 23:58:20 +00003662 }
3663
3664 // Replace a use of the {s|z}ext source with a use of the result.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003665 U = InsertedTrunc;
Cameron Zwarichced753f2011-01-05 17:27:27 +00003666 ++NumExtUses;
Evan Chengd3d80172007-12-05 23:58:20 +00003667 MadeChange = true;
3668 }
3669
3670 return MadeChange;
3671}
3672
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00003673/// isFormingBranchFromSelectProfitable - Returns true if a SelectInst should be
3674/// turned into an explicit branch.
3675static bool isFormingBranchFromSelectProfitable(SelectInst *SI) {
3676 // FIXME: This should use the same heuristics as IfConversion to determine
3677 // whether a select is better represented as a branch. This requires that
3678 // branch probability metadata is preserved for the select, which is not the
3679 // case currently.
3680
3681 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
3682
3683 // If the branch is predicted right, an out of order CPU can avoid blocking on
3684 // the compare. Emit cmovs on compares with a memory operand as branches to
3685 // avoid stalls on the load from memory. If the compare has more than one use
3686 // there's probably another cmov or setcc around so it's not worth emitting a
3687 // branch.
3688 if (!Cmp)
3689 return false;
3690
3691 Value *CmpOp0 = Cmp->getOperand(0);
3692 Value *CmpOp1 = Cmp->getOperand(1);
3693
3694 // We check that the memory operand has one use to avoid uses of the loaded
3695 // value directly after the compare, making branches unprofitable.
3696 return Cmp->hasOneUse() &&
3697 ((isa<LoadInst>(CmpOp0) && CmpOp0->hasOneUse()) ||
3698 (isa<LoadInst>(CmpOp1) && CmpOp1->hasOneUse()));
3699}
3700
3701
Nadav Rotem9d832022012-09-02 12:10:19 +00003702/// If we have a SelectInst that will likely profit from branch prediction,
3703/// turn it into a branch.
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00003704bool CodeGenPrepare::OptimizeSelectInst(SelectInst *SI) {
Nadav Rotem9d832022012-09-02 12:10:19 +00003705 bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
3706
3707 // Can we convert the 'select' to CF ?
3708 if (DisableSelectToBranch || OptSize || !TLI || VectorCond)
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00003709 return false;
3710
Nadav Rotem9d832022012-09-02 12:10:19 +00003711 TargetLowering::SelectSupportKind SelectKind;
3712 if (VectorCond)
3713 SelectKind = TargetLowering::VectorMaskSelect;
3714 else if (SI->getType()->isVectorTy())
3715 SelectKind = TargetLowering::ScalarCondVectorVal;
3716 else
3717 SelectKind = TargetLowering::ScalarValSelect;
3718
3719 // Do we have efficient codegen support for this kind of 'selects' ?
3720 if (TLI->isSelectSupported(SelectKind)) {
3721 // We have efficient codegen support for the select instruction.
3722 // Check if it is profitable to keep this 'select'.
3723 if (!TLI->isPredictableSelectExpensive() ||
3724 !isFormingBranchFromSelectProfitable(SI))
3725 return false;
3726 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00003727
3728 ModifiedDT = true;
3729
3730 // First, we split the block containing the select into 2 blocks.
3731 BasicBlock *StartBlock = SI->getParent();
3732 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(SI));
3733 BasicBlock *NextBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
3734
3735 // Create a new block serving as the landing pad for the branch.
3736 BasicBlock *SmallBlock = BasicBlock::Create(SI->getContext(), "select.mid",
3737 NextBlock->getParent(), NextBlock);
3738
3739 // Move the unconditional branch from the block with the select in it into our
3740 // landing pad block.
3741 StartBlock->getTerminator()->eraseFromParent();
3742 BranchInst::Create(NextBlock, SmallBlock);
3743
3744 // Insert the real conditional branch based on the original condition.
3745 BranchInst::Create(NextBlock, SmallBlock, SI->getCondition(), SI);
3746
3747 // The select itself is replaced with a PHI Node.
3748 PHINode *PN = PHINode::Create(SI->getType(), 2, "", NextBlock->begin());
3749 PN->takeName(SI);
3750 PN->addIncoming(SI->getTrueValue(), StartBlock);
3751 PN->addIncoming(SI->getFalseValue(), SmallBlock);
3752 SI->replaceAllUsesWith(PN);
3753 SI->eraseFromParent();
3754
3755 // Instruct OptimizeBlock to skip to the next block.
3756 CurInstIterator = StartBlock->end();
3757 ++NumSelectsExpanded;
3758 return true;
3759}
3760
Benjamin Kramer573ff362014-03-01 17:24:40 +00003761static bool isBroadcastShuffle(ShuffleVectorInst *SVI) {
Tim Northoveraeb8e062014-02-19 10:02:43 +00003762 SmallVector<int, 16> Mask(SVI->getShuffleMask());
3763 int SplatElem = -1;
3764 for (unsigned i = 0; i < Mask.size(); ++i) {
3765 if (SplatElem != -1 && Mask[i] != -1 && Mask[i] != SplatElem)
3766 return false;
3767 SplatElem = Mask[i];
3768 }
3769
3770 return true;
3771}
3772
3773/// Some targets have expensive vector shifts if the lanes aren't all the same
3774/// (e.g. x86 only introduced "vpsllvd" and friends with AVX2). In these cases
3775/// it's often worth sinking a shufflevector splat down to its use so that
3776/// codegen can spot all lanes are identical.
3777bool CodeGenPrepare::OptimizeShuffleVectorInst(ShuffleVectorInst *SVI) {
3778 BasicBlock *DefBB = SVI->getParent();
3779
3780 // Only do this xform if variable vector shifts are particularly expensive.
3781 if (!TLI || !TLI->isVectorShiftByScalarCheap(SVI->getType()))
3782 return false;
3783
3784 // We only expect better codegen by sinking a shuffle if we can recognise a
3785 // constant splat.
3786 if (!isBroadcastShuffle(SVI))
3787 return false;
3788
3789 // InsertedShuffles - Only insert a shuffle in each block once.
3790 DenseMap<BasicBlock*, Instruction*> InsertedShuffles;
3791
3792 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00003793 for (User *U : SVI->users()) {
3794 Instruction *UI = cast<Instruction>(U);
Tim Northoveraeb8e062014-02-19 10:02:43 +00003795
3796 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003797 BasicBlock *UserBB = UI->getParent();
Tim Northoveraeb8e062014-02-19 10:02:43 +00003798 if (UserBB == DefBB) continue;
3799
3800 // For now only apply this when the splat is used by a shift instruction.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003801 if (!UI->isShift()) continue;
Tim Northoveraeb8e062014-02-19 10:02:43 +00003802
3803 // Everything checks out, sink the shuffle if the user's block doesn't
3804 // already have a copy.
3805 Instruction *&InsertedShuffle = InsertedShuffles[UserBB];
3806
3807 if (!InsertedShuffle) {
3808 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
3809 InsertedShuffle = new ShuffleVectorInst(SVI->getOperand(0),
3810 SVI->getOperand(1),
3811 SVI->getOperand(2), "", InsertPt);
3812 }
3813
Chandler Carruthcdf47882014-03-09 03:16:01 +00003814 UI->replaceUsesOfWith(SVI, InsertedShuffle);
Tim Northoveraeb8e062014-02-19 10:02:43 +00003815 MadeChange = true;
3816 }
3817
3818 // If we removed all uses, nuke the shuffle.
3819 if (SVI->use_empty()) {
3820 SVI->eraseFromParent();
3821 MadeChange = true;
3822 }
3823
3824 return MadeChange;
3825}
3826
Quentin Colombetc32615d2014-10-31 17:52:53 +00003827namespace {
3828/// \brief Helper class to promote a scalar operation to a vector one.
3829/// This class is used to move downward extractelement transition.
3830/// E.g.,
3831/// a = vector_op <2 x i32>
3832/// b = extractelement <2 x i32> a, i32 0
3833/// c = scalar_op b
3834/// store c
3835///
3836/// =>
3837/// a = vector_op <2 x i32>
3838/// c = vector_op a (equivalent to scalar_op on the related lane)
3839/// * d = extractelement <2 x i32> c, i32 0
3840/// * store d
3841/// Assuming both extractelement and store can be combine, we get rid of the
3842/// transition.
3843class VectorPromoteHelper {
3844 /// Used to perform some checks on the legality of vector operations.
3845 const TargetLowering &TLI;
3846
3847 /// Used to estimated the cost of the promoted chain.
3848 const TargetTransformInfo &TTI;
3849
3850 /// The transition being moved downwards.
3851 Instruction *Transition;
3852 /// The sequence of instructions to be promoted.
3853 SmallVector<Instruction *, 4> InstsToBePromoted;
3854 /// Cost of combining a store and an extract.
3855 unsigned StoreExtractCombineCost;
3856 /// Instruction that will be combined with the transition.
3857 Instruction *CombineInst;
3858
3859 /// \brief The instruction that represents the current end of the transition.
3860 /// Since we are faking the promotion until we reach the end of the chain
3861 /// of computation, we need a way to get the current end of the transition.
3862 Instruction *getEndOfTransition() const {
3863 if (InstsToBePromoted.empty())
3864 return Transition;
3865 return InstsToBePromoted.back();
3866 }
3867
3868 /// \brief Return the index of the original value in the transition.
3869 /// E.g., for "extractelement <2 x i32> c, i32 1" the original value,
3870 /// c, is at index 0.
3871 unsigned getTransitionOriginalValueIdx() const {
3872 assert(isa<ExtractElementInst>(Transition) &&
3873 "Other kind of transitions are not supported yet");
3874 return 0;
3875 }
3876
3877 /// \brief Return the index of the index in the transition.
3878 /// E.g., for "extractelement <2 x i32> c, i32 0" the index
3879 /// is at index 1.
3880 unsigned getTransitionIdx() const {
3881 assert(isa<ExtractElementInst>(Transition) &&
3882 "Other kind of transitions are not supported yet");
3883 return 1;
3884 }
3885
3886 /// \brief Get the type of the transition.
3887 /// This is the type of the original value.
3888 /// E.g., for "extractelement <2 x i32> c, i32 1" the type of the
3889 /// transition is <2 x i32>.
3890 Type *getTransitionType() const {
3891 return Transition->getOperand(getTransitionOriginalValueIdx())->getType();
3892 }
3893
3894 /// \brief Promote \p ToBePromoted by moving \p Def downward through.
3895 /// I.e., we have the following sequence:
3896 /// Def = Transition <ty1> a to <ty2>
3897 /// b = ToBePromoted <ty2> Def, ...
3898 /// =>
3899 /// b = ToBePromoted <ty1> a, ...
3900 /// Def = Transition <ty1> ToBePromoted to <ty2>
3901 void promoteImpl(Instruction *ToBePromoted);
3902
3903 /// \brief Check whether or not it is profitable to promote all the
3904 /// instructions enqueued to be promoted.
3905 bool isProfitableToPromote() {
3906 Value *ValIdx = Transition->getOperand(getTransitionOriginalValueIdx());
3907 unsigned Index = isa<ConstantInt>(ValIdx)
3908 ? cast<ConstantInt>(ValIdx)->getZExtValue()
3909 : -1;
3910 Type *PromotedType = getTransitionType();
3911
3912 StoreInst *ST = cast<StoreInst>(CombineInst);
3913 unsigned AS = ST->getPointerAddressSpace();
3914 unsigned Align = ST->getAlignment();
3915 // Check if this store is supported.
3916 if (!TLI.allowsMisalignedMemoryAccesses(
Ahmed Bougacha026600d2014-11-12 23:05:03 +00003917 TLI.getValueType(ST->getValueOperand()->getType()), AS, Align)) {
Quentin Colombetc32615d2014-10-31 17:52:53 +00003918 // If this is not supported, there is no way we can combine
3919 // the extract with the store.
3920 return false;
3921 }
3922
3923 // The scalar chain of computation has to pay for the transition
3924 // scalar to vector.
3925 // The vector chain has to account for the combining cost.
3926 uint64_t ScalarCost =
3927 TTI.getVectorInstrCost(Transition->getOpcode(), PromotedType, Index);
3928 uint64_t VectorCost = StoreExtractCombineCost;
3929 for (const auto &Inst : InstsToBePromoted) {
3930 // Compute the cost.
3931 // By construction, all instructions being promoted are arithmetic ones.
3932 // Moreover, one argument is a constant that can be viewed as a splat
3933 // constant.
3934 Value *Arg0 = Inst->getOperand(0);
3935 bool IsArg0Constant = isa<UndefValue>(Arg0) || isa<ConstantInt>(Arg0) ||
3936 isa<ConstantFP>(Arg0);
3937 TargetTransformInfo::OperandValueKind Arg0OVK =
3938 IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
3939 : TargetTransformInfo::OK_AnyValue;
3940 TargetTransformInfo::OperandValueKind Arg1OVK =
3941 !IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
3942 : TargetTransformInfo::OK_AnyValue;
3943 ScalarCost += TTI.getArithmeticInstrCost(
3944 Inst->getOpcode(), Inst->getType(), Arg0OVK, Arg1OVK);
3945 VectorCost += TTI.getArithmeticInstrCost(Inst->getOpcode(), PromotedType,
3946 Arg0OVK, Arg1OVK);
3947 }
3948 DEBUG(dbgs() << "Estimated cost of computation to be promoted:\nScalar: "
3949 << ScalarCost << "\nVector: " << VectorCost << '\n');
3950 return ScalarCost > VectorCost;
3951 }
3952
3953 /// \brief Generate a constant vector with \p Val with the same
3954 /// number of elements as the transition.
3955 /// \p UseSplat defines whether or not \p Val should be replicated
3956 /// accross the whole vector.
3957 /// In other words, if UseSplat == true, we generate <Val, Val, ..., Val>,
3958 /// otherwise we generate a vector with as many undef as possible:
3959 /// <undef, ..., undef, Val, undef, ..., undef> where \p Val is only
3960 /// used at the index of the extract.
3961 Value *getConstantVector(Constant *Val, bool UseSplat) const {
3962 unsigned ExtractIdx = UINT_MAX;
3963 if (!UseSplat) {
3964 // If we cannot determine where the constant must be, we have to
3965 // use a splat constant.
3966 Value *ValExtractIdx = Transition->getOperand(getTransitionIdx());
3967 if (ConstantInt *CstVal = dyn_cast<ConstantInt>(ValExtractIdx))
3968 ExtractIdx = CstVal->getSExtValue();
3969 else
3970 UseSplat = true;
3971 }
3972
3973 unsigned End = getTransitionType()->getVectorNumElements();
3974 if (UseSplat)
3975 return ConstantVector::getSplat(End, Val);
3976
3977 SmallVector<Constant *, 4> ConstVec;
3978 UndefValue *UndefVal = UndefValue::get(Val->getType());
3979 for (unsigned Idx = 0; Idx != End; ++Idx) {
3980 if (Idx == ExtractIdx)
3981 ConstVec.push_back(Val);
3982 else
3983 ConstVec.push_back(UndefVal);
3984 }
3985 return ConstantVector::get(ConstVec);
3986 }
3987
3988 /// \brief Check if promoting to a vector type an operand at \p OperandIdx
3989 /// in \p Use can trigger undefined behavior.
3990 static bool canCauseUndefinedBehavior(const Instruction *Use,
3991 unsigned OperandIdx) {
3992 // This is not safe to introduce undef when the operand is on
3993 // the right hand side of a division-like instruction.
3994 if (OperandIdx != 1)
3995 return false;
3996 switch (Use->getOpcode()) {
3997 default:
3998 return false;
3999 case Instruction::SDiv:
4000 case Instruction::UDiv:
4001 case Instruction::SRem:
4002 case Instruction::URem:
4003 return true;
4004 case Instruction::FDiv:
4005 case Instruction::FRem:
4006 return !Use->hasNoNaNs();
4007 }
4008 llvm_unreachable(nullptr);
4009 }
4010
4011public:
4012 VectorPromoteHelper(const TargetLowering &TLI, const TargetTransformInfo &TTI,
4013 Instruction *Transition, unsigned CombineCost)
4014 : TLI(TLI), TTI(TTI), Transition(Transition),
4015 StoreExtractCombineCost(CombineCost), CombineInst(nullptr) {
4016 assert(Transition && "Do not know how to promote null");
4017 }
4018
4019 /// \brief Check if we can promote \p ToBePromoted to \p Type.
4020 bool canPromote(const Instruction *ToBePromoted) const {
4021 // We could support CastInst too.
4022 return isa<BinaryOperator>(ToBePromoted);
4023 }
4024
4025 /// \brief Check if it is profitable to promote \p ToBePromoted
4026 /// by moving downward the transition through.
4027 bool shouldPromote(const Instruction *ToBePromoted) const {
4028 // Promote only if all the operands can be statically expanded.
4029 // Indeed, we do not want to introduce any new kind of transitions.
4030 for (const Use &U : ToBePromoted->operands()) {
4031 const Value *Val = U.get();
4032 if (Val == getEndOfTransition()) {
4033 // If the use is a division and the transition is on the rhs,
4034 // we cannot promote the operation, otherwise we may create a
4035 // division by zero.
4036 if (canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()))
4037 return false;
4038 continue;
4039 }
4040 if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) &&
4041 !isa<ConstantFP>(Val))
4042 return false;
4043 }
4044 // Check that the resulting operation is legal.
4045 int ISDOpcode = TLI.InstructionOpcodeToISD(ToBePromoted->getOpcode());
4046 if (!ISDOpcode)
4047 return false;
4048 return StressStoreExtract ||
Ahmed Bougacha026600d2014-11-12 23:05:03 +00004049 TLI.isOperationLegalOrCustom(
4050 ISDOpcode, TLI.getValueType(getTransitionType(), true));
Quentin Colombetc32615d2014-10-31 17:52:53 +00004051 }
4052
4053 /// \brief Check whether or not \p Use can be combined
4054 /// with the transition.
4055 /// I.e., is it possible to do Use(Transition) => AnotherUse?
4056 bool canCombine(const Instruction *Use) { return isa<StoreInst>(Use); }
4057
4058 /// \brief Record \p ToBePromoted as part of the chain to be promoted.
4059 void enqueueForPromotion(Instruction *ToBePromoted) {
4060 InstsToBePromoted.push_back(ToBePromoted);
4061 }
4062
4063 /// \brief Set the instruction that will be combined with the transition.
4064 void recordCombineInstruction(Instruction *ToBeCombined) {
4065 assert(canCombine(ToBeCombined) && "Unsupported instruction to combine");
4066 CombineInst = ToBeCombined;
4067 }
4068
4069 /// \brief Promote all the instructions enqueued for promotion if it is
4070 /// is profitable.
4071 /// \return True if the promotion happened, false otherwise.
4072 bool promote() {
4073 // Check if there is something to promote.
4074 // Right now, if we do not have anything to combine with,
4075 // we assume the promotion is not profitable.
4076 if (InstsToBePromoted.empty() || !CombineInst)
4077 return false;
4078
4079 // Check cost.
4080 if (!StressStoreExtract && !isProfitableToPromote())
4081 return false;
4082
4083 // Promote.
4084 for (auto &ToBePromoted : InstsToBePromoted)
4085 promoteImpl(ToBePromoted);
4086 InstsToBePromoted.clear();
4087 return true;
4088 }
4089};
4090} // End of anonymous namespace.
4091
4092void VectorPromoteHelper::promoteImpl(Instruction *ToBePromoted) {
4093 // At this point, we know that all the operands of ToBePromoted but Def
4094 // can be statically promoted.
4095 // For Def, we need to use its parameter in ToBePromoted:
4096 // b = ToBePromoted ty1 a
4097 // Def = Transition ty1 b to ty2
4098 // Move the transition down.
4099 // 1. Replace all uses of the promoted operation by the transition.
4100 // = ... b => = ... Def.
4101 assert(ToBePromoted->getType() == Transition->getType() &&
4102 "The type of the result of the transition does not match "
4103 "the final type");
4104 ToBePromoted->replaceAllUsesWith(Transition);
4105 // 2. Update the type of the uses.
4106 // b = ToBePromoted ty2 Def => b = ToBePromoted ty1 Def.
4107 Type *TransitionTy = getTransitionType();
4108 ToBePromoted->mutateType(TransitionTy);
4109 // 3. Update all the operands of the promoted operation with promoted
4110 // operands.
4111 // b = ToBePromoted ty1 Def => b = ToBePromoted ty1 a.
4112 for (Use &U : ToBePromoted->operands()) {
4113 Value *Val = U.get();
4114 Value *NewVal = nullptr;
4115 if (Val == Transition)
4116 NewVal = Transition->getOperand(getTransitionOriginalValueIdx());
4117 else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) ||
4118 isa<ConstantFP>(Val)) {
4119 // Use a splat constant if it is not safe to use undef.
4120 NewVal = getConstantVector(
4121 cast<Constant>(Val),
4122 isa<UndefValue>(Val) ||
4123 canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()));
4124 } else
Craig Topperd3c02f12015-01-05 10:15:49 +00004125 llvm_unreachable("Did you modified shouldPromote and forgot to update "
4126 "this?");
Quentin Colombetc32615d2014-10-31 17:52:53 +00004127 ToBePromoted->setOperand(U.getOperandNo(), NewVal);
4128 }
4129 Transition->removeFromParent();
4130 Transition->insertAfter(ToBePromoted);
4131 Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted);
4132}
4133
4134/// Some targets can do store(extractelement) with one instruction.
4135/// Try to push the extractelement towards the stores when the target
4136/// has this feature and this is profitable.
4137bool CodeGenPrepare::OptimizeExtractElementInst(Instruction *Inst) {
4138 unsigned CombineCost = UINT_MAX;
4139 if (DisableStoreExtract || !TLI ||
4140 (!StressStoreExtract &&
4141 !TLI->canCombineStoreAndExtract(Inst->getOperand(0)->getType(),
4142 Inst->getOperand(1), CombineCost)))
4143 return false;
4144
4145 // At this point we know that Inst is a vector to scalar transition.
4146 // Try to move it down the def-use chain, until:
4147 // - We can combine the transition with its single use
4148 // => we got rid of the transition.
4149 // - We escape the current basic block
4150 // => we would need to check that we are moving it at a cheaper place and
4151 // we do not do that for now.
4152 BasicBlock *Parent = Inst->getParent();
4153 DEBUG(dbgs() << "Found an interesting transition: " << *Inst << '\n');
4154 VectorPromoteHelper VPH(*TLI, *TTI, Inst, CombineCost);
4155 // If the transition has more than one use, assume this is not going to be
4156 // beneficial.
4157 while (Inst->hasOneUse()) {
4158 Instruction *ToBePromoted = cast<Instruction>(*Inst->user_begin());
4159 DEBUG(dbgs() << "Use: " << *ToBePromoted << '\n');
4160
4161 if (ToBePromoted->getParent() != Parent) {
4162 DEBUG(dbgs() << "Instruction to promote is in a different block ("
4163 << ToBePromoted->getParent()->getName()
4164 << ") than the transition (" << Parent->getName() << ").\n");
4165 return false;
4166 }
4167
4168 if (VPH.canCombine(ToBePromoted)) {
4169 DEBUG(dbgs() << "Assume " << *Inst << '\n'
4170 << "will be combined with: " << *ToBePromoted << '\n');
4171 VPH.recordCombineInstruction(ToBePromoted);
4172 bool Changed = VPH.promote();
4173 NumStoreExtractExposed += Changed;
4174 return Changed;
4175 }
4176
4177 DEBUG(dbgs() << "Try promoting.\n");
4178 if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted))
4179 return false;
4180
4181 DEBUG(dbgs() << "Promoting is possible... Enqueue for promotion!\n");
4182
4183 VPH.enqueueForPromotion(ToBePromoted);
4184 Inst = ToBePromoted;
4185 }
4186 return false;
4187}
4188
Elena Demikhovsky87700a72014-12-28 08:54:45 +00004189bool CodeGenPrepare::OptimizeInst(Instruction *I, bool& ModifiedDT) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00004190 if (PHINode *P = dyn_cast<PHINode>(I)) {
4191 // It is possible for very late stage optimizations (such as SimplifyCFG)
4192 // to introduce PHI nodes too late to be cleaned up. If we detect such a
4193 // trivial PHI, go ahead and zap it here.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004194 const DataLayout &DL = I->getModule()->getDataLayout();
4195 if (Value *V = SimplifyInstruction(P, DL, TLInfo, DT)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00004196 P->replaceAllUsesWith(V);
4197 P->eraseFromParent();
4198 ++NumPHIsElim;
Chris Lattneree588de2011-01-15 07:29:01 +00004199 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00004200 }
Chris Lattneree588de2011-01-15 07:29:01 +00004201 return false;
4202 }
Nadav Rotem465834c2012-07-24 10:51:42 +00004203
Chris Lattneree588de2011-01-15 07:29:01 +00004204 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00004205 // If the source of the cast is a constant, then this should have
4206 // already been constant folded. The only reason NOT to constant fold
4207 // it is if something (e.g. LSR) was careful to place the constant
4208 // evaluation in a block other than then one that uses it (e.g. to hoist
4209 // the address of globals out of a loop). If this is the case, we don't
4210 // want to forward-subst the cast.
4211 if (isa<Constant>(CI->getOperand(0)))
4212 return false;
4213
Chris Lattneree588de2011-01-15 07:29:01 +00004214 if (TLI && OptimizeNoopCopyExpression(CI, *TLI))
4215 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00004216
Chris Lattneree588de2011-01-15 07:29:01 +00004217 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +00004218 /// Sink a zext or sext into its user blocks if the target type doesn't
4219 /// fit in one register
4220 if (TLI && TLI->getTypeAction(CI->getContext(),
4221 TLI->getValueType(CI->getType())) ==
4222 TargetLowering::TypeExpandInteger) {
4223 return SinkCast(CI);
4224 } else {
4225 bool MadeChange = MoveExtToFormExtLoad(I);
4226 return MadeChange | OptimizeExtUses(I);
4227 }
Cameron Zwarich14ac8652011-01-06 02:37:26 +00004228 }
Chris Lattneree588de2011-01-15 07:29:01 +00004229 return false;
4230 }
Nadav Rotem465834c2012-07-24 10:51:42 +00004231
Chris Lattneree588de2011-01-15 07:29:01 +00004232 if (CmpInst *CI = dyn_cast<CmpInst>(I))
Hal Finkeldecb0242014-01-02 21:13:43 +00004233 if (!TLI || !TLI->hasMultipleConditionRegisters())
4234 return OptimizeCmpExpression(CI);
Nadav Rotem465834c2012-07-24 10:51:42 +00004235
Chris Lattneree588de2011-01-15 07:29:01 +00004236 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00004237 if (TLI)
Hans Wennborgf3254832012-10-30 11:23:25 +00004238 return OptimizeMemoryInst(I, I->getOperand(0), LI->getType());
4239 return false;
Chris Lattneree588de2011-01-15 07:29:01 +00004240 }
Nadav Rotem465834c2012-07-24 10:51:42 +00004241
Chris Lattneree588de2011-01-15 07:29:01 +00004242 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00004243 if (TLI)
Chris Lattneree588de2011-01-15 07:29:01 +00004244 return OptimizeMemoryInst(I, SI->getOperand(1),
4245 SI->getOperand(0)->getType());
4246 return false;
4247 }
Nadav Rotem465834c2012-07-24 10:51:42 +00004248
Yi Jiangd069f632014-04-21 19:34:27 +00004249 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I);
4250
4251 if (BinOp && (BinOp->getOpcode() == Instruction::AShr ||
4252 BinOp->getOpcode() == Instruction::LShr)) {
4253 ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1));
4254 if (TLI && CI && TLI->hasExtractBitsInsn())
4255 return OptimizeExtractBits(BinOp, CI, *TLI);
4256
4257 return false;
4258 }
4259
Chris Lattneree588de2011-01-15 07:29:01 +00004260 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00004261 if (GEPI->hasAllZeroIndices()) {
4262 /// The GEP operand must be a pointer, so must its result -> BitCast
4263 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
4264 GEPI->getName(), GEPI);
4265 GEPI->replaceAllUsesWith(NC);
4266 GEPI->eraseFromParent();
4267 ++NumGEPsElim;
Elena Demikhovsky87700a72014-12-28 08:54:45 +00004268 OptimizeInst(NC, ModifiedDT);
Chris Lattneree588de2011-01-15 07:29:01 +00004269 return true;
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00004270 }
Chris Lattneree588de2011-01-15 07:29:01 +00004271 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00004272 }
Nadav Rotem465834c2012-07-24 10:51:42 +00004273
Chris Lattneree588de2011-01-15 07:29:01 +00004274 if (CallInst *CI = dyn_cast<CallInst>(I))
Elena Demikhovsky87700a72014-12-28 08:54:45 +00004275 return OptimizeCallInst(CI, ModifiedDT);
Cameron Zwarich14ac8652011-01-06 02:37:26 +00004276
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004277 if (SelectInst *SI = dyn_cast<SelectInst>(I))
4278 return OptimizeSelectInst(SI);
4279
Tim Northoveraeb8e062014-02-19 10:02:43 +00004280 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I))
4281 return OptimizeShuffleVectorInst(SVI);
4282
Quentin Colombetc32615d2014-10-31 17:52:53 +00004283 if (isa<ExtractElementInst>(I))
4284 return OptimizeExtractElementInst(I);
4285
Chris Lattneree588de2011-01-15 07:29:01 +00004286 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00004287}
4288
Chris Lattnerf2836d12007-03-31 04:06:36 +00004289// In this pass we look for GEP and cast instructions that are used
4290// across basic blocks and rewrite them to improve basic-block-at-a-time
4291// selection.
Elena Demikhovsky87700a72014-12-28 08:54:45 +00004292bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB, bool& ModifiedDT) {
Cameron Zwarichce3b9302011-01-06 00:42:50 +00004293 SunkAddrs.clear();
Cameron Zwarich5dd2aa22011-03-02 03:31:46 +00004294 bool MadeChange = false;
Eric Christopherc1ea1492008-09-24 05:32:41 +00004295
Chris Lattner7a277142011-01-15 07:14:54 +00004296 CurInstIterator = BB.begin();
Elena Demikhovsky87700a72014-12-28 08:54:45 +00004297 while (CurInstIterator != BB.end()) {
4298 MadeChange |= OptimizeInst(CurInstIterator++, ModifiedDT);
4299 if (ModifiedDT)
4300 return true;
4301 }
Benjamin Kramer455fa352012-11-23 19:17:06 +00004302 MadeChange |= DupRetToEnableTailCallOpts(&BB);
4303
Chris Lattnerf2836d12007-03-31 04:06:36 +00004304 return MadeChange;
4305}
Devang Patel53771ba2011-08-18 00:50:51 +00004306
4307// llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotem465834c2012-07-24 10:51:42 +00004308// handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patel53771ba2011-08-18 00:50:51 +00004309// find a node corresponding to the value.
4310bool CodeGenPrepare::PlaceDbgValues(Function &F) {
4311 bool MadeChange = false;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +00004312 for (BasicBlock &BB : F) {
Craig Topperc0196b12014-04-14 00:51:57 +00004313 Instruction *PrevNonDbgInst = nullptr;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +00004314 for (BasicBlock::iterator BI = BB.begin(), BE = BB.end(); BI != BE;) {
Duncan P. N. Exon Smithe90f1162015-01-08 21:07:55 +00004315 Instruction *Insn = BI++;
Devang Patel53771ba2011-08-18 00:50:51 +00004316 DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
Adrian Prantl32da8892014-04-25 20:49:25 +00004317 // Leave dbg.values that refer to an alloca alone. These
4318 // instrinsics describe the address of a variable (= the alloca)
4319 // being taken. They should not be moved next to the alloca
4320 // (and to the beginning of the scope), but rather stay close to
4321 // where said address is used.
4322 if (!DVI || (DVI->getValue() && isa<AllocaInst>(DVI->getValue()))) {
Devang Patel53771ba2011-08-18 00:50:51 +00004323 PrevNonDbgInst = Insn;
4324 continue;
4325 }
4326
4327 Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
4328 if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
4329 DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
4330 DVI->removeFromParent();
4331 if (isa<PHINode>(VI))
4332 DVI->insertBefore(VI->getParent()->getFirstInsertionPt());
4333 else
4334 DVI->insertAfter(VI);
4335 MadeChange = true;
4336 ++NumDbgValueMoved;
4337 }
4338 }
4339 }
4340 return MadeChange;
4341}
Tim Northovercea0abb2014-03-29 08:22:29 +00004342
4343// If there is a sequence that branches based on comparing a single bit
4344// against zero that can be combined into a single instruction, and the
4345// target supports folding these into a single instruction, sink the
4346// mask and compare into the branch uses. Do this before OptimizeBlock ->
4347// OptimizeInst -> OptimizeCmpExpression, which perturbs the pattern being
4348// searched for.
4349bool CodeGenPrepare::sinkAndCmp(Function &F) {
4350 if (!EnableAndCmpSinking)
4351 return false;
4352 if (!TLI || !TLI->isMaskAndBranchFoldingLegal())
4353 return false;
4354 bool MadeChange = false;
4355 for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
4356 BasicBlock *BB = I++;
4357
4358 // Does this BB end with the following?
4359 // %andVal = and %val, #single-bit-set
4360 // %icmpVal = icmp %andResult, 0
4361 // br i1 %cmpVal label %dest1, label %dest2"
4362 BranchInst *Brcc = dyn_cast<BranchInst>(BB->getTerminator());
4363 if (!Brcc || !Brcc->isConditional())
4364 continue;
4365 ICmpInst *Cmp = dyn_cast<ICmpInst>(Brcc->getOperand(0));
4366 if (!Cmp || Cmp->getParent() != BB)
4367 continue;
4368 ConstantInt *Zero = dyn_cast<ConstantInt>(Cmp->getOperand(1));
4369 if (!Zero || !Zero->isZero())
4370 continue;
4371 Instruction *And = dyn_cast<Instruction>(Cmp->getOperand(0));
4372 if (!And || And->getOpcode() != Instruction::And || And->getParent() != BB)
4373 continue;
4374 ConstantInt* Mask = dyn_cast<ConstantInt>(And->getOperand(1));
4375 if (!Mask || !Mask->getUniqueInteger().isPowerOf2())
4376 continue;
4377 DEBUG(dbgs() << "found and; icmp ?,0; brcc\n"); DEBUG(BB->dump());
4378
4379 // Push the "and; icmp" for any users that are conditional branches.
4380 // Since there can only be one branch use per BB, we don't need to keep
4381 // track of which BBs we insert into.
4382 for (Value::use_iterator UI = Cmp->use_begin(), E = Cmp->use_end();
4383 UI != E; ) {
4384 Use &TheUse = *UI;
4385 // Find brcc use.
4386 BranchInst *BrccUser = dyn_cast<BranchInst>(*UI);
4387 ++UI;
4388 if (!BrccUser || !BrccUser->isConditional())
4389 continue;
4390 BasicBlock *UserBB = BrccUser->getParent();
4391 if (UserBB == BB) continue;
4392 DEBUG(dbgs() << "found Brcc use\n");
4393
4394 // Sink the "and; icmp" to use.
4395 MadeChange = true;
4396 BinaryOperator *NewAnd =
4397 BinaryOperator::CreateAnd(And->getOperand(0), And->getOperand(1), "",
4398 BrccUser);
4399 CmpInst *NewCmp =
4400 CmpInst::Create(Cmp->getOpcode(), Cmp->getPredicate(), NewAnd, Zero,
4401 "", BrccUser);
4402 TheUse = NewCmp;
4403 ++NumAndCmpsMoved;
4404 DEBUG(BrccUser->getParent()->dump());
4405 }
4406 }
4407 return MadeChange;
4408}
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00004409
Juergen Ributzka194350a2014-12-09 17:32:12 +00004410/// \brief Retrieve the probabilities of a conditional branch. Returns true on
4411/// success, or returns false if no or invalid metadata was found.
4412static bool extractBranchMetadata(BranchInst *BI,
4413 uint64_t &ProbTrue, uint64_t &ProbFalse) {
4414 assert(BI->isConditional() &&
4415 "Looking for probabilities on unconditional branch?");
4416 auto *ProfileData = BI->getMetadata(LLVMContext::MD_prof);
4417 if (!ProfileData || ProfileData->getNumOperands() != 3)
4418 return false;
4419
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004420 const auto *CITrue =
4421 mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(1));
4422 const auto *CIFalse =
4423 mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(2));
Juergen Ributzka194350a2014-12-09 17:32:12 +00004424 if (!CITrue || !CIFalse)
4425 return false;
4426
4427 ProbTrue = CITrue->getValue().getZExtValue();
4428 ProbFalse = CIFalse->getValue().getZExtValue();
4429
4430 return true;
4431}
4432
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00004433/// \brief Scale down both weights to fit into uint32_t.
4434static void scaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) {
4435 uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
4436 uint32_t Scale = (NewMax / UINT32_MAX) + 1;
4437 NewTrue = NewTrue / Scale;
4438 NewFalse = NewFalse / Scale;
4439}
4440
4441/// \brief Some targets prefer to split a conditional branch like:
4442/// \code
4443/// %0 = icmp ne i32 %a, 0
4444/// %1 = icmp ne i32 %b, 0
4445/// %or.cond = or i1 %0, %1
4446/// br i1 %or.cond, label %TrueBB, label %FalseBB
4447/// \endcode
4448/// into multiple branch instructions like:
4449/// \code
4450/// bb1:
4451/// %0 = icmp ne i32 %a, 0
4452/// br i1 %0, label %TrueBB, label %bb2
4453/// bb2:
4454/// %1 = icmp ne i32 %b, 0
4455/// br i1 %1, label %TrueBB, label %FalseBB
4456/// \endcode
4457/// This usually allows instruction selection to do even further optimizations
4458/// and combine the compare with the branch instruction. Currently this is
4459/// applied for targets which have "cheap" jump instructions.
4460///
4461/// FIXME: Remove the (equivalent?) implementation in SelectionDAG.
4462///
4463bool CodeGenPrepare::splitBranchCondition(Function &F) {
David Blaikiedc3f01e2015-03-09 01:57:13 +00004464 if (!TM || !TM->Options.EnableFastISel || !TLI || TLI->isJumpExpensive())
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00004465 return false;
4466
4467 bool MadeChange = false;
4468 for (auto &BB : F) {
4469 // Does this BB end with the following?
4470 // %cond1 = icmp|fcmp|binary instruction ...
4471 // %cond2 = icmp|fcmp|binary instruction ...
4472 // %cond.or = or|and i1 %cond1, cond2
4473 // br i1 %cond.or label %dest1, label %dest2"
4474 BinaryOperator *LogicOp;
4475 BasicBlock *TBB, *FBB;
4476 if (!match(BB.getTerminator(), m_Br(m_OneUse(m_BinOp(LogicOp)), TBB, FBB)))
4477 continue;
4478
4479 unsigned Opc;
Juergen Ributzka8bda7382014-12-09 17:50:10 +00004480 Value *Cond1, *Cond2;
4481 if (match(LogicOp, m_And(m_OneUse(m_Value(Cond1)),
4482 m_OneUse(m_Value(Cond2)))))
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00004483 Opc = Instruction::And;
Juergen Ributzka8bda7382014-12-09 17:50:10 +00004484 else if (match(LogicOp, m_Or(m_OneUse(m_Value(Cond1)),
4485 m_OneUse(m_Value(Cond2)))))
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00004486 Opc = Instruction::Or;
4487 else
4488 continue;
4489
4490 if (!match(Cond1, m_CombineOr(m_Cmp(), m_BinOp())) ||
4491 !match(Cond2, m_CombineOr(m_Cmp(), m_BinOp())) )
4492 continue;
4493
4494 DEBUG(dbgs() << "Before branch condition splitting\n"; BB.dump());
4495
4496 // Create a new BB.
4497 auto *InsertBefore = std::next(Function::iterator(BB))
4498 .getNodePtrUnchecked();
4499 auto TmpBB = BasicBlock::Create(BB.getContext(),
4500 BB.getName() + ".cond.split",
4501 BB.getParent(), InsertBefore);
4502
4503 // Update original basic block by using the first condition directly by the
4504 // branch instruction and removing the no longer needed and/or instruction.
4505 auto *Br1 = cast<BranchInst>(BB.getTerminator());
4506 Br1->setCondition(Cond1);
4507 LogicOp->eraseFromParent();
Juergen Ributzka8bda7382014-12-09 17:50:10 +00004508
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00004509 // Depending on the conditon we have to either replace the true or the false
4510 // successor of the original branch instruction.
4511 if (Opc == Instruction::And)
4512 Br1->setSuccessor(0, TmpBB);
4513 else
4514 Br1->setSuccessor(1, TmpBB);
4515
4516 // Fill in the new basic block.
4517 auto *Br2 = IRBuilder<>(TmpBB).CreateCondBr(Cond2, TBB, FBB);
Juergen Ributzka8bda7382014-12-09 17:50:10 +00004518 if (auto *I = dyn_cast<Instruction>(Cond2)) {
4519 I->removeFromParent();
4520 I->insertBefore(Br2);
4521 }
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00004522
4523 // Update PHI nodes in both successors. The original BB needs to be
4524 // replaced in one succesor's PHI nodes, because the branch comes now from
4525 // the newly generated BB (NewBB). In the other successor we need to add one
4526 // incoming edge to the PHI nodes, because both branch instructions target
4527 // now the same successor. Depending on the original branch condition
4528 // (and/or) we have to swap the successors (TrueDest, FalseDest), so that
4529 // we perfrom the correct update for the PHI nodes.
4530 // This doesn't change the successor order of the just created branch
4531 // instruction (or any other instruction).
4532 if (Opc == Instruction::Or)
4533 std::swap(TBB, FBB);
4534
4535 // Replace the old BB with the new BB.
4536 for (auto &I : *TBB) {
4537 PHINode *PN = dyn_cast<PHINode>(&I);
4538 if (!PN)
4539 break;
4540 int i;
4541 while ((i = PN->getBasicBlockIndex(&BB)) >= 0)
4542 PN->setIncomingBlock(i, TmpBB);
4543 }
4544
4545 // Add another incoming edge form the new BB.
4546 for (auto &I : *FBB) {
4547 PHINode *PN = dyn_cast<PHINode>(&I);
4548 if (!PN)
4549 break;
4550 auto *Val = PN->getIncomingValueForBlock(&BB);
4551 PN->addIncoming(Val, TmpBB);
4552 }
4553
4554 // Update the branch weights (from SelectionDAGBuilder::
4555 // FindMergedConditions).
4556 if (Opc == Instruction::Or) {
4557 // Codegen X | Y as:
4558 // BB1:
4559 // jmp_if_X TBB
4560 // jmp TmpBB
4561 // TmpBB:
4562 // jmp_if_Y TBB
4563 // jmp FBB
4564 //
4565
4566 // We have flexibility in setting Prob for BB1 and Prob for NewBB.
4567 // The requirement is that
4568 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
4569 // = TrueProb for orignal BB.
4570 // Assuming the orignal weights are A and B, one choice is to set BB1's
4571 // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice
4572 // assumes that
4573 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
4574 // Another choice is to assume TrueProb for BB1 equals to TrueProb for
4575 // TmpBB, but the math is more complicated.
4576 uint64_t TrueWeight, FalseWeight;
Juergen Ributzka194350a2014-12-09 17:32:12 +00004577 if (extractBranchMetadata(Br1, TrueWeight, FalseWeight)) {
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00004578 uint64_t NewTrueWeight = TrueWeight;
4579 uint64_t NewFalseWeight = TrueWeight + 2 * FalseWeight;
4580 scaleWeights(NewTrueWeight, NewFalseWeight);
4581 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
4582 .createBranchWeights(TrueWeight, FalseWeight));
4583
4584 NewTrueWeight = TrueWeight;
4585 NewFalseWeight = 2 * FalseWeight;
4586 scaleWeights(NewTrueWeight, NewFalseWeight);
4587 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
4588 .createBranchWeights(TrueWeight, FalseWeight));
4589 }
4590 } else {
4591 // Codegen X & Y as:
4592 // BB1:
4593 // jmp_if_X TmpBB
4594 // jmp FBB
4595 // TmpBB:
4596 // jmp_if_Y TBB
4597 // jmp FBB
4598 //
4599 // This requires creation of TmpBB after CurBB.
4600
4601 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
4602 // The requirement is that
4603 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
4604 // = FalseProb for orignal BB.
4605 // Assuming the orignal weights are A and B, one choice is to set BB1's
4606 // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice
4607 // assumes that
4608 // FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB.
4609 uint64_t TrueWeight, FalseWeight;
Juergen Ributzka194350a2014-12-09 17:32:12 +00004610 if (extractBranchMetadata(Br1, TrueWeight, FalseWeight)) {
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00004611 uint64_t NewTrueWeight = 2 * TrueWeight + FalseWeight;
4612 uint64_t NewFalseWeight = FalseWeight;
4613 scaleWeights(NewTrueWeight, NewFalseWeight);
4614 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
4615 .createBranchWeights(TrueWeight, FalseWeight));
4616
4617 NewTrueWeight = 2 * TrueWeight;
4618 NewFalseWeight = FalseWeight;
4619 scaleWeights(NewTrueWeight, NewFalseWeight);
4620 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
4621 .createBranchWeights(TrueWeight, FalseWeight));
4622 }
4623 }
4624
4625 // Request DOM Tree update.
4626 // Note: No point in getting fancy here, since the DT info is never
4627 // available to CodeGenPrepare and the existing update code is broken
4628 // anyways.
4629 ModifiedDT = true;
4630
4631 MadeChange = true;
4632
4633 DEBUG(dbgs() << "After branch condition splitting\n"; BB.dump();
4634 TmpBB->dump());
4635 }
4636 return MadeChange;
4637}