blob: e2bb3780e3e6f1fd3436e345e04a8e40c3a3ffd9 [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"
Michael Kuperstein13bf8a22017-02-28 00:11:34 +000018#include "llvm/ADT/SetVector.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000019#include "llvm/ADT/SmallSet.h"
20#include "llvm/ADT/Statistic.h"
Jun Bum Lim90b6b502016-12-16 20:38:39 +000021#include "llvm/Analysis/BlockFrequencyInfo.h"
22#include "llvm/Analysis/BranchProbabilityInfo.h"
Michael Kuperstein13bf8a22017-02-28 00:11:34 +000023#include "llvm/Analysis/CFG.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000024#include "llvm/Analysis/InstructionSimplify.h"
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +000025#include "llvm/Analysis/LoopInfo.h"
Dehao Chen302b69c2016-10-18 20:42:47 +000026#include "llvm/Analysis/ProfileSummaryInfo.h"
Chandler Carruth62d42152015-01-15 02:16:27 +000027#include "llvm/Analysis/TargetLibraryInfo.h"
Quentin Colombetc32615d2014-10-31 17:52:53 +000028#include "llvm/Analysis/TargetTransformInfo.h"
Sanjay Patel69a50a12015-10-19 21:59:12 +000029#include "llvm/Analysis/ValueTracking.h"
Petar Jovanovic644b8c12016-04-13 12:25:25 +000030#include "llvm/Analysis/MemoryBuiltins.h"
Michael Kupersteinf79af6f2016-09-08 00:48:37 +000031#include "llvm/CodeGen/Analysis.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000032#include "llvm/IR/CallSite.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000033#include "llvm/IR/Constants.h"
34#include "llvm/IR/DataLayout.h"
35#include "llvm/IR/DerivedTypes.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000036#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000037#include "llvm/IR/Function.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000038#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000039#include "llvm/IR/IRBuilder.h"
40#include "llvm/IR/InlineAsm.h"
41#include "llvm/IR/Instructions.h"
42#include "llvm/IR/IntrinsicInst.h"
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +000043#include "llvm/IR/MDBuilder.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000044#include "llvm/IR/PatternMatch.h"
Ramkumar Ramachandradba73292015-01-14 23:27:07 +000045#include "llvm/IR/Statepoint.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +000046#include "llvm/IR/ValueHandle.h"
Chandler Carrutha4ea2692014-03-04 11:26:31 +000047#include "llvm/IR/ValueMap.h"
Chris Lattnerf2836d12007-03-31 04:06:36 +000048#include "llvm/Pass.h"
Sanjay Pateld66607b2016-04-26 17:11:17 +000049#include "llvm/Support/BranchProbability.h"
Evan Cheng8b637b12010-08-17 01:34:49 +000050#include "llvm/Support/CommandLine.h"
Evan Chengd3d80172007-12-05 23:58:20 +000051#include "llvm/Support/Debug.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000052#include "llvm/Support/raw_ostream.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000053#include "llvm/Target/TargetLowering.h"
Hal Finkelc3998302014-04-12 00:59:48 +000054#include "llvm/Target/TargetSubtargetInfo.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000055#include "llvm/Transforms/Utils/BasicBlockUtils.h"
56#include "llvm/Transforms/Utils/BuildLibCalls.h"
Preston Gurdcdf540d2012-09-04 18:22:17 +000057#include "llvm/Transforms/Utils/BypassSlowDivision.h"
Michael Kuperstein13bf8a22017-02-28 00:11:34 +000058#include "llvm/Transforms/Utils/Cloning.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000059#include "llvm/Transforms/Utils/Local.h"
Ahmed Bougachae03bef72015-01-12 17:22:43 +000060#include "llvm/Transforms/Utils/SimplifyLibCalls.h"
Michael Kuperstein13bf8a22017-02-28 00:11:34 +000061#include "llvm/Transforms/Utils/ValueMapper.h"
Chris Lattnerf2836d12007-03-31 04:06:36 +000062using namespace llvm;
Chris Lattnerd616ef52008-11-25 04:42:10 +000063using namespace llvm::PatternMatch;
Chris Lattnerf2836d12007-03-31 04:06:36 +000064
Chandler Carruth1b9dde02014-04-22 02:02:50 +000065#define DEBUG_TYPE "codegenprepare"
66
Cameron Zwarichced753f2011-01-05 17:27:27 +000067STATISTIC(NumBlocksElim, "Number of blocks eliminated");
Evan Cheng0663f232011-03-21 01:19:09 +000068STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated");
69STATISTIC(NumGEPsElim, "Number of GEPs converted to casts");
Cameron Zwarichced753f2011-01-05 17:27:27 +000070STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "
71 "sunken Cmps");
72STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
73 "of sunken Casts");
74STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "
75 "computations were sunk");
Evan Cheng0663f232011-03-21 01:19:09 +000076STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads");
77STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized");
Geoff Berry5256fca2015-11-20 22:34:39 +000078STATISTIC(NumAndsAdded,
79 "Number of and mask instructions added to form ext loads");
80STATISTIC(NumAndUses, "Number of uses of and mask instructions optimized");
Evan Cheng0663f232011-03-21 01:19:09 +000081STATISTIC(NumRetsDup, "Number of return instructions duplicated");
Devang Patel53771ba2011-08-18 00:50:51 +000082STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved");
Benjamin Kramer047d7ca2012-05-05 12:49:22 +000083STATISTIC(NumSelectsExpanded, "Number of selects turned into branches");
Quentin Colombetc32615d2014-10-31 17:52:53 +000084STATISTIC(NumStoreExtractExposed, "Number of store(extractelement) exposed");
Jakob Stoklund Oleseneb12f492010-09-30 20:51:52 +000085
Cameron Zwarich338d3622011-03-11 21:52:04 +000086static cl::opt<bool> DisableBranchOpts(
87 "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
88 cl::desc("Disable branch optimizations in CodeGenPrepare"));
89
Ramkumar Ramachandradba73292015-01-14 23:27:07 +000090static cl::opt<bool>
91 DisableGCOpts("disable-cgp-gc-opts", cl::Hidden, cl::init(false),
92 cl::desc("Disable GC optimizations in CodeGenPrepare"));
93
Benjamin Kramer3d38c172012-05-06 14:25:16 +000094static cl::opt<bool> DisableSelectToBranch(
95 "disable-cgp-select2branch", cl::Hidden, cl::init(false),
96 cl::desc("Disable select to branch conversion."));
Benjamin Kramer047d7ca2012-05-05 12:49:22 +000097
Hal Finkelc3998302014-04-12 00:59:48 +000098static cl::opt<bool> AddrSinkUsingGEPs(
Eli Friedman5fba1e52017-04-06 22:42:18 +000099 "addr-sink-using-gep", cl::Hidden, cl::init(true),
Hal Finkelc3998302014-04-12 00:59:48 +0000100 cl::desc("Address sinking in CGP using GEPs."));
101
Tim Northovercea0abb2014-03-29 08:22:29 +0000102static cl::opt<bool> EnableAndCmpSinking(
103 "enable-andcmp-sinking", cl::Hidden, cl::init(true),
104 cl::desc("Enable sinkinig and/cmp into branches."));
105
Quentin Colombetc32615d2014-10-31 17:52:53 +0000106static cl::opt<bool> DisableStoreExtract(
107 "disable-cgp-store-extract", cl::Hidden, cl::init(false),
108 cl::desc("Disable store(extract) optimizations in CodeGenPrepare"));
109
110static cl::opt<bool> StressStoreExtract(
111 "stress-cgp-store-extract", cl::Hidden, cl::init(false),
112 cl::desc("Stress test store(extract) optimizations in CodeGenPrepare"));
113
Quentin Colombetfc2201e2014-12-17 01:36:17 +0000114static cl::opt<bool> DisableExtLdPromotion(
115 "disable-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
116 cl::desc("Disable ext(promotable(ld)) -> promoted(ext(ld)) optimization in "
117 "CodeGenPrepare"));
118
119static cl::opt<bool> StressExtLdPromotion(
120 "stress-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
121 cl::desc("Stress test ext(promotable(ld)) -> promoted(ext(ld)) "
122 "optimization in CodeGenPrepare"));
123
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000124static cl::opt<bool> DisablePreheaderProtect(
125 "disable-preheader-prot", cl::Hidden, cl::init(false),
126 cl::desc("Disable protection against removing loop preheaders"));
127
Dehao Chen302b69c2016-10-18 20:42:47 +0000128static cl::opt<bool> ProfileGuidedSectionPrefix(
129 "profile-guided-section-prefix", cl::Hidden, cl::init(true),
130 cl::desc("Use profile info to add section prefix for hot/cold functions"));
131
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000132static cl::opt<unsigned> FreqRatioToSkipMerge(
133 "cgp-freq-ratio-to-skip-merge", cl::Hidden, cl::init(2),
134 cl::desc("Skip merging empty blocks if (frequency of empty block) / "
135 "(frequency of destination block) is greater than this ratio"));
136
Wei Mia2f0b592016-12-22 19:44:45 +0000137static cl::opt<bool> ForceSplitStore(
138 "force-split-store", cl::Hidden, cl::init(false),
139 cl::desc("Force store splitting no matter what the target query says."));
140
Jun Bum Limdee55652017-04-03 19:20:07 +0000141static cl::opt<bool>
142EnableTypePromotionMerge("cgp-type-promotion-merge", cl::Hidden,
143 cl::desc("Enable merging of redundant sexts when one is dominating"
144 " the other."), cl::init(true));
145
Eric Christopherc1ea1492008-09-24 05:32:41 +0000146namespace {
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000147typedef SmallPtrSet<Instruction *, 16> SetOfInstrs;
Benjamin Kramer4cd5faa2015-07-31 17:00:39 +0000148typedef PointerIntPair<Type *, 1, bool> TypeIsSExt;
Quentin Colombetf5485bb2014-11-13 01:44:51 +0000149typedef DenseMap<Instruction *, TypeIsSExt> InstrToOrigTy;
Jun Bum Limdee55652017-04-03 19:20:07 +0000150typedef SmallVector<Instruction *, 16> SExts;
151typedef DenseMap<Value *, SExts> ValueToSExts;
Quentin Colombetfc2201e2014-12-17 01:36:17 +0000152class TypePromotionTransaction;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000153
Chris Lattner2dd09db2009-09-02 06:11:42 +0000154 class CodeGenPrepare : public FunctionPass {
Bill Wendling7a639ea2013-06-19 21:07:11 +0000155 const TargetMachine *TM;
Igor Laevsky3be81ba2017-02-07 13:27:20 +0000156 const TargetSubtargetInfo *SubtargetInfo;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000157 const TargetLowering *TLI;
Igor Laevsky3be81ba2017-02-07 13:27:20 +0000158 const TargetRegisterInfo *TRI;
Quentin Colombetc32615d2014-10-31 17:52:53 +0000159 const TargetTransformInfo *TTI;
Chad Rosierc24b86f2011-12-01 03:08:23 +0000160 const TargetLibraryInfo *TLInfo;
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000161 const LoopInfo *LI;
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000162 std::unique_ptr<BlockFrequencyInfo> BFI;
163 std::unique_ptr<BranchProbabilityInfo> BPI;
Nadav Rotem465834c2012-07-24 10:51:42 +0000164
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000165 /// As we scan instructions optimizing them, this is the next instruction
166 /// to optimize. Transforms that can invalidate this should update it.
Chris Lattner7a277142011-01-15 07:14:54 +0000167 BasicBlock::iterator CurInstIterator;
Evan Cheng3b3de7c2008-12-19 18:03:11 +0000168
Evan Cheng0663f232011-03-21 01:19:09 +0000169 /// Keeps track of non-local addresses that have been sunk into a block.
170 /// This allows us to avoid inserting duplicate code for blocks with
171 /// multiple load/stores of the same address.
Nick Lewycky5fb19632013-05-08 09:00:10 +0000172 ValueMap<Value*, Value*> SunkAddrs;
Cameron Zwarichce3b9302011-01-06 00:42:50 +0000173
Ahmed Bougachaf3299142015-06-17 20:44:32 +0000174 /// Keeps track of all instructions inserted for the current function.
175 SetOfInstrs InsertedInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000176 /// Keeps track of the type of the related instruction before their
177 /// promotion for the current function.
178 InstrToOrigTy PromotedInsts;
179
Jun Bum Limdee55652017-04-03 19:20:07 +0000180 /// Keep track of instructions removed during promotion.
181 SetOfInstrs RemovedInsts;
182
183 /// Keep track of sext chains based on their initial value.
184 DenseMap<Value *, Instruction *> SeenChainsForSExt;
185
186 /// Keep track of SExt promoted.
187 ValueToSExts ValToSExtendedUses;
188
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000189 /// True if CFG is modified in any way.
Devang Patel8f606d72011-03-24 15:35:25 +0000190 bool ModifiedDT;
Evan Cheng0663f232011-03-21 01:19:09 +0000191
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000192 /// True if optimizing for size.
Benjamin Kramer047d7ca2012-05-05 12:49:22 +0000193 bool OptSize;
194
Mehdi Amini4fe37982015-07-07 18:45:17 +0000195 /// DataLayout for the Function being processed.
196 const DataLayout *DL;
197
Chris Lattnerf2836d12007-03-31 04:06:36 +0000198 public:
Nick Lewyckye7da2d62007-05-06 13:37:16 +0000199 static char ID; // Pass identification, replacement for typeid
Craig Topperc0196b12014-04-14 00:51:57 +0000200 explicit CodeGenPrepare(const TargetMachine *TM = nullptr)
Mehdi Amini4fe37982015-07-07 18:45:17 +0000201 : FunctionPass(ID), TM(TM), TLI(nullptr), TTI(nullptr), DL(nullptr) {
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000202 initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
203 }
Craig Topper4584cd52014-03-07 09:26:03 +0000204 bool runOnFunction(Function &F) override;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000205
Mehdi Amini117296c2016-10-01 02:56:57 +0000206 StringRef getPassName() const override { return "CodeGen Prepare"; }
Evan Cheng99cafb12012-12-21 01:48:14 +0000207
Craig Topper4584cd52014-03-07 09:26:03 +0000208 void getAnalysisUsage(AnalysisUsage &AU) const override {
George Burgess IVd4febd12016-03-22 21:25:08 +0000209 // FIXME: When we can selectively preserve passes, preserve the domtree.
Dehao Chen302b69c2016-10-18 20:42:47 +0000210 AU.addRequired<ProfileSummaryInfoWrapperPass>();
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000211 AU.addRequired<TargetLibraryInfoWrapperPass>();
Chandler Carruth705b1852015-01-31 03:43:40 +0000212 AU.addRequired<TargetTransformInfoWrapperPass>();
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000213 AU.addRequired<LoopInfoWrapperPass>();
Andreas Neustifterf8cb7582009-09-16 09:26:52 +0000214 }
215
Chris Lattnerf2836d12007-03-31 04:06:36 +0000216 private:
Sanjay Patelfc580a62015-09-21 23:03:16 +0000217 bool eliminateFallThrough(Function &F);
218 bool eliminateMostlyEmptyBlocks(Function &F);
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000219 BasicBlock *findDestBlockOfMergeableEmptyBlock(BasicBlock *BB);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000220 bool canMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
221 void eliminateMostlyEmptyBlock(BasicBlock *BB);
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000222 bool isMergingEmptyBlockProfitable(BasicBlock *BB, BasicBlock *DestBB,
223 bool isPreheader);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000224 bool optimizeBlock(BasicBlock &BB, bool& ModifiedDT);
225 bool optimizeInst(Instruction *I, bool& ModifiedDT);
226 bool optimizeMemoryInst(Instruction *I, Value *Addr,
Matt Arsenaultf72b49b2015-06-04 16:17:38 +0000227 Type *AccessTy, unsigned AS);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000228 bool optimizeInlineAsmInst(CallInst *CS);
229 bool optimizeCallInst(CallInst *CI, bool& ModifiedDT);
Jun Bum Limdee55652017-04-03 19:20:07 +0000230 bool optimizeExt(Instruction *&I);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000231 bool optimizeExtUses(Instruction *I);
Geoff Berry5256fca2015-11-20 22:34:39 +0000232 bool optimizeLoadExt(LoadInst *I);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000233 bool optimizeSelectInst(SelectInst *SI);
234 bool optimizeShuffleVectorInst(ShuffleVectorInst *SI);
Sanjay Patel0ed9aea2015-11-02 23:22:49 +0000235 bool optimizeSwitchInst(SwitchInst *CI);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000236 bool optimizeExtractElementInst(Instruction *Inst);
237 bool dupRetToEnableTailCallOpts(BasicBlock *BB);
238 bool placeDbgValues(Function &F);
Jun Bum Lim42301012017-03-17 19:05:21 +0000239 bool canFormExtLd(const SmallVectorImpl<Instruction *> &MovedExts,
240 LoadInst *&LI, Instruction *&Inst, bool HasPromoted);
241 bool tryToPromoteExts(TypePromotionTransaction &TPT,
242 const SmallVectorImpl<Instruction *> &Exts,
243 SmallVectorImpl<Instruction *> &ProfitablyMovedExts,
244 unsigned CreatedInstsCost = 0);
Jun Bum Limdee55652017-04-03 19:20:07 +0000245 bool mergeSExts(Function &F);
246 bool performAddressTypePromotion(
247 Instruction *&Inst,
248 bool AllowPromotionWithoutCommonHeader,
249 bool HasPromoted, TypePromotionTransaction &TPT,
250 SmallVectorImpl<Instruction *> &SpeculativelyMovedExts);
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +0000251 bool splitBranchCondition(Function &F);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000252 bool simplifyOffsetableRelocate(Instruction &I);
Michael Kuperstein13bf8a22017-02-28 00:11:34 +0000253 bool splitIndirectCriticalEdges(Function &F);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000254 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000255}
Devang Patel09f162c2007-05-01 21:15:47 +0000256
Devang Patel8c78a0b2007-05-03 01:11:54 +0000257char CodeGenPrepare::ID = 0;
Dehao Chen302b69c2016-10-18 20:42:47 +0000258INITIALIZE_TM_PASS_BEGIN(CodeGenPrepare, "codegenprepare",
259 "Optimize for code generation", false, false)
260INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
261INITIALIZE_TM_PASS_END(CodeGenPrepare, "codegenprepare",
262 "Optimize for code generation", false, false)
Chris Lattnerf2836d12007-03-31 04:06:36 +0000263
Bill Wendling7a639ea2013-06-19 21:07:11 +0000264FunctionPass *llvm::createCodeGenPreparePass(const TargetMachine *TM) {
265 return new CodeGenPrepare(TM);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000266}
267
Chris Lattnerf2836d12007-03-31 04:06:36 +0000268bool CodeGenPrepare::runOnFunction(Function &F) {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000269 if (skipFunction(F))
Paul Robinson7c99ec52014-03-31 17:43:35 +0000270 return false;
271
Mehdi Amini4fe37982015-07-07 18:45:17 +0000272 DL = &F.getParent()->getDataLayout();
273
Chris Lattnerf2836d12007-03-31 04:06:36 +0000274 bool EverMadeChange = false;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000275 // Clear per function information.
Ahmed Bougachaf3299142015-06-17 20:44:32 +0000276 InsertedInsts.clear();
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000277 PromotedInsts.clear();
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000278 BFI.reset();
279 BPI.reset();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000280
Devang Patel8f606d72011-03-24 15:35:25 +0000281 ModifiedDT = false;
Igor Laevsky3be81ba2017-02-07 13:27:20 +0000282 if (TM) {
283 SubtargetInfo = TM->getSubtargetImpl(F);
284 TLI = SubtargetInfo->getTargetLowering();
285 TRI = SubtargetInfo->getRegisterInfo();
286 }
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000287 TLInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Chandler Carruthfdb9c572015-02-01 12:01:35 +0000288 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000289 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Sanjay Patel82d91dd2015-08-11 19:39:36 +0000290 OptSize = F.optForSize();
Evan Cheng0663f232011-03-21 01:19:09 +0000291
Dehao Chen302b69c2016-10-18 20:42:47 +0000292 if (ProfileGuidedSectionPrefix) {
293 ProfileSummaryInfo *PSI =
294 getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
Dehao Chen775341a2017-03-23 23:14:11 +0000295 if (PSI->isFunctionHotInCallGraph(&F))
Dehao Chen302b69c2016-10-18 20:42:47 +0000296 F.setSectionPrefix(".hot");
Dehao Chen775341a2017-03-23 23:14:11 +0000297 else if (PSI->isFunctionColdInCallGraph(&F))
Dehao Chen302b69c2016-10-18 20:42:47 +0000298 F.setSectionPrefix(".cold");
299 }
300
Preston Gurdcdf540d2012-09-04 18:22:17 +0000301 /// This optimization identifies DIV instructions that can be
302 /// profitably bypassed and carried out with a shorter, faster divide.
Preston Gurd485296d2013-03-04 18:13:57 +0000303 if (!OptSize && TLI && TLI->isSlowDivBypassed()) {
Preston Gurd0d67f512012-10-04 21:33:40 +0000304 const DenseMap<unsigned int, unsigned int> &BypassWidths =
305 TLI->getBypassSlowDivWidths();
Eric Christopher49a7d6c2016-01-04 23:18:58 +0000306 BasicBlock* BB = &*F.begin();
307 while (BB != nullptr) {
308 // bypassSlowDivision may create new BBs, but we don't want to reapply the
309 // optimization to those blocks.
310 BasicBlock* Next = BB->getNextNode();
311 EverMadeChange |= bypassSlowDivision(BB, BypassWidths);
312 BB = Next;
313 }
Preston Gurdcdf540d2012-09-04 18:22:17 +0000314 }
315
316 // Eliminate blocks that contain only PHI nodes and an
Chris Lattnerc3748562007-04-02 01:35:34 +0000317 // unconditional branch.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000318 EverMadeChange |= eliminateMostlyEmptyBlocks(F);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000319
Devang Patel53771ba2011-08-18 00:50:51 +0000320 // llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotem465834c2012-07-24 10:51:42 +0000321 // handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patel53771ba2011-08-18 00:50:51 +0000322 // find a node corresponding to the value.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000323 EverMadeChange |= placeDbgValues(F);
Devang Patel53771ba2011-08-18 00:50:51 +0000324
Geoff Berry5d534b62017-02-21 18:53:14 +0000325 if (!DisableBranchOpts)
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +0000326 EverMadeChange |= splitBranchCondition(F);
Tim Northovercea0abb2014-03-29 08:22:29 +0000327
Michael Kuperstein13bf8a22017-02-28 00:11:34 +0000328 // Split some critical edges where one of the sources is an indirect branch,
329 // to help generate sane code for PHIs involving such edges.
330 EverMadeChange |= splitIndirectCriticalEdges(F);
331
Chris Lattnerc3748562007-04-02 01:35:34 +0000332 bool MadeChange = true;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000333 while (MadeChange) {
334 MadeChange = false;
Jun Bum Limdee55652017-04-03 19:20:07 +0000335 SeenChainsForSExt.clear();
336 ValToSExtendedUses.clear();
337 RemovedInsts.clear();
Hans Wennborg02fbc712012-09-19 07:48:16 +0000338 for (Function::iterator I = F.begin(); I != F.end(); ) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000339 BasicBlock *BB = &*I++;
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000340 bool ModifiedDTOnIteration = false;
Sanjay Patelfc580a62015-09-21 23:03:16 +0000341 MadeChange |= optimizeBlock(*BB, ModifiedDTOnIteration);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000342
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000343 // Restart BB iteration if the dominator tree of the Function was changed
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000344 if (ModifiedDTOnIteration)
345 break;
Evan Cheng0663f232011-03-21 01:19:09 +0000346 }
Jun Bum Limdee55652017-04-03 19:20:07 +0000347 if (EnableTypePromotionMerge && !ValToSExtendedUses.empty())
348 MadeChange |= mergeSExts(F);
349
350 // Really free removed instructions during promotion.
351 for (Instruction *I : RemovedInsts)
352 delete I;
353
Chris Lattnerf2836d12007-03-31 04:06:36 +0000354 EverMadeChange |= MadeChange;
355 }
Cameron Zwarichce3b9302011-01-06 00:42:50 +0000356
357 SunkAddrs.clear();
358
Cameron Zwarich338d3622011-03-11 21:52:04 +0000359 if (!DisableBranchOpts) {
360 MadeChange = false;
Bill Wendling97b93592012-03-04 10:46:01 +0000361 SmallPtrSet<BasicBlock*, 8> WorkList;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +0000362 for (BasicBlock &BB : F) {
363 SmallVector<BasicBlock *, 2> Successors(succ_begin(&BB), succ_end(&BB));
364 MadeChange |= ConstantFoldTerminator(&BB, true);
Bill Wendling97b93592012-03-04 10:46:01 +0000365 if (!MadeChange) continue;
366
367 for (SmallVectorImpl<BasicBlock*>::iterator
368 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
369 if (pred_begin(*II) == pred_end(*II))
370 WorkList.insert(*II);
371 }
372
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000373 // Delete the dead blocks and any of their dead successors.
Bill Wendlingab417b62012-12-06 00:30:20 +0000374 MadeChange |= !WorkList.empty();
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000375 while (!WorkList.empty()) {
376 BasicBlock *BB = *WorkList.begin();
377 WorkList.erase(BB);
378 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
379
380 DeleteDeadBlock(BB);
Stephen Lin837bba12013-07-15 17:55:02 +0000381
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000382 for (SmallVectorImpl<BasicBlock*>::iterator
383 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
384 if (pred_begin(*II) == pred_end(*II))
385 WorkList.insert(*II);
386 }
Cameron Zwarich338d3622011-03-11 21:52:04 +0000387
Nadav Rotem70409992012-08-14 05:19:07 +0000388 // Merge pairs of basic blocks with unconditional branches, connected by
389 // a single edge.
390 if (EverMadeChange || MadeChange)
Sanjay Patelfc580a62015-09-21 23:03:16 +0000391 MadeChange |= eliminateFallThrough(F);
Nadav Rotem70409992012-08-14 05:19:07 +0000392
Cameron Zwarich338d3622011-03-11 21:52:04 +0000393 EverMadeChange |= MadeChange;
394 }
395
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000396 if (!DisableGCOpts) {
397 SmallVector<Instruction *, 2> Statepoints;
398 for (BasicBlock &BB : F)
399 for (Instruction &I : BB)
400 if (isStatepoint(I))
401 Statepoints.push_back(&I);
402 for (auto &I : Statepoints)
403 EverMadeChange |= simplifyOffsetableRelocate(*I);
404 }
405
Chris Lattnerf2836d12007-03-31 04:06:36 +0000406 return EverMadeChange;
407}
408
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000409/// Merge basic blocks which are connected by a single edge, where one of the
410/// basic blocks has a single successor pointing to the other basic block,
411/// which has a single predecessor.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000412bool CodeGenPrepare::eliminateFallThrough(Function &F) {
Nadav Rotem70409992012-08-14 05:19:07 +0000413 bool Changed = false;
414 // Scan all of the blocks in the function, except for the entry block.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000415 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000416 BasicBlock *BB = &*I++;
Nadav Rotem70409992012-08-14 05:19:07 +0000417 // If the destination block has a single pred, then this is a trivial
418 // edge, just collapse it.
419 BasicBlock *SinglePred = BB->getSinglePredecessor();
420
Evan Cheng64a223a2012-09-28 23:58:57 +0000421 // Don't merge if BB's address is taken.
422 if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue;
Nadav Rotem70409992012-08-14 05:19:07 +0000423
424 BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
425 if (Term && !Term->isConditional()) {
426 Changed = true;
Michael Liao6e12d122012-08-21 05:55:22 +0000427 DEBUG(dbgs() << "To merge:\n"<< *SinglePred << "\n\n\n");
Nadav Rotem70409992012-08-14 05:19:07 +0000428 // Remember if SinglePred was the entry block of the function.
429 // If so, we will need to move BB back to the entry position.
430 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Quentin Colombet7bdd50d2015-03-18 23:17:28 +0000431 MergeBasicBlockIntoOnlyPred(BB, nullptr);
Nadav Rotem70409992012-08-14 05:19:07 +0000432
433 if (isEntry && BB != &BB->getParent()->getEntryBlock())
434 BB->moveBefore(&BB->getParent()->getEntryBlock());
435
436 // We have erased a block. Update the iterator.
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000437 I = BB->getIterator();
Nadav Rotem70409992012-08-14 05:19:07 +0000438 }
439 }
440 return Changed;
441}
442
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000443/// Find a destination block from BB if BB is mergeable empty block.
444BasicBlock *CodeGenPrepare::findDestBlockOfMergeableEmptyBlock(BasicBlock *BB) {
445 // If this block doesn't end with an uncond branch, ignore it.
446 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
447 if (!BI || !BI->isUnconditional())
448 return nullptr;
449
450 // If the instruction before the branch (skipping debug info) isn't a phi
451 // node, then other stuff is happening here.
452 BasicBlock::iterator BBI = BI->getIterator();
453 if (BBI != BB->begin()) {
454 --BBI;
455 while (isa<DbgInfoIntrinsic>(BBI)) {
456 if (BBI == BB->begin())
457 break;
458 --BBI;
459 }
460 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
461 return nullptr;
462 }
463
464 // Do not break infinite loops.
465 BasicBlock *DestBB = BI->getSuccessor(0);
466 if (DestBB == BB)
467 return nullptr;
468
469 if (!canMergeBlocks(BB, DestBB))
470 DestBB = nullptr;
471
472 return DestBB;
473}
474
Michael Kuperstein13bf8a22017-02-28 00:11:34 +0000475// Return the unique indirectbr predecessor of a block. This may return null
476// even if such a predecessor exists, if it's not useful for splitting.
477// If a predecessor is found, OtherPreds will contain all other (non-indirectbr)
478// predecessors of BB.
479static BasicBlock *
480findIBRPredecessor(BasicBlock *BB, SmallVectorImpl<BasicBlock *> &OtherPreds) {
481 // If the block doesn't have any PHIs, we don't care about it, since there's
482 // no point in splitting it.
483 PHINode *PN = dyn_cast<PHINode>(BB->begin());
484 if (!PN)
485 return nullptr;
486
487 // Verify we have exactly one IBR predecessor.
488 // Conservatively bail out if one of the other predecessors is not a "regular"
489 // terminator (that is, not a switch or a br).
490 BasicBlock *IBB = nullptr;
491 for (unsigned Pred = 0, E = PN->getNumIncomingValues(); Pred != E; ++Pred) {
492 BasicBlock *PredBB = PN->getIncomingBlock(Pred);
493 TerminatorInst *PredTerm = PredBB->getTerminator();
494 switch (PredTerm->getOpcode()) {
495 case Instruction::IndirectBr:
496 if (IBB)
497 return nullptr;
498 IBB = PredBB;
499 break;
500 case Instruction::Br:
501 case Instruction::Switch:
502 OtherPreds.push_back(PredBB);
503 continue;
504 default:
505 return nullptr;
506 }
507 }
508
509 return IBB;
510}
511
512// Split critical edges where the source of the edge is an indirectbr
513// instruction. This isn't always possible, but we can handle some easy cases.
514// This is useful because MI is unable to split such critical edges,
515// which means it will not be able to sink instructions along those edges.
516// This is especially painful for indirect branches with many successors, where
517// we end up having to prepare all outgoing values in the origin block.
518//
519// Our normal algorithm for splitting critical edges requires us to update
520// the outgoing edges of the edge origin block, but for an indirectbr this
521// is hard, since it would require finding and updating the block addresses
522// the indirect branch uses. But if a block only has a single indirectbr
523// predecessor, with the others being regular branches, we can do it in a
524// different way.
525// Say we have A -> D, B -> D, I -> D where only I -> D is an indirectbr.
526// We can split D into D0 and D1, where D0 contains only the PHIs from D,
527// and D1 is the D block body. We can then duplicate D0 as D0A and D0B, and
528// create the following structure:
529// A -> D0A, B -> D0A, I -> D0B, D0A -> D1, D0B -> D1
530bool CodeGenPrepare::splitIndirectCriticalEdges(Function &F) {
531 // Check whether the function has any indirectbrs, and collect which blocks
532 // they may jump to. Since most functions don't have indirect branches,
533 // this lowers the common case's overhead to O(Blocks) instead of O(Edges).
534 SmallSetVector<BasicBlock *, 16> Targets;
535 for (auto &BB : F) {
536 auto *IBI = dyn_cast<IndirectBrInst>(BB.getTerminator());
537 if (!IBI)
538 continue;
539
540 for (unsigned Succ = 0, E = IBI->getNumSuccessors(); Succ != E; ++Succ)
541 Targets.insert(IBI->getSuccessor(Succ));
542 }
543
544 if (Targets.empty())
545 return false;
546
547 bool Changed = false;
548 for (BasicBlock *Target : Targets) {
549 SmallVector<BasicBlock *, 16> OtherPreds;
550 BasicBlock *IBRPred = findIBRPredecessor(Target, OtherPreds);
551 // If we did not found an indirectbr, or the indirectbr is the only
552 // incoming edge, this isn't the kind of edge we're looking for.
553 if (!IBRPred || OtherPreds.empty())
554 continue;
555
556 // Don't even think about ehpads/landingpads.
557 Instruction *FirstNonPHI = Target->getFirstNonPHI();
558 if (FirstNonPHI->isEHPad() || Target->isLandingPad())
559 continue;
560
561 BasicBlock *BodyBlock = Target->splitBasicBlock(FirstNonPHI, ".split");
562 // It's possible Target was its own successor through an indirectbr.
563 // In this case, the indirectbr now comes from BodyBlock.
564 if (IBRPred == Target)
565 IBRPred = BodyBlock;
566
567 // At this point Target only has PHIs, and BodyBlock has the rest of the
568 // block's body. Create a copy of Target that will be used by the "direct"
569 // preds.
570 ValueToValueMapTy VMap;
571 BasicBlock *DirectSucc = CloneBasicBlock(Target, VMap, ".clone", &F);
572
573 for (BasicBlock *Pred : OtherPreds)
574 Pred->getTerminator()->replaceUsesOfWith(Target, DirectSucc);
575
576 // Ok, now fix up the PHIs. We know the two blocks only have PHIs, and that
577 // they are clones, so the number of PHIs are the same.
578 // (a) Remove the edge coming from IBRPred from the "Direct" PHI
579 // (b) Leave that as the only edge in the "Indirect" PHI.
580 // (c) Merge the two in the body block.
581 BasicBlock::iterator Indirect = Target->begin(),
582 End = Target->getFirstNonPHI()->getIterator();
583 BasicBlock::iterator Direct = DirectSucc->begin();
584 BasicBlock::iterator MergeInsert = BodyBlock->getFirstInsertionPt();
585
586 assert(&*End == Target->getTerminator() &&
587 "Block was expected to only contain PHIs");
588
589 while (Indirect != End) {
590 PHINode *DirPHI = cast<PHINode>(Direct);
591 PHINode *IndPHI = cast<PHINode>(Indirect);
592
593 // Now, clean up - the direct block shouldn't get the indirect value,
594 // and vice versa.
595 DirPHI->removeIncomingValue(IBRPred);
596 Direct++;
597
598 // Advance the pointer here, to avoid invalidation issues when the old
599 // PHI is erased.
600 Indirect++;
601
602 PHINode *NewIndPHI = PHINode::Create(IndPHI->getType(), 1, "ind", IndPHI);
603 NewIndPHI->addIncoming(IndPHI->getIncomingValueForBlock(IBRPred),
604 IBRPred);
605
606 // Create a PHI in the body block, to merge the direct and indirect
607 // predecessors.
608 PHINode *MergePHI =
609 PHINode::Create(IndPHI->getType(), 2, "merge", &*MergeInsert);
610 MergePHI->addIncoming(NewIndPHI, Target);
611 MergePHI->addIncoming(DirPHI, DirectSucc);
612
613 IndPHI->replaceAllUsesWith(MergePHI);
614 IndPHI->eraseFromParent();
615 }
616
617 Changed = true;
618 }
619
620 return Changed;
621}
622
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000623/// Eliminate blocks that contain only PHI nodes, debug info directives, and an
624/// unconditional branch. Passes before isel (e.g. LSR/loopsimplify) often split
625/// edges in ways that are non-optimal for isel. Start by eliminating these
626/// blocks so we can split them the way we want them.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000627bool CodeGenPrepare::eliminateMostlyEmptyBlocks(Function &F) {
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000628 SmallPtrSet<BasicBlock *, 16> Preheaders;
629 SmallVector<Loop *, 16> LoopList(LI->begin(), LI->end());
630 while (!LoopList.empty()) {
631 Loop *L = LoopList.pop_back_val();
632 LoopList.insert(LoopList.end(), L->begin(), L->end());
633 if (BasicBlock *Preheader = L->getLoopPreheader())
634 Preheaders.insert(Preheader);
635 }
636
Chris Lattnerc3748562007-04-02 01:35:34 +0000637 bool MadeChange = false;
638 // Note that this intentionally skips the entry block.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000639 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000640 BasicBlock *BB = &*I++;
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000641 BasicBlock *DestBB = findDestBlockOfMergeableEmptyBlock(BB);
642 if (!DestBB ||
643 !isMergingEmptyBlockProfitable(BB, DestBB, Preheaders.count(BB)))
Chris Lattnerc3748562007-04-02 01:35:34 +0000644 continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000645
Sanjay Patelfc580a62015-09-21 23:03:16 +0000646 eliminateMostlyEmptyBlock(BB);
Chris Lattnerc3748562007-04-02 01:35:34 +0000647 MadeChange = true;
648 }
649 return MadeChange;
650}
651
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000652bool CodeGenPrepare::isMergingEmptyBlockProfitable(BasicBlock *BB,
653 BasicBlock *DestBB,
654 bool isPreheader) {
655 // Do not delete loop preheaders if doing so would create a critical edge.
656 // Loop preheaders can be good locations to spill registers. If the
657 // preheader is deleted and we create a critical edge, registers may be
658 // spilled in the loop body instead.
659 if (!DisablePreheaderProtect && isPreheader &&
660 !(BB->getSinglePredecessor() &&
661 BB->getSinglePredecessor()->getSingleSuccessor()))
662 return false;
663
664 // Try to skip merging if the unique predecessor of BB is terminated by a
665 // switch or indirect branch instruction, and BB is used as an incoming block
666 // of PHIs in DestBB. In such case, merging BB and DestBB would cause ISel to
667 // add COPY instructions in the predecessor of BB instead of BB (if it is not
668 // merged). Note that the critical edge created by merging such blocks wont be
669 // split in MachineSink because the jump table is not analyzable. By keeping
670 // such empty block (BB), ISel will place COPY instructions in BB, not in the
671 // predecessor of BB.
672 BasicBlock *Pred = BB->getUniquePredecessor();
673 if (!Pred ||
674 !(isa<SwitchInst>(Pred->getTerminator()) ||
675 isa<IndirectBrInst>(Pred->getTerminator())))
676 return true;
677
678 if (BB->getTerminator() != BB->getFirstNonPHI())
679 return true;
680
681 // We use a simple cost heuristic which determine skipping merging is
682 // profitable if the cost of skipping merging is less than the cost of
683 // merging : Cost(skipping merging) < Cost(merging BB), where the
684 // Cost(skipping merging) is Freq(BB) * (Cost(Copy) + Cost(Branch)), and
685 // the Cost(merging BB) is Freq(Pred) * Cost(Copy).
686 // Assuming Cost(Copy) == Cost(Branch), we could simplify it to :
687 // Freq(Pred) / Freq(BB) > 2.
688 // Note that if there are multiple empty blocks sharing the same incoming
689 // value for the PHIs in the DestBB, we consider them together. In such
690 // case, Cost(merging BB) will be the sum of their frequencies.
691
692 if (!isa<PHINode>(DestBB->begin()))
693 return true;
694
695 SmallPtrSet<BasicBlock *, 16> SameIncomingValueBBs;
696
697 // Find all other incoming blocks from which incoming values of all PHIs in
698 // DestBB are the same as the ones from BB.
699 for (pred_iterator PI = pred_begin(DestBB), E = pred_end(DestBB); PI != E;
700 ++PI) {
701 BasicBlock *DestBBPred = *PI;
702 if (DestBBPred == BB)
703 continue;
704
705 bool HasAllSameValue = true;
706 BasicBlock::const_iterator DestBBI = DestBB->begin();
707 while (const PHINode *DestPN = dyn_cast<PHINode>(DestBBI++)) {
708 if (DestPN->getIncomingValueForBlock(BB) !=
709 DestPN->getIncomingValueForBlock(DestBBPred)) {
710 HasAllSameValue = false;
711 break;
712 }
713 }
714 if (HasAllSameValue)
715 SameIncomingValueBBs.insert(DestBBPred);
716 }
717
718 // See if all BB's incoming values are same as the value from Pred. In this
719 // case, no reason to skip merging because COPYs are expected to be place in
720 // Pred already.
721 if (SameIncomingValueBBs.count(Pred))
722 return true;
723
724 if (!BFI) {
725 Function &F = *BB->getParent();
726 LoopInfo LI{DominatorTree(F)};
727 BPI.reset(new BranchProbabilityInfo(F, LI));
728 BFI.reset(new BlockFrequencyInfo(F, *BPI, LI));
729 }
730
731 BlockFrequency PredFreq = BFI->getBlockFreq(Pred);
732 BlockFrequency BBFreq = BFI->getBlockFreq(BB);
733
734 for (auto SameValueBB : SameIncomingValueBBs)
735 if (SameValueBB->getUniquePredecessor() == Pred &&
736 DestBB == findDestBlockOfMergeableEmptyBlock(SameValueBB))
737 BBFreq += BFI->getBlockFreq(SameValueBB);
738
739 return PredFreq.getFrequency() <=
740 BBFreq.getFrequency() * FreqRatioToSkipMerge;
741}
742
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000743/// Return true if we can merge BB into DestBB if there is a single
744/// unconditional branch between them, and BB contains no other non-phi
Chris Lattnerc3748562007-04-02 01:35:34 +0000745/// instructions.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000746bool CodeGenPrepare::canMergeBlocks(const BasicBlock *BB,
Chris Lattnerc3748562007-04-02 01:35:34 +0000747 const BasicBlock *DestBB) const {
748 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
749 // the successor. If there are more complex condition (e.g. preheaders),
750 // don't mess around with them.
751 BasicBlock::const_iterator BBI = BB->begin();
752 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000753 for (const User *U : PN->users()) {
754 const Instruction *UI = cast<Instruction>(U);
755 if (UI->getParent() != DestBB || !isa<PHINode>(UI))
Chris Lattnerc3748562007-04-02 01:35:34 +0000756 return false;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000757 // If User is inside DestBB block and it is a PHINode then check
758 // incoming value. If incoming value is not from BB then this is
Devang Pateld3208522007-04-25 00:37:04 +0000759 // a complex condition (e.g. preheaders) we want to avoid here.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000760 if (UI->getParent() == DestBB) {
761 if (const PHINode *UPN = dyn_cast<PHINode>(UI))
Devang Pateld3208522007-04-25 00:37:04 +0000762 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
763 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
764 if (Insn && Insn->getParent() == BB &&
765 Insn->getParent() != UPN->getIncomingBlock(I))
766 return false;
767 }
768 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000769 }
770 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000771
Chris Lattnerc3748562007-04-02 01:35:34 +0000772 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
773 // and DestBB may have conflicting incoming values for the block. If so, we
774 // can't merge the block.
775 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
776 if (!DestBBPN) return true; // no conflict.
Eric Christopherc1ea1492008-09-24 05:32:41 +0000777
Chris Lattnerc3748562007-04-02 01:35:34 +0000778 // Collect the preds of BB.
Chris Lattner8201a9b2007-11-06 22:07:40 +0000779 SmallPtrSet<const BasicBlock*, 16> BBPreds;
Chris Lattnerc3748562007-04-02 01:35:34 +0000780 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
781 // It is faster to get preds from a PHI than with pred_iterator.
782 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
783 BBPreds.insert(BBPN->getIncomingBlock(i));
784 } else {
785 BBPreds.insert(pred_begin(BB), pred_end(BB));
786 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000787
Chris Lattnerc3748562007-04-02 01:35:34 +0000788 // Walk the preds of DestBB.
789 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
790 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
791 if (BBPreds.count(Pred)) { // Common predecessor?
792 BBI = DestBB->begin();
793 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
794 const Value *V1 = PN->getIncomingValueForBlock(Pred);
795 const Value *V2 = PN->getIncomingValueForBlock(BB);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000796
Chris Lattnerc3748562007-04-02 01:35:34 +0000797 // If V2 is a phi node in BB, look up what the mapped value will be.
798 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
799 if (V2PN->getParent() == BB)
800 V2 = V2PN->getIncomingValueForBlock(Pred);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000801
Chris Lattnerc3748562007-04-02 01:35:34 +0000802 // If there is a conflict, bail out.
803 if (V1 != V2) return false;
804 }
805 }
806 }
807
808 return true;
809}
810
811
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000812/// Eliminate a basic block that has only phi's and an unconditional branch in
813/// it.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000814void CodeGenPrepare::eliminateMostlyEmptyBlock(BasicBlock *BB) {
Chris Lattnerc3748562007-04-02 01:35:34 +0000815 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
816 BasicBlock *DestBB = BI->getSuccessor(0);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000817
David Greene74e2d492010-01-05 01:27:11 +0000818 DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000819
Chris Lattnerc3748562007-04-02 01:35:34 +0000820 // If the destination block has a single pred, then this is a trivial edge,
821 // just collapse it.
Chris Lattner4059f432008-11-27 19:29:14 +0000822 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
Chris Lattner8a172da2008-11-28 19:54:49 +0000823 if (SinglePred != DestBB) {
824 // Remember if SinglePred was the entry block of the function. If so, we
825 // will need to move BB back to the entry position.
826 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Quentin Colombet7bdd50d2015-03-18 23:17:28 +0000827 MergeBasicBlockIntoOnlyPred(DestBB, nullptr);
Chris Lattner4059f432008-11-27 19:29:14 +0000828
Chris Lattner8a172da2008-11-28 19:54:49 +0000829 if (isEntry && BB != &BB->getParent()->getEntryBlock())
830 BB->moveBefore(&BB->getParent()->getEntryBlock());
Nadav Rotem465834c2012-07-24 10:51:42 +0000831
David Greene74e2d492010-01-05 01:27:11 +0000832 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattner8a172da2008-11-28 19:54:49 +0000833 return;
834 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000835 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000836
Chris Lattnerc3748562007-04-02 01:35:34 +0000837 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
838 // to handle the new incoming edges it is about to have.
839 PHINode *PN;
840 for (BasicBlock::iterator BBI = DestBB->begin();
841 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
842 // Remove the incoming value for BB, and remember it.
843 Value *InVal = PN->removeIncomingValue(BB, false);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000844
Chris Lattnerc3748562007-04-02 01:35:34 +0000845 // Two options: either the InVal is a phi node defined in BB or it is some
846 // value that dominates BB.
847 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
848 if (InValPhi && InValPhi->getParent() == BB) {
849 // Add all of the input values of the input PHI as inputs of this phi.
850 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
851 PN->addIncoming(InValPhi->getIncomingValue(i),
852 InValPhi->getIncomingBlock(i));
853 } else {
854 // Otherwise, add one instance of the dominating value for each edge that
855 // we will be adding.
856 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
857 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
858 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
859 } else {
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000860 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
861 PN->addIncoming(InVal, *PI);
Chris Lattnerc3748562007-04-02 01:35:34 +0000862 }
863 }
864 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000865
Chris Lattnerc3748562007-04-02 01:35:34 +0000866 // The PHIs are now updated, change everything that refers to BB to use
867 // DestBB and remove BB.
868 BB->replaceAllUsesWith(DestBB);
869 BB->eraseFromParent();
Cameron Zwarichced753f2011-01-05 17:27:27 +0000870 ++NumBlocksElim;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000871
David Greene74e2d492010-01-05 01:27:11 +0000872 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerc3748562007-04-02 01:35:34 +0000873}
874
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000875// Computes a map of base pointer relocation instructions to corresponding
876// derived pointer relocation instructions given a vector of all relocate calls
877static void computeBaseDerivedRelocateMap(
Manuel Jacob83eefa62016-01-05 04:03:00 +0000878 const SmallVectorImpl<GCRelocateInst *> &AllRelocateCalls,
879 DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>>
880 &RelocateInstMap) {
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000881 // Collect information in two maps: one primarily for locating the base object
882 // while filling the second map; the second map is the final structure holding
883 // a mapping between Base and corresponding Derived relocate calls
Manuel Jacob83eefa62016-01-05 04:03:00 +0000884 DenseMap<std::pair<unsigned, unsigned>, GCRelocateInst *> RelocateIdxMap;
885 for (auto *ThisRelocate : AllRelocateCalls) {
886 auto K = std::make_pair(ThisRelocate->getBasePtrIndex(),
887 ThisRelocate->getDerivedPtrIndex());
888 RelocateIdxMap.insert(std::make_pair(K, ThisRelocate));
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000889 }
890 for (auto &Item : RelocateIdxMap) {
891 std::pair<unsigned, unsigned> Key = Item.first;
892 if (Key.first == Key.second)
893 // Base relocation: nothing to insert
894 continue;
895
Manuel Jacob83eefa62016-01-05 04:03:00 +0000896 GCRelocateInst *I = Item.second;
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000897 auto BaseKey = std::make_pair(Key.first, Key.first);
Sanjoy Dasb8186762015-02-27 02:24:16 +0000898
899 // We're iterating over RelocateIdxMap so we cannot modify it.
900 auto MaybeBase = RelocateIdxMap.find(BaseKey);
901 if (MaybeBase == RelocateIdxMap.end())
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000902 // TODO: We might want to insert a new base object relocate and gep off
903 // that, if there are enough derived object relocates.
904 continue;
Sanjoy Dasb8186762015-02-27 02:24:16 +0000905
906 RelocateInstMap[MaybeBase->second].push_back(I);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000907 }
908}
909
910// Accepts a GEP and extracts the operands into a vector provided they're all
911// small integer constants
912static bool getGEPSmallConstantIntOffsetV(GetElementPtrInst *GEP,
913 SmallVectorImpl<Value *> &OffsetV) {
914 for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
915 // Only accept small constant integer operands
916 auto Op = dyn_cast<ConstantInt>(GEP->getOperand(i));
917 if (!Op || Op->getZExtValue() > 20)
918 return false;
919 }
920
921 for (unsigned i = 1; i < GEP->getNumOperands(); i++)
922 OffsetV.push_back(GEP->getOperand(i));
923 return true;
924}
925
926// Takes a RelocatedBase (base pointer relocation instruction) and Targets to
927// replace, computes a replacement, and affects it.
928static bool
Manuel Jacob83eefa62016-01-05 04:03:00 +0000929simplifyRelocatesOffABase(GCRelocateInst *RelocatedBase,
930 const SmallVectorImpl<GCRelocateInst *> &Targets) {
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000931 bool MadeChange = false;
Manuel Jacob83eefa62016-01-05 04:03:00 +0000932 for (GCRelocateInst *ToReplace : Targets) {
933 assert(ToReplace->getBasePtrIndex() == RelocatedBase->getBasePtrIndex() &&
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000934 "Not relocating a derived object of the original base object");
Manuel Jacob83eefa62016-01-05 04:03:00 +0000935 if (ToReplace->getBasePtrIndex() == ToReplace->getDerivedPtrIndex()) {
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000936 // A duplicate relocate call. TODO: coalesce duplicates.
937 continue;
938 }
939
Igor Laevskyf637b4a2015-11-03 18:37:40 +0000940 if (RelocatedBase->getParent() != ToReplace->getParent()) {
941 // Base and derived relocates are in different basic blocks.
942 // In this case transform is only valid when base dominates derived
943 // relocate. However it would be too expensive to check dominance
944 // for each such relocate, so we skip the whole transformation.
945 continue;
946 }
947
Manuel Jacob83eefa62016-01-05 04:03:00 +0000948 Value *Base = ToReplace->getBasePtr();
949 auto Derived = dyn_cast<GetElementPtrInst>(ToReplace->getDerivedPtr());
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000950 if (!Derived || Derived->getPointerOperand() != Base)
951 continue;
952
953 SmallVector<Value *, 2> OffsetV;
954 if (!getGEPSmallConstantIntOffsetV(Derived, OffsetV))
955 continue;
956
957 // Create a Builder and replace the target callsite with a gep
Sanjay Patel545a4562016-01-20 18:59:16 +0000958 assert(RelocatedBase->getNextNode() &&
959 "Should always have one since it's not a terminator");
Sanjoy Das3d705e32015-05-11 23:47:30 +0000960
961 // Insert after RelocatedBase
962 IRBuilder<> Builder(RelocatedBase->getNextNode());
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000963 Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc());
Sanjoy Das89c54912015-05-11 18:49:34 +0000964
965 // If gc_relocate does not match the actual type, cast it to the right type.
966 // In theory, there must be a bitcast after gc_relocate if the type does not
967 // match, and we should reuse it to get the derived pointer. But it could be
968 // cases like this:
969 // bb1:
970 // ...
971 // %g1 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
972 // br label %merge
973 //
974 // bb2:
975 // ...
976 // %g2 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
977 // br label %merge
978 //
979 // merge:
980 // %p1 = phi i8 addrspace(1)* [ %g1, %bb1 ], [ %g2, %bb2 ]
981 // %cast = bitcast i8 addrspace(1)* %p1 in to i32 addrspace(1)*
982 //
983 // In this case, we can not find the bitcast any more. So we insert a new bitcast
984 // no matter there is already one or not. In this way, we can handle all cases, and
985 // the extra bitcast should be optimized away in later passes.
Manuel Jacob5b90b142015-12-19 18:38:42 +0000986 Value *ActualRelocatedBase = RelocatedBase;
Sanjoy Das89c54912015-05-11 18:49:34 +0000987 if (RelocatedBase->getType() != Base->getType()) {
988 ActualRelocatedBase =
Manuel Jacob5b90b142015-12-19 18:38:42 +0000989 Builder.CreateBitCast(RelocatedBase, Base->getType());
Sanjoy Das89c54912015-05-11 18:49:34 +0000990 }
David Blaikie68d535c2015-03-24 22:38:16 +0000991 Value *Replacement = Builder.CreateGEP(
Sanjoy Das89c54912015-05-11 18:49:34 +0000992 Derived->getSourceElementType(), ActualRelocatedBase, makeArrayRef(OffsetV));
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000993 Replacement->takeName(ToReplace);
Sanjoy Das89c54912015-05-11 18:49:34 +0000994 // If the newly generated derived pointer's type does not match the original derived
995 // pointer's type, cast the new derived pointer to match it. Same reasoning as above.
Manuel Jacob5b90b142015-12-19 18:38:42 +0000996 Value *ActualReplacement = Replacement;
997 if (Replacement->getType() != ToReplace->getType()) {
Sanjoy Das89c54912015-05-11 18:49:34 +0000998 ActualReplacement =
Manuel Jacob5b90b142015-12-19 18:38:42 +0000999 Builder.CreateBitCast(Replacement, ToReplace->getType());
Sanjoy Das89c54912015-05-11 18:49:34 +00001000 }
1001 ToReplace->replaceAllUsesWith(ActualReplacement);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +00001002 ToReplace->eraseFromParent();
1003
1004 MadeChange = true;
1005 }
1006 return MadeChange;
1007}
1008
1009// Turns this:
1010//
1011// %base = ...
1012// %ptr = gep %base + 15
1013// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
1014// %base' = relocate(%tok, i32 4, i32 4)
1015// %ptr' = relocate(%tok, i32 4, i32 5)
1016// %val = load %ptr'
1017//
1018// into this:
1019//
1020// %base = ...
1021// %ptr = gep %base + 15
1022// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
1023// %base' = gc.relocate(%tok, i32 4, i32 4)
1024// %ptr' = gep %base' + 15
1025// %val = load %ptr'
1026bool CodeGenPrepare::simplifyOffsetableRelocate(Instruction &I) {
1027 bool MadeChange = false;
Manuel Jacob83eefa62016-01-05 04:03:00 +00001028 SmallVector<GCRelocateInst *, 2> AllRelocateCalls;
Ramkumar Ramachandradba73292015-01-14 23:27:07 +00001029
1030 for (auto *U : I.users())
Manuel Jacob83eefa62016-01-05 04:03:00 +00001031 if (GCRelocateInst *Relocate = dyn_cast<GCRelocateInst>(U))
Ramkumar Ramachandradba73292015-01-14 23:27:07 +00001032 // Collect all the relocate calls associated with a statepoint
Manuel Jacob83eefa62016-01-05 04:03:00 +00001033 AllRelocateCalls.push_back(Relocate);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +00001034
1035 // We need atleast one base pointer relocation + one derived pointer
1036 // relocation to mangle
1037 if (AllRelocateCalls.size() < 2)
1038 return false;
1039
1040 // RelocateInstMap is a mapping from the base relocate instruction to the
1041 // corresponding derived relocate instructions
Manuel Jacob83eefa62016-01-05 04:03:00 +00001042 DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>> RelocateInstMap;
Ramkumar Ramachandradba73292015-01-14 23:27:07 +00001043 computeBaseDerivedRelocateMap(AllRelocateCalls, RelocateInstMap);
1044 if (RelocateInstMap.empty())
1045 return false;
1046
1047 for (auto &Item : RelocateInstMap)
1048 // Item.first is the RelocatedBase to offset against
1049 // Item.second is the vector of Targets to replace
1050 MadeChange = simplifyRelocatesOffABase(Item.first, Item.second);
1051 return MadeChange;
1052}
1053
Manuel Jacoba7c48f92014-03-13 13:36:25 +00001054/// SinkCast - Sink the specified cast instruction into its user blocks
1055static bool SinkCast(CastInst *CI) {
Chris Lattnerf2836d12007-03-31 04:06:36 +00001056 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +00001057
Chris Lattnerf2836d12007-03-31 04:06:36 +00001058 /// InsertedCasts - Only insert a cast in each block once.
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001059 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001060
Chris Lattnerf2836d12007-03-31 04:06:36 +00001061 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001062 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
Chris Lattnerf2836d12007-03-31 04:06:36 +00001063 UI != E; ) {
1064 Use &TheUse = UI.getUse();
1065 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +00001066
Chris Lattnerf2836d12007-03-31 04:06:36 +00001067 // Figure out which BB this cast is used in. For PHI's this is the
1068 // appropriate predecessor block.
1069 BasicBlock *UserBB = User->getParent();
1070 if (PHINode *PN = dyn_cast<PHINode>(User)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001071 UserBB = PN->getIncomingBlock(TheUse);
Chris Lattnerf2836d12007-03-31 04:06:36 +00001072 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001073
Chris Lattnerf2836d12007-03-31 04:06:36 +00001074 // Preincrement use iterator so we don't invalidate it.
1075 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001076
David Majnemer0c80e2e2016-04-27 19:36:38 +00001077 // The first insertion point of a block containing an EH pad is after the
1078 // pad. If the pad is the user, we cannot sink the cast past the pad.
1079 if (User->isEHPad())
1080 continue;
1081
Andrew Kaylord0430e82015-11-23 19:16:15 +00001082 // If the block selected to receive the cast is an EH pad that does not
1083 // allow non-PHI instructions before the terminator, we can't sink the
1084 // cast.
1085 if (UserBB->getTerminator()->isEHPad())
1086 continue;
1087
Chris Lattnerf2836d12007-03-31 04:06:36 +00001088 // If this user is in the same block as the cast, don't change the cast.
1089 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001090
Chris Lattnerf2836d12007-03-31 04:06:36 +00001091 // If we have already inserted a cast into this block, use it.
1092 CastInst *&InsertedCast = InsertedCasts[UserBB];
1093
1094 if (!InsertedCast) {
Bill Wendling8ddfc092011-08-16 20:45:24 +00001095 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001096 assert(InsertPt != UserBB->end());
1097 InsertedCast = CastInst::Create(CI->getOpcode(), CI->getOperand(0),
1098 CI->getType(), "", &*InsertPt);
Chris Lattnerf2836d12007-03-31 04:06:36 +00001099 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001100
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001101 // Replace a use of the cast with a use of the new cast.
Chris Lattnerf2836d12007-03-31 04:06:36 +00001102 TheUse = InsertedCast;
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +00001103 MadeChange = true;
Cameron Zwarichced753f2011-01-05 17:27:27 +00001104 ++NumCastUses;
Chris Lattnerf2836d12007-03-31 04:06:36 +00001105 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001106
Chris Lattnerf2836d12007-03-31 04:06:36 +00001107 // If we removed all uses, nuke the cast.
Duncan Sandsafa84da42008-01-20 16:51:46 +00001108 if (CI->use_empty()) {
Chris Lattnerf2836d12007-03-31 04:06:36 +00001109 CI->eraseFromParent();
Duncan Sandsafa84da42008-01-20 16:51:46 +00001110 MadeChange = true;
1111 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001112
Chris Lattnerf2836d12007-03-31 04:06:36 +00001113 return MadeChange;
1114}
1115
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001116/// If the specified cast instruction is a noop copy (e.g. it's casting from
1117/// one pointer type to another, i32->i8 on PPC), sink it into user blocks to
1118/// reduce the number of virtual registers that must be created and coalesced.
Manuel Jacoba7c48f92014-03-13 13:36:25 +00001119///
1120/// Return true if any changes are made.
1121///
Mehdi Amini44ede332015-07-09 02:09:04 +00001122static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI,
1123 const DataLayout &DL) {
Justin Lebar3e50a5b2016-11-21 22:49:15 +00001124 // Sink only "cheap" (or nop) address-space casts. This is a weaker condition
1125 // than sinking only nop casts, but is helpful on some platforms.
1126 if (auto *ASC = dyn_cast<AddrSpaceCastInst>(CI)) {
1127 if (!TLI.isCheapAddrSpaceCast(ASC->getSrcAddressSpace(),
1128 ASC->getDestAddressSpace()))
1129 return false;
1130 }
1131
Manuel Jacoba7c48f92014-03-13 13:36:25 +00001132 // If this is a noop copy,
Mehdi Amini44ede332015-07-09 02:09:04 +00001133 EVT SrcVT = TLI.getValueType(DL, CI->getOperand(0)->getType());
1134 EVT DstVT = TLI.getValueType(DL, CI->getType());
Manuel Jacoba7c48f92014-03-13 13:36:25 +00001135
1136 // This is an fp<->int conversion?
1137 if (SrcVT.isInteger() != DstVT.isInteger())
1138 return false;
1139
1140 // If this is an extension, it will be a zero or sign extension, which
1141 // isn't a noop.
1142 if (SrcVT.bitsLT(DstVT)) return false;
1143
1144 // If these values will be promoted, find out what they will be promoted
1145 // to. This helps us consider truncates on PPC as noop copies when they
1146 // are.
1147 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
1148 TargetLowering::TypePromoteInteger)
1149 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
1150 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
1151 TargetLowering::TypePromoteInteger)
1152 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
1153
1154 // If, after promotion, these are the same types, this is a noop copy.
1155 if (SrcVT != DstVT)
1156 return false;
1157
1158 return SinkCast(CI);
1159}
1160
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001161/// Try to combine CI into a call to the llvm.uadd.with.overflow intrinsic if
1162/// possible.
Sanjoy Dasb6c59142015-04-10 21:07:09 +00001163///
1164/// Return true if any changes were made.
1165static bool CombineUAddWithOverflow(CmpInst *CI) {
1166 Value *A, *B;
1167 Instruction *AddI;
1168 if (!match(CI,
1169 m_UAddWithOverflow(m_Value(A), m_Value(B), m_Instruction(AddI))))
1170 return false;
1171
1172 Type *Ty = AddI->getType();
1173 if (!isa<IntegerType>(Ty))
1174 return false;
1175
1176 // We don't want to move around uses of condition values this late, so we we
1177 // check if it is legal to create the call to the intrinsic in the basic
1178 // block containing the icmp:
1179
1180 if (AddI->getParent() != CI->getParent() && !AddI->hasOneUse())
1181 return false;
1182
1183#ifndef NDEBUG
1184 // Someday m_UAddWithOverflow may get smarter, but this is a safe assumption
1185 // for now:
1186 if (AddI->hasOneUse())
1187 assert(*AddI->user_begin() == CI && "expected!");
1188#endif
1189
Sanjay Patelaf674fb2015-12-14 17:24:23 +00001190 Module *M = CI->getModule();
Sanjoy Dasb6c59142015-04-10 21:07:09 +00001191 Value *F = Intrinsic::getDeclaration(M, Intrinsic::uadd_with_overflow, Ty);
1192
1193 auto *InsertPt = AddI->hasOneUse() ? CI : AddI;
1194
1195 auto *UAddWithOverflow =
1196 CallInst::Create(F, {A, B}, "uadd.overflow", InsertPt);
1197 auto *UAdd = ExtractValueInst::Create(UAddWithOverflow, 0, "uadd", InsertPt);
1198 auto *Overflow =
1199 ExtractValueInst::Create(UAddWithOverflow, 1, "overflow", InsertPt);
1200
1201 CI->replaceAllUsesWith(Overflow);
1202 AddI->replaceAllUsesWith(UAdd);
1203 CI->eraseFromParent();
1204 AddI->eraseFromParent();
1205 return true;
1206}
1207
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001208/// Sink the given CmpInst into user blocks to reduce the number of virtual
1209/// registers that must be created and coalesced. This is a clear win except on
1210/// targets with multiple condition code registers (PowerPC), where it might
1211/// lose; some adjustment may be wanted there.
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001212///
1213/// Return true if any changes are made.
Peter Zotov8efe38a2016-04-03 19:32:13 +00001214static bool SinkCmpExpression(CmpInst *CI, const TargetLowering *TLI) {
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001215 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +00001216
Peter Zotov0b6d7bc2016-04-03 16:36:17 +00001217 // Avoid sinking soft-FP comparisons, since this can move them into a loop.
Peter Zotov8efe38a2016-04-03 19:32:13 +00001218 if (TLI && TLI->useSoftFloat() && isa<FCmpInst>(CI))
Peter Zotov0b6d7bc2016-04-03 16:36:17 +00001219 return false;
1220
1221 // Only insert a cmp in each block once.
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001222 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001223
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001224 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001225 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001226 UI != E; ) {
1227 Use &TheUse = UI.getUse();
1228 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +00001229
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001230 // Preincrement use iterator so we don't invalidate it.
1231 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001232
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001233 // Don't bother for PHI nodes.
1234 if (isa<PHINode>(User))
1235 continue;
1236
1237 // Figure out which BB this cmp is used in.
1238 BasicBlock *UserBB = User->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +00001239
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001240 // If this user is in the same block as the cmp, don't change the cmp.
1241 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001242
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001243 // If we have already inserted a cmp into this block, use it.
1244 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
1245
1246 if (!InsertedCmp) {
Bill Wendling8ddfc092011-08-16 20:45:24 +00001247 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001248 assert(InsertPt != UserBB->end());
Eric Christopherc1ea1492008-09-24 05:32:41 +00001249 InsertedCmp =
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001250 CmpInst::Create(CI->getOpcode(), CI->getPredicate(),
1251 CI->getOperand(0), CI->getOperand(1), "", &*InsertPt);
Wolfgang Piebe51bede2016-10-06 21:43:45 +00001252 // Propagate the debug info.
1253 InsertedCmp->setDebugLoc(CI->getDebugLoc());
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001254 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001255
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001256 // Replace a use of the cmp with a use of the new cmp.
1257 TheUse = InsertedCmp;
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +00001258 MadeChange = true;
Cameron Zwarichced753f2011-01-05 17:27:27 +00001259 ++NumCmpUses;
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001260 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001261
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001262 // If we removed all uses, nuke the cmp.
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +00001263 if (CI->use_empty()) {
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001264 CI->eraseFromParent();
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +00001265 MadeChange = true;
1266 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001267
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001268 return MadeChange;
1269}
1270
Peter Zotovf87e5502016-04-03 17:11:53 +00001271static bool OptimizeCmpExpression(CmpInst *CI, const TargetLowering *TLI) {
Peter Zotov8efe38a2016-04-03 19:32:13 +00001272 if (SinkCmpExpression(CI, TLI))
Sanjoy Dasb6c59142015-04-10 21:07:09 +00001273 return true;
1274
1275 if (CombineUAddWithOverflow(CI))
1276 return true;
1277
1278 return false;
1279}
1280
Geoff Berry5d534b62017-02-21 18:53:14 +00001281/// Duplicate and sink the given 'and' instruction into user blocks where it is
1282/// used in a compare to allow isel to generate better code for targets where
1283/// this operation can be combined.
1284///
1285/// Return true if any changes are made.
1286static bool sinkAndCmp0Expression(Instruction *AndI,
1287 const TargetLowering &TLI,
1288 SetOfInstrs &InsertedInsts) {
1289 // Double-check that we're not trying to optimize an instruction that was
1290 // already optimized by some other part of this pass.
1291 assert(!InsertedInsts.count(AndI) &&
1292 "Attempting to optimize already optimized and instruction");
1293 (void) InsertedInsts;
1294
1295 // Nothing to do for single use in same basic block.
1296 if (AndI->hasOneUse() &&
1297 AndI->getParent() == cast<Instruction>(*AndI->user_begin())->getParent())
1298 return false;
1299
1300 // Try to avoid cases where sinking/duplicating is likely to increase register
1301 // pressure.
1302 if (!isa<ConstantInt>(AndI->getOperand(0)) &&
1303 !isa<ConstantInt>(AndI->getOperand(1)) &&
1304 AndI->getOperand(0)->hasOneUse() && AndI->getOperand(1)->hasOneUse())
1305 return false;
1306
1307 for (auto *U : AndI->users()) {
1308 Instruction *User = cast<Instruction>(U);
1309
1310 // Only sink for and mask feeding icmp with 0.
1311 if (!isa<ICmpInst>(User))
1312 return false;
1313
1314 auto *CmpC = dyn_cast<ConstantInt>(User->getOperand(1));
1315 if (!CmpC || !CmpC->isZero())
1316 return false;
1317 }
1318
1319 if (!TLI.isMaskAndCmp0FoldingBeneficial(*AndI))
1320 return false;
1321
1322 DEBUG(dbgs() << "found 'and' feeding only icmp 0;\n");
1323 DEBUG(AndI->getParent()->dump());
1324
1325 // Push the 'and' into the same block as the icmp 0. There should only be
1326 // one (icmp (and, 0)) in each block, since CSE/GVN should have removed any
1327 // others, so we don't need to keep track of which BBs we insert into.
1328 for (Value::user_iterator UI = AndI->user_begin(), E = AndI->user_end();
1329 UI != E; ) {
1330 Use &TheUse = UI.getUse();
1331 Instruction *User = cast<Instruction>(*UI);
1332
1333 // Preincrement use iterator so we don't invalidate it.
1334 ++UI;
1335
1336 DEBUG(dbgs() << "sinking 'and' use: " << *User << "\n");
1337
1338 // Keep the 'and' in the same place if the use is already in the same block.
1339 Instruction *InsertPt =
1340 User->getParent() == AndI->getParent() ? AndI : User;
1341 Instruction *InsertedAnd =
1342 BinaryOperator::Create(Instruction::And, AndI->getOperand(0),
1343 AndI->getOperand(1), "", InsertPt);
1344 // Propagate the debug info.
1345 InsertedAnd->setDebugLoc(AndI->getDebugLoc());
1346
1347 // Replace a use of the 'and' with a use of the new 'and'.
1348 TheUse = InsertedAnd;
1349 ++NumAndUses;
1350 DEBUG(User->getParent()->dump());
1351 }
1352
1353 // We removed all uses, nuke the and.
1354 AndI->eraseFromParent();
1355 return true;
1356}
1357
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001358/// Check if the candidates could be combined with a shift instruction, which
1359/// includes:
Yi Jiangd069f632014-04-21 19:34:27 +00001360/// 1. Truncate instruction
1361/// 2. And instruction and the imm is a mask of the low bits:
1362/// imm & (imm+1) == 0
Benjamin Kramer322053c2014-04-27 14:54:59 +00001363static bool isExtractBitsCandidateUse(Instruction *User) {
Yi Jiangd069f632014-04-21 19:34:27 +00001364 if (!isa<TruncInst>(User)) {
1365 if (User->getOpcode() != Instruction::And ||
1366 !isa<ConstantInt>(User->getOperand(1)))
1367 return false;
1368
Quentin Colombetd4f44692014-04-22 01:20:34 +00001369 const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue();
Yi Jiangd069f632014-04-21 19:34:27 +00001370
Quentin Colombetd4f44692014-04-22 01:20:34 +00001371 if ((Cimm & (Cimm + 1)).getBoolValue())
Yi Jiangd069f632014-04-21 19:34:27 +00001372 return false;
1373 }
1374 return true;
1375}
1376
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001377/// Sink both shift and truncate instruction to the use of truncate's BB.
Benjamin Kramer322053c2014-04-27 14:54:59 +00001378static bool
Yi Jiangd069f632014-04-21 19:34:27 +00001379SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI,
1380 DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts,
Mehdi Amini44ede332015-07-09 02:09:04 +00001381 const TargetLowering &TLI, const DataLayout &DL) {
Yi Jiangd069f632014-04-21 19:34:27 +00001382 BasicBlock *UserBB = User->getParent();
1383 DenseMap<BasicBlock *, CastInst *> InsertedTruncs;
1384 TruncInst *TruncI = dyn_cast<TruncInst>(User);
1385 bool MadeChange = false;
1386
1387 for (Value::user_iterator TruncUI = TruncI->user_begin(),
1388 TruncE = TruncI->user_end();
1389 TruncUI != TruncE;) {
1390
1391 Use &TruncTheUse = TruncUI.getUse();
1392 Instruction *TruncUser = cast<Instruction>(*TruncUI);
1393 // Preincrement use iterator so we don't invalidate it.
1394
1395 ++TruncUI;
1396
1397 int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode());
1398 if (!ISDOpcode)
1399 continue;
1400
Tim Northovere2239ff2014-07-29 10:20:22 +00001401 // If the use is actually a legal node, there will not be an
1402 // implicit truncate.
1403 // FIXME: always querying the result type is just an
1404 // approximation; some nodes' legality is determined by the
1405 // operand or other means. There's no good way to find out though.
Ahmed Bougacha0788d492014-11-12 22:16:55 +00001406 if (TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00001407 ISDOpcode, TLI.getValueType(DL, TruncUser->getType(), true)))
Yi Jiangd069f632014-04-21 19:34:27 +00001408 continue;
1409
1410 // Don't bother for PHI nodes.
1411 if (isa<PHINode>(TruncUser))
1412 continue;
1413
1414 BasicBlock *TruncUserBB = TruncUser->getParent();
1415
1416 if (UserBB == TruncUserBB)
1417 continue;
1418
1419 BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB];
1420 CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB];
1421
1422 if (!InsertedShift && !InsertedTrunc) {
1423 BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001424 assert(InsertPt != TruncUserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +00001425 // Sink the shift
1426 if (ShiftI->getOpcode() == Instruction::AShr)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001427 InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
1428 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001429 else
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001430 InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
1431 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001432
1433 // Sink the trunc
1434 BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt();
1435 TruncInsertPt++;
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001436 assert(TruncInsertPt != TruncUserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +00001437
1438 InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift,
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001439 TruncI->getType(), "", &*TruncInsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001440
1441 MadeChange = true;
1442
1443 TruncTheUse = InsertedTrunc;
1444 }
1445 }
1446 return MadeChange;
1447}
1448
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001449/// Sink the shift *right* instruction into user blocks if the uses could
1450/// potentially be combined with this shift instruction and generate BitExtract
1451/// instruction. It will only be applied if the architecture supports BitExtract
1452/// instruction. Here is an example:
Yi Jiangd069f632014-04-21 19:34:27 +00001453/// BB1:
1454/// %x.extract.shift = lshr i64 %arg1, 32
1455/// BB2:
1456/// %x.extract.trunc = trunc i64 %x.extract.shift to i16
1457/// ==>
1458///
1459/// BB2:
1460/// %x.extract.shift.1 = lshr i64 %arg1, 32
1461/// %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16
1462///
1463/// CodeGen will recoginze the pattern in BB2 and generate BitExtract
1464/// instruction.
1465/// Return true if any changes are made.
1466static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI,
Mehdi Amini44ede332015-07-09 02:09:04 +00001467 const TargetLowering &TLI,
1468 const DataLayout &DL) {
Yi Jiangd069f632014-04-21 19:34:27 +00001469 BasicBlock *DefBB = ShiftI->getParent();
1470
1471 /// Only insert instructions in each block once.
1472 DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts;
1473
Mehdi Amini44ede332015-07-09 02:09:04 +00001474 bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(DL, ShiftI->getType()));
Yi Jiangd069f632014-04-21 19:34:27 +00001475
1476 bool MadeChange = false;
1477 for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end();
1478 UI != E;) {
1479 Use &TheUse = UI.getUse();
1480 Instruction *User = cast<Instruction>(*UI);
1481 // Preincrement use iterator so we don't invalidate it.
1482 ++UI;
1483
1484 // Don't bother for PHI nodes.
1485 if (isa<PHINode>(User))
1486 continue;
1487
1488 if (!isExtractBitsCandidateUse(User))
1489 continue;
1490
1491 BasicBlock *UserBB = User->getParent();
1492
1493 if (UserBB == DefBB) {
1494 // If the shift and truncate instruction are in the same BB. The use of
1495 // the truncate(TruncUse) may still introduce another truncate if not
1496 // legal. In this case, we would like to sink both shift and truncate
1497 // instruction to the BB of TruncUse.
1498 // for example:
1499 // BB1:
1500 // i64 shift.result = lshr i64 opnd, imm
1501 // trunc.result = trunc shift.result to i16
1502 //
1503 // BB2:
1504 // ----> We will have an implicit truncate here if the architecture does
1505 // not have i16 compare.
1506 // cmp i16 trunc.result, opnd2
1507 //
1508 if (isa<TruncInst>(User) && shiftIsLegal
1509 // If the type of the truncate is legal, no trucate will be
1510 // introduced in other basic blocks.
Mehdi Amini44ede332015-07-09 02:09:04 +00001511 &&
1512 (!TLI.isTypeLegal(TLI.getValueType(DL, User->getType()))))
Yi Jiangd069f632014-04-21 19:34:27 +00001513 MadeChange =
Mehdi Amini44ede332015-07-09 02:09:04 +00001514 SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI, DL);
Yi Jiangd069f632014-04-21 19:34:27 +00001515
1516 continue;
1517 }
1518 // If we have already inserted a shift into this block, use it.
1519 BinaryOperator *&InsertedShift = InsertedShifts[UserBB];
1520
1521 if (!InsertedShift) {
1522 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001523 assert(InsertPt != UserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +00001524
1525 if (ShiftI->getOpcode() == Instruction::AShr)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001526 InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
1527 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001528 else
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001529 InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
1530 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001531
1532 MadeChange = true;
1533 }
1534
1535 // Replace a use of the shift with a use of the new shift.
1536 TheUse = InsertedShift;
1537 }
1538
1539 // If we removed all uses, nuke the shift.
1540 if (ShiftI->use_empty())
1541 ShiftI->eraseFromParent();
1542
1543 return MadeChange;
1544}
1545
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001546// Translate a masked load intrinsic like
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001547// <16 x i32 > @llvm.masked.load( <16 x i32>* %addr, i32 align,
1548// <16 x i1> %mask, <16 x i32> %passthru)
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001549// to a chain of basic blocks, with loading element one-by-one if
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001550// the appropriate mask bit is set
Junmo Parkaa9243a2016-01-08 04:20:32 +00001551//
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001552// %1 = bitcast i8* %addr to i32*
1553// %2 = extractelement <16 x i1> %mask, i32 0
1554// %3 = icmp eq i1 %2, true
1555// br i1 %3, label %cond.load, label %else
1556//
1557//cond.load: ; preds = %0
1558// %4 = getelementptr i32* %1, i32 0
1559// %5 = load i32* %4
1560// %6 = insertelement <16 x i32> undef, i32 %5, i32 0
1561// br label %else
1562//
1563//else: ; preds = %0, %cond.load
1564// %res.phi.else = phi <16 x i32> [ %6, %cond.load ], [ undef, %0 ]
1565// %7 = extractelement <16 x i1> %mask, i32 1
1566// %8 = icmp eq i1 %7, true
1567// br i1 %8, label %cond.load1, label %else2
1568//
1569//cond.load1: ; preds = %else
1570// %9 = getelementptr i32* %1, i32 1
1571// %10 = load i32* %9
1572// %11 = insertelement <16 x i32> %res.phi.else, i32 %10, i32 1
1573// br label %else2
1574//
1575//else2: ; preds = %else, %cond.load1
1576// %res.phi.else3 = phi <16 x i32> [ %11, %cond.load1 ], [ %res.phi.else, %else ]
1577// %12 = extractelement <16 x i1> %mask, i32 2
1578// %13 = icmp eq i1 %12, true
1579// br i1 %13, label %cond.load4, label %else5
1580//
Sanjay Patel3388d1f2016-01-22 21:11:47 +00001581static void scalarizeMaskedLoad(CallInst *CI) {
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001582 Value *Ptr = CI->getArgOperand(0);
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001583 Value *Alignment = CI->getArgOperand(1);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001584 Value *Mask = CI->getArgOperand(2);
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001585 Value *Src0 = CI->getArgOperand(3);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001586
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001587 unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
1588 VectorType *VecType = dyn_cast<VectorType>(CI->getType());
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001589 assert(VecType && "Unexpected return type of masked load intrinsic");
1590
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001591 Type *EltTy = CI->getType()->getVectorElementType();
1592
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001593 IRBuilder<> Builder(CI->getContext());
1594 Instruction *InsertPt = CI;
1595 BasicBlock *IfBlock = CI->getParent();
1596 BasicBlock *CondBlock = nullptr;
1597 BasicBlock *PrevIfBlock = CI->getParent();
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001598
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001599 Builder.SetInsertPoint(InsertPt);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001600 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1601
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001602 // Short-cut if the mask is all-true.
1603 bool IsAllOnesMask = isa<Constant>(Mask) &&
1604 cast<Constant>(Mask)->isAllOnesValue();
1605
1606 if (IsAllOnesMask) {
1607 Value *NewI = Builder.CreateAlignedLoad(Ptr, AlignVal);
1608 CI->replaceAllUsesWith(NewI);
1609 CI->eraseFromParent();
1610 return;
1611 }
1612
1613 // Adjust alignment for the scalar instruction.
1614 AlignVal = std::min(AlignVal, VecType->getScalarSizeInBits()/8);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001615 // Bitcast %addr fron i8* to EltTy*
1616 Type *NewPtrType =
1617 EltTy->getPointerTo(cast<PointerType>(Ptr->getType())->getAddressSpace());
1618 Value *FirstEltPtr = Builder.CreateBitCast(Ptr, NewPtrType);
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001619 unsigned VectorWidth = VecType->getNumElements();
1620
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001621 Value *UndefVal = UndefValue::get(VecType);
1622
1623 // The result vector
1624 Value *VResult = UndefVal;
1625
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001626 if (isa<ConstantVector>(Mask)) {
1627 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1628 if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
1629 continue;
1630 Value *Gep =
1631 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
1632 LoadInst* Load = Builder.CreateAlignedLoad(Gep, AlignVal);
1633 VResult = Builder.CreateInsertElement(VResult, Load,
1634 Builder.getInt32(Idx));
1635 }
1636 Value *NewI = Builder.CreateSelect(Mask, VResult, Src0);
1637 CI->replaceAllUsesWith(NewI);
1638 CI->eraseFromParent();
1639 return;
1640 }
1641
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001642 PHINode *Phi = nullptr;
1643 Value *PrevPhi = UndefVal;
1644
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001645 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1646
1647 // Fill the "else" block, created in the previous iteration
1648 //
1649 // %res.phi.else3 = phi <16 x i32> [ %11, %cond.load1 ], [ %res.phi.else, %else ]
1650 // %mask_1 = extractelement <16 x i1> %mask, i32 Idx
1651 // %to_load = icmp eq i1 %mask_1, true
1652 // br i1 %to_load, label %cond.load, label %else
1653 //
1654 if (Idx > 0) {
1655 Phi = Builder.CreatePHI(VecType, 2, "res.phi.else");
1656 Phi->addIncoming(VResult, CondBlock);
1657 Phi->addIncoming(PrevPhi, PrevIfBlock);
1658 PrevPhi = Phi;
1659 VResult = Phi;
1660 }
1661
1662 Value *Predicate = Builder.CreateExtractElement(Mask, Builder.getInt32(Idx));
1663 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
1664 ConstantInt::get(Predicate->getType(), 1));
1665
1666 // Create "cond" block
1667 //
1668 // %EltAddr = getelementptr i32* %1, i32 0
1669 // %Elt = load i32* %EltAddr
1670 // VResult = insertelement <16 x i32> VResult, i32 %Elt, i32 Idx
1671 //
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001672 CondBlock = IfBlock->splitBasicBlock(InsertPt->getIterator(), "cond.load");
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001673 Builder.SetInsertPoint(InsertPt);
David Blaikieaa41cd52015-04-03 21:33:42 +00001674
1675 Value *Gep =
1676 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
Elena Demikhovsky09285852015-10-25 15:37:55 +00001677 LoadInst *Load = Builder.CreateAlignedLoad(Gep, AlignVal);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001678 VResult = Builder.CreateInsertElement(VResult, Load, Builder.getInt32(Idx));
1679
1680 // Create "else" block, fill it in the next iteration
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001681 BasicBlock *NewIfBlock =
1682 CondBlock->splitBasicBlock(InsertPt->getIterator(), "else");
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001683 Builder.SetInsertPoint(InsertPt);
1684 Instruction *OldBr = IfBlock->getTerminator();
1685 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1686 OldBr->eraseFromParent();
1687 PrevIfBlock = IfBlock;
1688 IfBlock = NewIfBlock;
1689 }
1690
1691 Phi = Builder.CreatePHI(VecType, 2, "res.phi.select");
1692 Phi->addIncoming(VResult, CondBlock);
1693 Phi->addIncoming(PrevPhi, PrevIfBlock);
1694 Value *NewI = Builder.CreateSelect(Mask, Phi, Src0);
1695 CI->replaceAllUsesWith(NewI);
1696 CI->eraseFromParent();
1697}
1698
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001699// Translate a masked store intrinsic, like
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001700// void @llvm.masked.store(<16 x i32> %src, <16 x i32>* %addr, i32 align,
1701// <16 x i1> %mask)
1702// to a chain of basic blocks, that stores element one-by-one if
1703// the appropriate mask bit is set
1704//
1705// %1 = bitcast i8* %addr to i32*
1706// %2 = extractelement <16 x i1> %mask, i32 0
1707// %3 = icmp eq i1 %2, true
1708// br i1 %3, label %cond.store, label %else
1709//
1710// cond.store: ; preds = %0
1711// %4 = extractelement <16 x i32> %val, i32 0
1712// %5 = getelementptr i32* %1, i32 0
1713// store i32 %4, i32* %5
1714// br label %else
Junmo Parkaa9243a2016-01-08 04:20:32 +00001715//
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001716// else: ; preds = %0, %cond.store
1717// %6 = extractelement <16 x i1> %mask, i32 1
1718// %7 = icmp eq i1 %6, true
1719// br i1 %7, label %cond.store1, label %else2
Junmo Parkaa9243a2016-01-08 04:20:32 +00001720//
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001721// cond.store1: ; preds = %else
1722// %8 = extractelement <16 x i32> %val, i32 1
1723// %9 = getelementptr i32* %1, i32 1
1724// store i32 %8, i32* %9
1725// br label %else2
1726// . . .
Sanjay Patel3388d1f2016-01-22 21:11:47 +00001727static void scalarizeMaskedStore(CallInst *CI) {
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001728 Value *Src = CI->getArgOperand(0);
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001729 Value *Ptr = CI->getArgOperand(1);
1730 Value *Alignment = CI->getArgOperand(2);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001731 Value *Mask = CI->getArgOperand(3);
1732
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001733 unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001734 VectorType *VecType = dyn_cast<VectorType>(Src->getType());
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001735 assert(VecType && "Unexpected data type in masked store intrinsic");
1736
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001737 Type *EltTy = VecType->getElementType();
1738
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001739 IRBuilder<> Builder(CI->getContext());
1740 Instruction *InsertPt = CI;
1741 BasicBlock *IfBlock = CI->getParent();
1742 Builder.SetInsertPoint(InsertPt);
1743 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1744
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001745 // Short-cut if the mask is all-true.
1746 bool IsAllOnesMask = isa<Constant>(Mask) &&
1747 cast<Constant>(Mask)->isAllOnesValue();
1748
1749 if (IsAllOnesMask) {
1750 Builder.CreateAlignedStore(Src, Ptr, AlignVal);
1751 CI->eraseFromParent();
1752 return;
1753 }
1754
1755 // Adjust alignment for the scalar instruction.
1756 AlignVal = std::max(AlignVal, VecType->getScalarSizeInBits()/8);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001757 // Bitcast %addr fron i8* to EltTy*
1758 Type *NewPtrType =
1759 EltTy->getPointerTo(cast<PointerType>(Ptr->getType())->getAddressSpace());
1760 Value *FirstEltPtr = Builder.CreateBitCast(Ptr, NewPtrType);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001761 unsigned VectorWidth = VecType->getNumElements();
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001762
1763 if (isa<ConstantVector>(Mask)) {
1764 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1765 if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
1766 continue;
1767 Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx));
1768 Value *Gep =
1769 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
1770 Builder.CreateAlignedStore(OneElt, Gep, AlignVal);
1771 }
1772 CI->eraseFromParent();
1773 return;
1774 }
1775
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001776 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1777
1778 // Fill the "else" block, created in the previous iteration
1779 //
1780 // %mask_1 = extractelement <16 x i1> %mask, i32 Idx
1781 // %to_store = icmp eq i1 %mask_1, true
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001782 // br i1 %to_store, label %cond.store, label %else
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001783 //
1784 Value *Predicate = Builder.CreateExtractElement(Mask, Builder.getInt32(Idx));
1785 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
1786 ConstantInt::get(Predicate->getType(), 1));
1787
1788 // Create "cond" block
1789 //
1790 // %OneElt = extractelement <16 x i32> %Src, i32 Idx
1791 // %EltAddr = getelementptr i32* %1, i32 0
1792 // %store i32 %OneElt, i32* %EltAddr
1793 //
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001794 BasicBlock *CondBlock =
1795 IfBlock->splitBasicBlock(InsertPt->getIterator(), "cond.store");
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001796 Builder.SetInsertPoint(InsertPt);
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001797
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001798 Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx));
David Blaikieaa41cd52015-04-03 21:33:42 +00001799 Value *Gep =
1800 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001801 Builder.CreateAlignedStore(OneElt, Gep, AlignVal);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001802
1803 // Create "else" block, fill it in the next iteration
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001804 BasicBlock *NewIfBlock =
1805 CondBlock->splitBasicBlock(InsertPt->getIterator(), "else");
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001806 Builder.SetInsertPoint(InsertPt);
1807 Instruction *OldBr = IfBlock->getTerminator();
1808 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1809 OldBr->eraseFromParent();
1810 IfBlock = NewIfBlock;
1811 }
1812 CI->eraseFromParent();
1813}
1814
Elena Demikhovsky09285852015-10-25 15:37:55 +00001815// Translate a masked gather intrinsic like
1816// <16 x i32 > @llvm.masked.gather.v16i32( <16 x i32*> %Ptrs, i32 4,
1817// <16 x i1> %Mask, <16 x i32> %Src)
1818// to a chain of basic blocks, with loading element one-by-one if
1819// the appropriate mask bit is set
Junmo Parkaa9243a2016-01-08 04:20:32 +00001820//
Elena Demikhovsky09285852015-10-25 15:37:55 +00001821// % Ptrs = getelementptr i32, i32* %base, <16 x i64> %ind
1822// % Mask0 = extractelement <16 x i1> %Mask, i32 0
1823// % ToLoad0 = icmp eq i1 % Mask0, true
1824// br i1 % ToLoad0, label %cond.load, label %else
Junmo Parkaa9243a2016-01-08 04:20:32 +00001825//
Elena Demikhovsky09285852015-10-25 15:37:55 +00001826// cond.load:
1827// % Ptr0 = extractelement <16 x i32*> %Ptrs, i32 0
1828// % Load0 = load i32, i32* % Ptr0, align 4
1829// % Res0 = insertelement <16 x i32> undef, i32 % Load0, i32 0
1830// br label %else
Junmo Parkaa9243a2016-01-08 04:20:32 +00001831//
Elena Demikhovsky09285852015-10-25 15:37:55 +00001832// else:
1833// %res.phi.else = phi <16 x i32>[% Res0, %cond.load], [undef, % 0]
1834// % Mask1 = extractelement <16 x i1> %Mask, i32 1
1835// % ToLoad1 = icmp eq i1 % Mask1, true
1836// br i1 % ToLoad1, label %cond.load1, label %else2
Junmo Parkaa9243a2016-01-08 04:20:32 +00001837//
Elena Demikhovsky09285852015-10-25 15:37:55 +00001838// cond.load1:
1839// % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1
1840// % Load1 = load i32, i32* % Ptr1, align 4
1841// % Res1 = insertelement <16 x i32> %res.phi.else, i32 % Load1, i32 1
1842// br label %else2
1843// . . .
1844// % Result = select <16 x i1> %Mask, <16 x i32> %res.phi.select, <16 x i32> %Src
1845// ret <16 x i32> %Result
Sanjay Patel3388d1f2016-01-22 21:11:47 +00001846static void scalarizeMaskedGather(CallInst *CI) {
Elena Demikhovsky09285852015-10-25 15:37:55 +00001847 Value *Ptrs = CI->getArgOperand(0);
1848 Value *Alignment = CI->getArgOperand(1);
1849 Value *Mask = CI->getArgOperand(2);
1850 Value *Src0 = CI->getArgOperand(3);
1851
1852 VectorType *VecType = dyn_cast<VectorType>(CI->getType());
1853
1854 assert(VecType && "Unexpected return type of masked load intrinsic");
1855
1856 IRBuilder<> Builder(CI->getContext());
1857 Instruction *InsertPt = CI;
1858 BasicBlock *IfBlock = CI->getParent();
1859 BasicBlock *CondBlock = nullptr;
1860 BasicBlock *PrevIfBlock = CI->getParent();
1861 Builder.SetInsertPoint(InsertPt);
1862 unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
1863
1864 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1865
1866 Value *UndefVal = UndefValue::get(VecType);
1867
1868 // The result vector
1869 Value *VResult = UndefVal;
1870 unsigned VectorWidth = VecType->getNumElements();
1871
1872 // Shorten the way if the mask is a vector of constants.
1873 bool IsConstMask = isa<ConstantVector>(Mask);
1874
1875 if (IsConstMask) {
1876 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1877 if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
1878 continue;
1879 Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
1880 "Ptr" + Twine(Idx));
1881 LoadInst *Load = Builder.CreateAlignedLoad(Ptr, AlignVal,
1882 "Load" + Twine(Idx));
1883 VResult = Builder.CreateInsertElement(VResult, Load,
1884 Builder.getInt32(Idx),
1885 "Res" + Twine(Idx));
1886 }
1887 Value *NewI = Builder.CreateSelect(Mask, VResult, Src0);
1888 CI->replaceAllUsesWith(NewI);
1889 CI->eraseFromParent();
1890 return;
1891 }
1892
1893 PHINode *Phi = nullptr;
1894 Value *PrevPhi = UndefVal;
1895
1896 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1897
1898 // Fill the "else" block, created in the previous iteration
1899 //
1900 // %Mask1 = extractelement <16 x i1> %Mask, i32 1
1901 // %ToLoad1 = icmp eq i1 %Mask1, true
1902 // br i1 %ToLoad1, label %cond.load, label %else
1903 //
1904 if (Idx > 0) {
1905 Phi = Builder.CreatePHI(VecType, 2, "res.phi.else");
1906 Phi->addIncoming(VResult, CondBlock);
1907 Phi->addIncoming(PrevPhi, PrevIfBlock);
1908 PrevPhi = Phi;
1909 VResult = Phi;
1910 }
1911
1912 Value *Predicate = Builder.CreateExtractElement(Mask,
1913 Builder.getInt32(Idx),
1914 "Mask" + Twine(Idx));
1915 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
1916 ConstantInt::get(Predicate->getType(), 1),
1917 "ToLoad" + Twine(Idx));
1918
1919 // Create "cond" block
1920 //
1921 // %EltAddr = getelementptr i32* %1, i32 0
1922 // %Elt = load i32* %EltAddr
1923 // VResult = insertelement <16 x i32> VResult, i32 %Elt, i32 Idx
1924 //
1925 CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.load");
1926 Builder.SetInsertPoint(InsertPt);
1927
1928 Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
1929 "Ptr" + Twine(Idx));
1930 LoadInst *Load = Builder.CreateAlignedLoad(Ptr, AlignVal,
1931 "Load" + Twine(Idx));
1932 VResult = Builder.CreateInsertElement(VResult, Load, Builder.getInt32(Idx),
1933 "Res" + Twine(Idx));
1934
1935 // Create "else" block, fill it in the next iteration
1936 BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
1937 Builder.SetInsertPoint(InsertPt);
1938 Instruction *OldBr = IfBlock->getTerminator();
1939 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1940 OldBr->eraseFromParent();
1941 PrevIfBlock = IfBlock;
1942 IfBlock = NewIfBlock;
1943 }
1944
1945 Phi = Builder.CreatePHI(VecType, 2, "res.phi.select");
1946 Phi->addIncoming(VResult, CondBlock);
1947 Phi->addIncoming(PrevPhi, PrevIfBlock);
1948 Value *NewI = Builder.CreateSelect(Mask, Phi, Src0);
1949 CI->replaceAllUsesWith(NewI);
1950 CI->eraseFromParent();
1951}
1952
1953// Translate a masked scatter intrinsic, like
1954// void @llvm.masked.scatter.v16i32(<16 x i32> %Src, <16 x i32*>* %Ptrs, i32 4,
1955// <16 x i1> %Mask)
1956// to a chain of basic blocks, that stores element one-by-one if
1957// the appropriate mask bit is set.
1958//
1959// % Ptrs = getelementptr i32, i32* %ptr, <16 x i64> %ind
1960// % Mask0 = extractelement <16 x i1> % Mask, i32 0
1961// % ToStore0 = icmp eq i1 % Mask0, true
1962// br i1 %ToStore0, label %cond.store, label %else
1963//
1964// cond.store:
1965// % Elt0 = extractelement <16 x i32> %Src, i32 0
1966// % Ptr0 = extractelement <16 x i32*> %Ptrs, i32 0
1967// store i32 %Elt0, i32* % Ptr0, align 4
1968// br label %else
Junmo Parkaa9243a2016-01-08 04:20:32 +00001969//
Elena Demikhovsky09285852015-10-25 15:37:55 +00001970// else:
1971// % Mask1 = extractelement <16 x i1> % Mask, i32 1
1972// % ToStore1 = icmp eq i1 % Mask1, true
1973// br i1 % ToStore1, label %cond.store1, label %else2
1974//
1975// cond.store1:
1976// % Elt1 = extractelement <16 x i32> %Src, i32 1
1977// % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1
1978// store i32 % Elt1, i32* % Ptr1, align 4
1979// br label %else2
1980// . . .
Sanjay Patel3388d1f2016-01-22 21:11:47 +00001981static void scalarizeMaskedScatter(CallInst *CI) {
Elena Demikhovsky09285852015-10-25 15:37:55 +00001982 Value *Src = CI->getArgOperand(0);
1983 Value *Ptrs = CI->getArgOperand(1);
1984 Value *Alignment = CI->getArgOperand(2);
1985 Value *Mask = CI->getArgOperand(3);
1986
1987 assert(isa<VectorType>(Src->getType()) &&
1988 "Unexpected data type in masked scatter intrinsic");
1989 assert(isa<VectorType>(Ptrs->getType()) &&
1990 isa<PointerType>(Ptrs->getType()->getVectorElementType()) &&
1991 "Vector of pointers is expected in masked scatter intrinsic");
1992
1993 IRBuilder<> Builder(CI->getContext());
1994 Instruction *InsertPt = CI;
1995 BasicBlock *IfBlock = CI->getParent();
1996 Builder.SetInsertPoint(InsertPt);
1997 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1998
1999 unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
2000 unsigned VectorWidth = Src->getType()->getVectorNumElements();
2001
2002 // Shorten the way if the mask is a vector of constants.
2003 bool IsConstMask = isa<ConstantVector>(Mask);
2004
2005 if (IsConstMask) {
2006 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
2007 if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
2008 continue;
2009 Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx),
2010 "Elt" + Twine(Idx));
2011 Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
2012 "Ptr" + Twine(Idx));
2013 Builder.CreateAlignedStore(OneElt, Ptr, AlignVal);
2014 }
2015 CI->eraseFromParent();
2016 return;
2017 }
2018 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
2019 // Fill the "else" block, created in the previous iteration
2020 //
2021 // % Mask1 = extractelement <16 x i1> % Mask, i32 Idx
2022 // % ToStore = icmp eq i1 % Mask1, true
2023 // br i1 % ToStore, label %cond.store, label %else
2024 //
2025 Value *Predicate = Builder.CreateExtractElement(Mask,
2026 Builder.getInt32(Idx),
2027 "Mask" + Twine(Idx));
2028 Value *Cmp =
2029 Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
2030 ConstantInt::get(Predicate->getType(), 1),
2031 "ToStore" + Twine(Idx));
2032
2033 // Create "cond" block
2034 //
2035 // % Elt1 = extractelement <16 x i32> %Src, i32 1
2036 // % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1
2037 // %store i32 % Elt1, i32* % Ptr1
2038 //
2039 BasicBlock *CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store");
2040 Builder.SetInsertPoint(InsertPt);
2041
2042 Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx),
2043 "Elt" + Twine(Idx));
2044 Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
2045 "Ptr" + Twine(Idx));
2046 Builder.CreateAlignedStore(OneElt, Ptr, AlignVal);
2047
2048 // Create "else" block, fill it in the next iteration
2049 BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
2050 Builder.SetInsertPoint(InsertPt);
2051 Instruction *OldBr = IfBlock->getTerminator();
2052 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
2053 OldBr->eraseFromParent();
2054 IfBlock = NewIfBlock;
2055 }
2056 CI->eraseFromParent();
2057}
2058
Sanjay Patel4699b8a2015-11-19 16:37:10 +00002059/// If counting leading or trailing zeros is an expensive operation and a zero
2060/// input is defined, add a check for zero to avoid calling the intrinsic.
2061///
2062/// We want to transform:
2063/// %z = call i64 @llvm.cttz.i64(i64 %A, i1 false)
2064///
2065/// into:
2066/// entry:
2067/// %cmpz = icmp eq i64 %A, 0
2068/// br i1 %cmpz, label %cond.end, label %cond.false
2069/// cond.false:
2070/// %z = call i64 @llvm.cttz.i64(i64 %A, i1 true)
2071/// br label %cond.end
2072/// cond.end:
2073/// %ctz = phi i64 [ 64, %entry ], [ %z, %cond.false ]
2074///
2075/// If the transform is performed, return true and set ModifiedDT to true.
2076static bool despeculateCountZeros(IntrinsicInst *CountZeros,
2077 const TargetLowering *TLI,
2078 const DataLayout *DL,
2079 bool &ModifiedDT) {
2080 if (!TLI || !DL)
2081 return false;
2082
2083 // If a zero input is undefined, it doesn't make sense to despeculate that.
2084 if (match(CountZeros->getOperand(1), m_One()))
2085 return false;
2086
2087 // If it's cheap to speculate, there's nothing to do.
2088 auto IntrinsicID = CountZeros->getIntrinsicID();
2089 if ((IntrinsicID == Intrinsic::cttz && TLI->isCheapToSpeculateCttz()) ||
2090 (IntrinsicID == Intrinsic::ctlz && TLI->isCheapToSpeculateCtlz()))
2091 return false;
2092
2093 // Only handle legal scalar cases. Anything else requires too much work.
2094 Type *Ty = CountZeros->getType();
2095 unsigned SizeInBits = Ty->getPrimitiveSizeInBits();
Jun Bum Limbe11bdc2016-05-13 18:38:35 +00002096 if (Ty->isVectorTy() || SizeInBits > DL->getLargestLegalIntTypeSizeInBits())
Sanjay Patel4699b8a2015-11-19 16:37:10 +00002097 return false;
2098
2099 // The intrinsic will be sunk behind a compare against zero and branch.
2100 BasicBlock *StartBlock = CountZeros->getParent();
2101 BasicBlock *CallBlock = StartBlock->splitBasicBlock(CountZeros, "cond.false");
2102
2103 // Create another block after the count zero intrinsic. A PHI will be added
2104 // in this block to select the result of the intrinsic or the bit-width
2105 // constant if the input to the intrinsic is zero.
2106 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(CountZeros));
2107 BasicBlock *EndBlock = CallBlock->splitBasicBlock(SplitPt, "cond.end");
2108
2109 // Set up a builder to create a compare, conditional branch, and PHI.
2110 IRBuilder<> Builder(CountZeros->getContext());
2111 Builder.SetInsertPoint(StartBlock->getTerminator());
2112 Builder.SetCurrentDebugLocation(CountZeros->getDebugLoc());
2113
2114 // Replace the unconditional branch that was created by the first split with
2115 // a compare against zero and a conditional branch.
2116 Value *Zero = Constant::getNullValue(Ty);
2117 Value *Cmp = Builder.CreateICmpEQ(CountZeros->getOperand(0), Zero, "cmpz");
2118 Builder.CreateCondBr(Cmp, EndBlock, CallBlock);
2119 StartBlock->getTerminator()->eraseFromParent();
2120
2121 // Create a PHI in the end block to select either the output of the intrinsic
2122 // or the bit width of the operand.
2123 Builder.SetInsertPoint(&EndBlock->front());
2124 PHINode *PN = Builder.CreatePHI(Ty, 2, "ctz");
2125 CountZeros->replaceAllUsesWith(PN);
2126 Value *BitWidth = Builder.getInt(APInt(SizeInBits, SizeInBits));
2127 PN->addIncoming(BitWidth, StartBlock);
2128 PN->addIncoming(CountZeros, CallBlock);
2129
2130 // We are explicitly handling the zero case, so we can set the intrinsic's
2131 // undefined zero argument to 'true'. This will also prevent reprocessing the
2132 // intrinsic; we only despeculate when a zero input is defined.
2133 CountZeros->setArgOperand(1, Builder.getTrue());
2134 ModifiedDT = true;
2135 return true;
2136}
2137
Sanjay Patelfc580a62015-09-21 23:03:16 +00002138bool CodeGenPrepare::optimizeCallInst(CallInst *CI, bool& ModifiedDT) {
Chris Lattner7a277142011-01-15 07:14:54 +00002139 BasicBlock *BB = CI->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +00002140
Chris Lattner7a277142011-01-15 07:14:54 +00002141 // Lower inline assembly if we can.
2142 // If we found an inline asm expession, and if the target knows how to
2143 // lower it to normal LLVM code, do so now.
2144 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
2145 if (TLI->ExpandInlineAsm(CI)) {
2146 // Avoid invalidating the iterator.
2147 CurInstIterator = BB->begin();
2148 // Avoid processing instructions out of order, which could cause
2149 // reuse before a value is defined.
2150 SunkAddrs.clear();
2151 return true;
2152 }
2153 // Sink address computing for memory operands into the block.
Sanjay Patelfc580a62015-09-21 23:03:16 +00002154 if (optimizeInlineAsmInst(CI))
Chris Lattner7a277142011-01-15 07:14:54 +00002155 return true;
2156 }
Nadav Rotem465834c2012-07-24 10:51:42 +00002157
John Brawn0dbcd652015-03-18 12:01:59 +00002158 // Align the pointer arguments to this call if the target thinks it's a good
2159 // idea
2160 unsigned MinSize, PrefAlign;
Mehdi Amini4fe37982015-07-07 18:45:17 +00002161 if (TLI && TLI->shouldAlignPointerArgs(CI, MinSize, PrefAlign)) {
John Brawn0dbcd652015-03-18 12:01:59 +00002162 for (auto &Arg : CI->arg_operands()) {
2163 // We want to align both objects whose address is used directly and
2164 // objects whose address is used in casts and GEPs, though it only makes
2165 // sense for GEPs if the offset is a multiple of the desired alignment and
2166 // if size - offset meets the size threshold.
2167 if (!Arg->getType()->isPointerTy())
2168 continue;
Mehdi Amini4fe37982015-07-07 18:45:17 +00002169 APInt Offset(DL->getPointerSizeInBits(
2170 cast<PointerType>(Arg->getType())->getAddressSpace()),
2171 0);
2172 Value *Val = Arg->stripAndAccumulateInBoundsConstantOffsets(*DL, Offset);
John Brawn0dbcd652015-03-18 12:01:59 +00002173 uint64_t Offset2 = Offset.getLimitedValue();
John Brawne8fd6c82015-04-13 10:47:39 +00002174 if ((Offset2 & (PrefAlign-1)) != 0)
2175 continue;
John Brawn0dbcd652015-03-18 12:01:59 +00002176 AllocaInst *AI;
Mehdi Amini4fe37982015-07-07 18:45:17 +00002177 if ((AI = dyn_cast<AllocaInst>(Val)) && AI->getAlignment() < PrefAlign &&
2178 DL->getTypeAllocSize(AI->getAllocatedType()) >= MinSize + Offset2)
John Brawn0dbcd652015-03-18 12:01:59 +00002179 AI->setAlignment(PrefAlign);
John Brawne8fd6c82015-04-13 10:47:39 +00002180 // Global variables can only be aligned if they are defined in this
2181 // object (i.e. they are uniquely initialized in this object), and
2182 // over-aligning global variables that have an explicit section is
2183 // forbidden.
2184 GlobalVariable *GV;
James Y Knightac03dca2016-01-15 16:33:06 +00002185 if ((GV = dyn_cast<GlobalVariable>(Val)) && GV->canIncreaseAlignment() &&
Tim Northover918f0502016-07-18 18:28:52 +00002186 GV->getPointerAlignment(*DL) < PrefAlign &&
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00002187 DL->getTypeAllocSize(GV->getValueType()) >=
Mehdi Amini4fe37982015-07-07 18:45:17 +00002188 MinSize + Offset2)
John Brawne8fd6c82015-04-13 10:47:39 +00002189 GV->setAlignment(PrefAlign);
John Brawn0dbcd652015-03-18 12:01:59 +00002190 }
2191 // If this is a memcpy (or similar) then we may be able to improve the
2192 // alignment
2193 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(CI)) {
Mehdi Amini4fe37982015-07-07 18:45:17 +00002194 unsigned Align = getKnownAlignment(MI->getDest(), *DL);
John Brawn0dbcd652015-03-18 12:01:59 +00002195 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
Mehdi Amini4fe37982015-07-07 18:45:17 +00002196 Align = std::min(Align, getKnownAlignment(MTI->getSource(), *DL));
Pete Cooper67cf9a72015-11-19 05:56:52 +00002197 if (Align > MI->getAlignment())
2198 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(), Align));
John Brawn0dbcd652015-03-18 12:01:59 +00002199 }
2200 }
2201
Philip Reamesac115ed2016-03-09 23:13:12 +00002202 // If we have a cold call site, try to sink addressing computation into the
2203 // cold block. This interacts with our handling for loads and stores to
2204 // ensure that we can fold all uses of a potential addressing computation
2205 // into their uses. TODO: generalize this to work over profiling data
2206 if (!OptSize && CI->hasFnAttr(Attribute::Cold))
2207 for (auto &Arg : CI->arg_operands()) {
2208 if (!Arg->getType()->isPointerTy())
2209 continue;
2210 unsigned AS = Arg->getType()->getPointerAddressSpace();
2211 return optimizeMemoryInst(CI, Arg, Arg->getType(), AS);
2212 }
Junmo Park6098cbb2016-03-11 07:05:32 +00002213
Eric Christopher4b7948e2010-03-11 02:41:03 +00002214 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00002215 if (II) {
2216 switch (II->getIntrinsicID()) {
2217 default: break;
2218 case Intrinsic::objectsize: {
2219 // Lower all uses of llvm.objectsize.*
George Burgess IV3f089142016-12-20 23:46:36 +00002220 ConstantInt *RetVal =
2221 lowerObjectSizeCall(II, *DL, TLInfo, /*MustSucceed=*/true);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00002222 // Substituting this can cause recursive simplifications, which can
2223 // invalidate our iterator. Use a WeakVH to hold onto it in case this
2224 // happens.
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00002225 Value *CurValue = &*CurInstIterator;
2226 WeakVH IterHandle(CurValue);
Nadav Rotem465834c2012-07-24 10:51:42 +00002227
Sanjay Patel545a4562016-01-20 18:59:16 +00002228 replaceAndRecursivelySimplify(CI, RetVal, TLInfo, nullptr);
Chris Lattner1b93be52011-01-15 07:25:29 +00002229
Elena Demikhovsky87700a72014-12-28 08:54:45 +00002230 // If the iterator instruction was recursively deleted, start over at the
2231 // start of the block.
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00002232 if (IterHandle != CurValue) {
Elena Demikhovsky87700a72014-12-28 08:54:45 +00002233 CurInstIterator = BB->begin();
2234 SunkAddrs.clear();
2235 }
2236 return true;
Chris Lattner86d56c62011-01-18 20:53:04 +00002237 }
Elena Demikhovsky87700a72014-12-28 08:54:45 +00002238 case Intrinsic::masked_load: {
2239 // Scalarize unsupported vector masked load
Elena Demikhovsky20662e32015-10-19 07:43:38 +00002240 if (!TTI->isLegalMaskedLoad(CI->getType())) {
Sanjay Patel3388d1f2016-01-22 21:11:47 +00002241 scalarizeMaskedLoad(CI);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00002242 ModifiedDT = true;
2243 return true;
2244 }
2245 return false;
2246 }
2247 case Intrinsic::masked_store: {
Elena Demikhovsky20662e32015-10-19 07:43:38 +00002248 if (!TTI->isLegalMaskedStore(CI->getArgOperand(0)->getType())) {
Sanjay Patel3388d1f2016-01-22 21:11:47 +00002249 scalarizeMaskedStore(CI);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00002250 ModifiedDT = true;
2251 return true;
2252 }
2253 return false;
2254 }
Elena Demikhovsky09285852015-10-25 15:37:55 +00002255 case Intrinsic::masked_gather: {
2256 if (!TTI->isLegalMaskedGather(CI->getType())) {
Sanjay Patel3388d1f2016-01-22 21:11:47 +00002257 scalarizeMaskedGather(CI);
Elena Demikhovsky09285852015-10-25 15:37:55 +00002258 ModifiedDT = true;
2259 return true;
2260 }
2261 return false;
2262 }
2263 case Intrinsic::masked_scatter: {
2264 if (!TTI->isLegalMaskedScatter(CI->getArgOperand(0)->getType())) {
Sanjay Patel3388d1f2016-01-22 21:11:47 +00002265 scalarizeMaskedScatter(CI);
Elena Demikhovsky09285852015-10-25 15:37:55 +00002266 ModifiedDT = true;
2267 return true;
2268 }
2269 return false;
2270 }
Ahmed Bougacha236f9042015-05-22 21:37:17 +00002271 case Intrinsic::aarch64_stlxr:
2272 case Intrinsic::aarch64_stxr: {
2273 ZExtInst *ExtVal = dyn_cast<ZExtInst>(CI->getArgOperand(0));
2274 if (!ExtVal || !ExtVal->hasOneUse() ||
2275 ExtVal->getParent() == CI->getParent())
2276 return false;
2277 // Sink a zext feeding stlxr/stxr before it, so it can be folded into it.
2278 ExtVal->moveBefore(CI);
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002279 // Mark this instruction as "inserted by CGP", so that other
2280 // optimizations don't touch it.
2281 InsertedInsts.insert(ExtVal);
Ahmed Bougacha236f9042015-05-22 21:37:17 +00002282 return true;
2283 }
Piotr Padlewski6c15ec42015-09-15 18:32:14 +00002284 case Intrinsic::invariant_group_barrier:
2285 II->replaceAllUsesWith(II->getArgOperand(0));
2286 II->eraseFromParent();
2287 return true;
Sanjay Patel4699b8a2015-11-19 16:37:10 +00002288
2289 case Intrinsic::cttz:
2290 case Intrinsic::ctlz:
2291 // If counting zeros is expensive, try to avoid it.
2292 return despeculateCountZeros(II, TLI, DL, ModifiedDT);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00002293 }
Eric Christopher4b7948e2010-03-11 02:41:03 +00002294
Elena Demikhovsky87700a72014-12-28 08:54:45 +00002295 if (TLI) {
2296 SmallVector<Value*, 2> PtrOps;
2297 Type *AccessTy;
Matt Arsenault1672b1b2017-02-08 07:09:03 +00002298 if (TLI->getAddrModeArguments(II, PtrOps, AccessTy))
2299 while (!PtrOps.empty()) {
2300 Value *PtrVal = PtrOps.pop_back_val();
2301 unsigned AS = PtrVal->getType()->getPointerAddressSpace();
2302 if (optimizeMemoryInst(II, PtrVal, AccessTy, AS))
Elena Demikhovsky87700a72014-12-28 08:54:45 +00002303 return true;
Matt Arsenault1672b1b2017-02-08 07:09:03 +00002304 }
Elena Demikhovsky87700a72014-12-28 08:54:45 +00002305 }
Pete Cooper615fd892012-03-13 20:59:56 +00002306 }
2307
Eric Christopher4b7948e2010-03-11 02:41:03 +00002308 // From here on out we're working with named functions.
Craig Topperc0196b12014-04-14 00:51:57 +00002309 if (!CI->getCalledFunction()) return false;
Devang Patel0da52502011-05-26 21:51:06 +00002310
Benjamin Kramer7b88a492010-03-12 09:27:41 +00002311 // Lower all default uses of _chk calls. This is very similar
2312 // to what InstCombineCalls does, but here we are only lowering calls
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002313 // to fortified library functions (e.g. __memcpy_chk) that have the default
2314 // "don't know" as the objectsize. Anything else should be left alone.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002315 FortifiedLibCallSimplifier Simplifier(TLInfo, true);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002316 if (Value *V = Simplifier.optimizeCall(CI)) {
2317 CI->replaceAllUsesWith(V);
2318 CI->eraseFromParent();
2319 return true;
2320 }
2321 return false;
Eric Christopher4b7948e2010-03-11 02:41:03 +00002322}
Chris Lattner1b93be52011-01-15 07:25:29 +00002323
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002324/// Look for opportunities to duplicate return instructions to the predecessor
2325/// to enable tail call optimizations. The case it is currently looking for is:
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00002326/// @code
Evan Cheng0663f232011-03-21 01:19:09 +00002327/// bb0:
2328/// %tmp0 = tail call i32 @f0()
2329/// br label %return
2330/// bb1:
2331/// %tmp1 = tail call i32 @f1()
2332/// br label %return
2333/// bb2:
2334/// %tmp2 = tail call i32 @f2()
2335/// br label %return
2336/// return:
2337/// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
2338/// ret i32 %retval
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00002339/// @endcode
Evan Cheng0663f232011-03-21 01:19:09 +00002340///
2341/// =>
2342///
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00002343/// @code
Evan Cheng0663f232011-03-21 01:19:09 +00002344/// bb0:
2345/// %tmp0 = tail call i32 @f0()
2346/// ret i32 %tmp0
2347/// bb1:
2348/// %tmp1 = tail call i32 @f1()
2349/// ret i32 %tmp1
2350/// bb2:
2351/// %tmp2 = tail call i32 @f2()
2352/// ret i32 %tmp2
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00002353/// @endcode
Sanjay Patelfc580a62015-09-21 23:03:16 +00002354bool CodeGenPrepare::dupRetToEnableTailCallOpts(BasicBlock *BB) {
Cameron Zwarich47e71752011-03-24 04:51:51 +00002355 if (!TLI)
2356 return false;
2357
Michael Kuperstein71321562016-09-07 20:29:49 +00002358 ReturnInst *RetI = dyn_cast<ReturnInst>(BB->getTerminator());
2359 if (!RetI)
Benjamin Kramer455fa352012-11-23 19:17:06 +00002360 return false;
2361
Craig Topperc0196b12014-04-14 00:51:57 +00002362 PHINode *PN = nullptr;
2363 BitCastInst *BCI = nullptr;
Michael Kuperstein71321562016-09-07 20:29:49 +00002364 Value *V = RetI->getReturnValue();
Evan Cheng249716e2012-07-27 21:21:26 +00002365 if (V) {
2366 BCI = dyn_cast<BitCastInst>(V);
2367 if (BCI)
2368 V = BCI->getOperand(0);
2369
2370 PN = dyn_cast<PHINode>(V);
2371 if (!PN)
2372 return false;
2373 }
Evan Cheng0663f232011-03-21 01:19:09 +00002374
Cameron Zwarich4649f172011-03-24 04:52:10 +00002375 if (PN && PN->getParent() != BB)
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002376 return false;
Evan Cheng0663f232011-03-21 01:19:09 +00002377
Cameron Zwarich4649f172011-03-24 04:52:10 +00002378 // Make sure there are no instructions between the PHI and return, or that the
2379 // return is the first instruction in the block.
2380 if (PN) {
2381 BasicBlock::iterator BI = BB->begin();
2382 do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
Evan Cheng249716e2012-07-27 21:21:26 +00002383 if (&*BI == BCI)
2384 // Also skip over the bitcast.
2385 ++BI;
Michael Kuperstein71321562016-09-07 20:29:49 +00002386 if (&*BI != RetI)
Cameron Zwarich4649f172011-03-24 04:52:10 +00002387 return false;
2388 } else {
Cameron Zwarich74157ab2011-03-24 16:34:59 +00002389 BasicBlock::iterator BI = BB->begin();
2390 while (isa<DbgInfoIntrinsic>(BI)) ++BI;
Michael Kuperstein71321562016-09-07 20:29:49 +00002391 if (&*BI != RetI)
Cameron Zwarich4649f172011-03-24 04:52:10 +00002392 return false;
2393 }
Evan Cheng0663f232011-03-21 01:19:09 +00002394
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002395 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
2396 /// call.
Michael Kupersteinf79af6f2016-09-08 00:48:37 +00002397 const Function *F = BB->getParent();
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002398 SmallVector<CallInst*, 4> TailCalls;
Cameron Zwarich4649f172011-03-24 04:52:10 +00002399 if (PN) {
2400 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
2401 CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
2402 // Make sure the phi value is indeed produced by the tail call.
2403 if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
Michael Kupersteinf79af6f2016-09-08 00:48:37 +00002404 TLI->mayBeEmittedAsTailCall(CI) &&
2405 attributesPermitTailCall(F, CI, RetI, *TLI))
Cameron Zwarich4649f172011-03-24 04:52:10 +00002406 TailCalls.push_back(CI);
2407 }
2408 } else {
2409 SmallPtrSet<BasicBlock*, 4> VisitedBBs;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00002410 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
David Blaikie70573dc2014-11-19 07:49:26 +00002411 if (!VisitedBBs.insert(*PI).second)
Cameron Zwarich4649f172011-03-24 04:52:10 +00002412 continue;
2413
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00002414 BasicBlock::InstListType &InstList = (*PI)->getInstList();
Cameron Zwarich4649f172011-03-24 04:52:10 +00002415 BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
2416 BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
Cameron Zwarich74157ab2011-03-24 16:34:59 +00002417 do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
2418 if (RI == RE)
Cameron Zwarich4649f172011-03-24 04:52:10 +00002419 continue;
Cameron Zwarich74157ab2011-03-24 16:34:59 +00002420
Cameron Zwarich4649f172011-03-24 04:52:10 +00002421 CallInst *CI = dyn_cast<CallInst>(&*RI);
Michael Kupersteinf79af6f2016-09-08 00:48:37 +00002422 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI) &&
2423 attributesPermitTailCall(F, CI, RetI, *TLI))
Cameron Zwarich4649f172011-03-24 04:52:10 +00002424 TailCalls.push_back(CI);
2425 }
Evan Cheng0663f232011-03-21 01:19:09 +00002426 }
2427
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002428 bool Changed = false;
2429 for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
2430 CallInst *CI = TailCalls[i];
2431 CallSite CS(CI);
2432
2433 // Conservatively require the attributes of the call to match those of the
2434 // return. Ignore noalias because it doesn't affect the call sequence.
Reid Klecknerb5180542017-03-21 16:57:19 +00002435 AttributeList CalleeAttrs = CS.getAttributes();
2436 if (AttrBuilder(CalleeAttrs, AttributeList::ReturnIndex)
2437 .removeAttribute(Attribute::NoAlias) !=
2438 AttrBuilder(CalleeAttrs, AttributeList::ReturnIndex)
2439 .removeAttribute(Attribute::NoAlias))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002440 continue;
2441
2442 // Make sure the call instruction is followed by an unconditional branch to
2443 // the return block.
2444 BasicBlock *CallBB = CI->getParent();
2445 BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
2446 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
2447 continue;
2448
2449 // Duplicate the return into CallBB.
Michael Kuperstein71321562016-09-07 20:29:49 +00002450 (void)FoldReturnIntoUncondBranch(RetI, BB, CallBB);
Devang Patel8f606d72011-03-24 15:35:25 +00002451 ModifiedDT = Changed = true;
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002452 ++NumRetsDup;
2453 }
2454
2455 // If we eliminated all predecessors of the block, delete the block now.
Evan Cheng64a223a2012-09-28 23:58:57 +00002456 if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002457 BB->eraseFromParent();
2458
2459 return Changed;
Evan Cheng0663f232011-03-21 01:19:09 +00002460}
2461
Chris Lattner728f9022008-11-25 07:09:13 +00002462//===----------------------------------------------------------------------===//
Chris Lattner728f9022008-11-25 07:09:13 +00002463// Memory Optimization
2464//===----------------------------------------------------------------------===//
2465
Chandler Carruthc8925912013-01-05 02:09:22 +00002466namespace {
2467
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002468/// This is an extended version of TargetLowering::AddrMode
Chandler Carruthc8925912013-01-05 02:09:22 +00002469/// which holds actual Value*'s for register values.
Chandler Carruth95f83e02013-01-07 15:14:13 +00002470struct ExtAddrMode : public TargetLowering::AddrMode {
Chandler Carruthc8925912013-01-05 02:09:22 +00002471 Value *BaseReg;
2472 Value *ScaledReg;
Craig Topperc0196b12014-04-14 00:51:57 +00002473 ExtAddrMode() : BaseReg(nullptr), ScaledReg(nullptr) {}
Chandler Carruthc8925912013-01-05 02:09:22 +00002474 void print(raw_ostream &OS) const;
2475 void dump() const;
Stephen Lin837bba12013-07-15 17:55:02 +00002476
Chandler Carruthc8925912013-01-05 02:09:22 +00002477 bool operator==(const ExtAddrMode& O) const {
2478 return (BaseReg == O.BaseReg) && (ScaledReg == O.ScaledReg) &&
2479 (BaseGV == O.BaseGV) && (BaseOffs == O.BaseOffs) &&
2480 (HasBaseReg == O.HasBaseReg) && (Scale == O.Scale);
2481 }
2482};
2483
Eli Friedmanc1f1f852013-09-10 23:09:24 +00002484#ifndef NDEBUG
2485static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
2486 AM.print(OS);
2487 return OS;
2488}
2489#endif
2490
Chandler Carruthc8925912013-01-05 02:09:22 +00002491void ExtAddrMode::print(raw_ostream &OS) const {
2492 bool NeedPlus = false;
2493 OS << "[";
2494 if (BaseGV) {
2495 OS << (NeedPlus ? " + " : "")
2496 << "GV:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00002497 BaseGV->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00002498 NeedPlus = true;
2499 }
2500
Richard Trieuc0f91212014-05-30 03:15:17 +00002501 if (BaseOffs) {
2502 OS << (NeedPlus ? " + " : "")
2503 << BaseOffs;
2504 NeedPlus = true;
2505 }
Chandler Carruthc8925912013-01-05 02:09:22 +00002506
2507 if (BaseReg) {
2508 OS << (NeedPlus ? " + " : "")
2509 << "Base:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00002510 BaseReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00002511 NeedPlus = true;
2512 }
2513 if (Scale) {
2514 OS << (NeedPlus ? " + " : "")
2515 << Scale << "*";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00002516 ScaledReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00002517 }
2518
2519 OS << ']';
2520}
2521
2522#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Yaron Kereneb2a2542016-01-29 20:50:44 +00002523LLVM_DUMP_METHOD void ExtAddrMode::dump() const {
Chandler Carruthc8925912013-01-05 02:09:22 +00002524 print(dbgs());
2525 dbgs() << '\n';
2526}
2527#endif
2528
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002529/// \brief This class provides transaction based operation on the IR.
2530/// Every change made through this class is recorded in the internal state and
2531/// can be undone (rollback) until commit is called.
2532class TypePromotionTransaction {
2533
2534 /// \brief This represents the common interface of the individual transaction.
2535 /// Each class implements the logic for doing one specific modification on
2536 /// the IR via the TypePromotionTransaction.
2537 class TypePromotionAction {
2538 protected:
2539 /// The Instruction modified.
2540 Instruction *Inst;
2541
2542 public:
2543 /// \brief Constructor of the action.
2544 /// The constructor performs the related action on the IR.
2545 TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
2546
2547 virtual ~TypePromotionAction() {}
2548
2549 /// \brief Undo the modification done by this action.
2550 /// When this method is called, the IR must be in the same state as it was
2551 /// before this action was applied.
2552 /// \pre Undoing the action works if and only if the IR is in the exact same
2553 /// state as it was directly after this action was applied.
2554 virtual void undo() = 0;
2555
2556 /// \brief Advocate every change made by this action.
2557 /// When the results on the IR of the action are to be kept, it is important
2558 /// to call this function, otherwise hidden information may be kept forever.
2559 virtual void commit() {
2560 // Nothing to be done, this action is not doing anything.
2561 }
2562 };
2563
2564 /// \brief Utility to remember the position of an instruction.
2565 class InsertionHandler {
2566 /// Position of an instruction.
2567 /// Either an instruction:
2568 /// - Is the first in a basic block: BB is used.
2569 /// - Has a previous instructon: PrevInst is used.
2570 union {
2571 Instruction *PrevInst;
2572 BasicBlock *BB;
2573 } Point;
2574 /// Remember whether or not the instruction had a previous instruction.
2575 bool HasPrevInstruction;
2576
2577 public:
2578 /// \brief Record the position of \p Inst.
2579 InsertionHandler(Instruction *Inst) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002580 BasicBlock::iterator It = Inst->getIterator();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002581 HasPrevInstruction = (It != (Inst->getParent()->begin()));
2582 if (HasPrevInstruction)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002583 Point.PrevInst = &*--It;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002584 else
2585 Point.BB = Inst->getParent();
2586 }
2587
2588 /// \brief Insert \p Inst at the recorded position.
2589 void insert(Instruction *Inst) {
2590 if (HasPrevInstruction) {
2591 if (Inst->getParent())
2592 Inst->removeFromParent();
2593 Inst->insertAfter(Point.PrevInst);
2594 } else {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002595 Instruction *Position = &*Point.BB->getFirstInsertionPt();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002596 if (Inst->getParent())
2597 Inst->moveBefore(Position);
2598 else
2599 Inst->insertBefore(Position);
2600 }
2601 }
2602 };
2603
2604 /// \brief Move an instruction before another.
2605 class InstructionMoveBefore : public TypePromotionAction {
2606 /// Original position of the instruction.
2607 InsertionHandler Position;
2608
2609 public:
2610 /// \brief Move \p Inst before \p Before.
2611 InstructionMoveBefore(Instruction *Inst, Instruction *Before)
2612 : TypePromotionAction(Inst), Position(Inst) {
2613 DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before << "\n");
2614 Inst->moveBefore(Before);
2615 }
2616
2617 /// \brief Move the instruction back to its original position.
Craig Topper4584cd52014-03-07 09:26:03 +00002618 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002619 DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n");
2620 Position.insert(Inst);
2621 }
2622 };
2623
2624 /// \brief Set the operand of an instruction with a new value.
2625 class OperandSetter : public TypePromotionAction {
2626 /// Original operand of the instruction.
2627 Value *Origin;
2628 /// Index of the modified instruction.
2629 unsigned Idx;
2630
2631 public:
2632 /// \brief Set \p Idx operand of \p Inst with \p NewVal.
2633 OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
2634 : TypePromotionAction(Inst), Idx(Idx) {
2635 DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"
2636 << "for:" << *Inst << "\n"
2637 << "with:" << *NewVal << "\n");
2638 Origin = Inst->getOperand(Idx);
2639 Inst->setOperand(Idx, NewVal);
2640 }
2641
2642 /// \brief Restore the original value of the instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002643 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002644 DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"
2645 << "for: " << *Inst << "\n"
2646 << "with: " << *Origin << "\n");
2647 Inst->setOperand(Idx, Origin);
2648 }
2649 };
2650
2651 /// \brief Hide the operands of an instruction.
2652 /// Do as if this instruction was not using any of its operands.
2653 class OperandsHider : public TypePromotionAction {
2654 /// The list of original operands.
2655 SmallVector<Value *, 4> OriginalValues;
2656
2657 public:
2658 /// \brief Remove \p Inst from the uses of the operands of \p Inst.
2659 OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
2660 DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n");
2661 unsigned NumOpnds = Inst->getNumOperands();
2662 OriginalValues.reserve(NumOpnds);
2663 for (unsigned It = 0; It < NumOpnds; ++It) {
2664 // Save the current operand.
2665 Value *Val = Inst->getOperand(It);
2666 OriginalValues.push_back(Val);
2667 // Set a dummy one.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00002668 // We could use OperandSetter here, but that would imply an overhead
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002669 // that we are not willing to pay.
2670 Inst->setOperand(It, UndefValue::get(Val->getType()));
2671 }
2672 }
2673
2674 /// \brief Restore the original list of uses.
Craig Topper4584cd52014-03-07 09:26:03 +00002675 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002676 DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n");
2677 for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
2678 Inst->setOperand(It, OriginalValues[It]);
2679 }
2680 };
2681
2682 /// \brief Build a truncate instruction.
2683 class TruncBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00002684 Value *Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002685 public:
2686 /// \brief Build a truncate instruction of \p Opnd producing a \p Ty
2687 /// result.
2688 /// trunc Opnd to Ty.
2689 TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
2690 IRBuilder<> Builder(Opnd);
Quentin Colombetac55b152014-09-16 22:36:07 +00002691 Val = Builder.CreateTrunc(Opnd, Ty, "promoted");
2692 DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002693 }
2694
Quentin Colombetac55b152014-09-16 22:36:07 +00002695 /// \brief Get the built value.
2696 Value *getBuiltValue() { return Val; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002697
2698 /// \brief Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002699 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00002700 DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n");
2701 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2702 IVal->eraseFromParent();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002703 }
2704 };
2705
2706 /// \brief Build a sign extension instruction.
2707 class SExtBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00002708 Value *Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002709 public:
2710 /// \brief Build a sign extension instruction of \p Opnd producing a \p Ty
2711 /// result.
2712 /// sext Opnd to Ty.
2713 SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
Quentin Colombetac55b152014-09-16 22:36:07 +00002714 : TypePromotionAction(InsertPt) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002715 IRBuilder<> Builder(InsertPt);
Quentin Colombetac55b152014-09-16 22:36:07 +00002716 Val = Builder.CreateSExt(Opnd, Ty, "promoted");
2717 DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002718 }
2719
Quentin Colombetac55b152014-09-16 22:36:07 +00002720 /// \brief Get the built value.
2721 Value *getBuiltValue() { return Val; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002722
2723 /// \brief Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002724 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00002725 DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n");
2726 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2727 IVal->eraseFromParent();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002728 }
2729 };
2730
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002731 /// \brief Build a zero extension instruction.
2732 class ZExtBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00002733 Value *Val;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002734 public:
2735 /// \brief Build a zero extension instruction of \p Opnd producing a \p Ty
2736 /// result.
2737 /// zext Opnd to Ty.
2738 ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
Quentin Colombetac55b152014-09-16 22:36:07 +00002739 : TypePromotionAction(InsertPt) {
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002740 IRBuilder<> Builder(InsertPt);
Quentin Colombetac55b152014-09-16 22:36:07 +00002741 Val = Builder.CreateZExt(Opnd, Ty, "promoted");
2742 DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n");
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002743 }
2744
Quentin Colombetac55b152014-09-16 22:36:07 +00002745 /// \brief Get the built value.
2746 Value *getBuiltValue() { return Val; }
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002747
2748 /// \brief Remove the built instruction.
2749 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00002750 DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n");
2751 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2752 IVal->eraseFromParent();
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002753 }
2754 };
2755
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002756 /// \brief Mutate an instruction to another type.
2757 class TypeMutator : public TypePromotionAction {
2758 /// Record the original type.
2759 Type *OrigTy;
2760
2761 public:
2762 /// \brief Mutate the type of \p Inst into \p NewTy.
2763 TypeMutator(Instruction *Inst, Type *NewTy)
2764 : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
2765 DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy
2766 << "\n");
2767 Inst->mutateType(NewTy);
2768 }
2769
2770 /// \brief Mutate the instruction back to its original type.
Craig Topper4584cd52014-03-07 09:26:03 +00002771 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002772 DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy
2773 << "\n");
2774 Inst->mutateType(OrigTy);
2775 }
2776 };
2777
2778 /// \brief Replace the uses of an instruction by another instruction.
2779 class UsesReplacer : public TypePromotionAction {
2780 /// Helper structure to keep track of the replaced uses.
2781 struct InstructionAndIdx {
2782 /// The instruction using the instruction.
2783 Instruction *Inst;
2784 /// The index where this instruction is used for Inst.
2785 unsigned Idx;
2786 InstructionAndIdx(Instruction *Inst, unsigned Idx)
2787 : Inst(Inst), Idx(Idx) {}
2788 };
2789
2790 /// Keep track of the original uses (pair Instruction, Index).
2791 SmallVector<InstructionAndIdx, 4> OriginalUses;
2792 typedef SmallVectorImpl<InstructionAndIdx>::iterator use_iterator;
2793
2794 public:
2795 /// \brief Replace all the use of \p Inst by \p New.
2796 UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) {
2797 DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New
2798 << "\n");
2799 // Record the original uses.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002800 for (Use &U : Inst->uses()) {
2801 Instruction *UserI = cast<Instruction>(U.getUser());
2802 OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo()));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002803 }
2804 // Now, we can replace the uses.
2805 Inst->replaceAllUsesWith(New);
2806 }
2807
2808 /// \brief Reassign the original uses of Inst to Inst.
Craig Topper4584cd52014-03-07 09:26:03 +00002809 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002810 DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n");
2811 for (use_iterator UseIt = OriginalUses.begin(),
2812 EndIt = OriginalUses.end();
2813 UseIt != EndIt; ++UseIt) {
2814 UseIt->Inst->setOperand(UseIt->Idx, Inst);
2815 }
2816 }
2817 };
2818
2819 /// \brief Remove an instruction from the IR.
2820 class InstructionRemover : public TypePromotionAction {
2821 /// Original position of the instruction.
2822 InsertionHandler Inserter;
2823 /// Helper structure to hide all the link to the instruction. In other
2824 /// words, this helps to do as if the instruction was removed.
2825 OperandsHider Hider;
2826 /// Keep track of the uses replaced, if any.
2827 UsesReplacer *Replacer;
Jun Bum Limdee55652017-04-03 19:20:07 +00002828 /// Keep track of instructions removed.
2829 SetOfInstrs &RemovedInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002830
2831 public:
2832 /// \brief Remove all reference of \p Inst and optinally replace all its
2833 /// uses with New.
Jun Bum Limdee55652017-04-03 19:20:07 +00002834 /// \p RemovedInsts Keep track of the instructions removed by this Action.
Craig Topperc0196b12014-04-14 00:51:57 +00002835 /// \pre If !Inst->use_empty(), then New != nullptr
Jun Bum Limdee55652017-04-03 19:20:07 +00002836 InstructionRemover(Instruction *Inst, SetOfInstrs &RemovedInsts,
2837 Value *New = nullptr)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002838 : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
Jun Bum Limdee55652017-04-03 19:20:07 +00002839 Replacer(nullptr), RemovedInsts(RemovedInsts) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002840 if (New)
2841 Replacer = new UsesReplacer(Inst, New);
2842 DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n");
Jun Bum Limdee55652017-04-03 19:20:07 +00002843 RemovedInsts.insert(Inst);
2844 /// The instructions removed here will be freed after completing
2845 /// optimizeBlock() for all blocks as we need to keep track of the
2846 /// removed instructions during promotion.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002847 Inst->removeFromParent();
2848 }
2849
Alexander Kornienkof817c1c2015-04-11 02:11:45 +00002850 ~InstructionRemover() override { delete Replacer; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002851
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002852 /// \brief Resurrect the instruction and reassign it to the proper uses if
2853 /// new value was provided when build this action.
Craig Topper4584cd52014-03-07 09:26:03 +00002854 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002855 DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n");
2856 Inserter.insert(Inst);
2857 if (Replacer)
2858 Replacer->undo();
2859 Hider.undo();
Jun Bum Limdee55652017-04-03 19:20:07 +00002860 RemovedInsts.erase(Inst);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002861 }
2862 };
2863
2864public:
2865 /// Restoration point.
2866 /// The restoration point is a pointer to an action instead of an iterator
2867 /// because the iterator may be invalidated but not the pointer.
2868 typedef const TypePromotionAction *ConstRestorationPt;
Jun Bum Limdee55652017-04-03 19:20:07 +00002869
2870 TypePromotionTransaction(SetOfInstrs &RemovedInsts)
2871 : RemovedInsts(RemovedInsts) {}
2872
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002873 /// Advocate every changes made in that transaction.
2874 void commit();
2875 /// Undo all the changes made after the given point.
2876 void rollback(ConstRestorationPt Point);
2877 /// Get the current restoration point.
2878 ConstRestorationPt getRestorationPoint() const;
2879
2880 /// \name API for IR modification with state keeping to support rollback.
2881 /// @{
2882 /// Same as Instruction::setOperand.
2883 void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
2884 /// Same as Instruction::eraseFromParent.
Craig Topperc0196b12014-04-14 00:51:57 +00002885 void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002886 /// Same as Value::replaceAllUsesWith.
2887 void replaceAllUsesWith(Instruction *Inst, Value *New);
2888 /// Same as Value::mutateType.
2889 void mutateType(Instruction *Inst, Type *NewTy);
2890 /// Same as IRBuilder::createTrunc.
Quentin Colombetac55b152014-09-16 22:36:07 +00002891 Value *createTrunc(Instruction *Opnd, Type *Ty);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002892 /// Same as IRBuilder::createSExt.
Quentin Colombetac55b152014-09-16 22:36:07 +00002893 Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002894 /// Same as IRBuilder::createZExt.
Quentin Colombetac55b152014-09-16 22:36:07 +00002895 Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002896 /// Same as Instruction::moveBefore.
2897 void moveBefore(Instruction *Inst, Instruction *Before);
2898 /// @}
2899
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002900private:
2901 /// The ordered list of actions made so far.
David Blaikie7620b312014-04-15 06:17:44 +00002902 SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions;
2903 typedef SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator CommitPt;
Jun Bum Limdee55652017-04-03 19:20:07 +00002904 SetOfInstrs &RemovedInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002905};
2906
2907void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
2908 Value *NewVal) {
2909 Actions.push_back(
David Blaikie7620b312014-04-15 06:17:44 +00002910 make_unique<TypePromotionTransaction::OperandSetter>(Inst, Idx, NewVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002911}
2912
2913void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
2914 Value *NewVal) {
2915 Actions.push_back(
Jun Bum Limdee55652017-04-03 19:20:07 +00002916 make_unique<TypePromotionTransaction::InstructionRemover>(Inst,
2917 RemovedInsts, NewVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002918}
2919
2920void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
2921 Value *New) {
David Blaikie7620b312014-04-15 06:17:44 +00002922 Actions.push_back(make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002923}
2924
2925void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
David Blaikie7620b312014-04-15 06:17:44 +00002926 Actions.push_back(make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002927}
2928
Quentin Colombetac55b152014-09-16 22:36:07 +00002929Value *TypePromotionTransaction::createTrunc(Instruction *Opnd,
2930 Type *Ty) {
David Blaikie7620b312014-04-15 06:17:44 +00002931 std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002932 Value *Val = Ptr->getBuiltValue();
David Blaikie7620b312014-04-15 06:17:44 +00002933 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002934 return Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002935}
2936
Quentin Colombetac55b152014-09-16 22:36:07 +00002937Value *TypePromotionTransaction::createSExt(Instruction *Inst,
2938 Value *Opnd, Type *Ty) {
David Blaikie7620b312014-04-15 06:17:44 +00002939 std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002940 Value *Val = Ptr->getBuiltValue();
David Blaikie7620b312014-04-15 06:17:44 +00002941 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002942 return Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002943}
2944
Quentin Colombetac55b152014-09-16 22:36:07 +00002945Value *TypePromotionTransaction::createZExt(Instruction *Inst,
2946 Value *Opnd, Type *Ty) {
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002947 std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002948 Value *Val = Ptr->getBuiltValue();
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002949 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002950 return Val;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002951}
2952
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002953void TypePromotionTransaction::moveBefore(Instruction *Inst,
2954 Instruction *Before) {
2955 Actions.push_back(
David Blaikie7620b312014-04-15 06:17:44 +00002956 make_unique<TypePromotionTransaction::InstructionMoveBefore>(Inst, Before));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002957}
2958
2959TypePromotionTransaction::ConstRestorationPt
2960TypePromotionTransaction::getRestorationPoint() const {
David Blaikie7620b312014-04-15 06:17:44 +00002961 return !Actions.empty() ? Actions.back().get() : nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002962}
2963
2964void TypePromotionTransaction::commit() {
2965 for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt;
David Blaikie7620b312014-04-15 06:17:44 +00002966 ++It)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002967 (*It)->commit();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002968 Actions.clear();
2969}
2970
2971void TypePromotionTransaction::rollback(
2972 TypePromotionTransaction::ConstRestorationPt Point) {
David Blaikie7620b312014-04-15 06:17:44 +00002973 while (!Actions.empty() && Point != Actions.back().get()) {
2974 std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002975 Curr->undo();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002976 }
2977}
2978
Chandler Carruthc8925912013-01-05 02:09:22 +00002979/// \brief A helper class for matching addressing modes.
2980///
2981/// This encapsulates the logic for matching the target-legal addressing modes.
2982class AddressingModeMatcher {
2983 SmallVectorImpl<Instruction*> &AddrModeInsts;
2984 const TargetLowering &TLI;
Igor Laevsky3be81ba2017-02-07 13:27:20 +00002985 const TargetRegisterInfo &TRI;
Mehdi Amini4fe37982015-07-07 18:45:17 +00002986 const DataLayout &DL;
Chandler Carruthc8925912013-01-05 02:09:22 +00002987
2988 /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
2989 /// the memory instruction that we're computing this address for.
2990 Type *AccessTy;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002991 unsigned AddrSpace;
Chandler Carruthc8925912013-01-05 02:09:22 +00002992 Instruction *MemoryInst;
Stephen Lin837bba12013-07-15 17:55:02 +00002993
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002994 /// This is the addressing mode that we're building up. This is
Chandler Carruthc8925912013-01-05 02:09:22 +00002995 /// part of the return value of this addressing mode matching stuff.
2996 ExtAddrMode &AddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00002997
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002998 /// The instructions inserted by other CodeGenPrepare optimizations.
2999 const SetOfInstrs &InsertedInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003000 /// A map from the instructions to their type before promotion.
3001 InstrToOrigTy &PromotedInsts;
3002 /// The ongoing transaction where every action should be registered.
3003 TypePromotionTransaction &TPT;
3004
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003005 /// This is set to true when we should not do profitability checks.
3006 /// When true, IsProfitableToFoldIntoAddressingMode always returns true.
Chandler Carruthc8925912013-01-05 02:09:22 +00003007 bool IgnoreProfitability;
Stephen Lin837bba12013-07-15 17:55:02 +00003008
Eric Christopherd75c00c2015-02-26 22:38:34 +00003009 AddressingModeMatcher(SmallVectorImpl<Instruction *> &AMI,
Igor Laevsky3be81ba2017-02-07 13:27:20 +00003010 const TargetLowering &TLI,
3011 const TargetRegisterInfo &TRI,
3012 Type *AT, unsigned AS,
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003013 Instruction *MI, ExtAddrMode &AM,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003014 const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003015 InstrToOrigTy &PromotedInsts,
3016 TypePromotionTransaction &TPT)
Igor Laevsky3be81ba2017-02-07 13:27:20 +00003017 : AddrModeInsts(AMI), TLI(TLI), TRI(TRI),
Mehdi Amini4fe37982015-07-07 18:45:17 +00003018 DL(MI->getModule()->getDataLayout()), AccessTy(AT), AddrSpace(AS),
3019 MemoryInst(MI), AddrMode(AM), InsertedInsts(InsertedInsts),
3020 PromotedInsts(PromotedInsts), TPT(TPT) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003021 IgnoreProfitability = false;
3022 }
3023public:
Stephen Lin837bba12013-07-15 17:55:02 +00003024
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003025 /// Find the maximal addressing mode that a load/store of V can fold,
Chandler Carruthc8925912013-01-05 02:09:22 +00003026 /// give an access type of AccessTy. This returns a list of involved
3027 /// instructions in AddrModeInsts.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003028 /// \p InsertedInsts The instructions inserted by other CodeGenPrepare
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003029 /// optimizations.
3030 /// \p PromotedInsts maps the instructions to their type before promotion.
3031 /// \p The ongoing transaction where every action should be registered.
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003032 static ExtAddrMode Match(Value *V, Type *AccessTy, unsigned AS,
Chandler Carruthc8925912013-01-05 02:09:22 +00003033 Instruction *MemoryInst,
3034 SmallVectorImpl<Instruction*> &AddrModeInsts,
Igor Laevsky3be81ba2017-02-07 13:27:20 +00003035 const TargetLowering &TLI,
3036 const TargetRegisterInfo &TRI,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003037 const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003038 InstrToOrigTy &PromotedInsts,
3039 TypePromotionTransaction &TPT) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003040 ExtAddrMode Result;
3041
Igor Laevsky3be81ba2017-02-07 13:27:20 +00003042 bool Success = AddressingModeMatcher(AddrModeInsts, TLI, TRI,
3043 AccessTy, AS,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003044 MemoryInst, Result, InsertedInsts,
Sanjay Patelfc580a62015-09-21 23:03:16 +00003045 PromotedInsts, TPT).matchAddr(V, 0);
Chandler Carruthc8925912013-01-05 02:09:22 +00003046 (void)Success; assert(Success && "Couldn't select *anything*?");
3047 return Result;
3048 }
3049private:
Sanjay Patelfc580a62015-09-21 23:03:16 +00003050 bool matchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
3051 bool matchAddr(Value *V, unsigned Depth);
3052 bool matchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth,
Craig Topperc0196b12014-04-14 00:51:57 +00003053 bool *MovedAway = nullptr);
Sanjay Patelfc580a62015-09-21 23:03:16 +00003054 bool isProfitableToFoldIntoAddressingMode(Instruction *I,
Chandler Carruthc8925912013-01-05 02:09:22 +00003055 ExtAddrMode &AMBefore,
3056 ExtAddrMode &AMAfter);
Sanjay Patelfc580a62015-09-21 23:03:16 +00003057 bool valueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
3058 bool isPromotionProfitable(unsigned NewCost, unsigned OldCost,
Quentin Colombet867c5502014-02-14 22:23:22 +00003059 Value *PromotedOperand) const;
Chandler Carruthc8925912013-01-05 02:09:22 +00003060};
3061
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003062/// Try adding ScaleReg*Scale to the current addressing mode.
Chandler Carruthc8925912013-01-05 02:09:22 +00003063/// Return true and update AddrMode if this addr mode is legal for the target,
3064/// false if not.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003065bool AddressingModeMatcher::matchScaledValue(Value *ScaleReg, int64_t Scale,
Chandler Carruthc8925912013-01-05 02:09:22 +00003066 unsigned Depth) {
3067 // If Scale is 1, then this is the same as adding ScaleReg to the addressing
3068 // mode. Just process that directly.
3069 if (Scale == 1)
Sanjay Patelfc580a62015-09-21 23:03:16 +00003070 return matchAddr(ScaleReg, Depth);
Stephen Lin837bba12013-07-15 17:55:02 +00003071
Chandler Carruthc8925912013-01-05 02:09:22 +00003072 // If the scale is 0, it takes nothing to add this.
3073 if (Scale == 0)
3074 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003075
Chandler Carruthc8925912013-01-05 02:09:22 +00003076 // If we already have a scale of this value, we can add to it, otherwise, we
3077 // need an available scale field.
3078 if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
3079 return false;
3080
3081 ExtAddrMode TestAddrMode = AddrMode;
3082
3083 // Add scale to turn X*4+X*3 -> X*7. This could also do things like
3084 // [A+B + A*7] -> [B+A*8].
3085 TestAddrMode.Scale += Scale;
3086 TestAddrMode.ScaledReg = ScaleReg;
3087
3088 // If the new address isn't legal, bail out.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003089 if (!TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003090 return false;
3091
3092 // It was legal, so commit it.
3093 AddrMode = TestAddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00003094
Chandler Carruthc8925912013-01-05 02:09:22 +00003095 // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
3096 // to see if ScaleReg is actually X+C. If so, we can turn this into adding
3097 // X*Scale + C*Scale to addr mode.
Craig Topperc0196b12014-04-14 00:51:57 +00003098 ConstantInt *CI = nullptr; Value *AddLHS = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003099 if (isa<Instruction>(ScaleReg) && // not a constant expr.
3100 match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
3101 TestAddrMode.ScaledReg = AddLHS;
3102 TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00003103
Chandler Carruthc8925912013-01-05 02:09:22 +00003104 // If this addressing mode is legal, commit it and remember that we folded
3105 // this instruction.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003106 if (TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003107 AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
3108 AddrMode = TestAddrMode;
3109 return true;
3110 }
3111 }
3112
3113 // Otherwise, not (x+c)*scale, just return what we have.
3114 return true;
3115}
3116
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003117/// This is a little filter, which returns true if an addressing computation
3118/// involving I might be folded into a load/store accessing it.
3119/// This doesn't need to be perfect, but needs to accept at least
Chandler Carruthc8925912013-01-05 02:09:22 +00003120/// the set of instructions that MatchOperationAddr can.
3121static bool MightBeFoldableInst(Instruction *I) {
3122 switch (I->getOpcode()) {
3123 case Instruction::BitCast:
Eli Benderskyf13a0562014-05-22 00:02:52 +00003124 case Instruction::AddrSpaceCast:
Chandler Carruthc8925912013-01-05 02:09:22 +00003125 // Don't touch identity bitcasts.
3126 if (I->getType() == I->getOperand(0)->getType())
3127 return false;
3128 return I->getType()->isPointerTy() || I->getType()->isIntegerTy();
3129 case Instruction::PtrToInt:
3130 // PtrToInt is always a noop, as we know that the int type is pointer sized.
3131 return true;
3132 case Instruction::IntToPtr:
3133 // We know the input is intptr_t, so this is foldable.
3134 return true;
3135 case Instruction::Add:
3136 return true;
3137 case Instruction::Mul:
3138 case Instruction::Shl:
3139 // Can only handle X*C and X << C.
3140 return isa<ConstantInt>(I->getOperand(1));
3141 case Instruction::GetElementPtr:
3142 return true;
3143 default:
3144 return false;
3145 }
3146}
3147
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003148/// \brief Check whether or not \p Val is a legal instruction for \p TLI.
3149/// \note \p Val is assumed to be the product of some type promotion.
3150/// Therefore if \p Val has an undefined state in \p TLI, this is assumed
3151/// to be legal, as the non-promoted value would have had the same state.
Mehdi Amini44ede332015-07-09 02:09:04 +00003152static bool isPromotedInstructionLegal(const TargetLowering &TLI,
3153 const DataLayout &DL, Value *Val) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003154 Instruction *PromotedInst = dyn_cast<Instruction>(Val);
3155 if (!PromotedInst)
3156 return false;
3157 int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode());
3158 // If the ISDOpcode is undefined, it was undefined before the promotion.
3159 if (!ISDOpcode)
3160 return true;
3161 // Otherwise, check if the promoted instruction is legal or not.
3162 return TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00003163 ISDOpcode, TLI.getValueType(DL, PromotedInst->getType()));
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003164}
3165
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003166/// \brief Hepler class to perform type promotion.
3167class TypePromotionHelper {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003168 /// \brief Utility function to check whether or not a sign or zero extension
3169 /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by
3170 /// either using the operands of \p Inst or promoting \p Inst.
3171 /// The type of the extension is defined by \p IsSExt.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003172 /// In other words, check if:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003173 /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003174 /// #1 Promotion applies:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003175 /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...).
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003176 /// #2 Operand reuses:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003177 /// ext opnd1 to ConsideredExtType.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003178 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003179 static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType,
3180 const InstrToOrigTy &PromotedInsts, bool IsSExt);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003181
3182 /// \brief Utility function to determine if \p OpIdx should be promoted when
3183 /// promoting \p Inst.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003184 static bool shouldExtOperand(const Instruction *Inst, int OpIdx) {
Rafael Espindola84921b92015-10-24 23:11:13 +00003185 return !(isa<SelectInst>(Inst) && OpIdx == 0);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003186 }
3187
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003188 /// \brief Utility function to promote the operand of \p Ext when this
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003189 /// operand is a promotable trunc or sext or zext.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003190 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003191 /// \p CreatedInstsCost[out] contains the cost of all instructions
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003192 /// created to promote the operand of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003193 /// Newly added extensions are inserted in \p Exts.
3194 /// Newly added truncates are inserted in \p Truncs.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003195 /// Should never be called directly.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003196 /// \return The promoted value which is used instead of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003197 static Value *promoteOperandForTruncAndAnyExt(
3198 Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003199 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003200 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003201 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003202
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003203 /// \brief Utility function to promote the operand of \p Ext when this
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003204 /// operand is promotable and is not a supported trunc or sext.
3205 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003206 /// \p CreatedInstsCost[out] contains the cost of all the instructions
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003207 /// created to promote the operand of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003208 /// Newly added extensions are inserted in \p Exts.
3209 /// Newly added truncates are inserted in \p Truncs.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003210 /// Should never be called directly.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003211 /// \return The promoted value which is used instead of Ext.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003212 static Value *promoteOperandForOther(Instruction *Ext,
3213 TypePromotionTransaction &TPT,
3214 InstrToOrigTy &PromotedInsts,
3215 unsigned &CreatedInstsCost,
3216 SmallVectorImpl<Instruction *> *Exts,
3217 SmallVectorImpl<Instruction *> *Truncs,
3218 const TargetLowering &TLI, bool IsSExt);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003219
3220 /// \see promoteOperandForOther.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003221 static Value *signExtendOperandForOther(
3222 Instruction *Ext, TypePromotionTransaction &TPT,
3223 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
3224 SmallVectorImpl<Instruction *> *Exts,
3225 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
3226 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
3227 Exts, Truncs, TLI, true);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003228 }
3229
3230 /// \see promoteOperandForOther.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003231 static Value *zeroExtendOperandForOther(
3232 Instruction *Ext, TypePromotionTransaction &TPT,
3233 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
3234 SmallVectorImpl<Instruction *> *Exts,
3235 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
3236 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
3237 Exts, Truncs, TLI, false);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003238 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003239
3240public:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003241 /// Type for the utility function that promotes the operand of Ext.
3242 typedef Value *(*Action)(Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003243 InstrToOrigTy &PromotedInsts,
3244 unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003245 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003246 SmallVectorImpl<Instruction *> *Truncs,
3247 const TargetLowering &TLI);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003248 /// \brief Given a sign/zero extend instruction \p Ext, return the approriate
3249 /// action to promote the operand of \p Ext instead of using Ext.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003250 /// \return NULL if no promotable action is possible with the current
3251 /// sign extension.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003252 /// \p InsertedInsts keeps track of all the instructions inserted by the
3253 /// other CodeGenPrepare optimizations. This information is important
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003254 /// because we do not want to promote these instructions as CodeGenPrepare
3255 /// will reinsert them later. Thus creating an infinite loop: create/remove.
3256 /// \p PromotedInsts maps the instructions to their type before promotion.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003257 static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003258 const TargetLowering &TLI,
3259 const InstrToOrigTy &PromotedInsts);
3260};
3261
3262bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003263 Type *ConsideredExtType,
3264 const InstrToOrigTy &PromotedInsts,
3265 bool IsSExt) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003266 // The promotion helper does not know how to deal with vector types yet.
3267 // To be able to fix that, we would need to fix the places where we
3268 // statically extend, e.g., constants and such.
3269 if (Inst->getType()->isVectorTy())
3270 return false;
3271
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003272 // We can always get through zext.
3273 if (isa<ZExtInst>(Inst))
3274 return true;
3275
3276 // sext(sext) is ok too.
3277 if (IsSExt && isa<SExtInst>(Inst))
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003278 return true;
3279
3280 // We can get through binary operator, if it is legal. In other words, the
3281 // binary operator must have a nuw or nsw flag.
3282 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
3283 if (BinOp && isa<OverflowingBinaryOperator>(BinOp) &&
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003284 ((!IsSExt && BinOp->hasNoUnsignedWrap()) ||
3285 (IsSExt && BinOp->hasNoSignedWrap())))
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003286 return true;
3287
3288 // Check if we can do the following simplification.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003289 // ext(trunc(opnd)) --> ext(opnd)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003290 if (!isa<TruncInst>(Inst))
3291 return false;
3292
3293 Value *OpndVal = Inst->getOperand(0);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003294 // Check if we can use this operand in the extension.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003295 // If the type is larger than the result type of the extension, we cannot.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003296 if (!OpndVal->getType()->isIntegerTy() ||
3297 OpndVal->getType()->getIntegerBitWidth() >
3298 ConsideredExtType->getIntegerBitWidth())
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003299 return false;
3300
3301 // If the operand of the truncate is not an instruction, we will not have
3302 // any information on the dropped bits.
3303 // (Actually we could for constant but it is not worth the extra logic).
3304 Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
3305 if (!Opnd)
3306 return false;
3307
3308 // Check if the source of the type is narrow enough.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003309 // I.e., check that trunc just drops extended bits of the same kind of
3310 // the extension.
3311 // #1 get the type of the operand and check the kind of the extended bits.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003312 const Type *OpndType;
3313 InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
Benjamin Kramer4cd5faa2015-07-31 17:00:39 +00003314 if (It != PromotedInsts.end() && It->second.getInt() == IsSExt)
3315 OpndType = It->second.getPointer();
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003316 else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd)))
3317 OpndType = Opnd->getOperand(0)->getType();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003318 else
3319 return false;
3320
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003321 // #2 check that the truncate just drops extended bits.
Rafael Espindola84921b92015-10-24 23:11:13 +00003322 return Inst->getType()->getIntegerBitWidth() >=
3323 OpndType->getIntegerBitWidth();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003324}
3325
3326TypePromotionHelper::Action TypePromotionHelper::getAction(
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003327 Instruction *Ext, const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003328 const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003329 assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
3330 "Unexpected instruction type");
3331 Instruction *ExtOpnd = dyn_cast<Instruction>(Ext->getOperand(0));
3332 Type *ExtTy = Ext->getType();
3333 bool IsSExt = isa<SExtInst>(Ext);
3334 // If the operand of the extension is not an instruction, we cannot
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003335 // get through.
3336 // If it, check we can get through.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003337 if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt))
Craig Topperc0196b12014-04-14 00:51:57 +00003338 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003339
3340 // Do not promote if the operand has been added by codegenprepare.
3341 // Otherwise, it means we are undoing an optimization that is likely to be
3342 // redone, thus causing potential infinite loop.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003343 if (isa<TruncInst>(ExtOpnd) && InsertedInsts.count(ExtOpnd))
Craig Topperc0196b12014-04-14 00:51:57 +00003344 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003345
3346 // SExt or Trunc instructions.
3347 // Return the related handler.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003348 if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) ||
3349 isa<ZExtInst>(ExtOpnd))
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003350 return promoteOperandForTruncAndAnyExt;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003351
3352 // Regular instruction.
3353 // Abort early if we will have to insert non-free instructions.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003354 if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(ExtTy, ExtOpnd->getType()))
Craig Topperc0196b12014-04-14 00:51:57 +00003355 return nullptr;
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003356 return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003357}
3358
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003359Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt(
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003360 llvm::Instruction *SExt, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003361 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003362 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003363 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003364 // By construction, the operand of SExt is an instruction. Otherwise we cannot
3365 // get through it and this method should not be called.
3366 Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
Quentin Colombetac55b152014-09-16 22:36:07 +00003367 Value *ExtVal = SExt;
Quentin Colombet1b274f92015-03-10 21:48:15 +00003368 bool HasMergedNonFreeExt = false;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003369 if (isa<ZExtInst>(SExtOpnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003370 // Replace s|zext(zext(opnd))
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003371 // => zext(opnd).
Quentin Colombet1b274f92015-03-10 21:48:15 +00003372 HasMergedNonFreeExt = !TLI.isExtFree(SExtOpnd);
Quentin Colombetac55b152014-09-16 22:36:07 +00003373 Value *ZExt =
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003374 TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType());
3375 TPT.replaceAllUsesWith(SExt, ZExt);
3376 TPT.eraseInstruction(SExt);
Quentin Colombetac55b152014-09-16 22:36:07 +00003377 ExtVal = ZExt;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003378 } else {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003379 // Replace z|sext(trunc(opnd)) or sext(sext(opnd))
3380 // => z|sext(opnd).
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003381 TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
3382 }
Quentin Colombet1b274f92015-03-10 21:48:15 +00003383 CreatedInstsCost = 0;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003384
3385 // Remove dead code.
3386 if (SExtOpnd->use_empty())
3387 TPT.eraseInstruction(SExtOpnd);
3388
Quentin Colombet9dcb7242014-09-15 18:26:58 +00003389 // Check if the extension is still needed.
Quentin Colombetac55b152014-09-16 22:36:07 +00003390 Instruction *ExtInst = dyn_cast<Instruction>(ExtVal);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003391 if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType()) {
Quentin Colombet1b274f92015-03-10 21:48:15 +00003392 if (ExtInst) {
3393 if (Exts)
3394 Exts->push_back(ExtInst);
3395 CreatedInstsCost = !TLI.isExtFree(ExtInst) && !HasMergedNonFreeExt;
3396 }
Quentin Colombetac55b152014-09-16 22:36:07 +00003397 return ExtVal;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003398 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003399
Quentin Colombet9dcb7242014-09-15 18:26:58 +00003400 // At this point we have: ext ty opnd to ty.
3401 // Reassign the uses of ExtInst to the opnd and remove ExtInst.
3402 Value *NextVal = ExtInst->getOperand(0);
3403 TPT.eraseInstruction(ExtInst, NextVal);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003404 return NextVal;
3405}
3406
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003407Value *TypePromotionHelper::promoteOperandForOther(
3408 Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003409 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003410 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003411 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI,
3412 bool IsSExt) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003413 // By construction, the operand of Ext is an instruction. Otherwise we cannot
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003414 // get through it and this method should not be called.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003415 Instruction *ExtOpnd = cast<Instruction>(Ext->getOperand(0));
Quentin Colombet1b274f92015-03-10 21:48:15 +00003416 CreatedInstsCost = 0;
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003417 if (!ExtOpnd->hasOneUse()) {
3418 // ExtOpnd will be promoted.
3419 // All its uses, but Ext, will need to use a truncated value of the
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003420 // promoted version.
3421 // Create the truncate now.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003422 Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->getType());
Quentin Colombetac55b152014-09-16 22:36:07 +00003423 if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) {
3424 ITrunc->removeFromParent();
3425 // Insert it just after the definition.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003426 ITrunc->insertAfter(ExtOpnd);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003427 if (Truncs)
3428 Truncs->push_back(ITrunc);
Quentin Colombetac55b152014-09-16 22:36:07 +00003429 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003430
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003431 TPT.replaceAllUsesWith(ExtOpnd, Trunc);
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003432 // Restore the operand of Ext (which has been replaced by the previous call
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003433 // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003434 TPT.setOperand(Ext, 0, ExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003435 }
3436
3437 // Get through the Instruction:
3438 // 1. Update its type.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003439 // 2. Replace the uses of Ext by Inst.
3440 // 3. Extend each operand that needs to be extended.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003441
3442 // Remember the original type of the instruction before promotion.
3443 // This is useful to know that the high bits are sign extended bits.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003444 PromotedInsts.insert(std::pair<Instruction *, TypeIsSExt>(
3445 ExtOpnd, TypeIsSExt(ExtOpnd->getType(), IsSExt)));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003446 // Step #1.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003447 TPT.mutateType(ExtOpnd, Ext->getType());
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003448 // Step #2.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003449 TPT.replaceAllUsesWith(Ext, ExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003450 // Step #3.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003451 Instruction *ExtForOpnd = Ext;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003452
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003453 DEBUG(dbgs() << "Propagate Ext to operands\n");
3454 for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003455 ++OpIdx) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003456 DEBUG(dbgs() << "Operand:\n" << *(ExtOpnd->getOperand(OpIdx)) << '\n');
3457 if (ExtOpnd->getOperand(OpIdx)->getType() == Ext->getType() ||
3458 !shouldExtOperand(ExtOpnd, OpIdx)) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003459 DEBUG(dbgs() << "No need to propagate\n");
3460 continue;
3461 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003462 // Check if we can statically extend the operand.
3463 Value *Opnd = ExtOpnd->getOperand(OpIdx);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003464 if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003465 DEBUG(dbgs() << "Statically extend\n");
3466 unsigned BitWidth = Ext->getType()->getIntegerBitWidth();
3467 APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth)
3468 : Cst->getValue().zext(BitWidth);
3469 TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->getType(), CstVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003470 continue;
3471 }
3472 // UndefValue are typed, so we have to statically sign extend them.
3473 if (isa<UndefValue>(Opnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003474 DEBUG(dbgs() << "Statically extend\n");
3475 TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->getType()));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003476 continue;
3477 }
3478
3479 // Otherwise we have to explicity sign extend the operand.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003480 // Check if Ext was reused to extend an operand.
3481 if (!ExtForOpnd) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003482 // If yes, create a new one.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003483 DEBUG(dbgs() << "More operands to ext\n");
Quentin Colombet84f89cc2014-12-22 18:11:52 +00003484 Value *ValForExtOpnd = IsSExt ? TPT.createSExt(Ext, Opnd, Ext->getType())
3485 : TPT.createZExt(Ext, Opnd, Ext->getType());
3486 if (!isa<Instruction>(ValForExtOpnd)) {
3487 TPT.setOperand(ExtOpnd, OpIdx, ValForExtOpnd);
3488 continue;
3489 }
3490 ExtForOpnd = cast<Instruction>(ValForExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003491 }
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003492 if (Exts)
3493 Exts->push_back(ExtForOpnd);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003494 TPT.setOperand(ExtForOpnd, 0, Opnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003495
3496 // Move the sign extension before the insertion point.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003497 TPT.moveBefore(ExtForOpnd, ExtOpnd);
3498 TPT.setOperand(ExtOpnd, OpIdx, ExtForOpnd);
Quentin Colombet1b274f92015-03-10 21:48:15 +00003499 CreatedInstsCost += !TLI.isExtFree(ExtForOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003500 // If more sext are required, new instructions will have to be created.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003501 ExtForOpnd = nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003502 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003503 if (ExtForOpnd == Ext) {
3504 DEBUG(dbgs() << "Extension is useless now\n");
3505 TPT.eraseInstruction(Ext);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003506 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003507 return ExtOpnd;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003508}
3509
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003510/// Check whether or not promoting an instruction to a wider type is profitable.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003511/// \p NewCost gives the cost of extension instructions created by the
3512/// promotion.
3513/// \p OldCost gives the cost of extension instructions before the promotion
3514/// plus the number of instructions that have been
3515/// matched in the addressing mode the promotion.
Quentin Colombet867c5502014-02-14 22:23:22 +00003516/// \p PromotedOperand is the value that has been promoted.
3517/// \return True if the promotion is profitable, false otherwise.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003518bool AddressingModeMatcher::isPromotionProfitable(
Quentin Colombet1b274f92015-03-10 21:48:15 +00003519 unsigned NewCost, unsigned OldCost, Value *PromotedOperand) const {
3520 DEBUG(dbgs() << "OldCost: " << OldCost << "\tNewCost: " << NewCost << '\n');
3521 // The cost of the new extensions is greater than the cost of the
3522 // old extension plus what we folded.
Quentin Colombet867c5502014-02-14 22:23:22 +00003523 // This is not profitable.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003524 if (NewCost > OldCost)
Quentin Colombet867c5502014-02-14 22:23:22 +00003525 return false;
Quentin Colombet1b274f92015-03-10 21:48:15 +00003526 if (NewCost < OldCost)
Quentin Colombet867c5502014-02-14 22:23:22 +00003527 return true;
3528 // The promotion is neutral but it may help folding the sign extension in
3529 // loads for instance.
3530 // Check that we did not create an illegal instruction.
Mehdi Amini44ede332015-07-09 02:09:04 +00003531 return isPromotedInstructionLegal(TLI, DL, PromotedOperand);
Quentin Colombet867c5502014-02-14 22:23:22 +00003532}
3533
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003534/// Given an instruction or constant expr, see if we can fold the operation
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003535/// into the addressing mode. If so, update the addressing mode and return
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003536/// true, otherwise return false without modifying AddrMode.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003537/// If \p MovedAway is not NULL, it contains the information of whether or
3538/// not AddrInst has to be folded into the addressing mode on success.
3539/// If \p MovedAway == true, \p AddrInst will not be part of the addressing
3540/// because it has been moved away.
3541/// Thus AddrInst must not be added in the matched instructions.
3542/// This state can happen when AddrInst is a sext, since it may be moved away.
3543/// Therefore, AddrInst may not be valid when MovedAway is true and it must
3544/// not be referenced anymore.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003545bool AddressingModeMatcher::matchOperationAddr(User *AddrInst, unsigned Opcode,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003546 unsigned Depth,
3547 bool *MovedAway) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003548 // Avoid exponential behavior on extremely deep expression trees.
3549 if (Depth >= 5) return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003550
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003551 // By default, all matched instructions stay in place.
3552 if (MovedAway)
3553 *MovedAway = false;
3554
Chandler Carruthc8925912013-01-05 02:09:22 +00003555 switch (Opcode) {
3556 case Instruction::PtrToInt:
3557 // PtrToInt is always a noop, as we know that the int type is pointer sized.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003558 return matchAddr(AddrInst->getOperand(0), Depth);
Mehdi Amini44ede332015-07-09 02:09:04 +00003559 case Instruction::IntToPtr: {
3560 auto AS = AddrInst->getType()->getPointerAddressSpace();
3561 auto PtrTy = MVT::getIntegerVT(DL.getPointerSizeInBits(AS));
Chandler Carruthc8925912013-01-05 02:09:22 +00003562 // This inttoptr is a no-op if the integer type is pointer sized.
Mehdi Amini44ede332015-07-09 02:09:04 +00003563 if (TLI.getValueType(DL, AddrInst->getOperand(0)->getType()) == PtrTy)
Sanjay Patelfc580a62015-09-21 23:03:16 +00003564 return matchAddr(AddrInst->getOperand(0), Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00003565 return false;
Mehdi Amini44ede332015-07-09 02:09:04 +00003566 }
Chandler Carruthc8925912013-01-05 02:09:22 +00003567 case Instruction::BitCast:
3568 // BitCast is always a noop, and we can handle it as long as it is
3569 // int->int or pointer->pointer (we don't want int<->fp or something).
3570 if ((AddrInst->getOperand(0)->getType()->isPointerTy() ||
3571 AddrInst->getOperand(0)->getType()->isIntegerTy()) &&
3572 // Don't touch identity bitcasts. These were probably put here by LSR,
3573 // and we don't want to mess around with them. Assume it knows what it
3574 // is doing.
3575 AddrInst->getOperand(0)->getType() != AddrInst->getType())
Sanjay Patelfc580a62015-09-21 23:03:16 +00003576 return matchAddr(AddrInst->getOperand(0), Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00003577 return false;
Matt Arsenaultf05b0232015-05-26 16:59:43 +00003578 case Instruction::AddrSpaceCast: {
3579 unsigned SrcAS
3580 = AddrInst->getOperand(0)->getType()->getPointerAddressSpace();
3581 unsigned DestAS = AddrInst->getType()->getPointerAddressSpace();
3582 if (TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
Sanjay Patelfc580a62015-09-21 23:03:16 +00003583 return matchAddr(AddrInst->getOperand(0), Depth);
Matt Arsenaultf05b0232015-05-26 16:59:43 +00003584 return false;
3585 }
Chandler Carruthc8925912013-01-05 02:09:22 +00003586 case Instruction::Add: {
3587 // Check to see if we can merge in the RHS then the LHS. If so, we win.
3588 ExtAddrMode BackupAddrMode = AddrMode;
3589 unsigned OldSize = AddrModeInsts.size();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003590 // Start a transaction at this point.
3591 // The LHS may match but not the RHS.
3592 // Therefore, we need a higher level restoration point to undo partially
3593 // matched operation.
3594 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3595 TPT.getRestorationPoint();
3596
Sanjay Patelfc580a62015-09-21 23:03:16 +00003597 if (matchAddr(AddrInst->getOperand(1), Depth+1) &&
3598 matchAddr(AddrInst->getOperand(0), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00003599 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003600
Chandler Carruthc8925912013-01-05 02:09:22 +00003601 // Restore the old addr mode info.
3602 AddrMode = BackupAddrMode;
3603 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003604 TPT.rollback(LastKnownGood);
Stephen Lin837bba12013-07-15 17:55:02 +00003605
Chandler Carruthc8925912013-01-05 02:09:22 +00003606 // Otherwise this was over-aggressive. Try merging in the LHS then the RHS.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003607 if (matchAddr(AddrInst->getOperand(0), Depth+1) &&
3608 matchAddr(AddrInst->getOperand(1), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00003609 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003610
Chandler Carruthc8925912013-01-05 02:09:22 +00003611 // Otherwise we definitely can't merge the ADD in.
3612 AddrMode = BackupAddrMode;
3613 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003614 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003615 break;
3616 }
3617 //case Instruction::Or:
3618 // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
3619 //break;
3620 case Instruction::Mul:
3621 case Instruction::Shl: {
3622 // Can only handle X*C and X << C.
3623 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
Sanjay Pateld3bbfa12014-07-16 22:40:28 +00003624 if (!RHS)
3625 return false;
Chandler Carruthc8925912013-01-05 02:09:22 +00003626 int64_t Scale = RHS->getSExtValue();
3627 if (Opcode == Instruction::Shl)
3628 Scale = 1LL << Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00003629
Sanjay Patelfc580a62015-09-21 23:03:16 +00003630 return matchScaledValue(AddrInst->getOperand(0), Scale, Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00003631 }
3632 case Instruction::GetElementPtr: {
3633 // Scan the GEP. We check it if it contains constant offsets and at most
3634 // one variable offset.
3635 int VariableOperand = -1;
3636 unsigned VariableScale = 0;
Stephen Lin837bba12013-07-15 17:55:02 +00003637
Chandler Carruthc8925912013-01-05 02:09:22 +00003638 int64_t ConstantOffset = 0;
Chandler Carruthc8925912013-01-05 02:09:22 +00003639 gep_type_iterator GTI = gep_type_begin(AddrInst);
3640 for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
Peter Collingbourneab85225b2016-12-02 02:24:42 +00003641 if (StructType *STy = GTI.getStructTypeOrNull()) {
Mehdi Amini4fe37982015-07-07 18:45:17 +00003642 const StructLayout *SL = DL.getStructLayout(STy);
Chandler Carruthc8925912013-01-05 02:09:22 +00003643 unsigned Idx =
3644 cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
3645 ConstantOffset += SL->getElementOffset(Idx);
3646 } else {
Mehdi Amini4fe37982015-07-07 18:45:17 +00003647 uint64_t TypeSize = DL.getTypeAllocSize(GTI.getIndexedType());
Chandler Carruthc8925912013-01-05 02:09:22 +00003648 if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
3649 ConstantOffset += CI->getSExtValue()*TypeSize;
3650 } else if (TypeSize) { // Scales of zero don't do anything.
3651 // We only allow one variable index at the moment.
3652 if (VariableOperand != -1)
3653 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003654
Chandler Carruthc8925912013-01-05 02:09:22 +00003655 // Remember the variable index.
3656 VariableOperand = i;
3657 VariableScale = TypeSize;
3658 }
3659 }
3660 }
Stephen Lin837bba12013-07-15 17:55:02 +00003661
Chandler Carruthc8925912013-01-05 02:09:22 +00003662 // A common case is for the GEP to only do a constant offset. In this case,
3663 // just add it to the disp field and check validity.
3664 if (VariableOperand == -1) {
3665 AddrMode.BaseOffs += ConstantOffset;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003666 if (ConstantOffset == 0 ||
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003667 TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003668 // Check to see if we can fold the base pointer in too.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003669 if (matchAddr(AddrInst->getOperand(0), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00003670 return true;
3671 }
3672 AddrMode.BaseOffs -= ConstantOffset;
3673 return false;
3674 }
3675
3676 // Save the valid addressing mode in case we can't match.
3677 ExtAddrMode BackupAddrMode = AddrMode;
3678 unsigned OldSize = AddrModeInsts.size();
3679
3680 // See if the scale and offset amount is valid for this target.
3681 AddrMode.BaseOffs += ConstantOffset;
3682
3683 // Match the base operand of the GEP.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003684 if (!matchAddr(AddrInst->getOperand(0), Depth+1)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003685 // If it couldn't be matched, just stuff the value in a register.
3686 if (AddrMode.HasBaseReg) {
3687 AddrMode = BackupAddrMode;
3688 AddrModeInsts.resize(OldSize);
3689 return false;
3690 }
3691 AddrMode.HasBaseReg = true;
3692 AddrMode.BaseReg = AddrInst->getOperand(0);
3693 }
3694
3695 // Match the remaining variable portion of the GEP.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003696 if (!matchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
Chandler Carruthc8925912013-01-05 02:09:22 +00003697 Depth)) {
3698 // If it couldn't be matched, try stuffing the base into a register
3699 // instead of matching it, and retrying the match of the scale.
3700 AddrMode = BackupAddrMode;
3701 AddrModeInsts.resize(OldSize);
3702 if (AddrMode.HasBaseReg)
3703 return false;
3704 AddrMode.HasBaseReg = true;
3705 AddrMode.BaseReg = AddrInst->getOperand(0);
3706 AddrMode.BaseOffs += ConstantOffset;
Sanjay Patelfc580a62015-09-21 23:03:16 +00003707 if (!matchScaledValue(AddrInst->getOperand(VariableOperand),
Chandler Carruthc8925912013-01-05 02:09:22 +00003708 VariableScale, Depth)) {
3709 // If even that didn't work, bail.
3710 AddrMode = BackupAddrMode;
3711 AddrModeInsts.resize(OldSize);
3712 return false;
3713 }
3714 }
3715
3716 return true;
3717 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003718 case Instruction::SExt:
3719 case Instruction::ZExt: {
3720 Instruction *Ext = dyn_cast<Instruction>(AddrInst);
3721 if (!Ext)
Sanjay Pateld3bbfa12014-07-16 22:40:28 +00003722 return false;
Sanjay Patelab60d042014-07-16 21:08:10 +00003723
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003724 // Try to move this ext out of the way of the addressing mode.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003725 // Ask for a method for doing so.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003726 TypePromotionHelper::Action TPH =
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003727 TypePromotionHelper::getAction(Ext, InsertedInsts, TLI, PromotedInsts);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003728 if (!TPH)
3729 return false;
3730
3731 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3732 TPT.getRestorationPoint();
Quentin Colombet1b274f92015-03-10 21:48:15 +00003733 unsigned CreatedInstsCost = 0;
3734 unsigned ExtCost = !TLI.isExtFree(Ext);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003735 Value *PromotedOperand =
Quentin Colombet1b274f92015-03-10 21:48:15 +00003736 TPH(Ext, TPT, PromotedInsts, CreatedInstsCost, nullptr, nullptr, TLI);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003737 // SExt has been moved away.
3738 // Thus either it will be rematched later in the recursive calls or it is
3739 // gone. Anyway, we must not fold it into the addressing mode at this point.
3740 // E.g.,
3741 // op = add opnd, 1
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003742 // idx = ext op
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003743 // addr = gep base, idx
3744 // is now:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003745 // promotedOpnd = ext opnd <- no match here
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003746 // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls)
3747 // addr = gep base, op <- match
3748 if (MovedAway)
3749 *MovedAway = true;
3750
3751 assert(PromotedOperand &&
3752 "TypePromotionHelper should have filtered out those cases");
3753
3754 ExtAddrMode BackupAddrMode = AddrMode;
3755 unsigned OldSize = AddrModeInsts.size();
3756
Sanjay Patelfc580a62015-09-21 23:03:16 +00003757 if (!matchAddr(PromotedOperand, Depth) ||
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003758 // The total of the new cost is equal to the cost of the created
Quentin Colombet1b274f92015-03-10 21:48:15 +00003759 // instructions.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003760 // The total of the old cost is equal to the cost of the extension plus
Quentin Colombet1b274f92015-03-10 21:48:15 +00003761 // what we have saved in the addressing mode.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003762 !isPromotionProfitable(CreatedInstsCost,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003763 ExtCost + (AddrModeInsts.size() - OldSize),
Quentin Colombet867c5502014-02-14 22:23:22 +00003764 PromotedOperand)) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003765 AddrMode = BackupAddrMode;
3766 AddrModeInsts.resize(OldSize);
3767 DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
3768 TPT.rollback(LastKnownGood);
3769 return false;
3770 }
3771 return true;
3772 }
Chandler Carruthc8925912013-01-05 02:09:22 +00003773 }
3774 return false;
3775}
3776
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003777/// If we can, try to add the value of 'Addr' into the current addressing mode.
3778/// If Addr can't be added to AddrMode this returns false and leaves AddrMode
3779/// unmodified. This assumes that Addr is either a pointer type or intptr_t
3780/// for the target.
Chandler Carruthc8925912013-01-05 02:09:22 +00003781///
Sanjay Patelfc580a62015-09-21 23:03:16 +00003782bool AddressingModeMatcher::matchAddr(Value *Addr, unsigned Depth) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003783 // Start a transaction at this point that we will rollback if the matching
3784 // fails.
3785 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3786 TPT.getRestorationPoint();
Chandler Carruthc8925912013-01-05 02:09:22 +00003787 if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
3788 // Fold in immediates if legal for the target.
3789 AddrMode.BaseOffs += CI->getSExtValue();
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003790 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003791 return true;
3792 AddrMode.BaseOffs -= CI->getSExtValue();
3793 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
3794 // If this is a global variable, try to fold it into the addressing mode.
Craig Topperc0196b12014-04-14 00:51:57 +00003795 if (!AddrMode.BaseGV) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003796 AddrMode.BaseGV = GV;
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003797 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003798 return true;
Craig Topperc0196b12014-04-14 00:51:57 +00003799 AddrMode.BaseGV = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003800 }
3801 } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
3802 ExtAddrMode BackupAddrMode = AddrMode;
3803 unsigned OldSize = AddrModeInsts.size();
3804
3805 // Check to see if it is possible to fold this operation.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003806 bool MovedAway = false;
Sanjay Patelfc580a62015-09-21 23:03:16 +00003807 if (matchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003808 // This instruction may have been moved away. If so, there is nothing
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003809 // to check here.
3810 if (MovedAway)
3811 return true;
Chandler Carruthc8925912013-01-05 02:09:22 +00003812 // Okay, it's possible to fold this. Check to see if it is actually
3813 // *profitable* to do so. We use a simple cost model to avoid increasing
3814 // register pressure too much.
3815 if (I->hasOneUse() ||
Sanjay Patelfc580a62015-09-21 23:03:16 +00003816 isProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003817 AddrModeInsts.push_back(I);
3818 return true;
3819 }
Stephen Lin837bba12013-07-15 17:55:02 +00003820
Chandler Carruthc8925912013-01-05 02:09:22 +00003821 // It isn't profitable to do this, roll back.
3822 //cerr << "NOT FOLDING: " << *I;
3823 AddrMode = BackupAddrMode;
3824 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003825 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003826 }
3827 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
Sanjay Patelfc580a62015-09-21 23:03:16 +00003828 if (matchOperationAddr(CE, CE->getOpcode(), Depth))
Chandler Carruthc8925912013-01-05 02:09:22 +00003829 return true;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003830 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003831 } else if (isa<ConstantPointerNull>(Addr)) {
3832 // Null pointer gets folded without affecting the addressing mode.
3833 return true;
3834 }
3835
3836 // Worse case, the target should support [reg] addressing modes. :)
3837 if (!AddrMode.HasBaseReg) {
3838 AddrMode.HasBaseReg = true;
3839 AddrMode.BaseReg = Addr;
3840 // Still check for legality in case the target supports [imm] but not [i+r].
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003841 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003842 return true;
3843 AddrMode.HasBaseReg = false;
Craig Topperc0196b12014-04-14 00:51:57 +00003844 AddrMode.BaseReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003845 }
3846
3847 // If the base register is already taken, see if we can do [r+r].
3848 if (AddrMode.Scale == 0) {
3849 AddrMode.Scale = 1;
3850 AddrMode.ScaledReg = Addr;
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003851 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003852 return true;
3853 AddrMode.Scale = 0;
Craig Topperc0196b12014-04-14 00:51:57 +00003854 AddrMode.ScaledReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003855 }
3856 // Couldn't match.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003857 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003858 return false;
3859}
3860
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003861/// Check to see if all uses of OpVal by the specified inline asm call are due
3862/// to memory operands. If so, return true, otherwise return false.
Chandler Carruthc8925912013-01-05 02:09:22 +00003863static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
Igor Laevsky3be81ba2017-02-07 13:27:20 +00003864 const TargetLowering &TLI,
3865 const TargetRegisterInfo &TRI) {
Eric Christopher11e4df72015-02-26 22:38:43 +00003866 const Function *F = CI->getParent()->getParent();
Eric Christopherd75c00c2015-02-26 22:38:34 +00003867 TargetLowering::AsmOperandInfoVector TargetConstraints =
Igor Laevsky3be81ba2017-02-07 13:27:20 +00003868 TLI.ParseConstraints(F->getParent()->getDataLayout(), &TRI,
Mehdi Amini8ac7a9d2015-07-07 19:07:19 +00003869 ImmutableCallSite(CI));
Igor Laevsky3be81ba2017-02-07 13:27:20 +00003870
Chandler Carruthc8925912013-01-05 02:09:22 +00003871 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
3872 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Stephen Lin837bba12013-07-15 17:55:02 +00003873
Chandler Carruthc8925912013-01-05 02:09:22 +00003874 // Compute the constraint code and ConstraintType to use.
Igor Laevsky3be81ba2017-02-07 13:27:20 +00003875 TLI.ComputeConstraintToUse(OpInfo, SDValue());
Chandler Carruthc8925912013-01-05 02:09:22 +00003876
3877 // If this asm operand is our Value*, and if it isn't an indirect memory
3878 // operand, we can't fold it!
3879 if (OpInfo.CallOperandVal == OpVal &&
3880 (OpInfo.ConstraintType != TargetLowering::C_Memory ||
3881 !OpInfo.isIndirect))
3882 return false;
3883 }
3884
3885 return true;
3886}
3887
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003888/// Recursively walk all the uses of I until we find a memory use.
3889/// If we find an obviously non-foldable instruction, return true.
Chandler Carruthc8925912013-01-05 02:09:22 +00003890/// Add the ultimately found memory instructions to MemoryUses.
Eric Christopher11e4df72015-02-26 22:38:43 +00003891static bool FindAllMemoryUses(
3892 Instruction *I,
3893 SmallVectorImpl<std::pair<Instruction *, unsigned>> &MemoryUses,
Igor Laevsky3be81ba2017-02-07 13:27:20 +00003894 SmallPtrSetImpl<Instruction *> &ConsideredInsts,
3895 const TargetLowering &TLI, const TargetRegisterInfo &TRI) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003896 // If we already considered this instruction, we're done.
David Blaikie70573dc2014-11-19 07:49:26 +00003897 if (!ConsideredInsts.insert(I).second)
Chandler Carruthc8925912013-01-05 02:09:22 +00003898 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003899
Chandler Carruthc8925912013-01-05 02:09:22 +00003900 // If this is an obviously unfoldable instruction, bail out.
3901 if (!MightBeFoldableInst(I))
3902 return true;
3903
Philip Reamesac115ed2016-03-09 23:13:12 +00003904 const bool OptSize = I->getFunction()->optForSize();
3905
Chandler Carruthc8925912013-01-05 02:09:22 +00003906 // Loop over all the uses, recursively processing them.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003907 for (Use &U : I->uses()) {
3908 Instruction *UserI = cast<Instruction>(U.getUser());
Chandler Carruthc8925912013-01-05 02:09:22 +00003909
Chandler Carruthcdf47882014-03-09 03:16:01 +00003910 if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
3911 MemoryUses.push_back(std::make_pair(LI, U.getOperandNo()));
Chandler Carruthc8925912013-01-05 02:09:22 +00003912 continue;
3913 }
Stephen Lin837bba12013-07-15 17:55:02 +00003914
Chandler Carruthcdf47882014-03-09 03:16:01 +00003915 if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
3916 unsigned opNo = U.getOperandNo();
Matt Arsenault02d915b2017-03-15 22:35:20 +00003917 if (opNo != StoreInst::getPointerOperandIndex())
3918 return true; // Storing addr, not into addr.
Chandler Carruthc8925912013-01-05 02:09:22 +00003919 MemoryUses.push_back(std::make_pair(SI, opNo));
3920 continue;
3921 }
Stephen Lin837bba12013-07-15 17:55:02 +00003922
Matt Arsenault02d915b2017-03-15 22:35:20 +00003923 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(UserI)) {
3924 unsigned opNo = U.getOperandNo();
3925 if (opNo != AtomicRMWInst::getPointerOperandIndex())
3926 return true; // Storing addr, not into addr.
3927 MemoryUses.push_back(std::make_pair(RMW, opNo));
3928 continue;
3929 }
3930
3931 if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(UserI)) {
3932 unsigned opNo = U.getOperandNo();
3933 if (opNo != AtomicCmpXchgInst::getPointerOperandIndex())
3934 return true; // Storing addr, not into addr.
3935 MemoryUses.push_back(std::make_pair(CmpX, opNo));
3936 continue;
3937 }
3938
Chandler Carruthcdf47882014-03-09 03:16:01 +00003939 if (CallInst *CI = dyn_cast<CallInst>(UserI)) {
Philip Reamesac115ed2016-03-09 23:13:12 +00003940 // If this is a cold call, we can sink the addressing calculation into
3941 // the cold path. See optimizeCallInst
3942 if (!OptSize && CI->hasFnAttr(Attribute::Cold))
3943 continue;
Junmo Park6098cbb2016-03-11 07:05:32 +00003944
Chandler Carruthc8925912013-01-05 02:09:22 +00003945 InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
3946 if (!IA) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003947
Chandler Carruthc8925912013-01-05 02:09:22 +00003948 // If this is a memory operand, we're cool, otherwise bail out.
Igor Laevsky3be81ba2017-02-07 13:27:20 +00003949 if (!IsOperandAMemoryOperand(CI, IA, I, TLI, TRI))
Chandler Carruthc8925912013-01-05 02:09:22 +00003950 return true;
3951 continue;
3952 }
Stephen Lin837bba12013-07-15 17:55:02 +00003953
Igor Laevsky3be81ba2017-02-07 13:27:20 +00003954 if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TLI, TRI))
Chandler Carruthc8925912013-01-05 02:09:22 +00003955 return true;
3956 }
3957
3958 return false;
3959}
3960
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003961/// Return true if Val is already known to be live at the use site that we're
3962/// folding it into. If so, there is no cost to include it in the addressing
3963/// mode. KnownLive1 and KnownLive2 are two values that we know are live at the
3964/// instruction already.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003965bool AddressingModeMatcher::valueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
Chandler Carruthc8925912013-01-05 02:09:22 +00003966 Value *KnownLive2) {
3967 // If Val is either of the known-live values, we know it is live!
Craig Topperc0196b12014-04-14 00:51:57 +00003968 if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2)
Chandler Carruthc8925912013-01-05 02:09:22 +00003969 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003970
Chandler Carruthc8925912013-01-05 02:09:22 +00003971 // All values other than instructions and arguments (e.g. constants) are live.
3972 if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003973
Chandler Carruthc8925912013-01-05 02:09:22 +00003974 // If Val is a constant sized alloca in the entry block, it is live, this is
3975 // true because it is just a reference to the stack/frame pointer, which is
3976 // live for the whole function.
3977 if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
3978 if (AI->isStaticAlloca())
3979 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003980
Chandler Carruthc8925912013-01-05 02:09:22 +00003981 // Check to see if this value is already used in the memory instruction's
3982 // block. If so, it's already live into the block at the very least, so we
3983 // can reasonably fold it.
3984 return Val->isUsedInBasicBlock(MemoryInst->getParent());
3985}
3986
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003987/// It is possible for the addressing mode of the machine to fold the specified
3988/// instruction into a load or store that ultimately uses it.
3989/// However, the specified instruction has multiple uses.
3990/// Given this, it may actually increase register pressure to fold it
3991/// into the load. For example, consider this code:
Chandler Carruthc8925912013-01-05 02:09:22 +00003992///
3993/// X = ...
3994/// Y = X+1
3995/// use(Y) -> nonload/store
3996/// Z = Y+1
3997/// load Z
3998///
3999/// In this case, Y has multiple uses, and can be folded into the load of Z
4000/// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to
4001/// be live at the use(Y) line. If we don't fold Y into load Z, we use one
4002/// fewer register. Since Y can't be folded into "use(Y)" we don't increase the
4003/// number of computations either.
4004///
4005/// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If
4006/// X was live across 'load Z' for other reasons, we actually *would* want to
4007/// fold the addressing mode in the Z case. This would make Y die earlier.
4008bool AddressingModeMatcher::
Sanjay Patelfc580a62015-09-21 23:03:16 +00004009isProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
Chandler Carruthc8925912013-01-05 02:09:22 +00004010 ExtAddrMode &AMAfter) {
4011 if (IgnoreProfitability) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00004012
Chandler Carruthc8925912013-01-05 02:09:22 +00004013 // AMBefore is the addressing mode before this instruction was folded into it,
4014 // and AMAfter is the addressing mode after the instruction was folded. Get
4015 // the set of registers referenced by AMAfter and subtract out those
4016 // referenced by AMBefore: this is the set of values which folding in this
4017 // address extends the lifetime of.
4018 //
4019 // Note that there are only two potential values being referenced here,
4020 // BaseReg and ScaleReg (global addresses are always available, as are any
4021 // folded immediates).
4022 Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
Stephen Lin837bba12013-07-15 17:55:02 +00004023
Chandler Carruthc8925912013-01-05 02:09:22 +00004024 // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
4025 // lifetime wasn't extended by adding this instruction.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004026 if (valueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
Craig Topperc0196b12014-04-14 00:51:57 +00004027 BaseReg = nullptr;
Sanjay Patelfc580a62015-09-21 23:03:16 +00004028 if (valueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
Craig Topperc0196b12014-04-14 00:51:57 +00004029 ScaledReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00004030
4031 // If folding this instruction (and it's subexprs) didn't extend any live
4032 // ranges, we're ok with it.
Craig Topperc0196b12014-04-14 00:51:57 +00004033 if (!BaseReg && !ScaledReg)
Chandler Carruthc8925912013-01-05 02:09:22 +00004034 return true;
4035
Philip Reamesac115ed2016-03-09 23:13:12 +00004036 // If all uses of this instruction can have the address mode sunk into them,
4037 // we can remove the addressing mode and effectively trade one live register
4038 // for another (at worst.) In this context, folding an addressing mode into
Junmo Park6098cbb2016-03-11 07:05:32 +00004039 // the use is just a particularly nice way of sinking it.
Chandler Carruthc8925912013-01-05 02:09:22 +00004040 SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
4041 SmallPtrSet<Instruction*, 16> ConsideredInsts;
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004042 if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TLI, TRI))
Chandler Carruthc8925912013-01-05 02:09:22 +00004043 return false; // Has a non-memory, non-foldable use!
Stephen Lin837bba12013-07-15 17:55:02 +00004044
Chandler Carruthc8925912013-01-05 02:09:22 +00004045 // Now that we know that all uses of this instruction are part of a chain of
4046 // computation involving only operations that could theoretically be folded
Philip Reamesac115ed2016-03-09 23:13:12 +00004047 // into a memory use, loop over each of these memory operation uses and see
4048 // if they could *actually* fold the instruction. The assumption is that
4049 // addressing modes are cheap and that duplicating the computation involved
4050 // many times is worthwhile, even on a fastpath. For sinking candidates
4051 // (i.e. cold call sites), this serves as a way to prevent excessive code
4052 // growth since most architectures have some reasonable small and fast way to
4053 // compute an effective address. (i.e LEA on x86)
Chandler Carruthc8925912013-01-05 02:09:22 +00004054 SmallVector<Instruction*, 32> MatchedAddrModeInsts;
4055 for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
4056 Instruction *User = MemoryUses[i].first;
4057 unsigned OpNo = MemoryUses[i].second;
Stephen Lin837bba12013-07-15 17:55:02 +00004058
Chandler Carruthc8925912013-01-05 02:09:22 +00004059 // Get the access type of this use. If the use isn't a pointer, we don't
4060 // know what it accesses.
4061 Value *Address = User->getOperand(OpNo);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00004062 PointerType *AddrTy = dyn_cast<PointerType>(Address->getType());
4063 if (!AddrTy)
Chandler Carruthc8925912013-01-05 02:09:22 +00004064 return false;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00004065 Type *AddressAccessTy = AddrTy->getElementType();
4066 unsigned AS = AddrTy->getAddressSpace();
Stephen Lin837bba12013-07-15 17:55:02 +00004067
Chandler Carruthc8925912013-01-05 02:09:22 +00004068 // Do a match against the root of this address, ignoring profitability. This
4069 // will tell us if the addressing mode for the memory operation will
4070 // *actually* cover the shared instruction.
4071 ExtAddrMode Result;
Quentin Colombet5a69dda2014-02-11 01:59:02 +00004072 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4073 TPT.getRestorationPoint();
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004074 AddressingModeMatcher Matcher(MatchedAddrModeInsts, TLI, TRI,
4075 AddressAccessTy, AS,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00004076 MemoryInst, Result, InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004077 PromotedInsts, TPT);
Chandler Carruthc8925912013-01-05 02:09:22 +00004078 Matcher.IgnoreProfitability = true;
Sanjay Patelfc580a62015-09-21 23:03:16 +00004079 bool Success = Matcher.matchAddr(Address, 0);
Chandler Carruthc8925912013-01-05 02:09:22 +00004080 (void)Success; assert(Success && "Couldn't select *anything*?");
4081
Quentin Colombet5a69dda2014-02-11 01:59:02 +00004082 // The match was to check the profitability, the changes made are not
4083 // part of the original matcher. Therefore, they should be dropped
4084 // otherwise the original matcher will not present the right state.
4085 TPT.rollback(LastKnownGood);
4086
Chandler Carruthc8925912013-01-05 02:09:22 +00004087 // If the match didn't cover I, then it won't be shared by it.
David Majnemer0d955d02016-08-11 22:21:41 +00004088 if (!is_contained(MatchedAddrModeInsts, I))
Chandler Carruthc8925912013-01-05 02:09:22 +00004089 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00004090
Chandler Carruthc8925912013-01-05 02:09:22 +00004091 MatchedAddrModeInsts.clear();
4092 }
Stephen Lin837bba12013-07-15 17:55:02 +00004093
Chandler Carruthc8925912013-01-05 02:09:22 +00004094 return true;
4095}
4096
4097} // end anonymous namespace
4098
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004099/// Return true if the specified values are defined in a
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004100/// different basic block than BB.
4101static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
4102 if (Instruction *I = dyn_cast<Instruction>(V))
4103 return I->getParent() != BB;
4104 return false;
4105}
4106
Philip Reamesac115ed2016-03-09 23:13:12 +00004107/// Sink addressing mode computation immediate before MemoryInst if doing so
4108/// can be done without increasing register pressure. The need for the
4109/// register pressure constraint means this can end up being an all or nothing
4110/// decision for all uses of the same addressing computation.
4111///
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004112/// Load and Store Instructions often have addressing modes that can do
4113/// significant amounts of computation. As such, instruction selection will try
4114/// to get the load or store to do as much computation as possible for the
4115/// program. The problem is that isel can only see within a single block. As
4116/// such, we sink as much legal addressing mode work into the block as possible.
Chris Lattner728f9022008-11-25 07:09:13 +00004117///
4118/// This method is used to optimize both load/store and inline asms with memory
Philip Reamesac115ed2016-03-09 23:13:12 +00004119/// operands. It's also used to sink addressing computations feeding into cold
4120/// call sites into their (cold) basic block.
4121///
4122/// The motivation for handling sinking into cold blocks is that doing so can
4123/// both enable other address mode sinking (by satisfying the register pressure
4124/// constraint above), and reduce register pressure globally (by removing the
4125/// addressing mode computation from the fast path entirely.).
Sanjay Patelfc580a62015-09-21 23:03:16 +00004126bool CodeGenPrepare::optimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00004127 Type *AccessTy, unsigned AddrSpace) {
Owen Anderson8ba5f392010-11-27 08:15:55 +00004128 Value *Repl = Addr;
Nadav Rotem465834c2012-07-24 10:51:42 +00004129
4130 // Try to collapse single-value PHI nodes. This is necessary to undo
Owen Andersondfb8c3b2010-11-19 22:15:03 +00004131 // unprofitable PRE transformations.
Cameron Zwarich43cecb12011-01-03 06:33:01 +00004132 SmallVector<Value*, 8> worklist;
4133 SmallPtrSet<Value*, 16> Visited;
Owen Anderson8ba5f392010-11-27 08:15:55 +00004134 worklist.push_back(Addr);
Nadav Rotem465834c2012-07-24 10:51:42 +00004135
Owen Anderson8ba5f392010-11-27 08:15:55 +00004136 // Use a worklist to iteratively look through PHI nodes, and ensure that
4137 // the addressing mode obtained from the non-PHI roots of the graph
4138 // are equivalent.
Craig Topperc0196b12014-04-14 00:51:57 +00004139 Value *Consensus = nullptr;
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00004140 unsigned NumUsesConsensus = 0;
Cameron Zwarich13c885d2011-03-05 08:12:26 +00004141 bool IsNumUsesConsensusValid = false;
Owen Anderson8ba5f392010-11-27 08:15:55 +00004142 SmallVector<Instruction*, 16> AddrModeInsts;
4143 ExtAddrMode AddrMode;
Jun Bum Limdee55652017-04-03 19:20:07 +00004144 TypePromotionTransaction TPT(RemovedInsts);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004145 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4146 TPT.getRestorationPoint();
Owen Anderson8ba5f392010-11-27 08:15:55 +00004147 while (!worklist.empty()) {
4148 Value *V = worklist.back();
4149 worklist.pop_back();
Nadav Rotem465834c2012-07-24 10:51:42 +00004150
Owen Anderson8ba5f392010-11-27 08:15:55 +00004151 // Break use-def graph loops.
David Blaikie70573dc2014-11-19 07:49:26 +00004152 if (!Visited.insert(V).second) {
Craig Topperc0196b12014-04-14 00:51:57 +00004153 Consensus = nullptr;
Owen Anderson8ba5f392010-11-27 08:15:55 +00004154 break;
Owen Andersondfb8c3b2010-11-19 22:15:03 +00004155 }
Nadav Rotem465834c2012-07-24 10:51:42 +00004156
Owen Anderson8ba5f392010-11-27 08:15:55 +00004157 // For a PHI node, push all of its incoming values.
4158 if (PHINode *P = dyn_cast<PHINode>(V)) {
Pete Cooper833f34d2015-05-12 20:05:31 +00004159 for (Value *IncValue : P->incoming_values())
4160 worklist.push_back(IncValue);
Owen Anderson8ba5f392010-11-27 08:15:55 +00004161 continue;
4162 }
Nadav Rotem465834c2012-07-24 10:51:42 +00004163
Philip Reamesac115ed2016-03-09 23:13:12 +00004164 // For non-PHIs, determine the addressing mode being computed. Note that
4165 // the result may differ depending on what other uses our candidate
4166 // addressing instructions might have.
Owen Anderson8ba5f392010-11-27 08:15:55 +00004167 SmallVector<Instruction*, 16> NewAddrModeInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004168 ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004169 V, AccessTy, AddrSpace, MemoryInst, NewAddrModeInsts, *TLI, *TRI,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00004170 InsertedInsts, PromotedInsts, TPT);
Cameron Zwarich13c885d2011-03-05 08:12:26 +00004171
4172 // This check is broken into two cases with very similar code to avoid using
4173 // getNumUses() as much as possible. Some values have a lot of uses, so
4174 // calling getNumUses() unconditionally caused a significant compile-time
4175 // regression.
4176 if (!Consensus) {
4177 Consensus = V;
4178 AddrMode = NewAddrMode;
4179 AddrModeInsts = NewAddrModeInsts;
4180 continue;
4181 } else if (NewAddrMode == AddrMode) {
4182 if (!IsNumUsesConsensusValid) {
4183 NumUsesConsensus = Consensus->getNumUses();
4184 IsNumUsesConsensusValid = true;
4185 }
4186
4187 // Ensure that the obtained addressing mode is equivalent to that obtained
4188 // for all other roots of the PHI traversal. Also, when choosing one
4189 // such root as representative, select the one with the most uses in order
4190 // to keep the cost modeling heuristics in AddressingModeMatcher
4191 // applicable.
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00004192 unsigned NumUses = V->getNumUses();
4193 if (NumUses > NumUsesConsensus) {
Owen Anderson8ba5f392010-11-27 08:15:55 +00004194 Consensus = V;
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00004195 NumUsesConsensus = NumUses;
Owen Anderson8ba5f392010-11-27 08:15:55 +00004196 AddrModeInsts = NewAddrModeInsts;
4197 }
4198 continue;
4199 }
Nadav Rotem465834c2012-07-24 10:51:42 +00004200
Craig Topperc0196b12014-04-14 00:51:57 +00004201 Consensus = nullptr;
Owen Anderson8ba5f392010-11-27 08:15:55 +00004202 break;
Owen Andersondfb8c3b2010-11-19 22:15:03 +00004203 }
Nadav Rotem465834c2012-07-24 10:51:42 +00004204
Owen Anderson8ba5f392010-11-27 08:15:55 +00004205 // If the addressing mode couldn't be determined, or if multiple different
4206 // ones were determined, bail out now.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004207 if (!Consensus) {
4208 TPT.rollback(LastKnownGood);
4209 return false;
4210 }
4211 TPT.commit();
Nadav Rotem465834c2012-07-24 10:51:42 +00004212
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004213 // If all the instructions matched are already in this BB, don't do anything.
Justin Lebar838c7f52016-11-21 22:49:11 +00004214 if (none_of(AddrModeInsts, [&](Value *V) {
4215 return IsNonLocalValue(V, MemoryInst->getParent());
4216 })) {
David Greene74e2d492010-01-05 01:27:11 +00004217 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004218 return false;
4219 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00004220
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004221 // Insert this computation right after this user. Since our caller is
4222 // scanning from the top of the BB to the bottom, reuse of the expr are
4223 // guaranteed to happen later.
Devang Patelc10e52a2011-09-06 18:49:53 +00004224 IRBuilder<> Builder(MemoryInst);
Eric Christopherc1ea1492008-09-24 05:32:41 +00004225
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004226 // Now that we determined the addressing expression we want to use and know
4227 // that we have to sink it into this block. Check to see if we have already
4228 // done this for some other load/store instr in this block. If so, reuse the
4229 // computation.
4230 Value *&SunkAddr = SunkAddrs[Addr];
4231 if (SunkAddr) {
David Greene74e2d492010-01-05 01:27:11 +00004232 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00004233 << *MemoryInst << "\n");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004234 if (SunkAddr->getType() != Addr->getType())
Eli Friedmanc12a5a72017-02-24 20:51:36 +00004235 SunkAddr = Builder.CreatePointerCast(SunkAddr, Addr->getType());
Eric Christopherfccff372015-01-27 01:01:38 +00004236 } else if (AddrSinkUsingGEPs ||
4237 (!AddrSinkUsingGEPs.getNumOccurrences() && TM &&
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004238 SubtargetInfo->useAA())) {
Hal Finkelc3998302014-04-12 00:59:48 +00004239 // By default, we use the GEP-based method when AA is used later. This
4240 // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities.
4241 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00004242 << *MemoryInst << "\n");
Mehdi Amini4fe37982015-07-07 18:45:17 +00004243 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
Craig Topperc0196b12014-04-14 00:51:57 +00004244 Value *ResultPtr = nullptr, *ResultIndex = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00004245
4246 // First, find the pointer.
4247 if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) {
4248 ResultPtr = AddrMode.BaseReg;
Craig Topperc0196b12014-04-14 00:51:57 +00004249 AddrMode.BaseReg = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00004250 }
4251
4252 if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) {
4253 // We can't add more than one pointer together, nor can we scale a
4254 // pointer (both of which seem meaningless).
4255 if (ResultPtr || AddrMode.Scale != 1)
4256 return false;
4257
4258 ResultPtr = AddrMode.ScaledReg;
4259 AddrMode.Scale = 0;
4260 }
4261
4262 if (AddrMode.BaseGV) {
4263 if (ResultPtr)
4264 return false;
4265
4266 ResultPtr = AddrMode.BaseGV;
4267 }
4268
4269 // If the real base value actually came from an inttoptr, then the matcher
4270 // will look through it and provide only the integer value. In that case,
4271 // use it here.
4272 if (!ResultPtr && AddrMode.BaseReg) {
4273 ResultPtr =
4274 Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(), "sunkaddr");
Craig Topperc0196b12014-04-14 00:51:57 +00004275 AddrMode.BaseReg = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00004276 } else if (!ResultPtr && AddrMode.Scale == 1) {
4277 ResultPtr =
4278 Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(), "sunkaddr");
4279 AddrMode.Scale = 0;
4280 }
4281
4282 if (!ResultPtr &&
4283 !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) {
4284 SunkAddr = Constant::getNullValue(Addr->getType());
4285 } else if (!ResultPtr) {
4286 return false;
4287 } else {
4288 Type *I8PtrTy =
David Blaikie3909da72015-03-30 20:42:56 +00004289 Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace());
4290 Type *I8Ty = Builder.getInt8Ty();
Hal Finkelc3998302014-04-12 00:59:48 +00004291
4292 // Start with the base register. Do this first so that subsequent address
4293 // matching finds it last, which will prevent it from trying to match it
4294 // as the scaled value in case it happens to be a mul. That would be
4295 // problematic if we've sunk a different mul for the scale, because then
4296 // we'd end up sinking both muls.
4297 if (AddrMode.BaseReg) {
4298 Value *V = AddrMode.BaseReg;
4299 if (V->getType() != IntPtrTy)
4300 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
4301
4302 ResultIndex = V;
4303 }
4304
4305 // Add the scale value.
4306 if (AddrMode.Scale) {
4307 Value *V = AddrMode.ScaledReg;
4308 if (V->getType() == IntPtrTy) {
4309 // done.
4310 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
4311 cast<IntegerType>(V->getType())->getBitWidth()) {
4312 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
4313 } else {
4314 // It is only safe to sign extend the BaseReg if we know that the math
4315 // required to create it did not overflow before we extend it. Since
4316 // the original IR value was tossed in favor of a constant back when
4317 // the AddrMode was created we need to bail out gracefully if widths
4318 // do not match instead of extending it.
4319 Instruction *I = dyn_cast_or_null<Instruction>(ResultIndex);
4320 if (I && (ResultIndex != AddrMode.BaseReg))
4321 I->eraseFromParent();
4322 return false;
4323 }
4324
4325 if (AddrMode.Scale != 1)
4326 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
4327 "sunkaddr");
4328 if (ResultIndex)
4329 ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr");
4330 else
4331 ResultIndex = V;
4332 }
4333
4334 // Add in the Base Offset if present.
4335 if (AddrMode.BaseOffs) {
4336 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
4337 if (ResultIndex) {
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00004338 // We need to add this separately from the scale above to help with
4339 // SDAG consecutive load/store merging.
Hal Finkelc3998302014-04-12 00:59:48 +00004340 if (ResultPtr->getType() != I8PtrTy)
Eli Friedmanc12a5a72017-02-24 20:51:36 +00004341 ResultPtr = Builder.CreatePointerCast(ResultPtr, I8PtrTy);
David Blaikie3909da72015-03-30 20:42:56 +00004342 ResultPtr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
Hal Finkelc3998302014-04-12 00:59:48 +00004343 }
4344
4345 ResultIndex = V;
4346 }
4347
4348 if (!ResultIndex) {
4349 SunkAddr = ResultPtr;
4350 } else {
4351 if (ResultPtr->getType() != I8PtrTy)
Eli Friedmanc12a5a72017-02-24 20:51:36 +00004352 ResultPtr = Builder.CreatePointerCast(ResultPtr, I8PtrTy);
David Blaikie3909da72015-03-30 20:42:56 +00004353 SunkAddr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
Hal Finkelc3998302014-04-12 00:59:48 +00004354 }
4355
4356 if (SunkAddr->getType() != Addr->getType())
Eli Friedmanc12a5a72017-02-24 20:51:36 +00004357 SunkAddr = Builder.CreatePointerCast(SunkAddr, Addr->getType());
Hal Finkelc3998302014-04-12 00:59:48 +00004358 }
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004359 } else {
David Greene74e2d492010-01-05 01:27:11 +00004360 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00004361 << *MemoryInst << "\n");
Mehdi Amini4fe37982015-07-07 18:45:17 +00004362 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
Craig Topperc0196b12014-04-14 00:51:57 +00004363 Value *Result = nullptr;
Dan Gohmanca194452010-01-19 22:45:06 +00004364
4365 // Start with the base register. Do this first so that subsequent address
4366 // matching finds it last, which will prevent it from trying to match it
4367 // as the scaled value in case it happens to be a mul. That would be
4368 // problematic if we've sunk a different mul for the scale, because then
4369 // we'd end up sinking both muls.
4370 if (AddrMode.BaseReg) {
4371 Value *V = AddrMode.BaseReg;
Duncan Sands19d0b472010-02-16 11:11:14 +00004372 if (V->getType()->isPointerTy())
Devang Patelc10e52a2011-09-06 18:49:53 +00004373 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00004374 if (V->getType() != IntPtrTy)
Devang Patelc10e52a2011-09-06 18:49:53 +00004375 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00004376 Result = V;
4377 }
4378
4379 // Add the scale value.
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004380 if (AddrMode.Scale) {
4381 Value *V = AddrMode.ScaledReg;
4382 if (V->getType() == IntPtrTy) {
4383 // done.
Duncan Sands19d0b472010-02-16 11:11:14 +00004384 } else if (V->getType()->isPointerTy()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00004385 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004386 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
4387 cast<IntegerType>(V->getType())->getBitWidth()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00004388 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004389 } else {
Jim Grosbached2cd392014-03-26 17:27:01 +00004390 // It is only safe to sign extend the BaseReg if we know that the math
4391 // required to create it did not overflow before we extend it. Since
4392 // the original IR value was tossed in favor of a constant back when
4393 // the AddrMode was created we need to bail out gracefully if widths
4394 // do not match instead of extending it.
Joey Gouly12a8bf02014-05-13 15:42:45 +00004395 Instruction *I = dyn_cast_or_null<Instruction>(Result);
Jim Grosbach83b44e12014-04-10 00:27:45 +00004396 if (I && (Result != AddrMode.BaseReg))
4397 I->eraseFromParent();
Jim Grosbached2cd392014-03-26 17:27:01 +00004398 return false;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004399 }
4400 if (AddrMode.Scale != 1)
Devang Patelc10e52a2011-09-06 18:49:53 +00004401 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
4402 "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004403 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00004404 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004405 else
4406 Result = V;
4407 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00004408
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004409 // Add in the BaseGV if present.
4410 if (AddrMode.BaseGV) {
Devang Patelc10e52a2011-09-06 18:49:53 +00004411 Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004412 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00004413 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004414 else
4415 Result = V;
4416 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00004417
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004418 // Add in the Base Offset if present.
4419 if (AddrMode.BaseOffs) {
Owen Andersonedb4a702009-07-24 23:12:02 +00004420 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004421 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00004422 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004423 else
4424 Result = V;
4425 }
4426
Craig Topperc0196b12014-04-14 00:51:57 +00004427 if (!Result)
Owen Anderson5a1acd92009-07-31 20:28:14 +00004428 SunkAddr = Constant::getNullValue(Addr->getType());
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004429 else
Devang Patelc10e52a2011-09-06 18:49:53 +00004430 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004431 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00004432
Owen Andersondfb8c3b2010-11-19 22:15:03 +00004433 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
Eric Christopherc1ea1492008-09-24 05:32:41 +00004434
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004435 // If we have no uses, recursively delete the value and all dead instructions
4436 // using it.
Owen Andersondfb8c3b2010-11-19 22:15:03 +00004437 if (Repl->use_empty()) {
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004438 // This can cause recursive deletion, which can invalidate our iterator.
4439 // Use a WeakVH to hold onto it in case this happens.
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00004440 Value *CurValue = &*CurInstIterator;
4441 WeakVH IterHandle(CurValue);
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004442 BasicBlock *BB = CurInstIterator->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +00004443
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00004444 RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004445
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00004446 if (IterHandle != CurValue) {
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004447 // If the iterator instruction was recursively deleted, start over at the
4448 // start of the block.
4449 CurInstIterator = BB->begin();
4450 SunkAddrs.clear();
Nadav Rotem465834c2012-07-24 10:51:42 +00004451 }
Dale Johannesenb67a6e662010-03-31 20:37:15 +00004452 }
Cameron Zwarichced753f2011-01-05 17:27:27 +00004453 ++NumMemoryInsts;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004454 return true;
4455}
4456
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004457/// If there are any memory operands, use OptimizeMemoryInst to sink their
4458/// address computing into the block when possible / profitable.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004459bool CodeGenPrepare::optimizeInlineAsmInst(CallInst *CS) {
Evan Cheng1da25002008-02-26 02:42:37 +00004460 bool MadeChange = false;
Evan Cheng1da25002008-02-26 02:42:37 +00004461
Eric Christopher11e4df72015-02-26 22:38:43 +00004462 const TargetRegisterInfo *TRI =
4463 TM->getSubtargetImpl(*CS->getParent()->getParent())->getRegisterInfo();
Mehdi Amini8ac7a9d2015-07-07 19:07:19 +00004464 TargetLowering::AsmOperandInfoVector TargetConstraints =
4465 TLI->ParseConstraints(*DL, TRI, CS);
Dale Johannesenf95f59a2010-09-16 18:30:55 +00004466 unsigned ArgNo = 0;
John Thompson1094c802010-09-13 18:15:37 +00004467 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
4468 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Nadav Rotem465834c2012-07-24 10:51:42 +00004469
Evan Cheng1da25002008-02-26 02:42:37 +00004470 // Compute the constraint code and ConstraintType to use.
Dale Johannesence97d552010-06-25 21:55:36 +00004471 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Evan Cheng1da25002008-02-26 02:42:37 +00004472
Eli Friedman666bbe32008-02-26 18:37:49 +00004473 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
4474 OpInfo.isIndirect) {
Chris Lattner7a277142011-01-15 07:14:54 +00004475 Value *OpVal = CS->getArgOperand(ArgNo++);
Sanjay Patelfc580a62015-09-21 23:03:16 +00004476 MadeChange |= optimizeMemoryInst(CS, OpVal, OpVal->getType(), ~0u);
Dale Johannesenf95f59a2010-09-16 18:30:55 +00004477 } else if (OpInfo.Type == InlineAsm::isInput)
4478 ArgNo++;
Evan Cheng1da25002008-02-26 02:42:37 +00004479 }
4480
4481 return MadeChange;
4482}
4483
Jun Bum Lim42301012017-03-17 19:05:21 +00004484/// \brief Check if all the uses of \p Val are equivalent (or free) zero or
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004485/// sign extensions.
Jun Bum Lim42301012017-03-17 19:05:21 +00004486static bool hasSameExtUse(Value *Val, const TargetLowering &TLI) {
4487 assert(!Val->use_empty() && "Input must have at least one use");
4488 const Instruction *FirstUser = cast<Instruction>(*Val->user_begin());
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004489 bool IsSExt = isa<SExtInst>(FirstUser);
4490 Type *ExtTy = FirstUser->getType();
Jun Bum Lim42301012017-03-17 19:05:21 +00004491 for (const User *U : Val->users()) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004492 const Instruction *UI = cast<Instruction>(U);
4493 if ((IsSExt && !isa<SExtInst>(UI)) || (!IsSExt && !isa<ZExtInst>(UI)))
4494 return false;
4495 Type *CurTy = UI->getType();
4496 // Same input and output types: Same instruction after CSE.
4497 if (CurTy == ExtTy)
4498 continue;
4499
4500 // If IsSExt is true, we are in this situation:
Jun Bum Lim42301012017-03-17 19:05:21 +00004501 // a = Val
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004502 // b = sext ty1 a to ty2
4503 // c = sext ty1 a to ty3
4504 // Assuming ty2 is shorter than ty3, this could be turned into:
Jun Bum Lim42301012017-03-17 19:05:21 +00004505 // a = Val
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004506 // b = sext ty1 a to ty2
4507 // c = sext ty2 b to ty3
4508 // However, the last sext is not free.
4509 if (IsSExt)
4510 return false;
4511
4512 // This is a ZExt, maybe this is free to extend from one type to another.
4513 // In that case, we would not account for a different use.
4514 Type *NarrowTy;
4515 Type *LargeTy;
4516 if (ExtTy->getScalarType()->getIntegerBitWidth() >
4517 CurTy->getScalarType()->getIntegerBitWidth()) {
4518 NarrowTy = CurTy;
4519 LargeTy = ExtTy;
4520 } else {
4521 NarrowTy = ExtTy;
4522 LargeTy = CurTy;
4523 }
4524
4525 if (!TLI.isZExtFree(NarrowTy, LargeTy))
4526 return false;
4527 }
4528 // All uses are the same or can be derived from one another for free.
4529 return true;
4530}
4531
Jun Bum Lim42301012017-03-17 19:05:21 +00004532/// \brief Try to speculatively promote extensions in \p Exts and continue
4533/// promoting through newly promoted operands recursively as far as doing so is
4534/// profitable. Save extensions profitably moved up, in \p ProfitablyMovedExts.
4535/// When some promotion happened, \p TPT contains the proper state to revert
4536/// them.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004537///
Jun Bum Lim42301012017-03-17 19:05:21 +00004538/// \return true if some promotion happened, false otherwise.
Jun Bum Lim42301012017-03-17 19:05:21 +00004539bool CodeGenPrepare::tryToPromoteExts(
4540 TypePromotionTransaction &TPT, const SmallVectorImpl<Instruction *> &Exts,
4541 SmallVectorImpl<Instruction *> &ProfitablyMovedExts,
4542 unsigned CreatedInstsCost) {
4543 bool Promoted = false;
4544
4545 // Iterate over all the extensions to try to promote them.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004546 for (auto I : Exts) {
Jun Bum Lim42301012017-03-17 19:05:21 +00004547 // Early check if we directly have ext(load).
4548 if (isa<LoadInst>(I->getOperand(0))) {
4549 ProfitablyMovedExts.push_back(I);
4550 continue;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004551 }
Jun Bum Lim42301012017-03-17 19:05:21 +00004552
4553 // Check whether or not we want to do any promotion. The reason we have
4554 // this check inside the for loop is to catch the case where an extension
4555 // is directly fed by a load because in such case the extension can be moved
4556 // up without any promotion on its operands.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004557 if (!TLI || !TLI->enableExtLdPromotion() || DisableExtLdPromotion)
Jun Bum Lim42301012017-03-17 19:05:21 +00004558 return false;
4559
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004560 // Get the action to perform the promotion.
Jun Bum Lim42301012017-03-17 19:05:21 +00004561 TypePromotionHelper::Action TPH =
4562 TypePromotionHelper::getAction(I, InsertedInsts, *TLI, PromotedInsts);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004563 // Check if we can promote.
Jun Bum Lim42301012017-03-17 19:05:21 +00004564 if (!TPH) {
4565 // Save the current extension as we cannot move up through its operand.
4566 ProfitablyMovedExts.push_back(I);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004567 continue;
Jun Bum Lim42301012017-03-17 19:05:21 +00004568 }
4569
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004570 // Save the current state.
4571 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4572 TPT.getRestorationPoint();
4573 SmallVector<Instruction *, 4> NewExts;
Quentin Colombet1b274f92015-03-10 21:48:15 +00004574 unsigned NewCreatedInstsCost = 0;
4575 unsigned ExtCost = !TLI->isExtFree(I);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004576 // Promote.
Quentin Colombet1b274f92015-03-10 21:48:15 +00004577 Value *PromotedVal = TPH(I, TPT, PromotedInsts, NewCreatedInstsCost,
4578 &NewExts, nullptr, *TLI);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004579 assert(PromotedVal &&
4580 "TypePromotionHelper should have filtered out those cases");
4581
4582 // We would be able to merge only one extension in a load.
4583 // Therefore, if we have more than 1 new extension we heuristically
4584 // cut this search path, because it means we degrade the code quality.
4585 // With exactly 2, the transformation is neutral, because we will merge
4586 // one extension but leave one. However, we optimistically keep going,
4587 // because the new extension may be removed too.
Quentin Colombet1b274f92015-03-10 21:48:15 +00004588 long long TotalCreatedInstsCost = CreatedInstsCost + NewCreatedInstsCost;
Jun Bum Limb99a06b2017-01-27 17:16:37 +00004589 // FIXME: It would be possible to propagate a negative value instead of
Jun Bum Lim42301012017-03-17 19:05:21 +00004590 // conservatively ceiling it to 0.
Jun Bum Limb99a06b2017-01-27 17:16:37 +00004591 TotalCreatedInstsCost =
4592 std::max((long long)0, (TotalCreatedInstsCost - ExtCost));
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004593 if (!StressExtLdPromotion &&
Quentin Colombet1b274f92015-03-10 21:48:15 +00004594 (TotalCreatedInstsCost > 1 ||
Mehdi Amini44ede332015-07-09 02:09:04 +00004595 !isPromotedInstructionLegal(*TLI, *DL, PromotedVal))) {
Jun Bum Lim42301012017-03-17 19:05:21 +00004596 // This promotion is not profitable, rollback to the previous state, and
4597 // save the current extension in ProfitablyMovedExts as the latest
4598 // speculative promotion turned out to be unprofitable.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004599 TPT.rollback(LastKnownGood);
Jun Bum Lim42301012017-03-17 19:05:21 +00004600 ProfitablyMovedExts.push_back(I);
4601 continue;
4602 }
4603 // Continue promoting NewExts as far as doing so is profitable.
4604 SmallVector<Instruction *, 2> NewlyMovedExts;
4605 (void)tryToPromoteExts(TPT, NewExts, NewlyMovedExts, TotalCreatedInstsCost);
4606 bool NewPromoted = false;
4607 for (auto ExtInst : NewlyMovedExts) {
4608 Instruction *MovedExt = cast<Instruction>(ExtInst);
4609 Value *ExtOperand = MovedExt->getOperand(0);
4610 // If we have reached to a load, we need this extra profitability check
4611 // as it could potentially be merged into an ext(load).
4612 if (isa<LoadInst>(ExtOperand) &&
4613 !(StressExtLdPromotion || NewCreatedInstsCost <= ExtCost ||
4614 (ExtOperand->hasOneUse() || hasSameExtUse(ExtOperand, *TLI))))
4615 continue;
4616
4617 ProfitablyMovedExts.push_back(MovedExt);
4618 NewPromoted = true;
4619 }
4620
4621 // If none of speculative promotions for NewExts is profitable, rollback
4622 // and save the current extension (I) as the last profitable extension.
4623 if (!NewPromoted) {
4624 TPT.rollback(LastKnownGood);
4625 ProfitablyMovedExts.push_back(I);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004626 continue;
4627 }
4628 // The promotion is profitable.
Jun Bum Lim42301012017-03-17 19:05:21 +00004629 Promoted = true;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004630 }
Jun Bum Lim42301012017-03-17 19:05:21 +00004631 return Promoted;
4632}
4633
Jun Bum Limdee55652017-04-03 19:20:07 +00004634/// Merging redundant sexts when one is dominating the other.
4635bool CodeGenPrepare::mergeSExts(Function &F) {
4636 DominatorTree DT(F);
4637 bool Changed = false;
4638 for (auto &Entry : ValToSExtendedUses) {
4639 SExts &Insts = Entry.second;
4640 SExts CurPts;
4641 for (Instruction *Inst : Insts) {
4642 if (RemovedInsts.count(Inst) || !isa<SExtInst>(Inst) ||
4643 Inst->getOperand(0) != Entry.first)
4644 continue;
4645 bool inserted = false;
4646 for (auto &Pt : CurPts) {
4647 if (DT.dominates(Inst, Pt)) {
4648 Pt->replaceAllUsesWith(Inst);
4649 RemovedInsts.insert(Pt);
4650 Pt->removeFromParent();
4651 Pt = Inst;
4652 inserted = true;
4653 Changed = true;
4654 break;
4655 }
4656 if (!DT.dominates(Pt, Inst))
4657 // Give up if we need to merge in a common dominator as the
4658 // expermients show it is not profitable.
4659 continue;
4660 Inst->replaceAllUsesWith(Pt);
4661 RemovedInsts.insert(Inst);
4662 Inst->removeFromParent();
4663 inserted = true;
4664 Changed = true;
4665 break;
4666 }
4667 if (!inserted)
4668 CurPts.push_back(Inst);
4669 }
4670 }
4671 return Changed;
4672}
4673
Jun Bum Lim42301012017-03-17 19:05:21 +00004674/// Return true, if an ext(load) can be formed from an extension in
4675/// \p MovedExts.
4676bool CodeGenPrepare::canFormExtLd(
4677 const SmallVectorImpl<Instruction *> &MovedExts, LoadInst *&LI,
4678 Instruction *&Inst, bool HasPromoted) {
4679 for (auto *MovedExtInst : MovedExts) {
4680 if (isa<LoadInst>(MovedExtInst->getOperand(0))) {
4681 LI = cast<LoadInst>(MovedExtInst->getOperand(0));
4682 Inst = MovedExtInst;
4683 break;
4684 }
4685 }
4686 if (!LI)
4687 return false;
4688
4689 // If they're already in the same block, there's nothing to do.
4690 // Make the cheap checks first if we did not promote.
4691 // If we promoted, we need to check if it is indeed profitable.
4692 if (!HasPromoted && LI->getParent() == Inst->getParent())
4693 return false;
4694
4695 EVT VT = TLI->getValueType(*DL, Inst->getType());
4696 EVT LoadVT = TLI->getValueType(*DL, LI->getType());
4697
4698 // If the load has other users and the truncate is not free, this probably
4699 // isn't worthwhile.
4700 if (!LI->hasOneUse() && (TLI->isTypeLegal(LoadVT) || !TLI->isTypeLegal(VT)) &&
4701 !TLI->isTruncateFree(Inst->getType(), LI->getType()))
4702 return false;
4703
4704 // Check whether the target supports casts folded into loads.
4705 unsigned LType;
4706 if (isa<ZExtInst>(Inst))
4707 LType = ISD::ZEXTLOAD;
4708 else {
4709 assert(isa<SExtInst>(Inst) && "Unexpected ext type!");
4710 LType = ISD::SEXTLOAD;
4711 }
4712
4713 return TLI->isLoadExtLegal(LType, VT, LoadVT);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004714}
4715
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004716/// Move a zext or sext fed by a load into the same basic block as the load,
4717/// unless conditions are unfavorable. This allows SelectionDAG to fold the
4718/// extend into the load.
Dan Gohman99429a02009-10-16 20:59:35 +00004719///
Jun Bum Limdee55652017-04-03 19:20:07 +00004720/// E.g.,
4721/// \code
4722/// %ld = load i32* %addr
4723/// %add = add nuw i32 %ld, 4
4724/// %zext = zext i32 %add to i64
4725// \endcode
4726/// =>
4727/// \code
4728/// %ld = load i32* %addr
4729/// %zext = zext i32 %ld to i64
4730/// %add = add nuw i64 %zext, 4
4731/// \encode
4732/// Note that the promotion in %add to i64 is done in tryToPromoteExts(), which
4733/// allow us to match zext(load i32*) to i64.
4734///
4735/// Also, try to promote the computations used to obtain a sign extended
4736/// value used into memory accesses.
4737/// E.g.,
4738/// \code
4739/// a = add nsw i32 b, 3
4740/// d = sext i32 a to i64
4741/// e = getelementptr ..., i64 d
4742/// \endcode
4743/// =>
4744/// \code
4745/// f = sext i32 b to i64
4746/// a = add nsw i64 f, 3
4747/// e = getelementptr ..., i64 a
4748/// \endcode
4749///
4750/// \p Inst[in/out] the extension may be modified during the process if some
4751/// promotions apply.
4752bool CodeGenPrepare::optimizeExt(Instruction *&Inst) {
4753 // ExtLoad formation and address type promotion infrastructure requires TLI to
4754 // be effective.
Chandler Carruth0f139b42016-11-04 06:54:00 +00004755 if (!TLI)
4756 return false;
4757
Jun Bum Limdee55652017-04-03 19:20:07 +00004758 bool AllowPromotionWithoutCommonHeader = false;
4759 /// See if it is an interesting sext operations for the address type
4760 /// promotion before trying to promote it, e.g., the ones with the right
4761 /// type and used in memory accesses.
4762 bool ATPConsiderable = TTI->shouldConsiderAddressTypePromotion(
4763 *Inst, AllowPromotionWithoutCommonHeader);
4764 TypePromotionTransaction TPT(RemovedInsts);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004765 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
Jun Bum Lim42301012017-03-17 19:05:21 +00004766 TPT.getRestorationPoint();
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004767 SmallVector<Instruction *, 1> Exts;
Jun Bum Limdee55652017-04-03 19:20:07 +00004768 SmallVector<Instruction *, 2> SpeculativelyMovedExts;
4769 Exts.push_back(Inst);
Jun Bum Lim42301012017-03-17 19:05:21 +00004770
Jun Bum Limdee55652017-04-03 19:20:07 +00004771 bool HasPromoted = tryToPromoteExts(TPT, Exts, SpeculativelyMovedExts);
Jun Bum Lim42301012017-03-17 19:05:21 +00004772
Dan Gohman99429a02009-10-16 20:59:35 +00004773 // Look for a load being extended.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004774 LoadInst *LI = nullptr;
Jun Bum Limdee55652017-04-03 19:20:07 +00004775 Instruction *ExtFedByLoad;
4776
4777 // Try to promote a chain of computation if it allows to form an extended
4778 // load.
4779 if (canFormExtLd(SpeculativelyMovedExts, LI, ExtFedByLoad, HasPromoted)) {
4780 assert(LI && ExtFedByLoad && "Expect a valid load and extension");
4781 TPT.commit();
4782 // Move the extend into the same block as the load
4783 ExtFedByLoad->removeFromParent();
4784 ExtFedByLoad->insertAfter(LI);
4785 // CGP does not check if the zext would be speculatively executed when moved
4786 // to the same basic block as the load. Preserving its original location
4787 // would pessimize the debugging experience, as well as negatively impact
4788 // the quality of sample pgo. We don't want to use "line 0" as that has a
4789 // size cost in the line-table section and logically the zext can be seen as
4790 // part of the load. Therefore we conservatively reuse the same debug
4791 // location for the load and the zext.
4792 ExtFedByLoad->setDebugLoc(LI->getDebugLoc());
4793 ++NumExtsMoved;
4794 Inst = ExtFedByLoad;
4795 return true;
4796 }
4797
4798 // Continue promoting SExts if known as considerable depending on targets.
4799 if (ATPConsiderable &&
4800 performAddressTypePromotion(Inst, AllowPromotionWithoutCommonHeader,
4801 HasPromoted, TPT, SpeculativelyMovedExts))
4802 return true;
4803
4804 TPT.rollback(LastKnownGood);
4805 return false;
4806}
4807
4808// Perform address type promotion if doing so is profitable.
4809// If AllowPromotionWithoutCommonHeader == false, we should find other sext
4810// instructions that sign extended the same initial value. However, if
4811// AllowPromotionWithoutCommonHeader == true, we expect promoting the
4812// extension is just profitable.
4813bool CodeGenPrepare::performAddressTypePromotion(
4814 Instruction *&Inst, bool AllowPromotionWithoutCommonHeader,
4815 bool HasPromoted, TypePromotionTransaction &TPT,
4816 SmallVectorImpl<Instruction *> &SpeculativelyMovedExts) {
4817 bool Promoted = false;
4818 SmallPtrSet<Instruction *, 1> UnhandledExts;
4819 bool AllSeenFirst = true;
4820 for (auto I : SpeculativelyMovedExts) {
4821 Value *HeadOfChain = I->getOperand(0);
4822 DenseMap<Value *, Instruction *>::iterator AlreadySeen =
4823 SeenChainsForSExt.find(HeadOfChain);
4824 // If there is an unhandled SExt which has the same header, try to promote
4825 // it as well.
4826 if (AlreadySeen != SeenChainsForSExt.end()) {
4827 if (AlreadySeen->second != nullptr)
4828 UnhandledExts.insert(AlreadySeen->second);
4829 AllSeenFirst = false;
4830 }
4831 }
4832
4833 if (!AllSeenFirst || (AllowPromotionWithoutCommonHeader &&
4834 SpeculativelyMovedExts.size() == 1)) {
4835 TPT.commit();
4836 if (HasPromoted)
4837 Promoted = true;
4838 for (auto I : SpeculativelyMovedExts) {
4839 Value *HeadOfChain = I->getOperand(0);
4840 SeenChainsForSExt[HeadOfChain] = nullptr;
4841 ValToSExtendedUses[HeadOfChain].push_back(I);
4842 }
4843 // Update Inst as promotion happen.
4844 Inst = SpeculativelyMovedExts.pop_back_val();
4845 } else {
4846 // This is the first chain visited from the header, keep the current chain
4847 // as unhandled. Defer to promote this until we encounter another SExt
4848 // chain derived from the same header.
4849 for (auto I : SpeculativelyMovedExts) {
4850 Value *HeadOfChain = I->getOperand(0);
4851 SeenChainsForSExt[HeadOfChain] = Inst;
4852 }
Dan Gohman99429a02009-10-16 20:59:35 +00004853 return false;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004854 }
Dan Gohman99429a02009-10-16 20:59:35 +00004855
Jun Bum Limdee55652017-04-03 19:20:07 +00004856 if (!AllSeenFirst && !UnhandledExts.empty())
4857 for (auto VisitedSExt : UnhandledExts) {
4858 if (RemovedInsts.count(VisitedSExt))
4859 continue;
4860 TypePromotionTransaction TPT(RemovedInsts);
4861 SmallVector<Instruction *, 1> Exts;
4862 SmallVector<Instruction *, 2> Chains;
4863 Exts.push_back(VisitedSExt);
4864 bool HasPromoted = tryToPromoteExts(TPT, Exts, Chains);
4865 TPT.commit();
4866 if (HasPromoted)
4867 Promoted = true;
4868 for (auto I : Chains) {
4869 Value *HeadOfChain = I->getOperand(0);
4870 // Mark this as handled.
4871 SeenChainsForSExt[HeadOfChain] = nullptr;
4872 ValToSExtendedUses[HeadOfChain].push_back(I);
4873 }
4874 }
4875 return Promoted;
Dan Gohman99429a02009-10-16 20:59:35 +00004876}
4877
Sanjay Patelfc580a62015-09-21 23:03:16 +00004878bool CodeGenPrepare::optimizeExtUses(Instruction *I) {
Evan Chengd3d80172007-12-05 23:58:20 +00004879 BasicBlock *DefBB = I->getParent();
4880
Bob Wilsonff714f92010-09-21 21:44:14 +00004881 // If the result of a {s|z}ext and its source are both live out, rewrite all
Evan Chengd3d80172007-12-05 23:58:20 +00004882 // other uses of the source with result of extension.
4883 Value *Src = I->getOperand(0);
4884 if (Src->hasOneUse())
4885 return false;
4886
Evan Cheng2011df42007-12-13 07:50:36 +00004887 // Only do this xform if truncating is free.
Gabor Greifaa261722008-02-26 19:13:21 +00004888 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
Evan Cheng37c36ed2007-12-13 03:32:53 +00004889 return false;
4890
Evan Cheng7bc89422007-12-12 00:51:06 +00004891 // Only safe to perform the optimization if the source is also defined in
Evan Cheng63d33cf2007-12-12 02:53:41 +00004892 // this block.
4893 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
Evan Cheng7bc89422007-12-12 00:51:06 +00004894 return false;
4895
Evan Chengd3d80172007-12-05 23:58:20 +00004896 bool DefIsLiveOut = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00004897 for (User *U : I->users()) {
4898 Instruction *UI = cast<Instruction>(U);
Evan Chengd3d80172007-12-05 23:58:20 +00004899
4900 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004901 BasicBlock *UserBB = UI->getParent();
Evan Chengd3d80172007-12-05 23:58:20 +00004902 if (UserBB == DefBB) continue;
4903 DefIsLiveOut = true;
4904 break;
4905 }
4906 if (!DefIsLiveOut)
4907 return false;
4908
Jim Grosbach0f38c1e2013-04-15 17:40:48 +00004909 // Make sure none of the uses are PHI nodes.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004910 for (User *U : Src->users()) {
4911 Instruction *UI = cast<Instruction>(U);
4912 BasicBlock *UserBB = UI->getParent();
Evan Cheng37c36ed2007-12-13 03:32:53 +00004913 if (UserBB == DefBB) continue;
4914 // Be conservative. We don't want this xform to end up introducing
4915 // reloads just before load / store instructions.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004916 if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI))
Evan Cheng63d33cf2007-12-12 02:53:41 +00004917 return false;
4918 }
4919
Evan Chengd3d80172007-12-05 23:58:20 +00004920 // InsertedTruncs - Only insert one trunc in each block once.
4921 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
4922
4923 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00004924 for (Use &U : Src->uses()) {
4925 Instruction *User = cast<Instruction>(U.getUser());
Evan Chengd3d80172007-12-05 23:58:20 +00004926
4927 // Figure out which BB this ext is used in.
4928 BasicBlock *UserBB = User->getParent();
4929 if (UserBB == DefBB) continue;
4930
4931 // Both src and def are live in this block. Rewrite the use.
4932 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
4933
4934 if (!InsertedTrunc) {
Bill Wendling8ddfc092011-08-16 20:45:24 +00004935 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00004936 assert(InsertPt != UserBB->end());
4937 InsertedTrunc = new TruncInst(I, Src->getType(), "", &*InsertPt);
Ahmed Bougachaf3299142015-06-17 20:44:32 +00004938 InsertedInsts.insert(InsertedTrunc);
Evan Chengd3d80172007-12-05 23:58:20 +00004939 }
4940
4941 // Replace a use of the {s|z}ext source with a use of the result.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004942 U = InsertedTrunc;
Cameron Zwarichced753f2011-01-05 17:27:27 +00004943 ++NumExtUses;
Evan Chengd3d80172007-12-05 23:58:20 +00004944 MadeChange = true;
4945 }
4946
4947 return MadeChange;
4948}
4949
Geoff Berry5256fca2015-11-20 22:34:39 +00004950// Find loads whose uses only use some of the loaded value's bits. Add an "and"
4951// just after the load if the target can fold this into one extload instruction,
4952// with the hope of eliminating some of the other later "and" instructions using
4953// the loaded value. "and"s that are made trivially redundant by the insertion
4954// of the new "and" are removed by this function, while others (e.g. those whose
4955// path from the load goes through a phi) are left for isel to potentially
4956// remove.
4957//
4958// For example:
4959//
4960// b0:
4961// x = load i32
4962// ...
4963// b1:
4964// y = and x, 0xff
4965// z = use y
4966//
4967// becomes:
4968//
4969// b0:
4970// x = load i32
4971// x' = and x, 0xff
4972// ...
4973// b1:
4974// z = use x'
4975//
4976// whereas:
4977//
4978// b0:
4979// x1 = load i32
4980// ...
4981// b1:
4982// x2 = load i32
4983// ...
4984// b2:
4985// x = phi x1, x2
4986// y = and x, 0xff
4987//
4988// becomes (after a call to optimizeLoadExt for each load):
4989//
4990// b0:
4991// x1 = load i32
4992// x1' = and x1, 0xff
4993// ...
4994// b1:
4995// x2 = load i32
4996// x2' = and x2, 0xff
4997// ...
4998// b2:
4999// x = phi x1', x2'
5000// y = and x, 0xff
5001//
5002
5003bool CodeGenPrepare::optimizeLoadExt(LoadInst *Load) {
5004
5005 if (!Load->isSimple() ||
5006 !(Load->getType()->isIntegerTy() || Load->getType()->isPointerTy()))
5007 return false;
5008
Geoff Berry5d534b62017-02-21 18:53:14 +00005009 // Skip loads we've already transformed.
5010 if (Load->hasOneUse() &&
5011 InsertedInsts.count(cast<Instruction>(*Load->user_begin())))
5012 return false;
Geoff Berry5256fca2015-11-20 22:34:39 +00005013
5014 // Look at all uses of Load, looking through phis, to determine how many bits
5015 // of the loaded value are needed.
5016 SmallVector<Instruction *, 8> WorkList;
5017 SmallPtrSet<Instruction *, 16> Visited;
5018 SmallVector<Instruction *, 8> AndsToMaybeRemove;
5019 for (auto *U : Load->users())
5020 WorkList.push_back(cast<Instruction>(U));
5021
5022 EVT LoadResultVT = TLI->getValueType(*DL, Load->getType());
5023 unsigned BitWidth = LoadResultVT.getSizeInBits();
5024 APInt DemandBits(BitWidth, 0);
5025 APInt WidestAndBits(BitWidth, 0);
5026
5027 while (!WorkList.empty()) {
5028 Instruction *I = WorkList.back();
5029 WorkList.pop_back();
5030
5031 // Break use-def graph loops.
5032 if (!Visited.insert(I).second)
5033 continue;
5034
5035 // For a PHI node, push all of its users.
5036 if (auto *Phi = dyn_cast<PHINode>(I)) {
5037 for (auto *U : Phi->users())
5038 WorkList.push_back(cast<Instruction>(U));
5039 continue;
5040 }
5041
5042 switch (I->getOpcode()) {
5043 case llvm::Instruction::And: {
5044 auto *AndC = dyn_cast<ConstantInt>(I->getOperand(1));
5045 if (!AndC)
5046 return false;
5047 APInt AndBits = AndC->getValue();
5048 DemandBits |= AndBits;
5049 // Keep track of the widest and mask we see.
5050 if (AndBits.ugt(WidestAndBits))
5051 WidestAndBits = AndBits;
5052 if (AndBits == WidestAndBits && I->getOperand(0) == Load)
5053 AndsToMaybeRemove.push_back(I);
5054 break;
5055 }
5056
5057 case llvm::Instruction::Shl: {
5058 auto *ShlC = dyn_cast<ConstantInt>(I->getOperand(1));
5059 if (!ShlC)
5060 return false;
5061 uint64_t ShiftAmt = ShlC->getLimitedValue(BitWidth - 1);
5062 auto ShlDemandBits = APInt::getAllOnesValue(BitWidth).lshr(ShiftAmt);
5063 DemandBits |= ShlDemandBits;
5064 break;
5065 }
5066
5067 case llvm::Instruction::Trunc: {
5068 EVT TruncVT = TLI->getValueType(*DL, I->getType());
5069 unsigned TruncBitWidth = TruncVT.getSizeInBits();
5070 auto TruncBits = APInt::getAllOnesValue(TruncBitWidth).zext(BitWidth);
5071 DemandBits |= TruncBits;
5072 break;
5073 }
5074
5075 default:
5076 return false;
5077 }
5078 }
5079
5080 uint32_t ActiveBits = DemandBits.getActiveBits();
5081 // Avoid hoisting (and (load x) 1) since it is unlikely to be folded by the
5082 // target even if isLoadExtLegal says an i1 EXTLOAD is valid. For example,
5083 // for the AArch64 target isLoadExtLegal(ZEXTLOAD, i32, i1) returns true, but
5084 // (and (load x) 1) is not matched as a single instruction, rather as a LDR
5085 // followed by an AND.
5086 // TODO: Look into removing this restriction by fixing backends to either
5087 // return false for isLoadExtLegal for i1 or have them select this pattern to
5088 // a single instruction.
5089 //
5090 // Also avoid hoisting if we didn't see any ands with the exact DemandBits
5091 // mask, since these are the only ands that will be removed by isel.
Craig Topperd33ee1b2017-04-03 16:34:59 +00005092 if (ActiveBits <= 1 || !DemandBits.isMask(ActiveBits) ||
Geoff Berry5256fca2015-11-20 22:34:39 +00005093 WidestAndBits != DemandBits)
5094 return false;
5095
5096 LLVMContext &Ctx = Load->getType()->getContext();
5097 Type *TruncTy = Type::getIntNTy(Ctx, ActiveBits);
5098 EVT TruncVT = TLI->getValueType(*DL, TruncTy);
5099
5100 // Reject cases that won't be matched as extloads.
5101 if (!LoadResultVT.bitsGT(TruncVT) || !TruncVT.isRound() ||
5102 !TLI->isLoadExtLegal(ISD::ZEXTLOAD, LoadResultVT, TruncVT))
5103 return false;
5104
5105 IRBuilder<> Builder(Load->getNextNode());
5106 auto *NewAnd = dyn_cast<Instruction>(
5107 Builder.CreateAnd(Load, ConstantInt::get(Ctx, DemandBits)));
Geoff Berry5d534b62017-02-21 18:53:14 +00005108 // Mark this instruction as "inserted by CGP", so that other
5109 // optimizations don't touch it.
5110 InsertedInsts.insert(NewAnd);
Geoff Berry5256fca2015-11-20 22:34:39 +00005111
5112 // Replace all uses of load with new and (except for the use of load in the
5113 // new and itself).
5114 Load->replaceAllUsesWith(NewAnd);
5115 NewAnd->setOperand(0, Load);
5116
5117 // Remove any and instructions that are now redundant.
5118 for (auto *And : AndsToMaybeRemove)
5119 // Check that the and mask is the same as the one we decided to put on the
5120 // new and.
5121 if (cast<ConstantInt>(And->getOperand(1))->getValue() == DemandBits) {
5122 And->replaceAllUsesWith(NewAnd);
5123 if (&*CurInstIterator == And)
5124 CurInstIterator = std::next(And->getIterator());
5125 And->eraseFromParent();
5126 ++NumAndUses;
5127 }
5128
5129 ++NumAndsAdded;
5130 return true;
5131}
5132
Sanjay Patel69a50a12015-10-19 21:59:12 +00005133/// Check if V (an operand of a select instruction) is an expensive instruction
5134/// that is only used once.
5135static bool sinkSelectOperand(const TargetTransformInfo *TTI, Value *V) {
5136 auto *I = dyn_cast<Instruction>(V);
5137 // If it's safe to speculatively execute, then it should not have side
5138 // effects; therefore, it's safe to sink and possibly *not* execute.
Rafael Espindola84921b92015-10-24 23:11:13 +00005139 return I && I->hasOneUse() && isSafeToSpeculativelyExecute(I) &&
5140 TTI->getUserCost(I) >= TargetTransformInfo::TCC_Expensive;
Sanjay Patel69a50a12015-10-19 21:59:12 +00005141}
5142
Sanjay Patel4ac6b112015-09-21 22:47:23 +00005143/// Returns true if a SelectInst should be turned into an explicit branch.
Sanjay Patel69a50a12015-10-19 21:59:12 +00005144static bool isFormingBranchFromSelectProfitable(const TargetTransformInfo *TTI,
Sanjay Pateld66607b2016-04-26 17:11:17 +00005145 const TargetLowering *TLI,
Sanjay Patel69a50a12015-10-19 21:59:12 +00005146 SelectInst *SI) {
Sanjay Pateld66607b2016-04-26 17:11:17 +00005147 // If even a predictable select is cheap, then a branch can't be cheaper.
5148 if (!TLI->isPredictableSelectExpensive())
5149 return false;
5150
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005151 // FIXME: This should use the same heuristics as IfConversion to determine
Sanjay Pateld66607b2016-04-26 17:11:17 +00005152 // whether a select is better represented as a branch.
5153
5154 // If metadata tells us that the select condition is obviously predictable,
5155 // then we want to replace the select with a branch.
5156 uint64_t TrueWeight, FalseWeight;
5157 if (SI->extractProfMetadata(TrueWeight, FalseWeight)) {
5158 uint64_t Max = std::max(TrueWeight, FalseWeight);
5159 uint64_t Sum = TrueWeight + FalseWeight;
Sanjay Patelc7b91e62016-05-09 17:31:55 +00005160 if (Sum != 0) {
5161 auto Probability = BranchProbability::getBranchProbability(Max, Sum);
5162 if (Probability > TLI->getPredictableBranchThreshold())
5163 return true;
5164 }
Sanjay Pateld66607b2016-04-26 17:11:17 +00005165 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005166
5167 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
5168
Sanjay Patel4e652762015-09-28 22:14:51 +00005169 // If a branch is predictable, an out-of-order CPU can avoid blocking on its
5170 // comparison condition. If the compare has more than one use, there's
5171 // probably another cmov or setcc around, so it's not worth emitting a branch.
Sanjay Patel5e5f0e92015-09-28 21:44:46 +00005172 if (!Cmp || !Cmp->hasOneUse())
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005173 return false;
5174
Sanjay Patel69a50a12015-10-19 21:59:12 +00005175 // If either operand of the select is expensive and only needed on one side
5176 // of the select, we should form a branch.
5177 if (sinkSelectOperand(TTI, SI->getTrueValue()) ||
5178 sinkSelectOperand(TTI, SI->getFalseValue()))
5179 return true;
5180
5181 return false;
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005182}
5183
Dehao Chen9bbb9412016-09-12 20:23:28 +00005184/// If \p isTrue is true, return the true value of \p SI, otherwise return
5185/// false value of \p SI. If the true/false value of \p SI is defined by any
5186/// select instructions in \p Selects, look through the defining select
5187/// instruction until the true/false value is not defined in \p Selects.
5188static Value *getTrueOrFalseValue(
5189 SelectInst *SI, bool isTrue,
5190 const SmallPtrSet<const Instruction *, 2> &Selects) {
5191 Value *V;
5192
5193 for (SelectInst *DefSI = SI; DefSI != nullptr && Selects.count(DefSI);
5194 DefSI = dyn_cast<SelectInst>(V)) {
Dehao Chenc32d7122016-09-12 20:29:54 +00005195 assert(DefSI->getCondition() == SI->getCondition() &&
Dehao Chen9bbb9412016-09-12 20:23:28 +00005196 "The condition of DefSI does not match with SI");
5197 V = (isTrue ? DefSI->getTrueValue() : DefSI->getFalseValue());
5198 }
5199 return V;
5200}
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005201
Nadav Rotem9d832022012-09-02 12:10:19 +00005202/// If we have a SelectInst that will likely profit from branch prediction,
5203/// turn it into a branch.
Sanjay Patelfc580a62015-09-21 23:03:16 +00005204bool CodeGenPrepare::optimizeSelectInst(SelectInst *SI) {
Dehao Chen9bbb9412016-09-12 20:23:28 +00005205 // Find all consecutive select instructions that share the same condition.
5206 SmallVector<SelectInst *, 2> ASI;
5207 ASI.push_back(SI);
5208 for (BasicBlock::iterator It = ++BasicBlock::iterator(SI);
5209 It != SI->getParent()->end(); ++It) {
5210 SelectInst *I = dyn_cast<SelectInst>(&*It);
5211 if (I && SI->getCondition() == I->getCondition()) {
5212 ASI.push_back(I);
5213 } else {
5214 break;
5215 }
5216 }
5217
5218 SelectInst *LastSI = ASI.back();
5219 // Increment the current iterator to skip all the rest of select instructions
5220 // because they will be either "not lowered" or "all lowered" to branch.
5221 CurInstIterator = std::next(LastSI->getIterator());
5222
Nadav Rotem9d832022012-09-02 12:10:19 +00005223 bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
5224
5225 // Can we convert the 'select' to CF ?
Sanjay Patela31b0c02016-04-26 00:47:39 +00005226 if (DisableSelectToBranch || OptSize || !TLI || VectorCond ||
5227 SI->getMetadata(LLVMContext::MD_unpredictable))
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005228 return false;
5229
Nadav Rotem9d832022012-09-02 12:10:19 +00005230 TargetLowering::SelectSupportKind SelectKind;
5231 if (VectorCond)
5232 SelectKind = TargetLowering::VectorMaskSelect;
5233 else if (SI->getType()->isVectorTy())
5234 SelectKind = TargetLowering::ScalarCondVectorVal;
5235 else
5236 SelectKind = TargetLowering::ScalarValSelect;
5237
Sanjay Pateld66607b2016-04-26 17:11:17 +00005238 if (TLI->isSelectSupported(SelectKind) &&
5239 !isFormingBranchFromSelectProfitable(TTI, TLI, SI))
5240 return false;
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005241
5242 ModifiedDT = true;
5243
Sanjay Patel69a50a12015-10-19 21:59:12 +00005244 // Transform a sequence like this:
5245 // start:
5246 // %cmp = cmp uge i32 %a, %b
5247 // %sel = select i1 %cmp, i32 %c, i32 %d
5248 //
5249 // Into:
5250 // start:
5251 // %cmp = cmp uge i32 %a, %b
5252 // br i1 %cmp, label %select.true, label %select.false
5253 // select.true:
5254 // br label %select.end
5255 // select.false:
5256 // br label %select.end
5257 // select.end:
5258 // %sel = phi i32 [ %c, %select.true ], [ %d, %select.false ]
5259 //
5260 // In addition, we may sink instructions that produce %c or %d from
5261 // the entry block into the destination(s) of the new branch.
5262 // If the true or false blocks do not contain a sunken instruction, that
5263 // block and its branch may be optimized away. In that case, one side of the
5264 // first branch will point directly to select.end, and the corresponding PHI
5265 // predecessor block will be the start block.
5266
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005267 // First, we split the block containing the select into 2 blocks.
5268 BasicBlock *StartBlock = SI->getParent();
Dehao Chen9bbb9412016-09-12 20:23:28 +00005269 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(LastSI));
Sanjay Patel69a50a12015-10-19 21:59:12 +00005270 BasicBlock *EndBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005271
Sanjay Patel69a50a12015-10-19 21:59:12 +00005272 // Delete the unconditional branch that was just created by the split.
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005273 StartBlock->getTerminator()->eraseFromParent();
Sanjay Patel69a50a12015-10-19 21:59:12 +00005274
5275 // These are the new basic blocks for the conditional branch.
5276 // At least one will become an actual new basic block.
5277 BasicBlock *TrueBlock = nullptr;
5278 BasicBlock *FalseBlock = nullptr;
Dehao Chen9bbb9412016-09-12 20:23:28 +00005279 BranchInst *TrueBranch = nullptr;
5280 BranchInst *FalseBranch = nullptr;
Sanjay Patel69a50a12015-10-19 21:59:12 +00005281
5282 // Sink expensive instructions into the conditional blocks to avoid executing
5283 // them speculatively.
Dehao Chen9bbb9412016-09-12 20:23:28 +00005284 for (SelectInst *SI : ASI) {
5285 if (sinkSelectOperand(TTI, SI->getTrueValue())) {
5286 if (TrueBlock == nullptr) {
5287 TrueBlock = BasicBlock::Create(SI->getContext(), "select.true.sink",
5288 EndBlock->getParent(), EndBlock);
5289 TrueBranch = BranchInst::Create(EndBlock, TrueBlock);
5290 }
5291 auto *TrueInst = cast<Instruction>(SI->getTrueValue());
5292 TrueInst->moveBefore(TrueBranch);
5293 }
5294 if (sinkSelectOperand(TTI, SI->getFalseValue())) {
5295 if (FalseBlock == nullptr) {
5296 FalseBlock = BasicBlock::Create(SI->getContext(), "select.false.sink",
5297 EndBlock->getParent(), EndBlock);
5298 FalseBranch = BranchInst::Create(EndBlock, FalseBlock);
5299 }
5300 auto *FalseInst = cast<Instruction>(SI->getFalseValue());
5301 FalseInst->moveBefore(FalseBranch);
5302 }
Sanjay Patel69a50a12015-10-19 21:59:12 +00005303 }
5304
5305 // If there was nothing to sink, then arbitrarily choose the 'false' side
5306 // for a new input value to the PHI.
5307 if (TrueBlock == FalseBlock) {
5308 assert(TrueBlock == nullptr &&
5309 "Unexpected basic block transform while optimizing select");
5310
5311 FalseBlock = BasicBlock::Create(SI->getContext(), "select.false",
5312 EndBlock->getParent(), EndBlock);
5313 BranchInst::Create(EndBlock, FalseBlock);
5314 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005315
5316 // Insert the real conditional branch based on the original condition.
Sanjay Patel69a50a12015-10-19 21:59:12 +00005317 // If we did not create a new block for one of the 'true' or 'false' paths
5318 // of the condition, it means that side of the branch goes to the end block
5319 // directly and the path originates from the start block from the point of
5320 // view of the new PHI.
Xinliang David Li241e6c72016-09-03 21:26:36 +00005321 BasicBlock *TT, *FT;
Sanjay Patel69a50a12015-10-19 21:59:12 +00005322 if (TrueBlock == nullptr) {
Xinliang David Li241e6c72016-09-03 21:26:36 +00005323 TT = EndBlock;
5324 FT = FalseBlock;
Sanjay Patel69a50a12015-10-19 21:59:12 +00005325 TrueBlock = StartBlock;
5326 } else if (FalseBlock == nullptr) {
Xinliang David Li241e6c72016-09-03 21:26:36 +00005327 TT = TrueBlock;
5328 FT = EndBlock;
Sanjay Patel69a50a12015-10-19 21:59:12 +00005329 FalseBlock = StartBlock;
5330 } else {
Xinliang David Li241e6c72016-09-03 21:26:36 +00005331 TT = TrueBlock;
5332 FT = FalseBlock;
Sanjay Patel69a50a12015-10-19 21:59:12 +00005333 }
Xinliang David Li241e6c72016-09-03 21:26:36 +00005334 IRBuilder<>(SI).CreateCondBr(SI->getCondition(), TT, FT, SI);
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005335
Dehao Chen9bbb9412016-09-12 20:23:28 +00005336 SmallPtrSet<const Instruction *, 2> INS;
5337 INS.insert(ASI.begin(), ASI.end());
5338 // Use reverse iterator because later select may use the value of the
5339 // earlier select, and we need to propagate value through earlier select
5340 // to get the PHI operand.
5341 for (auto It = ASI.rbegin(); It != ASI.rend(); ++It) {
5342 SelectInst *SI = *It;
5343 // The select itself is replaced with a PHI Node.
5344 PHINode *PN = PHINode::Create(SI->getType(), 2, "", &EndBlock->front());
5345 PN->takeName(SI);
5346 PN->addIncoming(getTrueOrFalseValue(SI, true, INS), TrueBlock);
5347 PN->addIncoming(getTrueOrFalseValue(SI, false, INS), FalseBlock);
Sanjay Patel69a50a12015-10-19 21:59:12 +00005348
Dehao Chen9bbb9412016-09-12 20:23:28 +00005349 SI->replaceAllUsesWith(PN);
5350 SI->eraseFromParent();
5351 INS.erase(SI);
5352 ++NumSelectsExpanded;
5353 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005354
5355 // Instruct OptimizeBlock to skip to the next block.
5356 CurInstIterator = StartBlock->end();
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005357 return true;
5358}
5359
Benjamin Kramer573ff362014-03-01 17:24:40 +00005360static bool isBroadcastShuffle(ShuffleVectorInst *SVI) {
Tim Northoveraeb8e062014-02-19 10:02:43 +00005361 SmallVector<int, 16> Mask(SVI->getShuffleMask());
5362 int SplatElem = -1;
5363 for (unsigned i = 0; i < Mask.size(); ++i) {
5364 if (SplatElem != -1 && Mask[i] != -1 && Mask[i] != SplatElem)
5365 return false;
5366 SplatElem = Mask[i];
5367 }
5368
5369 return true;
5370}
5371
5372/// Some targets have expensive vector shifts if the lanes aren't all the same
5373/// (e.g. x86 only introduced "vpsllvd" and friends with AVX2). In these cases
5374/// it's often worth sinking a shufflevector splat down to its use so that
5375/// codegen can spot all lanes are identical.
Sanjay Patelfc580a62015-09-21 23:03:16 +00005376bool CodeGenPrepare::optimizeShuffleVectorInst(ShuffleVectorInst *SVI) {
Tim Northoveraeb8e062014-02-19 10:02:43 +00005377 BasicBlock *DefBB = SVI->getParent();
5378
5379 // Only do this xform if variable vector shifts are particularly expensive.
5380 if (!TLI || !TLI->isVectorShiftByScalarCheap(SVI->getType()))
5381 return false;
5382
5383 // We only expect better codegen by sinking a shuffle if we can recognise a
5384 // constant splat.
5385 if (!isBroadcastShuffle(SVI))
5386 return false;
5387
5388 // InsertedShuffles - Only insert a shuffle in each block once.
5389 DenseMap<BasicBlock*, Instruction*> InsertedShuffles;
5390
5391 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00005392 for (User *U : SVI->users()) {
5393 Instruction *UI = cast<Instruction>(U);
Tim Northoveraeb8e062014-02-19 10:02:43 +00005394
5395 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00005396 BasicBlock *UserBB = UI->getParent();
Tim Northoveraeb8e062014-02-19 10:02:43 +00005397 if (UserBB == DefBB) continue;
5398
5399 // For now only apply this when the splat is used by a shift instruction.
Chandler Carruthcdf47882014-03-09 03:16:01 +00005400 if (!UI->isShift()) continue;
Tim Northoveraeb8e062014-02-19 10:02:43 +00005401
5402 // Everything checks out, sink the shuffle if the user's block doesn't
5403 // already have a copy.
5404 Instruction *&InsertedShuffle = InsertedShuffles[UserBB];
5405
5406 if (!InsertedShuffle) {
5407 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00005408 assert(InsertPt != UserBB->end());
5409 InsertedShuffle =
5410 new ShuffleVectorInst(SVI->getOperand(0), SVI->getOperand(1),
5411 SVI->getOperand(2), "", &*InsertPt);
Tim Northoveraeb8e062014-02-19 10:02:43 +00005412 }
5413
Chandler Carruthcdf47882014-03-09 03:16:01 +00005414 UI->replaceUsesOfWith(SVI, InsertedShuffle);
Tim Northoveraeb8e062014-02-19 10:02:43 +00005415 MadeChange = true;
5416 }
5417
5418 // If we removed all uses, nuke the shuffle.
5419 if (SVI->use_empty()) {
5420 SVI->eraseFromParent();
5421 MadeChange = true;
5422 }
5423
5424 return MadeChange;
5425}
5426
Sanjay Patel0ed9aea2015-11-02 23:22:49 +00005427bool CodeGenPrepare::optimizeSwitchInst(SwitchInst *SI) {
5428 if (!TLI || !DL)
5429 return false;
5430
5431 Value *Cond = SI->getCondition();
5432 Type *OldType = Cond->getType();
5433 LLVMContext &Context = Cond->getContext();
5434 MVT RegType = TLI->getRegisterType(Context, TLI->getValueType(*DL, OldType));
5435 unsigned RegWidth = RegType.getSizeInBits();
5436
5437 if (RegWidth <= cast<IntegerType>(OldType)->getBitWidth())
5438 return false;
5439
5440 // If the register width is greater than the type width, expand the condition
5441 // of the switch instruction and each case constant to the width of the
5442 // register. By widening the type of the switch condition, subsequent
5443 // comparisons (for case comparisons) will not need to be extended to the
5444 // preferred register width, so we will potentially eliminate N-1 extends,
5445 // where N is the number of cases in the switch.
5446 auto *NewType = Type::getIntNTy(Context, RegWidth);
5447
5448 // Zero-extend the switch condition and case constants unless the switch
5449 // condition is a function argument that is already being sign-extended.
5450 // In that case, we can avoid an unnecessary mask/extension by sign-extending
5451 // everything instead.
5452 Instruction::CastOps ExtType = Instruction::ZExt;
5453 if (auto *Arg = dyn_cast<Argument>(Cond))
5454 if (Arg->hasSExtAttr())
5455 ExtType = Instruction::SExt;
5456
5457 auto *ExtInst = CastInst::Create(ExtType, Cond, NewType);
5458 ExtInst->insertBefore(SI);
5459 SI->setCondition(ExtInst);
5460 for (SwitchInst::CaseIt Case : SI->cases()) {
5461 APInt NarrowConst = Case.getCaseValue()->getValue();
5462 APInt WideConst = (ExtType == Instruction::ZExt) ?
5463 NarrowConst.zext(RegWidth) : NarrowConst.sext(RegWidth);
5464 Case.setValue(ConstantInt::get(Context, WideConst));
5465 }
5466
5467 return true;
5468}
5469
Quentin Colombetc32615d2014-10-31 17:52:53 +00005470namespace {
5471/// \brief Helper class to promote a scalar operation to a vector one.
5472/// This class is used to move downward extractelement transition.
5473/// E.g.,
5474/// a = vector_op <2 x i32>
5475/// b = extractelement <2 x i32> a, i32 0
5476/// c = scalar_op b
5477/// store c
5478///
5479/// =>
5480/// a = vector_op <2 x i32>
5481/// c = vector_op a (equivalent to scalar_op on the related lane)
5482/// * d = extractelement <2 x i32> c, i32 0
5483/// * store d
5484/// Assuming both extractelement and store can be combine, we get rid of the
5485/// transition.
5486class VectorPromoteHelper {
Mehdi Amini44ede332015-07-09 02:09:04 +00005487 /// DataLayout associated with the current module.
5488 const DataLayout &DL;
5489
Quentin Colombetc32615d2014-10-31 17:52:53 +00005490 /// Used to perform some checks on the legality of vector operations.
5491 const TargetLowering &TLI;
5492
5493 /// Used to estimated the cost of the promoted chain.
5494 const TargetTransformInfo &TTI;
5495
5496 /// The transition being moved downwards.
5497 Instruction *Transition;
5498 /// The sequence of instructions to be promoted.
5499 SmallVector<Instruction *, 4> InstsToBePromoted;
5500 /// Cost of combining a store and an extract.
5501 unsigned StoreExtractCombineCost;
5502 /// Instruction that will be combined with the transition.
5503 Instruction *CombineInst;
5504
5505 /// \brief The instruction that represents the current end of the transition.
5506 /// Since we are faking the promotion until we reach the end of the chain
5507 /// of computation, we need a way to get the current end of the transition.
5508 Instruction *getEndOfTransition() const {
5509 if (InstsToBePromoted.empty())
5510 return Transition;
5511 return InstsToBePromoted.back();
5512 }
5513
5514 /// \brief Return the index of the original value in the transition.
5515 /// E.g., for "extractelement <2 x i32> c, i32 1" the original value,
5516 /// c, is at index 0.
5517 unsigned getTransitionOriginalValueIdx() const {
5518 assert(isa<ExtractElementInst>(Transition) &&
5519 "Other kind of transitions are not supported yet");
5520 return 0;
5521 }
5522
5523 /// \brief Return the index of the index in the transition.
5524 /// E.g., for "extractelement <2 x i32> c, i32 0" the index
5525 /// is at index 1.
5526 unsigned getTransitionIdx() const {
5527 assert(isa<ExtractElementInst>(Transition) &&
5528 "Other kind of transitions are not supported yet");
5529 return 1;
5530 }
5531
5532 /// \brief Get the type of the transition.
5533 /// This is the type of the original value.
5534 /// E.g., for "extractelement <2 x i32> c, i32 1" the type of the
5535 /// transition is <2 x i32>.
5536 Type *getTransitionType() const {
5537 return Transition->getOperand(getTransitionOriginalValueIdx())->getType();
5538 }
5539
5540 /// \brief Promote \p ToBePromoted by moving \p Def downward through.
5541 /// I.e., we have the following sequence:
5542 /// Def = Transition <ty1> a to <ty2>
5543 /// b = ToBePromoted <ty2> Def, ...
5544 /// =>
5545 /// b = ToBePromoted <ty1> a, ...
5546 /// Def = Transition <ty1> ToBePromoted to <ty2>
5547 void promoteImpl(Instruction *ToBePromoted);
5548
5549 /// \brief Check whether or not it is profitable to promote all the
5550 /// instructions enqueued to be promoted.
5551 bool isProfitableToPromote() {
5552 Value *ValIdx = Transition->getOperand(getTransitionOriginalValueIdx());
5553 unsigned Index = isa<ConstantInt>(ValIdx)
5554 ? cast<ConstantInt>(ValIdx)->getZExtValue()
5555 : -1;
5556 Type *PromotedType = getTransitionType();
5557
5558 StoreInst *ST = cast<StoreInst>(CombineInst);
5559 unsigned AS = ST->getPointerAddressSpace();
5560 unsigned Align = ST->getAlignment();
5561 // Check if this store is supported.
5562 if (!TLI.allowsMisalignedMemoryAccesses(
Mehdi Amini44ede332015-07-09 02:09:04 +00005563 TLI.getValueType(DL, ST->getValueOperand()->getType()), AS,
5564 Align)) {
Quentin Colombetc32615d2014-10-31 17:52:53 +00005565 // If this is not supported, there is no way we can combine
5566 // the extract with the store.
5567 return false;
5568 }
5569
5570 // The scalar chain of computation has to pay for the transition
5571 // scalar to vector.
5572 // The vector chain has to account for the combining cost.
5573 uint64_t ScalarCost =
5574 TTI.getVectorInstrCost(Transition->getOpcode(), PromotedType, Index);
5575 uint64_t VectorCost = StoreExtractCombineCost;
5576 for (const auto &Inst : InstsToBePromoted) {
5577 // Compute the cost.
5578 // By construction, all instructions being promoted are arithmetic ones.
5579 // Moreover, one argument is a constant that can be viewed as a splat
5580 // constant.
5581 Value *Arg0 = Inst->getOperand(0);
5582 bool IsArg0Constant = isa<UndefValue>(Arg0) || isa<ConstantInt>(Arg0) ||
5583 isa<ConstantFP>(Arg0);
5584 TargetTransformInfo::OperandValueKind Arg0OVK =
5585 IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
5586 : TargetTransformInfo::OK_AnyValue;
5587 TargetTransformInfo::OperandValueKind Arg1OVK =
5588 !IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
5589 : TargetTransformInfo::OK_AnyValue;
5590 ScalarCost += TTI.getArithmeticInstrCost(
5591 Inst->getOpcode(), Inst->getType(), Arg0OVK, Arg1OVK);
5592 VectorCost += TTI.getArithmeticInstrCost(Inst->getOpcode(), PromotedType,
5593 Arg0OVK, Arg1OVK);
5594 }
5595 DEBUG(dbgs() << "Estimated cost of computation to be promoted:\nScalar: "
5596 << ScalarCost << "\nVector: " << VectorCost << '\n');
5597 return ScalarCost > VectorCost;
5598 }
5599
5600 /// \brief Generate a constant vector with \p Val with the same
5601 /// number of elements as the transition.
5602 /// \p UseSplat defines whether or not \p Val should be replicated
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00005603 /// across the whole vector.
Quentin Colombetc32615d2014-10-31 17:52:53 +00005604 /// In other words, if UseSplat == true, we generate <Val, Val, ..., Val>,
5605 /// otherwise we generate a vector with as many undef as possible:
5606 /// <undef, ..., undef, Val, undef, ..., undef> where \p Val is only
5607 /// used at the index of the extract.
5608 Value *getConstantVector(Constant *Val, bool UseSplat) const {
5609 unsigned ExtractIdx = UINT_MAX;
5610 if (!UseSplat) {
5611 // If we cannot determine where the constant must be, we have to
5612 // use a splat constant.
5613 Value *ValExtractIdx = Transition->getOperand(getTransitionIdx());
5614 if (ConstantInt *CstVal = dyn_cast<ConstantInt>(ValExtractIdx))
5615 ExtractIdx = CstVal->getSExtValue();
5616 else
5617 UseSplat = true;
5618 }
5619
5620 unsigned End = getTransitionType()->getVectorNumElements();
5621 if (UseSplat)
5622 return ConstantVector::getSplat(End, Val);
5623
5624 SmallVector<Constant *, 4> ConstVec;
5625 UndefValue *UndefVal = UndefValue::get(Val->getType());
5626 for (unsigned Idx = 0; Idx != End; ++Idx) {
5627 if (Idx == ExtractIdx)
5628 ConstVec.push_back(Val);
5629 else
5630 ConstVec.push_back(UndefVal);
5631 }
5632 return ConstantVector::get(ConstVec);
5633 }
5634
5635 /// \brief Check if promoting to a vector type an operand at \p OperandIdx
5636 /// in \p Use can trigger undefined behavior.
5637 static bool canCauseUndefinedBehavior(const Instruction *Use,
5638 unsigned OperandIdx) {
5639 // This is not safe to introduce undef when the operand is on
5640 // the right hand side of a division-like instruction.
5641 if (OperandIdx != 1)
5642 return false;
5643 switch (Use->getOpcode()) {
5644 default:
5645 return false;
5646 case Instruction::SDiv:
5647 case Instruction::UDiv:
5648 case Instruction::SRem:
5649 case Instruction::URem:
5650 return true;
5651 case Instruction::FDiv:
5652 case Instruction::FRem:
5653 return !Use->hasNoNaNs();
5654 }
5655 llvm_unreachable(nullptr);
5656 }
5657
5658public:
Mehdi Amini44ede332015-07-09 02:09:04 +00005659 VectorPromoteHelper(const DataLayout &DL, const TargetLowering &TLI,
5660 const TargetTransformInfo &TTI, Instruction *Transition,
5661 unsigned CombineCost)
5662 : DL(DL), TLI(TLI), TTI(TTI), Transition(Transition),
Quentin Colombetc32615d2014-10-31 17:52:53 +00005663 StoreExtractCombineCost(CombineCost), CombineInst(nullptr) {
5664 assert(Transition && "Do not know how to promote null");
5665 }
5666
5667 /// \brief Check if we can promote \p ToBePromoted to \p Type.
5668 bool canPromote(const Instruction *ToBePromoted) const {
5669 // We could support CastInst too.
5670 return isa<BinaryOperator>(ToBePromoted);
5671 }
5672
5673 /// \brief Check if it is profitable to promote \p ToBePromoted
5674 /// by moving downward the transition through.
5675 bool shouldPromote(const Instruction *ToBePromoted) const {
5676 // Promote only if all the operands can be statically expanded.
5677 // Indeed, we do not want to introduce any new kind of transitions.
5678 for (const Use &U : ToBePromoted->operands()) {
5679 const Value *Val = U.get();
5680 if (Val == getEndOfTransition()) {
5681 // If the use is a division and the transition is on the rhs,
5682 // we cannot promote the operation, otherwise we may create a
5683 // division by zero.
5684 if (canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()))
5685 return false;
5686 continue;
5687 }
5688 if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) &&
5689 !isa<ConstantFP>(Val))
5690 return false;
5691 }
5692 // Check that the resulting operation is legal.
5693 int ISDOpcode = TLI.InstructionOpcodeToISD(ToBePromoted->getOpcode());
5694 if (!ISDOpcode)
5695 return false;
5696 return StressStoreExtract ||
Ahmed Bougacha026600d2014-11-12 23:05:03 +00005697 TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00005698 ISDOpcode, TLI.getValueType(DL, getTransitionType(), true));
Quentin Colombetc32615d2014-10-31 17:52:53 +00005699 }
5700
5701 /// \brief Check whether or not \p Use can be combined
5702 /// with the transition.
5703 /// I.e., is it possible to do Use(Transition) => AnotherUse?
5704 bool canCombine(const Instruction *Use) { return isa<StoreInst>(Use); }
5705
5706 /// \brief Record \p ToBePromoted as part of the chain to be promoted.
5707 void enqueueForPromotion(Instruction *ToBePromoted) {
5708 InstsToBePromoted.push_back(ToBePromoted);
5709 }
5710
5711 /// \brief Set the instruction that will be combined with the transition.
5712 void recordCombineInstruction(Instruction *ToBeCombined) {
5713 assert(canCombine(ToBeCombined) && "Unsupported instruction to combine");
5714 CombineInst = ToBeCombined;
5715 }
5716
5717 /// \brief Promote all the instructions enqueued for promotion if it is
5718 /// is profitable.
5719 /// \return True if the promotion happened, false otherwise.
5720 bool promote() {
5721 // Check if there is something to promote.
5722 // Right now, if we do not have anything to combine with,
5723 // we assume the promotion is not profitable.
5724 if (InstsToBePromoted.empty() || !CombineInst)
5725 return false;
5726
5727 // Check cost.
5728 if (!StressStoreExtract && !isProfitableToPromote())
5729 return false;
5730
5731 // Promote.
5732 for (auto &ToBePromoted : InstsToBePromoted)
5733 promoteImpl(ToBePromoted);
5734 InstsToBePromoted.clear();
5735 return true;
5736 }
5737};
5738} // End of anonymous namespace.
5739
5740void VectorPromoteHelper::promoteImpl(Instruction *ToBePromoted) {
5741 // At this point, we know that all the operands of ToBePromoted but Def
5742 // can be statically promoted.
5743 // For Def, we need to use its parameter in ToBePromoted:
5744 // b = ToBePromoted ty1 a
5745 // Def = Transition ty1 b to ty2
5746 // Move the transition down.
5747 // 1. Replace all uses of the promoted operation by the transition.
5748 // = ... b => = ... Def.
5749 assert(ToBePromoted->getType() == Transition->getType() &&
5750 "The type of the result of the transition does not match "
5751 "the final type");
5752 ToBePromoted->replaceAllUsesWith(Transition);
5753 // 2. Update the type of the uses.
5754 // b = ToBePromoted ty2 Def => b = ToBePromoted ty1 Def.
5755 Type *TransitionTy = getTransitionType();
5756 ToBePromoted->mutateType(TransitionTy);
5757 // 3. Update all the operands of the promoted operation with promoted
5758 // operands.
5759 // b = ToBePromoted ty1 Def => b = ToBePromoted ty1 a.
5760 for (Use &U : ToBePromoted->operands()) {
5761 Value *Val = U.get();
5762 Value *NewVal = nullptr;
5763 if (Val == Transition)
5764 NewVal = Transition->getOperand(getTransitionOriginalValueIdx());
5765 else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) ||
5766 isa<ConstantFP>(Val)) {
5767 // Use a splat constant if it is not safe to use undef.
5768 NewVal = getConstantVector(
5769 cast<Constant>(Val),
5770 isa<UndefValue>(Val) ||
5771 canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()));
5772 } else
Craig Topperd3c02f12015-01-05 10:15:49 +00005773 llvm_unreachable("Did you modified shouldPromote and forgot to update "
5774 "this?");
Quentin Colombetc32615d2014-10-31 17:52:53 +00005775 ToBePromoted->setOperand(U.getOperandNo(), NewVal);
5776 }
5777 Transition->removeFromParent();
5778 Transition->insertAfter(ToBePromoted);
5779 Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted);
5780}
5781
5782/// Some targets can do store(extractelement) with one instruction.
5783/// Try to push the extractelement towards the stores when the target
5784/// has this feature and this is profitable.
Sanjay Patelfc580a62015-09-21 23:03:16 +00005785bool CodeGenPrepare::optimizeExtractElementInst(Instruction *Inst) {
Quentin Colombetc32615d2014-10-31 17:52:53 +00005786 unsigned CombineCost = UINT_MAX;
5787 if (DisableStoreExtract || !TLI ||
5788 (!StressStoreExtract &&
5789 !TLI->canCombineStoreAndExtract(Inst->getOperand(0)->getType(),
5790 Inst->getOperand(1), CombineCost)))
5791 return false;
5792
5793 // At this point we know that Inst is a vector to scalar transition.
5794 // Try to move it down the def-use chain, until:
5795 // - We can combine the transition with its single use
5796 // => we got rid of the transition.
5797 // - We escape the current basic block
5798 // => we would need to check that we are moving it at a cheaper place and
5799 // we do not do that for now.
5800 BasicBlock *Parent = Inst->getParent();
5801 DEBUG(dbgs() << "Found an interesting transition: " << *Inst << '\n');
Mehdi Amini44ede332015-07-09 02:09:04 +00005802 VectorPromoteHelper VPH(*DL, *TLI, *TTI, Inst, CombineCost);
Quentin Colombetc32615d2014-10-31 17:52:53 +00005803 // If the transition has more than one use, assume this is not going to be
5804 // beneficial.
5805 while (Inst->hasOneUse()) {
5806 Instruction *ToBePromoted = cast<Instruction>(*Inst->user_begin());
5807 DEBUG(dbgs() << "Use: " << *ToBePromoted << '\n');
5808
5809 if (ToBePromoted->getParent() != Parent) {
5810 DEBUG(dbgs() << "Instruction to promote is in a different block ("
5811 << ToBePromoted->getParent()->getName()
5812 << ") than the transition (" << Parent->getName() << ").\n");
5813 return false;
5814 }
5815
5816 if (VPH.canCombine(ToBePromoted)) {
5817 DEBUG(dbgs() << "Assume " << *Inst << '\n'
5818 << "will be combined with: " << *ToBePromoted << '\n');
5819 VPH.recordCombineInstruction(ToBePromoted);
5820 bool Changed = VPH.promote();
5821 NumStoreExtractExposed += Changed;
5822 return Changed;
5823 }
5824
5825 DEBUG(dbgs() << "Try promoting.\n");
5826 if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted))
5827 return false;
5828
5829 DEBUG(dbgs() << "Promoting is possible... Enqueue for promotion!\n");
5830
5831 VPH.enqueueForPromotion(ToBePromoted);
5832 Inst = ToBePromoted;
5833 }
5834 return false;
5835}
5836
Wei Mia2f0b592016-12-22 19:44:45 +00005837/// For the instruction sequence of store below, F and I values
5838/// are bundled together as an i64 value before being stored into memory.
5839/// Sometimes it is more efficent to generate separate stores for F and I,
5840/// which can remove the bitwise instructions or sink them to colder places.
5841///
5842/// (store (or (zext (bitcast F to i32) to i64),
5843/// (shl (zext I to i64), 32)), addr) -->
5844/// (store F, addr) and (store I, addr+4)
5845///
5846/// Similarly, splitting for other merged store can also be beneficial, like:
5847/// For pair of {i32, i32}, i64 store --> two i32 stores.
5848/// For pair of {i32, i16}, i64 store --> two i32 stores.
5849/// For pair of {i16, i16}, i32 store --> two i16 stores.
5850/// For pair of {i16, i8}, i32 store --> two i16 stores.
5851/// For pair of {i8, i8}, i16 store --> two i8 stores.
5852///
5853/// We allow each target to determine specifically which kind of splitting is
5854/// supported.
5855///
5856/// The store patterns are commonly seen from the simple code snippet below
5857/// if only std::make_pair(...) is sroa transformed before inlined into hoo.
5858/// void goo(const std::pair<int, float> &);
5859/// hoo() {
5860/// ...
5861/// goo(std::make_pair(tmp, ftmp));
5862/// ...
5863/// }
5864///
5865/// Although we already have similar splitting in DAG Combine, we duplicate
5866/// it in CodeGenPrepare to catch the case in which pattern is across
5867/// multiple BBs. The logic in DAG Combine is kept to catch case generated
5868/// during code expansion.
5869static bool splitMergedValStore(StoreInst &SI, const DataLayout &DL,
5870 const TargetLowering &TLI) {
5871 // Handle simple but common cases only.
5872 Type *StoreType = SI.getValueOperand()->getType();
5873 if (DL.getTypeStoreSizeInBits(StoreType) != DL.getTypeSizeInBits(StoreType) ||
5874 DL.getTypeSizeInBits(StoreType) == 0)
5875 return false;
5876
5877 unsigned HalfValBitSize = DL.getTypeSizeInBits(StoreType) / 2;
5878 Type *SplitStoreType = Type::getIntNTy(SI.getContext(), HalfValBitSize);
5879 if (DL.getTypeStoreSizeInBits(SplitStoreType) !=
5880 DL.getTypeSizeInBits(SplitStoreType))
5881 return false;
5882
5883 // Match the following patterns:
5884 // (store (or (zext LValue to i64),
5885 // (shl (zext HValue to i64), 32)), HalfValBitSize)
5886 // or
5887 // (store (or (shl (zext HValue to i64), 32)), HalfValBitSize)
5888 // (zext LValue to i64),
5889 // Expect both operands of OR and the first operand of SHL have only
5890 // one use.
5891 Value *LValue, *HValue;
5892 if (!match(SI.getValueOperand(),
5893 m_c_Or(m_OneUse(m_ZExt(m_Value(LValue))),
5894 m_OneUse(m_Shl(m_OneUse(m_ZExt(m_Value(HValue))),
5895 m_SpecificInt(HalfValBitSize))))))
5896 return false;
5897
5898 // Check LValue and HValue are int with size less or equal than 32.
5899 if (!LValue->getType()->isIntegerTy() ||
5900 DL.getTypeSizeInBits(LValue->getType()) > HalfValBitSize ||
5901 !HValue->getType()->isIntegerTy() ||
5902 DL.getTypeSizeInBits(HValue->getType()) > HalfValBitSize)
5903 return false;
5904
5905 // If LValue/HValue is a bitcast instruction, use the EVT before bitcast
5906 // as the input of target query.
5907 auto *LBC = dyn_cast<BitCastInst>(LValue);
5908 auto *HBC = dyn_cast<BitCastInst>(HValue);
5909 EVT LowTy = LBC ? EVT::getEVT(LBC->getOperand(0)->getType())
5910 : EVT::getEVT(LValue->getType());
5911 EVT HighTy = HBC ? EVT::getEVT(HBC->getOperand(0)->getType())
5912 : EVT::getEVT(HValue->getType());
5913 if (!ForceSplitStore && !TLI.isMultiStoresCheaperThanBitsMerge(LowTy, HighTy))
5914 return false;
5915
5916 // Start to split store.
5917 IRBuilder<> Builder(SI.getContext());
5918 Builder.SetInsertPoint(&SI);
5919
5920 // If LValue/HValue is a bitcast in another BB, create a new one in current
5921 // BB so it may be merged with the splitted stores by dag combiner.
5922 if (LBC && LBC->getParent() != SI.getParent())
5923 LValue = Builder.CreateBitCast(LBC->getOperand(0), LBC->getType());
5924 if (HBC && HBC->getParent() != SI.getParent())
5925 HValue = Builder.CreateBitCast(HBC->getOperand(0), HBC->getType());
5926
5927 auto CreateSplitStore = [&](Value *V, bool Upper) {
5928 V = Builder.CreateZExtOrBitCast(V, SplitStoreType);
5929 Value *Addr = Builder.CreateBitCast(
5930 SI.getOperand(1),
5931 SplitStoreType->getPointerTo(SI.getPointerAddressSpace()));
5932 if (Upper)
5933 Addr = Builder.CreateGEP(
5934 SplitStoreType, Addr,
5935 ConstantInt::get(Type::getInt32Ty(SI.getContext()), 1));
5936 Builder.CreateAlignedStore(
5937 V, Addr, Upper ? SI.getAlignment() / 2 : SI.getAlignment());
5938 };
5939
5940 CreateSplitStore(LValue, false);
5941 CreateSplitStore(HValue, true);
5942
5943 // Delete the old store.
5944 SI.eraseFromParent();
5945 return true;
5946}
5947
Sanjay Patelfc580a62015-09-21 23:03:16 +00005948bool CodeGenPrepare::optimizeInst(Instruction *I, bool& ModifiedDT) {
Ahmed Bougachaf3299142015-06-17 20:44:32 +00005949 // Bail out if we inserted the instruction to prevent optimizations from
5950 // stepping on each other's toes.
5951 if (InsertedInsts.count(I))
5952 return false;
5953
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005954 if (PHINode *P = dyn_cast<PHINode>(I)) {
5955 // It is possible for very late stage optimizations (such as SimplifyCFG)
5956 // to introduce PHI nodes too late to be cleaned up. If we detect such a
5957 // trivial PHI, go ahead and zap it here.
Mehdi Amini4fe37982015-07-07 18:45:17 +00005958 if (Value *V = SimplifyInstruction(P, *DL, TLInfo, nullptr)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005959 P->replaceAllUsesWith(V);
5960 P->eraseFromParent();
5961 ++NumPHIsElim;
Chris Lattneree588de2011-01-15 07:29:01 +00005962 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005963 }
Chris Lattneree588de2011-01-15 07:29:01 +00005964 return false;
5965 }
Nadav Rotem465834c2012-07-24 10:51:42 +00005966
Chris Lattneree588de2011-01-15 07:29:01 +00005967 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005968 // If the source of the cast is a constant, then this should have
5969 // already been constant folded. The only reason NOT to constant fold
5970 // it is if something (e.g. LSR) was careful to place the constant
5971 // evaluation in a block other than then one that uses it (e.g. to hoist
5972 // the address of globals out of a loop). If this is the case, we don't
5973 // want to forward-subst the cast.
5974 if (isa<Constant>(CI->getOperand(0)))
5975 return false;
5976
Mehdi Amini44ede332015-07-09 02:09:04 +00005977 if (TLI && OptimizeNoopCopyExpression(CI, *TLI, *DL))
Chris Lattneree588de2011-01-15 07:29:01 +00005978 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005979
Chris Lattneree588de2011-01-15 07:29:01 +00005980 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +00005981 /// Sink a zext or sext into its user blocks if the target type doesn't
5982 /// fit in one register
Mehdi Amini44ede332015-07-09 02:09:04 +00005983 if (TLI &&
5984 TLI->getTypeAction(CI->getContext(),
5985 TLI->getValueType(*DL, CI->getType())) ==
5986 TargetLowering::TypeExpandInteger) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +00005987 return SinkCast(CI);
5988 } else {
Jun Bum Limdee55652017-04-03 19:20:07 +00005989 bool MadeChange = optimizeExt(I);
Sanjay Patelfc580a62015-09-21 23:03:16 +00005990 return MadeChange | optimizeExtUses(I);
Manuel Jacoba7c48f92014-03-13 13:36:25 +00005991 }
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005992 }
Chris Lattneree588de2011-01-15 07:29:01 +00005993 return false;
5994 }
Nadav Rotem465834c2012-07-24 10:51:42 +00005995
Chris Lattneree588de2011-01-15 07:29:01 +00005996 if (CmpInst *CI = dyn_cast<CmpInst>(I))
Hal Finkeldecb0242014-01-02 21:13:43 +00005997 if (!TLI || !TLI->hasMultipleConditionRegisters())
Peter Zotovf87e5502016-04-03 17:11:53 +00005998 return OptimizeCmpExpression(CI, TLI);
Nadav Rotem465834c2012-07-24 10:51:42 +00005999
Chris Lattneree588de2011-01-15 07:29:01 +00006000 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Sanjoy Das00757272016-12-16 20:29:39 +00006001 LI->setMetadata(LLVMContext::MD_invariant_group, nullptr);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00006002 if (TLI) {
Geoff Berry5256fca2015-11-20 22:34:39 +00006003 bool Modified = optimizeLoadExt(LI);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00006004 unsigned AS = LI->getPointerAddressSpace();
Geoff Berry5256fca2015-11-20 22:34:39 +00006005 Modified |= optimizeMemoryInst(I, I->getOperand(0), LI->getType(), AS);
6006 return Modified;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00006007 }
Hans Wennborgf3254832012-10-30 11:23:25 +00006008 return false;
Chris Lattneree588de2011-01-15 07:29:01 +00006009 }
Nadav Rotem465834c2012-07-24 10:51:42 +00006010
Chris Lattneree588de2011-01-15 07:29:01 +00006011 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Wei Mia2f0b592016-12-22 19:44:45 +00006012 if (TLI && splitMergedValStore(*SI, *DL, *TLI))
6013 return true;
Sanjoy Das00757272016-12-16 20:29:39 +00006014 SI->setMetadata(LLVMContext::MD_invariant_group, nullptr);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00006015 if (TLI) {
6016 unsigned AS = SI->getPointerAddressSpace();
Sanjay Patelfc580a62015-09-21 23:03:16 +00006017 return optimizeMemoryInst(I, SI->getOperand(1),
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00006018 SI->getOperand(0)->getType(), AS);
6019 }
Chris Lattneree588de2011-01-15 07:29:01 +00006020 return false;
6021 }
Nadav Rotem465834c2012-07-24 10:51:42 +00006022
Matt Arsenault02d915b2017-03-15 22:35:20 +00006023 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
6024 unsigned AS = RMW->getPointerAddressSpace();
6025 return optimizeMemoryInst(I, RMW->getPointerOperand(),
6026 RMW->getType(), AS);
6027 }
6028
6029 if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(I)) {
6030 unsigned AS = CmpX->getPointerAddressSpace();
6031 return optimizeMemoryInst(I, CmpX->getPointerOperand(),
6032 CmpX->getCompareOperand()->getType(), AS);
6033 }
6034
Yi Jiangd069f632014-04-21 19:34:27 +00006035 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I);
6036
Geoff Berry5d534b62017-02-21 18:53:14 +00006037 if (BinOp && (BinOp->getOpcode() == Instruction::And) &&
6038 EnableAndCmpSinking && TLI)
6039 return sinkAndCmp0Expression(BinOp, *TLI, InsertedInsts);
6040
Yi Jiangd069f632014-04-21 19:34:27 +00006041 if (BinOp && (BinOp->getOpcode() == Instruction::AShr ||
6042 BinOp->getOpcode() == Instruction::LShr)) {
6043 ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1));
6044 if (TLI && CI && TLI->hasExtractBitsInsn())
Mehdi Amini44ede332015-07-09 02:09:04 +00006045 return OptimizeExtractBits(BinOp, CI, *TLI, *DL);
Yi Jiangd069f632014-04-21 19:34:27 +00006046
6047 return false;
6048 }
6049
Chris Lattneree588de2011-01-15 07:29:01 +00006050 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00006051 if (GEPI->hasAllZeroIndices()) {
6052 /// The GEP operand must be a pointer, so must its result -> BitCast
6053 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
6054 GEPI->getName(), GEPI);
6055 GEPI->replaceAllUsesWith(NC);
6056 GEPI->eraseFromParent();
6057 ++NumGEPsElim;
Sanjay Patelfc580a62015-09-21 23:03:16 +00006058 optimizeInst(NC, ModifiedDT);
Chris Lattneree588de2011-01-15 07:29:01 +00006059 return true;
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00006060 }
Chris Lattneree588de2011-01-15 07:29:01 +00006061 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006062 }
Nadav Rotem465834c2012-07-24 10:51:42 +00006063
Chris Lattneree588de2011-01-15 07:29:01 +00006064 if (CallInst *CI = dyn_cast<CallInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00006065 return optimizeCallInst(CI, ModifiedDT);
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006066
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00006067 if (SelectInst *SI = dyn_cast<SelectInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00006068 return optimizeSelectInst(SI);
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00006069
Tim Northoveraeb8e062014-02-19 10:02:43 +00006070 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00006071 return optimizeShuffleVectorInst(SVI);
Tim Northoveraeb8e062014-02-19 10:02:43 +00006072
Sanjay Patel0ed9aea2015-11-02 23:22:49 +00006073 if (auto *Switch = dyn_cast<SwitchInst>(I))
6074 return optimizeSwitchInst(Switch);
6075
Quentin Colombetc32615d2014-10-31 17:52:53 +00006076 if (isa<ExtractElementInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00006077 return optimizeExtractElementInst(I);
Quentin Colombetc32615d2014-10-31 17:52:53 +00006078
Chris Lattneree588de2011-01-15 07:29:01 +00006079 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006080}
6081
James Molloyf01488e2016-01-15 09:20:19 +00006082/// Given an OR instruction, check to see if this is a bitreverse
6083/// idiom. If so, insert the new intrinsic and return true.
6084static bool makeBitReverse(Instruction &I, const DataLayout &DL,
6085 const TargetLowering &TLI) {
6086 if (!I.getType()->isIntegerTy() ||
6087 !TLI.isOperationLegalOrCustom(ISD::BITREVERSE,
6088 TLI.getValueType(DL, I.getType(), true)))
6089 return false;
6090
6091 SmallVector<Instruction*, 4> Insts;
Chad Rosiera00df492016-05-25 16:22:14 +00006092 if (!recognizeBSwapOrBitReverseIdiom(&I, false, true, Insts))
James Molloyf01488e2016-01-15 09:20:19 +00006093 return false;
6094 Instruction *LastInst = Insts.back();
6095 I.replaceAllUsesWith(LastInst);
6096 RecursivelyDeleteTriviallyDeadInstructions(&I);
6097 return true;
6098}
6099
Chris Lattnerf2836d12007-03-31 04:06:36 +00006100// In this pass we look for GEP and cast instructions that are used
6101// across basic blocks and rewrite them to improve basic-block-at-a-time
6102// selection.
Sanjay Patelfc580a62015-09-21 23:03:16 +00006103bool CodeGenPrepare::optimizeBlock(BasicBlock &BB, bool& ModifiedDT) {
Cameron Zwarichce3b9302011-01-06 00:42:50 +00006104 SunkAddrs.clear();
Cameron Zwarich5dd2aa22011-03-02 03:31:46 +00006105 bool MadeChange = false;
Eric Christopherc1ea1492008-09-24 05:32:41 +00006106
Chris Lattner7a277142011-01-15 07:14:54 +00006107 CurInstIterator = BB.begin();
Elena Demikhovsky87700a72014-12-28 08:54:45 +00006108 while (CurInstIterator != BB.end()) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00006109 MadeChange |= optimizeInst(&*CurInstIterator++, ModifiedDT);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00006110 if (ModifiedDT)
6111 return true;
6112 }
Benjamin Kramer455fa352012-11-23 19:17:06 +00006113
James Molloyf01488e2016-01-15 09:20:19 +00006114 bool MadeBitReverse = true;
6115 while (TLI && MadeBitReverse) {
6116 MadeBitReverse = false;
6117 for (auto &I : reverse(BB)) {
6118 if (makeBitReverse(I, *DL, *TLI)) {
6119 MadeBitReverse = MadeChange = true;
George Burgess IVd4febd12016-03-22 21:25:08 +00006120 ModifiedDT = true;
James Molloyf01488e2016-01-15 09:20:19 +00006121 break;
6122 }
6123 }
6124 }
James Molloy3ef84c42016-01-15 10:36:01 +00006125 MadeChange |= dupRetToEnableTailCallOpts(&BB);
Junmo Park7d6c5f12016-01-28 09:42:39 +00006126
Chris Lattnerf2836d12007-03-31 04:06:36 +00006127 return MadeChange;
6128}
Devang Patel53771ba2011-08-18 00:50:51 +00006129
6130// llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotem465834c2012-07-24 10:51:42 +00006131// handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patel53771ba2011-08-18 00:50:51 +00006132// find a node corresponding to the value.
Sanjay Patelfc580a62015-09-21 23:03:16 +00006133bool CodeGenPrepare::placeDbgValues(Function &F) {
Devang Patel53771ba2011-08-18 00:50:51 +00006134 bool MadeChange = false;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +00006135 for (BasicBlock &BB : F) {
Craig Topperc0196b12014-04-14 00:51:57 +00006136 Instruction *PrevNonDbgInst = nullptr;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +00006137 for (BasicBlock::iterator BI = BB.begin(), BE = BB.end(); BI != BE;) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00006138 Instruction *Insn = &*BI++;
Devang Patel53771ba2011-08-18 00:50:51 +00006139 DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
Adrian Prantl32da8892014-04-25 20:49:25 +00006140 // Leave dbg.values that refer to an alloca alone. These
6141 // instrinsics describe the address of a variable (= the alloca)
6142 // being taken. They should not be moved next to the alloca
6143 // (and to the beginning of the scope), but rather stay close to
6144 // where said address is used.
6145 if (!DVI || (DVI->getValue() && isa<AllocaInst>(DVI->getValue()))) {
Devang Patel53771ba2011-08-18 00:50:51 +00006146 PrevNonDbgInst = Insn;
6147 continue;
6148 }
6149
6150 Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
6151 if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
Reid Kleckner8de1fe22015-12-08 23:00:03 +00006152 // If VI is a phi in a block with an EHPad terminator, we can't insert
6153 // after it.
6154 if (isa<PHINode>(VI) && VI->getParent()->getTerminator()->isEHPad())
6155 continue;
Devang Patel53771ba2011-08-18 00:50:51 +00006156 DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
6157 DVI->removeFromParent();
Reid Klecknere18f92b2015-12-08 22:33:23 +00006158 if (isa<PHINode>(VI))
6159 DVI->insertBefore(&*VI->getParent()->getFirstInsertionPt());
6160 else
6161 DVI->insertAfter(VI);
Devang Patel53771ba2011-08-18 00:50:51 +00006162 MadeChange = true;
6163 ++NumDbgValueMoved;
6164 }
6165 }
6166 }
6167 return MadeChange;
6168}
Tim Northovercea0abb2014-03-29 08:22:29 +00006169
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006170/// \brief Scale down both weights to fit into uint32_t.
6171static void scaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) {
6172 uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
6173 uint32_t Scale = (NewMax / UINT32_MAX) + 1;
6174 NewTrue = NewTrue / Scale;
6175 NewFalse = NewFalse / Scale;
6176}
6177
6178/// \brief Some targets prefer to split a conditional branch like:
6179/// \code
6180/// %0 = icmp ne i32 %a, 0
6181/// %1 = icmp ne i32 %b, 0
6182/// %or.cond = or i1 %0, %1
6183/// br i1 %or.cond, label %TrueBB, label %FalseBB
6184/// \endcode
6185/// into multiple branch instructions like:
6186/// \code
6187/// bb1:
6188/// %0 = icmp ne i32 %a, 0
6189/// br i1 %0, label %TrueBB, label %bb2
6190/// bb2:
6191/// %1 = icmp ne i32 %b, 0
6192/// br i1 %1, label %TrueBB, label %FalseBB
6193/// \endcode
6194/// This usually allows instruction selection to do even further optimizations
6195/// and combine the compare with the branch instruction. Currently this is
6196/// applied for targets which have "cheap" jump instructions.
6197///
6198/// FIXME: Remove the (equivalent?) implementation in SelectionDAG.
6199///
6200bool CodeGenPrepare::splitBranchCondition(Function &F) {
David Blaikiedc3f01e2015-03-09 01:57:13 +00006201 if (!TM || !TM->Options.EnableFastISel || !TLI || TLI->isJumpExpensive())
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006202 return false;
6203
6204 bool MadeChange = false;
6205 for (auto &BB : F) {
6206 // Does this BB end with the following?
6207 // %cond1 = icmp|fcmp|binary instruction ...
6208 // %cond2 = icmp|fcmp|binary instruction ...
6209 // %cond.or = or|and i1 %cond1, cond2
6210 // br i1 %cond.or label %dest1, label %dest2"
6211 BinaryOperator *LogicOp;
6212 BasicBlock *TBB, *FBB;
6213 if (!match(BB.getTerminator(), m_Br(m_OneUse(m_BinOp(LogicOp)), TBB, FBB)))
6214 continue;
6215
Sanjay Patel42574202015-09-02 19:23:23 +00006216 auto *Br1 = cast<BranchInst>(BB.getTerminator());
6217 if (Br1->getMetadata(LLVMContext::MD_unpredictable))
6218 continue;
6219
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006220 unsigned Opc;
Juergen Ributzka8bda7382014-12-09 17:50:10 +00006221 Value *Cond1, *Cond2;
6222 if (match(LogicOp, m_And(m_OneUse(m_Value(Cond1)),
6223 m_OneUse(m_Value(Cond2)))))
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006224 Opc = Instruction::And;
Juergen Ributzka8bda7382014-12-09 17:50:10 +00006225 else if (match(LogicOp, m_Or(m_OneUse(m_Value(Cond1)),
6226 m_OneUse(m_Value(Cond2)))))
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006227 Opc = Instruction::Or;
6228 else
6229 continue;
6230
6231 if (!match(Cond1, m_CombineOr(m_Cmp(), m_BinOp())) ||
6232 !match(Cond2, m_CombineOr(m_Cmp(), m_BinOp())) )
6233 continue;
6234
6235 DEBUG(dbgs() << "Before branch condition splitting\n"; BB.dump());
6236
6237 // Create a new BB.
Duncan P. N. Exon Smitha848c472016-02-21 19:52:15 +00006238 auto TmpBB =
6239 BasicBlock::Create(BB.getContext(), BB.getName() + ".cond.split",
6240 BB.getParent(), BB.getNextNode());
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006241
6242 // Update original basic block by using the first condition directly by the
6243 // branch instruction and removing the no longer needed and/or instruction.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006244 Br1->setCondition(Cond1);
6245 LogicOp->eraseFromParent();
Juergen Ributzka8bda7382014-12-09 17:50:10 +00006246
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006247 // Depending on the conditon we have to either replace the true or the false
6248 // successor of the original branch instruction.
6249 if (Opc == Instruction::And)
6250 Br1->setSuccessor(0, TmpBB);
6251 else
6252 Br1->setSuccessor(1, TmpBB);
6253
6254 // Fill in the new basic block.
6255 auto *Br2 = IRBuilder<>(TmpBB).CreateCondBr(Cond2, TBB, FBB);
Juergen Ributzka8bda7382014-12-09 17:50:10 +00006256 if (auto *I = dyn_cast<Instruction>(Cond2)) {
6257 I->removeFromParent();
6258 I->insertBefore(Br2);
6259 }
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006260
6261 // Update PHI nodes in both successors. The original BB needs to be
6262 // replaced in one succesor's PHI nodes, because the branch comes now from
6263 // the newly generated BB (NewBB). In the other successor we need to add one
6264 // incoming edge to the PHI nodes, because both branch instructions target
6265 // now the same successor. Depending on the original branch condition
6266 // (and/or) we have to swap the successors (TrueDest, FalseDest), so that
Simon Pilgrimf2fbf432016-11-20 13:47:59 +00006267 // we perform the correct update for the PHI nodes.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006268 // This doesn't change the successor order of the just created branch
6269 // instruction (or any other instruction).
6270 if (Opc == Instruction::Or)
6271 std::swap(TBB, FBB);
6272
6273 // Replace the old BB with the new BB.
6274 for (auto &I : *TBB) {
6275 PHINode *PN = dyn_cast<PHINode>(&I);
6276 if (!PN)
6277 break;
6278 int i;
6279 while ((i = PN->getBasicBlockIndex(&BB)) >= 0)
6280 PN->setIncomingBlock(i, TmpBB);
6281 }
6282
6283 // Add another incoming edge form the new BB.
6284 for (auto &I : *FBB) {
6285 PHINode *PN = dyn_cast<PHINode>(&I);
6286 if (!PN)
6287 break;
6288 auto *Val = PN->getIncomingValueForBlock(&BB);
6289 PN->addIncoming(Val, TmpBB);
6290 }
6291
6292 // Update the branch weights (from SelectionDAGBuilder::
6293 // FindMergedConditions).
6294 if (Opc == Instruction::Or) {
6295 // Codegen X | Y as:
6296 // BB1:
6297 // jmp_if_X TBB
6298 // jmp TmpBB
6299 // TmpBB:
6300 // jmp_if_Y TBB
6301 // jmp FBB
6302 //
6303
6304 // We have flexibility in setting Prob for BB1 and Prob for NewBB.
6305 // The requirement is that
6306 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
6307 // = TrueProb for orignal BB.
6308 // Assuming the orignal weights are A and B, one choice is to set BB1's
6309 // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice
6310 // assumes that
6311 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
6312 // Another choice is to assume TrueProb for BB1 equals to TrueProb for
6313 // TmpBB, but the math is more complicated.
6314 uint64_t TrueWeight, FalseWeight;
Sanjay Pateldc88bd62016-04-23 20:01:22 +00006315 if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) {
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006316 uint64_t NewTrueWeight = TrueWeight;
6317 uint64_t NewFalseWeight = TrueWeight + 2 * FalseWeight;
6318 scaleWeights(NewTrueWeight, NewFalseWeight);
6319 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
6320 .createBranchWeights(TrueWeight, FalseWeight));
6321
6322 NewTrueWeight = TrueWeight;
6323 NewFalseWeight = 2 * FalseWeight;
6324 scaleWeights(NewTrueWeight, NewFalseWeight);
6325 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
6326 .createBranchWeights(TrueWeight, FalseWeight));
6327 }
6328 } else {
6329 // Codegen X & Y as:
6330 // BB1:
6331 // jmp_if_X TmpBB
6332 // jmp FBB
6333 // TmpBB:
6334 // jmp_if_Y TBB
6335 // jmp FBB
6336 //
6337 // This requires creation of TmpBB after CurBB.
6338
6339 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
6340 // The requirement is that
6341 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
6342 // = FalseProb for orignal BB.
6343 // Assuming the orignal weights are A and B, one choice is to set BB1's
6344 // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice
6345 // assumes that
6346 // FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB.
6347 uint64_t TrueWeight, FalseWeight;
Sanjay Pateldc88bd62016-04-23 20:01:22 +00006348 if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) {
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006349 uint64_t NewTrueWeight = 2 * TrueWeight + FalseWeight;
6350 uint64_t NewFalseWeight = FalseWeight;
6351 scaleWeights(NewTrueWeight, NewFalseWeight);
6352 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
6353 .createBranchWeights(TrueWeight, FalseWeight));
6354
6355 NewTrueWeight = 2 * TrueWeight;
6356 NewFalseWeight = FalseWeight;
6357 scaleWeights(NewTrueWeight, NewFalseWeight);
6358 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
6359 .createBranchWeights(TrueWeight, FalseWeight));
6360 }
6361 }
6362
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006363 // Note: No point in getting fancy here, since the DT info is never
Quentin Colombet7bdd50d2015-03-18 23:17:28 +00006364 // available to CodeGenPrepare.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006365 ModifiedDT = true;
6366
6367 MadeChange = true;
6368
6369 DEBUG(dbgs() << "After branch condition splitting\n"; BB.dump();
6370 TmpBB->dump());
6371 }
6372 return MadeChange;
6373}