blob: 85c6787cd55e424e477a60f3e6917263fb07cdeb [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
Chandler Carruthed0881b2012-12-03 16:50:05 +000016#include "llvm/ADT/DenseMap.h"
Michael Kuperstein13bf8a22017-02-28 00:11:34 +000017#include "llvm/ADT/SetVector.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000018#include "llvm/ADT/SmallSet.h"
19#include "llvm/ADT/Statistic.h"
Jun Bum Lim90b6b502016-12-16 20:38:39 +000020#include "llvm/Analysis/BlockFrequencyInfo.h"
21#include "llvm/Analysis/BranchProbabilityInfo.h"
Michael Kuperstein13bf8a22017-02-28 00:11:34 +000022#include "llvm/Analysis/CFG.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000023#include "llvm/Analysis/InstructionSimplify.h"
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +000024#include "llvm/Analysis/LoopInfo.h"
Zaara Syeda3a7578c2017-05-31 17:12:38 +000025#include "llvm/Analysis/MemoryBuiltins.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"
Michael Kupersteinf79af6f2016-09-08 00:48:37 +000030#include "llvm/CodeGen/Analysis.h"
Zaara Syeda3a7578c2017-05-31 17:12:38 +000031#include "llvm/CodeGen/Passes.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000032#include "llvm/CodeGen/TargetPassConfig.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000033#include "llvm/IR/CallSite.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000034#include "llvm/IR/Constants.h"
35#include "llvm/IR/DataLayout.h"
36#include "llvm/IR/DerivedTypes.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000037#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000038#include "llvm/IR/Function.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000039#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000040#include "llvm/IR/IRBuilder.h"
41#include "llvm/IR/InlineAsm.h"
42#include "llvm/IR/Instructions.h"
43#include "llvm/IR/IntrinsicInst.h"
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +000044#include "llvm/IR/MDBuilder.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000045#include "llvm/IR/PatternMatch.h"
Ramkumar Ramachandradba73292015-01-14 23:27:07 +000046#include "llvm/IR/Statepoint.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +000047#include "llvm/IR/ValueHandle.h"
Chandler Carrutha4ea2692014-03-04 11:26:31 +000048#include "llvm/IR/ValueMap.h"
Chris Lattnerf2836d12007-03-31 04:06:36 +000049#include "llvm/Pass.h"
Sanjay Pateld66607b2016-04-26 17:11:17 +000050#include "llvm/Support/BranchProbability.h"
Evan Cheng8b637b12010-08-17 01:34:49 +000051#include "llvm/Support/CommandLine.h"
Evan Chengd3d80172007-12-05 23:58:20 +000052#include "llvm/Support/Debug.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000053#include "llvm/Support/raw_ostream.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000054#include "llvm/Target/TargetLowering.h"
Hal Finkelc3998302014-04-12 00:59:48 +000055#include "llvm/Target/TargetSubtargetInfo.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000056#include "llvm/Transforms/Utils/BasicBlockUtils.h"
57#include "llvm/Transforms/Utils/BuildLibCalls.h"
Preston Gurdcdf540d2012-09-04 18:22:17 +000058#include "llvm/Transforms/Utils/BypassSlowDivision.h"
Michael Kuperstein13bf8a22017-02-28 00:11:34 +000059#include "llvm/Transforms/Utils/Cloning.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000060#include "llvm/Transforms/Utils/Local.h"
Ahmed Bougachae03bef72015-01-12 17:22:43 +000061#include "llvm/Transforms/Utils/SimplifyLibCalls.h"
Michael Kuperstein13bf8a22017-02-28 00:11:34 +000062#include "llvm/Transforms/Utils/ValueMapper.h"
Zaara Syeda3a7578c2017-05-31 17:12:38 +000063
Chris Lattnerf2836d12007-03-31 04:06:36 +000064using namespace llvm;
Chris Lattnerd616ef52008-11-25 04:42:10 +000065using namespace llvm::PatternMatch;
Chris Lattnerf2836d12007-03-31 04:06:36 +000066
Chandler Carruth1b9dde02014-04-22 02:02:50 +000067#define DEBUG_TYPE "codegenprepare"
68
Cameron Zwarichced753f2011-01-05 17:27:27 +000069STATISTIC(NumBlocksElim, "Number of blocks eliminated");
Evan Cheng0663f232011-03-21 01:19:09 +000070STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated");
71STATISTIC(NumGEPsElim, "Number of GEPs converted to casts");
Cameron Zwarichced753f2011-01-05 17:27:27 +000072STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "
73 "sunken Cmps");
74STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
75 "of sunken Casts");
76STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "
77 "computations were sunk");
Evan Cheng0663f232011-03-21 01:19:09 +000078STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads");
79STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized");
Geoff Berry5256fca2015-11-20 22:34:39 +000080STATISTIC(NumAndsAdded,
81 "Number of and mask instructions added to form ext loads");
82STATISTIC(NumAndUses, "Number of uses of and mask instructions optimized");
Evan Cheng0663f232011-03-21 01:19:09 +000083STATISTIC(NumRetsDup, "Number of return instructions duplicated");
Devang Patel53771ba2011-08-18 00:50:51 +000084STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved");
Benjamin Kramer047d7ca2012-05-05 12:49:22 +000085STATISTIC(NumSelectsExpanded, "Number of selects turned into branches");
Quentin Colombetc32615d2014-10-31 17:52:53 +000086STATISTIC(NumStoreExtractExposed, "Number of store(extractelement) exposed");
Jakob Stoklund Oleseneb12f492010-09-30 20:51:52 +000087
Zaara Syeda3a7578c2017-05-31 17:12:38 +000088STATISTIC(NumMemCmpCalls, "Number of memcmp calls");
89STATISTIC(NumMemCmpNotConstant, "Number of memcmp calls without constant size");
90STATISTIC(NumMemCmpGreaterThanMax,
91 "Number of memcmp calls with size greater than max size");
92STATISTIC(NumMemCmpInlined, "Number of inlined memcmp calls");
93
Cameron Zwarich338d3622011-03-11 21:52:04 +000094static cl::opt<bool> DisableBranchOpts(
95 "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
96 cl::desc("Disable branch optimizations in CodeGenPrepare"));
97
Ramkumar Ramachandradba73292015-01-14 23:27:07 +000098static cl::opt<bool>
99 DisableGCOpts("disable-cgp-gc-opts", cl::Hidden, cl::init(false),
100 cl::desc("Disable GC optimizations in CodeGenPrepare"));
101
Benjamin Kramer3d38c172012-05-06 14:25:16 +0000102static cl::opt<bool> DisableSelectToBranch(
103 "disable-cgp-select2branch", cl::Hidden, cl::init(false),
104 cl::desc("Disable select to branch conversion."));
Benjamin Kramer047d7ca2012-05-05 12:49:22 +0000105
Hal Finkelc3998302014-04-12 00:59:48 +0000106static cl::opt<bool> AddrSinkUsingGEPs(
Eli Friedman5fba1e52017-04-06 22:42:18 +0000107 "addr-sink-using-gep", cl::Hidden, cl::init(true),
Hal Finkelc3998302014-04-12 00:59:48 +0000108 cl::desc("Address sinking in CGP using GEPs."));
109
Tim Northovercea0abb2014-03-29 08:22:29 +0000110static cl::opt<bool> EnableAndCmpSinking(
111 "enable-andcmp-sinking", cl::Hidden, cl::init(true),
112 cl::desc("Enable sinkinig and/cmp into branches."));
113
Quentin Colombetc32615d2014-10-31 17:52:53 +0000114static cl::opt<bool> DisableStoreExtract(
115 "disable-cgp-store-extract", cl::Hidden, cl::init(false),
116 cl::desc("Disable store(extract) optimizations in CodeGenPrepare"));
117
118static cl::opt<bool> StressStoreExtract(
119 "stress-cgp-store-extract", cl::Hidden, cl::init(false),
120 cl::desc("Stress test store(extract) optimizations in CodeGenPrepare"));
121
Quentin Colombetfc2201e2014-12-17 01:36:17 +0000122static cl::opt<bool> DisableExtLdPromotion(
123 "disable-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
124 cl::desc("Disable ext(promotable(ld)) -> promoted(ext(ld)) optimization in "
125 "CodeGenPrepare"));
126
127static cl::opt<bool> StressExtLdPromotion(
128 "stress-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
129 cl::desc("Stress test ext(promotable(ld)) -> promoted(ext(ld)) "
130 "optimization in CodeGenPrepare"));
131
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000132static cl::opt<bool> DisablePreheaderProtect(
133 "disable-preheader-prot", cl::Hidden, cl::init(false),
134 cl::desc("Disable protection against removing loop preheaders"));
135
Dehao Chen302b69c2016-10-18 20:42:47 +0000136static cl::opt<bool> ProfileGuidedSectionPrefix(
137 "profile-guided-section-prefix", cl::Hidden, cl::init(true),
138 cl::desc("Use profile info to add section prefix for hot/cold functions"));
139
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000140static cl::opt<unsigned> FreqRatioToSkipMerge(
141 "cgp-freq-ratio-to-skip-merge", cl::Hidden, cl::init(2),
142 cl::desc("Skip merging empty blocks if (frequency of empty block) / "
143 "(frequency of destination block) is greater than this ratio"));
144
Wei Mia2f0b592016-12-22 19:44:45 +0000145static cl::opt<bool> ForceSplitStore(
146 "force-split-store", cl::Hidden, cl::init(false),
147 cl::desc("Force store splitting no matter what the target query says."));
148
Jun Bum Limdee55652017-04-03 19:20:07 +0000149static cl::opt<bool>
150EnableTypePromotionMerge("cgp-type-promotion-merge", cl::Hidden,
151 cl::desc("Enable merging of redundant sexts when one is dominating"
152 " the other."), cl::init(true));
153
Zaara Syeda3a7578c2017-05-31 17:12:38 +0000154static cl::opt<unsigned> MemCmpNumLoadsPerBlock(
155 "memcmp-num-loads-per-block", cl::Hidden, cl::init(1),
156 cl::desc("The number of loads per basic block for inline expansion of "
157 "memcmp that is only being compared against zero."));
158
Eric Christopherc1ea1492008-09-24 05:32:41 +0000159namespace {
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000160typedef SmallPtrSet<Instruction *, 16> SetOfInstrs;
Benjamin Kramer4cd5faa2015-07-31 17:00:39 +0000161typedef PointerIntPair<Type *, 1, bool> TypeIsSExt;
Quentin Colombetf5485bb2014-11-13 01:44:51 +0000162typedef DenseMap<Instruction *, TypeIsSExt> InstrToOrigTy;
Jun Bum Limdee55652017-04-03 19:20:07 +0000163typedef SmallVector<Instruction *, 16> SExts;
164typedef DenseMap<Value *, SExts> ValueToSExts;
Quentin Colombetfc2201e2014-12-17 01:36:17 +0000165class TypePromotionTransaction;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000166
Chris Lattner2dd09db2009-09-02 06:11:42 +0000167 class CodeGenPrepare : public FunctionPass {
Bill Wendling7a639ea2013-06-19 21:07:11 +0000168 const TargetMachine *TM;
Igor Laevsky3be81ba2017-02-07 13:27:20 +0000169 const TargetSubtargetInfo *SubtargetInfo;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000170 const TargetLowering *TLI;
Igor Laevsky3be81ba2017-02-07 13:27:20 +0000171 const TargetRegisterInfo *TRI;
Quentin Colombetc32615d2014-10-31 17:52:53 +0000172 const TargetTransformInfo *TTI;
Chad Rosierc24b86f2011-12-01 03:08:23 +0000173 const TargetLibraryInfo *TLInfo;
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000174 const LoopInfo *LI;
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000175 std::unique_ptr<BlockFrequencyInfo> BFI;
176 std::unique_ptr<BranchProbabilityInfo> BPI;
Nadav Rotem465834c2012-07-24 10:51:42 +0000177
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000178 /// As we scan instructions optimizing them, this is the next instruction
179 /// to optimize. Transforms that can invalidate this should update it.
Chris Lattner7a277142011-01-15 07:14:54 +0000180 BasicBlock::iterator CurInstIterator;
Evan Cheng3b3de7c2008-12-19 18:03:11 +0000181
Evan Cheng0663f232011-03-21 01:19:09 +0000182 /// Keeps track of non-local addresses that have been sunk into a block.
183 /// This allows us to avoid inserting duplicate code for blocks with
184 /// multiple load/stores of the same address.
Nick Lewycky5fb19632013-05-08 09:00:10 +0000185 ValueMap<Value*, Value*> SunkAddrs;
Cameron Zwarichce3b9302011-01-06 00:42:50 +0000186
Ahmed Bougachaf3299142015-06-17 20:44:32 +0000187 /// Keeps track of all instructions inserted for the current function.
188 SetOfInstrs InsertedInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000189 /// Keeps track of the type of the related instruction before their
190 /// promotion for the current function.
191 InstrToOrigTy PromotedInsts;
192
Jun Bum Limdee55652017-04-03 19:20:07 +0000193 /// Keep track of instructions removed during promotion.
194 SetOfInstrs RemovedInsts;
195
196 /// Keep track of sext chains based on their initial value.
197 DenseMap<Value *, Instruction *> SeenChainsForSExt;
198
199 /// Keep track of SExt promoted.
200 ValueToSExts ValToSExtendedUses;
201
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000202 /// True if CFG is modified in any way.
Devang Patel8f606d72011-03-24 15:35:25 +0000203 bool ModifiedDT;
Evan Cheng0663f232011-03-21 01:19:09 +0000204
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000205 /// True if optimizing for size.
Benjamin Kramer047d7ca2012-05-05 12:49:22 +0000206 bool OptSize;
207
Mehdi Amini4fe37982015-07-07 18:45:17 +0000208 /// DataLayout for the Function being processed.
209 const DataLayout *DL;
210
Chris Lattnerf2836d12007-03-31 04:06:36 +0000211 public:
Nick Lewyckye7da2d62007-05-06 13:37:16 +0000212 static char ID; // Pass identification, replacement for typeid
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000213 CodeGenPrepare()
214 : FunctionPass(ID), TM(nullptr), TLI(nullptr), TTI(nullptr),
215 DL(nullptr) {
216 initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
217 }
Craig Topper4584cd52014-03-07 09:26:03 +0000218 bool runOnFunction(Function &F) override;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000219
Mehdi Amini117296c2016-10-01 02:56:57 +0000220 StringRef getPassName() const override { return "CodeGen Prepare"; }
Evan Cheng99cafb12012-12-21 01:48:14 +0000221
Craig Topper4584cd52014-03-07 09:26:03 +0000222 void getAnalysisUsage(AnalysisUsage &AU) const override {
George Burgess IVd4febd12016-03-22 21:25:08 +0000223 // FIXME: When we can selectively preserve passes, preserve the domtree.
Dehao Chen302b69c2016-10-18 20:42:47 +0000224 AU.addRequired<ProfileSummaryInfoWrapperPass>();
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000225 AU.addRequired<TargetLibraryInfoWrapperPass>();
Chandler Carruth705b1852015-01-31 03:43:40 +0000226 AU.addRequired<TargetTransformInfoWrapperPass>();
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000227 AU.addRequired<LoopInfoWrapperPass>();
Andreas Neustifterf8cb7582009-09-16 09:26:52 +0000228 }
229
Chris Lattnerf2836d12007-03-31 04:06:36 +0000230 private:
Sanjay Patelfc580a62015-09-21 23:03:16 +0000231 bool eliminateFallThrough(Function &F);
232 bool eliminateMostlyEmptyBlocks(Function &F);
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000233 BasicBlock *findDestBlockOfMergeableEmptyBlock(BasicBlock *BB);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000234 bool canMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
235 void eliminateMostlyEmptyBlock(BasicBlock *BB);
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000236 bool isMergingEmptyBlockProfitable(BasicBlock *BB, BasicBlock *DestBB,
237 bool isPreheader);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000238 bool optimizeBlock(BasicBlock &BB, bool& ModifiedDT);
239 bool optimizeInst(Instruction *I, bool& ModifiedDT);
240 bool optimizeMemoryInst(Instruction *I, Value *Addr,
Matt Arsenaultf72b49b2015-06-04 16:17:38 +0000241 Type *AccessTy, unsigned AS);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000242 bool optimizeInlineAsmInst(CallInst *CS);
243 bool optimizeCallInst(CallInst *CI, bool& ModifiedDT);
Jun Bum Limdee55652017-04-03 19:20:07 +0000244 bool optimizeExt(Instruction *&I);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000245 bool optimizeExtUses(Instruction *I);
Geoff Berry5256fca2015-11-20 22:34:39 +0000246 bool optimizeLoadExt(LoadInst *I);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000247 bool optimizeSelectInst(SelectInst *SI);
248 bool optimizeShuffleVectorInst(ShuffleVectorInst *SI);
Sanjay Patel0ed9aea2015-11-02 23:22:49 +0000249 bool optimizeSwitchInst(SwitchInst *CI);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000250 bool optimizeExtractElementInst(Instruction *Inst);
251 bool dupRetToEnableTailCallOpts(BasicBlock *BB);
252 bool placeDbgValues(Function &F);
Jun Bum Lim42301012017-03-17 19:05:21 +0000253 bool canFormExtLd(const SmallVectorImpl<Instruction *> &MovedExts,
254 LoadInst *&LI, Instruction *&Inst, bool HasPromoted);
255 bool tryToPromoteExts(TypePromotionTransaction &TPT,
256 const SmallVectorImpl<Instruction *> &Exts,
257 SmallVectorImpl<Instruction *> &ProfitablyMovedExts,
258 unsigned CreatedInstsCost = 0);
Jun Bum Limdee55652017-04-03 19:20:07 +0000259 bool mergeSExts(Function &F);
260 bool performAddressTypePromotion(
261 Instruction *&Inst,
262 bool AllowPromotionWithoutCommonHeader,
263 bool HasPromoted, TypePromotionTransaction &TPT,
264 SmallVectorImpl<Instruction *> &SpeculativelyMovedExts);
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +0000265 bool splitBranchCondition(Function &F);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000266 bool simplifyOffsetableRelocate(Instruction &I);
Michael Kuperstein13bf8a22017-02-28 00:11:34 +0000267 bool splitIndirectCriticalEdges(Function &F);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000268 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000269}
Devang Patel09f162c2007-05-01 21:15:47 +0000270
Devang Patel8c78a0b2007-05-03 01:11:54 +0000271char CodeGenPrepare::ID = 0;
Matthias Braun1527baa2017-05-25 21:26:32 +0000272INITIALIZE_PASS_BEGIN(CodeGenPrepare, DEBUG_TYPE,
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000273 "Optimize for code generation", false, false)
Dehao Chen302b69c2016-10-18 20:42:47 +0000274INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
Matthias Braun1527baa2017-05-25 21:26:32 +0000275INITIALIZE_PASS_END(CodeGenPrepare, DEBUG_TYPE,
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000276 "Optimize for code generation", false, false)
Chris Lattnerf2836d12007-03-31 04:06:36 +0000277
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000278FunctionPass *llvm::createCodeGenPreparePass() { return new CodeGenPrepare(); }
Chris Lattnerf2836d12007-03-31 04:06:36 +0000279
Chris Lattnerf2836d12007-03-31 04:06:36 +0000280bool CodeGenPrepare::runOnFunction(Function &F) {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000281 if (skipFunction(F))
Paul Robinson7c99ec52014-03-31 17:43:35 +0000282 return false;
283
Mehdi Amini4fe37982015-07-07 18:45:17 +0000284 DL = &F.getParent()->getDataLayout();
285
Chris Lattnerf2836d12007-03-31 04:06:36 +0000286 bool EverMadeChange = false;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000287 // Clear per function information.
Ahmed Bougachaf3299142015-06-17 20:44:32 +0000288 InsertedInsts.clear();
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000289 PromotedInsts.clear();
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000290 BFI.reset();
291 BPI.reset();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000292
Devang Patel8f606d72011-03-24 15:35:25 +0000293 ModifiedDT = false;
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000294 if (auto *TPC = getAnalysisIfAvailable<TargetPassConfig>()) {
295 TM = &TPC->getTM<TargetMachine>();
Igor Laevsky3be81ba2017-02-07 13:27:20 +0000296 SubtargetInfo = TM->getSubtargetImpl(F);
297 TLI = SubtargetInfo->getTargetLowering();
298 TRI = SubtargetInfo->getRegisterInfo();
299 }
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000300 TLInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Chandler Carruthfdb9c572015-02-01 12:01:35 +0000301 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000302 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Sanjay Patel82d91dd2015-08-11 19:39:36 +0000303 OptSize = F.optForSize();
Evan Cheng0663f232011-03-21 01:19:09 +0000304
Dehao Chen302b69c2016-10-18 20:42:47 +0000305 if (ProfileGuidedSectionPrefix) {
306 ProfileSummaryInfo *PSI =
307 getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
Dehao Chen775341a2017-03-23 23:14:11 +0000308 if (PSI->isFunctionHotInCallGraph(&F))
Dehao Chen302b69c2016-10-18 20:42:47 +0000309 F.setSectionPrefix(".hot");
Dehao Chen775341a2017-03-23 23:14:11 +0000310 else if (PSI->isFunctionColdInCallGraph(&F))
Teresa Johnson720d9b42017-05-09 01:43:24 +0000311 F.setSectionPrefix(".unlikely");
Dehao Chen302b69c2016-10-18 20:42:47 +0000312 }
313
Preston Gurdcdf540d2012-09-04 18:22:17 +0000314 /// This optimization identifies DIV instructions that can be
315 /// profitably bypassed and carried out with a shorter, faster divide.
Preston Gurd485296d2013-03-04 18:13:57 +0000316 if (!OptSize && TLI && TLI->isSlowDivBypassed()) {
Preston Gurd0d67f512012-10-04 21:33:40 +0000317 const DenseMap<unsigned int, unsigned int> &BypassWidths =
318 TLI->getBypassSlowDivWidths();
Eric Christopher49a7d6c2016-01-04 23:18:58 +0000319 BasicBlock* BB = &*F.begin();
320 while (BB != nullptr) {
321 // bypassSlowDivision may create new BBs, but we don't want to reapply the
322 // optimization to those blocks.
323 BasicBlock* Next = BB->getNextNode();
324 EverMadeChange |= bypassSlowDivision(BB, BypassWidths);
325 BB = Next;
326 }
Preston Gurdcdf540d2012-09-04 18:22:17 +0000327 }
328
329 // Eliminate blocks that contain only PHI nodes and an
Chris Lattnerc3748562007-04-02 01:35:34 +0000330 // unconditional branch.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000331 EverMadeChange |= eliminateMostlyEmptyBlocks(F);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000332
Devang Patel53771ba2011-08-18 00:50:51 +0000333 // llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotem465834c2012-07-24 10:51:42 +0000334 // handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patel53771ba2011-08-18 00:50:51 +0000335 // find a node corresponding to the value.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000336 EverMadeChange |= placeDbgValues(F);
Devang Patel53771ba2011-08-18 00:50:51 +0000337
Geoff Berry5d534b62017-02-21 18:53:14 +0000338 if (!DisableBranchOpts)
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +0000339 EverMadeChange |= splitBranchCondition(F);
Tim Northovercea0abb2014-03-29 08:22:29 +0000340
Michael Kuperstein13bf8a22017-02-28 00:11:34 +0000341 // Split some critical edges where one of the sources is an indirect branch,
342 // to help generate sane code for PHIs involving such edges.
343 EverMadeChange |= splitIndirectCriticalEdges(F);
344
Chris Lattnerc3748562007-04-02 01:35:34 +0000345 bool MadeChange = true;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000346 while (MadeChange) {
347 MadeChange = false;
Jun Bum Limdee55652017-04-03 19:20:07 +0000348 SeenChainsForSExt.clear();
349 ValToSExtendedUses.clear();
350 RemovedInsts.clear();
Hans Wennborg02fbc712012-09-19 07:48:16 +0000351 for (Function::iterator I = F.begin(); I != F.end(); ) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000352 BasicBlock *BB = &*I++;
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000353 bool ModifiedDTOnIteration = false;
Sanjay Patelfc580a62015-09-21 23:03:16 +0000354 MadeChange |= optimizeBlock(*BB, ModifiedDTOnIteration);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000355
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000356 // Restart BB iteration if the dominator tree of the Function was changed
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000357 if (ModifiedDTOnIteration)
358 break;
Evan Cheng0663f232011-03-21 01:19:09 +0000359 }
Jun Bum Limdee55652017-04-03 19:20:07 +0000360 if (EnableTypePromotionMerge && !ValToSExtendedUses.empty())
361 MadeChange |= mergeSExts(F);
362
363 // Really free removed instructions during promotion.
364 for (Instruction *I : RemovedInsts)
Reid Kleckner96ab8722017-05-18 17:24:10 +0000365 I->deleteValue();
Jun Bum Limdee55652017-04-03 19:20:07 +0000366
Chris Lattnerf2836d12007-03-31 04:06:36 +0000367 EverMadeChange |= MadeChange;
368 }
Cameron Zwarichce3b9302011-01-06 00:42:50 +0000369
370 SunkAddrs.clear();
371
Cameron Zwarich338d3622011-03-11 21:52:04 +0000372 if (!DisableBranchOpts) {
373 MadeChange = false;
Bill Wendling97b93592012-03-04 10:46:01 +0000374 SmallPtrSet<BasicBlock*, 8> WorkList;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +0000375 for (BasicBlock &BB : F) {
376 SmallVector<BasicBlock *, 2> Successors(succ_begin(&BB), succ_end(&BB));
377 MadeChange |= ConstantFoldTerminator(&BB, true);
Bill Wendling97b93592012-03-04 10:46:01 +0000378 if (!MadeChange) continue;
379
380 for (SmallVectorImpl<BasicBlock*>::iterator
381 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
382 if (pred_begin(*II) == pred_end(*II))
383 WorkList.insert(*II);
384 }
385
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000386 // Delete the dead blocks and any of their dead successors.
Bill Wendlingab417b62012-12-06 00:30:20 +0000387 MadeChange |= !WorkList.empty();
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000388 while (!WorkList.empty()) {
389 BasicBlock *BB = *WorkList.begin();
390 WorkList.erase(BB);
391 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
392
393 DeleteDeadBlock(BB);
Stephen Lin837bba12013-07-15 17:55:02 +0000394
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000395 for (SmallVectorImpl<BasicBlock*>::iterator
396 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
397 if (pred_begin(*II) == pred_end(*II))
398 WorkList.insert(*II);
399 }
Cameron Zwarich338d3622011-03-11 21:52:04 +0000400
Nadav Rotem70409992012-08-14 05:19:07 +0000401 // Merge pairs of basic blocks with unconditional branches, connected by
402 // a single edge.
403 if (EverMadeChange || MadeChange)
Sanjay Patelfc580a62015-09-21 23:03:16 +0000404 MadeChange |= eliminateFallThrough(F);
Nadav Rotem70409992012-08-14 05:19:07 +0000405
Cameron Zwarich338d3622011-03-11 21:52:04 +0000406 EverMadeChange |= MadeChange;
407 }
408
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000409 if (!DisableGCOpts) {
410 SmallVector<Instruction *, 2> Statepoints;
411 for (BasicBlock &BB : F)
412 for (Instruction &I : BB)
413 if (isStatepoint(I))
414 Statepoints.push_back(&I);
415 for (auto &I : Statepoints)
416 EverMadeChange |= simplifyOffsetableRelocate(*I);
417 }
418
Chris Lattnerf2836d12007-03-31 04:06:36 +0000419 return EverMadeChange;
420}
421
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000422/// Merge basic blocks which are connected by a single edge, where one of the
423/// basic blocks has a single successor pointing to the other basic block,
424/// which has a single predecessor.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000425bool CodeGenPrepare::eliminateFallThrough(Function &F) {
Nadav Rotem70409992012-08-14 05:19:07 +0000426 bool Changed = false;
427 // Scan all of the blocks in the function, except for the entry block.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000428 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000429 BasicBlock *BB = &*I++;
Nadav Rotem70409992012-08-14 05:19:07 +0000430 // If the destination block has a single pred, then this is a trivial
431 // edge, just collapse it.
432 BasicBlock *SinglePred = BB->getSinglePredecessor();
433
Evan Cheng64a223a2012-09-28 23:58:57 +0000434 // Don't merge if BB's address is taken.
435 if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue;
Nadav Rotem70409992012-08-14 05:19:07 +0000436
437 BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
438 if (Term && !Term->isConditional()) {
439 Changed = true;
Michael Liao6e12d122012-08-21 05:55:22 +0000440 DEBUG(dbgs() << "To merge:\n"<< *SinglePred << "\n\n\n");
Nadav Rotem70409992012-08-14 05:19:07 +0000441 // Remember if SinglePred was the entry block of the function.
442 // If so, we will need to move BB back to the entry position.
443 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Quentin Colombet7bdd50d2015-03-18 23:17:28 +0000444 MergeBasicBlockIntoOnlyPred(BB, nullptr);
Nadav Rotem70409992012-08-14 05:19:07 +0000445
446 if (isEntry && BB != &BB->getParent()->getEntryBlock())
447 BB->moveBefore(&BB->getParent()->getEntryBlock());
448
449 // We have erased a block. Update the iterator.
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000450 I = BB->getIterator();
Nadav Rotem70409992012-08-14 05:19:07 +0000451 }
452 }
453 return Changed;
454}
455
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000456/// Find a destination block from BB if BB is mergeable empty block.
457BasicBlock *CodeGenPrepare::findDestBlockOfMergeableEmptyBlock(BasicBlock *BB) {
458 // If this block doesn't end with an uncond branch, ignore it.
459 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
460 if (!BI || !BI->isUnconditional())
461 return nullptr;
462
463 // If the instruction before the branch (skipping debug info) isn't a phi
464 // node, then other stuff is happening here.
465 BasicBlock::iterator BBI = BI->getIterator();
466 if (BBI != BB->begin()) {
467 --BBI;
468 while (isa<DbgInfoIntrinsic>(BBI)) {
469 if (BBI == BB->begin())
470 break;
471 --BBI;
472 }
473 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
474 return nullptr;
475 }
476
477 // Do not break infinite loops.
478 BasicBlock *DestBB = BI->getSuccessor(0);
479 if (DestBB == BB)
480 return nullptr;
481
482 if (!canMergeBlocks(BB, DestBB))
483 DestBB = nullptr;
484
485 return DestBB;
486}
487
Michael Kuperstein13bf8a22017-02-28 00:11:34 +0000488// Return the unique indirectbr predecessor of a block. This may return null
489// even if such a predecessor exists, if it's not useful for splitting.
490// If a predecessor is found, OtherPreds will contain all other (non-indirectbr)
491// predecessors of BB.
492static BasicBlock *
493findIBRPredecessor(BasicBlock *BB, SmallVectorImpl<BasicBlock *> &OtherPreds) {
494 // If the block doesn't have any PHIs, we don't care about it, since there's
495 // no point in splitting it.
496 PHINode *PN = dyn_cast<PHINode>(BB->begin());
497 if (!PN)
498 return nullptr;
499
500 // Verify we have exactly one IBR predecessor.
501 // Conservatively bail out if one of the other predecessors is not a "regular"
502 // terminator (that is, not a switch or a br).
503 BasicBlock *IBB = nullptr;
504 for (unsigned Pred = 0, E = PN->getNumIncomingValues(); Pred != E; ++Pred) {
505 BasicBlock *PredBB = PN->getIncomingBlock(Pred);
506 TerminatorInst *PredTerm = PredBB->getTerminator();
507 switch (PredTerm->getOpcode()) {
508 case Instruction::IndirectBr:
509 if (IBB)
510 return nullptr;
511 IBB = PredBB;
512 break;
513 case Instruction::Br:
514 case Instruction::Switch:
515 OtherPreds.push_back(PredBB);
516 continue;
517 default:
518 return nullptr;
519 }
520 }
521
522 return IBB;
523}
524
525// Split critical edges where the source of the edge is an indirectbr
526// instruction. This isn't always possible, but we can handle some easy cases.
527// This is useful because MI is unable to split such critical edges,
528// which means it will not be able to sink instructions along those edges.
529// This is especially painful for indirect branches with many successors, where
530// we end up having to prepare all outgoing values in the origin block.
531//
532// Our normal algorithm for splitting critical edges requires us to update
533// the outgoing edges of the edge origin block, but for an indirectbr this
534// is hard, since it would require finding and updating the block addresses
535// the indirect branch uses. But if a block only has a single indirectbr
536// predecessor, with the others being regular branches, we can do it in a
537// different way.
538// Say we have A -> D, B -> D, I -> D where only I -> D is an indirectbr.
539// We can split D into D0 and D1, where D0 contains only the PHIs from D,
540// and D1 is the D block body. We can then duplicate D0 as D0A and D0B, and
541// create the following structure:
542// A -> D0A, B -> D0A, I -> D0B, D0A -> D1, D0B -> D1
543bool CodeGenPrepare::splitIndirectCriticalEdges(Function &F) {
544 // Check whether the function has any indirectbrs, and collect which blocks
545 // they may jump to. Since most functions don't have indirect branches,
546 // this lowers the common case's overhead to O(Blocks) instead of O(Edges).
547 SmallSetVector<BasicBlock *, 16> Targets;
548 for (auto &BB : F) {
549 auto *IBI = dyn_cast<IndirectBrInst>(BB.getTerminator());
550 if (!IBI)
551 continue;
552
553 for (unsigned Succ = 0, E = IBI->getNumSuccessors(); Succ != E; ++Succ)
554 Targets.insert(IBI->getSuccessor(Succ));
555 }
556
557 if (Targets.empty())
558 return false;
559
560 bool Changed = false;
561 for (BasicBlock *Target : Targets) {
562 SmallVector<BasicBlock *, 16> OtherPreds;
563 BasicBlock *IBRPred = findIBRPredecessor(Target, OtherPreds);
564 // If we did not found an indirectbr, or the indirectbr is the only
565 // incoming edge, this isn't the kind of edge we're looking for.
566 if (!IBRPred || OtherPreds.empty())
567 continue;
568
569 // Don't even think about ehpads/landingpads.
570 Instruction *FirstNonPHI = Target->getFirstNonPHI();
571 if (FirstNonPHI->isEHPad() || Target->isLandingPad())
572 continue;
573
574 BasicBlock *BodyBlock = Target->splitBasicBlock(FirstNonPHI, ".split");
575 // It's possible Target was its own successor through an indirectbr.
576 // In this case, the indirectbr now comes from BodyBlock.
577 if (IBRPred == Target)
578 IBRPred = BodyBlock;
579
580 // At this point Target only has PHIs, and BodyBlock has the rest of the
581 // block's body. Create a copy of Target that will be used by the "direct"
582 // preds.
583 ValueToValueMapTy VMap;
584 BasicBlock *DirectSucc = CloneBasicBlock(Target, VMap, ".clone", &F);
585
Brendon Cahoon7769a082017-04-17 19:11:04 +0000586 for (BasicBlock *Pred : OtherPreds) {
587 // If the target is a loop to itself, then the terminator of the split
588 // block needs to be updated.
589 if (Pred == Target)
590 BodyBlock->getTerminator()->replaceUsesOfWith(Target, DirectSucc);
591 else
592 Pred->getTerminator()->replaceUsesOfWith(Target, DirectSucc);
593 }
Michael Kuperstein13bf8a22017-02-28 00:11:34 +0000594
595 // Ok, now fix up the PHIs. We know the two blocks only have PHIs, and that
596 // they are clones, so the number of PHIs are the same.
597 // (a) Remove the edge coming from IBRPred from the "Direct" PHI
598 // (b) Leave that as the only edge in the "Indirect" PHI.
599 // (c) Merge the two in the body block.
600 BasicBlock::iterator Indirect = Target->begin(),
601 End = Target->getFirstNonPHI()->getIterator();
602 BasicBlock::iterator Direct = DirectSucc->begin();
603 BasicBlock::iterator MergeInsert = BodyBlock->getFirstInsertionPt();
604
605 assert(&*End == Target->getTerminator() &&
606 "Block was expected to only contain PHIs");
607
608 while (Indirect != End) {
609 PHINode *DirPHI = cast<PHINode>(Direct);
610 PHINode *IndPHI = cast<PHINode>(Indirect);
611
612 // Now, clean up - the direct block shouldn't get the indirect value,
613 // and vice versa.
614 DirPHI->removeIncomingValue(IBRPred);
615 Direct++;
616
617 // Advance the pointer here, to avoid invalidation issues when the old
618 // PHI is erased.
619 Indirect++;
620
621 PHINode *NewIndPHI = PHINode::Create(IndPHI->getType(), 1, "ind", IndPHI);
622 NewIndPHI->addIncoming(IndPHI->getIncomingValueForBlock(IBRPred),
623 IBRPred);
624
625 // Create a PHI in the body block, to merge the direct and indirect
626 // predecessors.
627 PHINode *MergePHI =
628 PHINode::Create(IndPHI->getType(), 2, "merge", &*MergeInsert);
629 MergePHI->addIncoming(NewIndPHI, Target);
630 MergePHI->addIncoming(DirPHI, DirectSucc);
631
632 IndPHI->replaceAllUsesWith(MergePHI);
633 IndPHI->eraseFromParent();
634 }
635
636 Changed = true;
637 }
638
639 return Changed;
640}
641
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000642/// Eliminate blocks that contain only PHI nodes, debug info directives, and an
643/// unconditional branch. Passes before isel (e.g. LSR/loopsimplify) often split
644/// edges in ways that are non-optimal for isel. Start by eliminating these
645/// blocks so we can split them the way we want them.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000646bool CodeGenPrepare::eliminateMostlyEmptyBlocks(Function &F) {
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000647 SmallPtrSet<BasicBlock *, 16> Preheaders;
648 SmallVector<Loop *, 16> LoopList(LI->begin(), LI->end());
649 while (!LoopList.empty()) {
650 Loop *L = LoopList.pop_back_val();
651 LoopList.insert(LoopList.end(), L->begin(), L->end());
652 if (BasicBlock *Preheader = L->getLoopPreheader())
653 Preheaders.insert(Preheader);
654 }
655
Chris Lattnerc3748562007-04-02 01:35:34 +0000656 bool MadeChange = false;
657 // Note that this intentionally skips the entry block.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000658 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000659 BasicBlock *BB = &*I++;
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000660 BasicBlock *DestBB = findDestBlockOfMergeableEmptyBlock(BB);
661 if (!DestBB ||
662 !isMergingEmptyBlockProfitable(BB, DestBB, Preheaders.count(BB)))
Chris Lattnerc3748562007-04-02 01:35:34 +0000663 continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000664
Sanjay Patelfc580a62015-09-21 23:03:16 +0000665 eliminateMostlyEmptyBlock(BB);
Chris Lattnerc3748562007-04-02 01:35:34 +0000666 MadeChange = true;
667 }
668 return MadeChange;
669}
670
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000671bool CodeGenPrepare::isMergingEmptyBlockProfitable(BasicBlock *BB,
672 BasicBlock *DestBB,
673 bool isPreheader) {
674 // Do not delete loop preheaders if doing so would create a critical edge.
675 // Loop preheaders can be good locations to spill registers. If the
676 // preheader is deleted and we create a critical edge, registers may be
677 // spilled in the loop body instead.
678 if (!DisablePreheaderProtect && isPreheader &&
679 !(BB->getSinglePredecessor() &&
680 BB->getSinglePredecessor()->getSingleSuccessor()))
681 return false;
682
683 // Try to skip merging if the unique predecessor of BB is terminated by a
684 // switch or indirect branch instruction, and BB is used as an incoming block
685 // of PHIs in DestBB. In such case, merging BB and DestBB would cause ISel to
686 // add COPY instructions in the predecessor of BB instead of BB (if it is not
687 // merged). Note that the critical edge created by merging such blocks wont be
688 // split in MachineSink because the jump table is not analyzable. By keeping
689 // such empty block (BB), ISel will place COPY instructions in BB, not in the
690 // predecessor of BB.
691 BasicBlock *Pred = BB->getUniquePredecessor();
692 if (!Pred ||
693 !(isa<SwitchInst>(Pred->getTerminator()) ||
694 isa<IndirectBrInst>(Pred->getTerminator())))
695 return true;
696
697 if (BB->getTerminator() != BB->getFirstNonPHI())
698 return true;
699
700 // We use a simple cost heuristic which determine skipping merging is
701 // profitable if the cost of skipping merging is less than the cost of
702 // merging : Cost(skipping merging) < Cost(merging BB), where the
703 // Cost(skipping merging) is Freq(BB) * (Cost(Copy) + Cost(Branch)), and
704 // the Cost(merging BB) is Freq(Pred) * Cost(Copy).
705 // Assuming Cost(Copy) == Cost(Branch), we could simplify it to :
706 // Freq(Pred) / Freq(BB) > 2.
707 // Note that if there are multiple empty blocks sharing the same incoming
708 // value for the PHIs in the DestBB, we consider them together. In such
709 // case, Cost(merging BB) will be the sum of their frequencies.
710
711 if (!isa<PHINode>(DestBB->begin()))
712 return true;
713
714 SmallPtrSet<BasicBlock *, 16> SameIncomingValueBBs;
715
716 // Find all other incoming blocks from which incoming values of all PHIs in
717 // DestBB are the same as the ones from BB.
718 for (pred_iterator PI = pred_begin(DestBB), E = pred_end(DestBB); PI != E;
719 ++PI) {
720 BasicBlock *DestBBPred = *PI;
721 if (DestBBPred == BB)
722 continue;
723
724 bool HasAllSameValue = true;
725 BasicBlock::const_iterator DestBBI = DestBB->begin();
726 while (const PHINode *DestPN = dyn_cast<PHINode>(DestBBI++)) {
727 if (DestPN->getIncomingValueForBlock(BB) !=
728 DestPN->getIncomingValueForBlock(DestBBPred)) {
729 HasAllSameValue = false;
730 break;
731 }
732 }
733 if (HasAllSameValue)
734 SameIncomingValueBBs.insert(DestBBPred);
735 }
736
737 // See if all BB's incoming values are same as the value from Pred. In this
738 // case, no reason to skip merging because COPYs are expected to be place in
739 // Pred already.
740 if (SameIncomingValueBBs.count(Pred))
741 return true;
742
743 if (!BFI) {
744 Function &F = *BB->getParent();
745 LoopInfo LI{DominatorTree(F)};
746 BPI.reset(new BranchProbabilityInfo(F, LI));
747 BFI.reset(new BlockFrequencyInfo(F, *BPI, LI));
748 }
749
750 BlockFrequency PredFreq = BFI->getBlockFreq(Pred);
751 BlockFrequency BBFreq = BFI->getBlockFreq(BB);
752
753 for (auto SameValueBB : SameIncomingValueBBs)
754 if (SameValueBB->getUniquePredecessor() == Pred &&
755 DestBB == findDestBlockOfMergeableEmptyBlock(SameValueBB))
756 BBFreq += BFI->getBlockFreq(SameValueBB);
757
758 return PredFreq.getFrequency() <=
759 BBFreq.getFrequency() * FreqRatioToSkipMerge;
760}
761
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000762/// Return true if we can merge BB into DestBB if there is a single
763/// unconditional branch between them, and BB contains no other non-phi
Chris Lattnerc3748562007-04-02 01:35:34 +0000764/// instructions.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000765bool CodeGenPrepare::canMergeBlocks(const BasicBlock *BB,
Chris Lattnerc3748562007-04-02 01:35:34 +0000766 const BasicBlock *DestBB) const {
767 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
768 // the successor. If there are more complex condition (e.g. preheaders),
769 // don't mess around with them.
770 BasicBlock::const_iterator BBI = BB->begin();
771 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000772 for (const User *U : PN->users()) {
773 const Instruction *UI = cast<Instruction>(U);
774 if (UI->getParent() != DestBB || !isa<PHINode>(UI))
Chris Lattnerc3748562007-04-02 01:35:34 +0000775 return false;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000776 // If User is inside DestBB block and it is a PHINode then check
777 // incoming value. If incoming value is not from BB then this is
Devang Pateld3208522007-04-25 00:37:04 +0000778 // a complex condition (e.g. preheaders) we want to avoid here.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000779 if (UI->getParent() == DestBB) {
780 if (const PHINode *UPN = dyn_cast<PHINode>(UI))
Devang Pateld3208522007-04-25 00:37:04 +0000781 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
782 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
783 if (Insn && Insn->getParent() == BB &&
784 Insn->getParent() != UPN->getIncomingBlock(I))
785 return false;
786 }
787 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000788 }
789 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000790
Chris Lattnerc3748562007-04-02 01:35:34 +0000791 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
792 // and DestBB may have conflicting incoming values for the block. If so, we
793 // can't merge the block.
794 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
795 if (!DestBBPN) return true; // no conflict.
Eric Christopherc1ea1492008-09-24 05:32:41 +0000796
Chris Lattnerc3748562007-04-02 01:35:34 +0000797 // Collect the preds of BB.
Chris Lattner8201a9b2007-11-06 22:07:40 +0000798 SmallPtrSet<const BasicBlock*, 16> BBPreds;
Chris Lattnerc3748562007-04-02 01:35:34 +0000799 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
800 // It is faster to get preds from a PHI than with pred_iterator.
801 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
802 BBPreds.insert(BBPN->getIncomingBlock(i));
803 } else {
804 BBPreds.insert(pred_begin(BB), pred_end(BB));
805 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000806
Chris Lattnerc3748562007-04-02 01:35:34 +0000807 // Walk the preds of DestBB.
808 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
809 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
810 if (BBPreds.count(Pred)) { // Common predecessor?
811 BBI = DestBB->begin();
812 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
813 const Value *V1 = PN->getIncomingValueForBlock(Pred);
814 const Value *V2 = PN->getIncomingValueForBlock(BB);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000815
Chris Lattnerc3748562007-04-02 01:35:34 +0000816 // If V2 is a phi node in BB, look up what the mapped value will be.
817 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
818 if (V2PN->getParent() == BB)
819 V2 = V2PN->getIncomingValueForBlock(Pred);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000820
Chris Lattnerc3748562007-04-02 01:35:34 +0000821 // If there is a conflict, bail out.
822 if (V1 != V2) return false;
823 }
824 }
825 }
826
827 return true;
828}
829
830
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000831/// Eliminate a basic block that has only phi's and an unconditional branch in
832/// it.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000833void CodeGenPrepare::eliminateMostlyEmptyBlock(BasicBlock *BB) {
Chris Lattnerc3748562007-04-02 01:35:34 +0000834 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
835 BasicBlock *DestBB = BI->getSuccessor(0);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000836
David Greene74e2d492010-01-05 01:27:11 +0000837 DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000838
Chris Lattnerc3748562007-04-02 01:35:34 +0000839 // If the destination block has a single pred, then this is a trivial edge,
840 // just collapse it.
Chris Lattner4059f432008-11-27 19:29:14 +0000841 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
Chris Lattner8a172da2008-11-28 19:54:49 +0000842 if (SinglePred != DestBB) {
843 // Remember if SinglePred was the entry block of the function. If so, we
844 // will need to move BB back to the entry position.
845 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Quentin Colombet7bdd50d2015-03-18 23:17:28 +0000846 MergeBasicBlockIntoOnlyPred(DestBB, nullptr);
Chris Lattner4059f432008-11-27 19:29:14 +0000847
Chris Lattner8a172da2008-11-28 19:54:49 +0000848 if (isEntry && BB != &BB->getParent()->getEntryBlock())
849 BB->moveBefore(&BB->getParent()->getEntryBlock());
Nadav Rotem465834c2012-07-24 10:51:42 +0000850
David Greene74e2d492010-01-05 01:27:11 +0000851 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattner8a172da2008-11-28 19:54:49 +0000852 return;
853 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000854 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000855
Chris Lattnerc3748562007-04-02 01:35:34 +0000856 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
857 // to handle the new incoming edges it is about to have.
858 PHINode *PN;
859 for (BasicBlock::iterator BBI = DestBB->begin();
860 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
861 // Remove the incoming value for BB, and remember it.
862 Value *InVal = PN->removeIncomingValue(BB, false);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000863
Chris Lattnerc3748562007-04-02 01:35:34 +0000864 // Two options: either the InVal is a phi node defined in BB or it is some
865 // value that dominates BB.
866 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
867 if (InValPhi && InValPhi->getParent() == BB) {
868 // Add all of the input values of the input PHI as inputs of this phi.
869 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
870 PN->addIncoming(InValPhi->getIncomingValue(i),
871 InValPhi->getIncomingBlock(i));
872 } else {
873 // Otherwise, add one instance of the dominating value for each edge that
874 // we will be adding.
875 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
876 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
877 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
878 } else {
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000879 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
880 PN->addIncoming(InVal, *PI);
Chris Lattnerc3748562007-04-02 01:35:34 +0000881 }
882 }
883 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000884
Chris Lattnerc3748562007-04-02 01:35:34 +0000885 // The PHIs are now updated, change everything that refers to BB to use
886 // DestBB and remove BB.
887 BB->replaceAllUsesWith(DestBB);
888 BB->eraseFromParent();
Cameron Zwarichced753f2011-01-05 17:27:27 +0000889 ++NumBlocksElim;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000890
David Greene74e2d492010-01-05 01:27:11 +0000891 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerc3748562007-04-02 01:35:34 +0000892}
893
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000894// Computes a map of base pointer relocation instructions to corresponding
895// derived pointer relocation instructions given a vector of all relocate calls
896static void computeBaseDerivedRelocateMap(
Manuel Jacob83eefa62016-01-05 04:03:00 +0000897 const SmallVectorImpl<GCRelocateInst *> &AllRelocateCalls,
898 DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>>
899 &RelocateInstMap) {
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000900 // Collect information in two maps: one primarily for locating the base object
901 // while filling the second map; the second map is the final structure holding
902 // a mapping between Base and corresponding Derived relocate calls
Manuel Jacob83eefa62016-01-05 04:03:00 +0000903 DenseMap<std::pair<unsigned, unsigned>, GCRelocateInst *> RelocateIdxMap;
904 for (auto *ThisRelocate : AllRelocateCalls) {
905 auto K = std::make_pair(ThisRelocate->getBasePtrIndex(),
906 ThisRelocate->getDerivedPtrIndex());
907 RelocateIdxMap.insert(std::make_pair(K, ThisRelocate));
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000908 }
909 for (auto &Item : RelocateIdxMap) {
910 std::pair<unsigned, unsigned> Key = Item.first;
911 if (Key.first == Key.second)
912 // Base relocation: nothing to insert
913 continue;
914
Manuel Jacob83eefa62016-01-05 04:03:00 +0000915 GCRelocateInst *I = Item.second;
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000916 auto BaseKey = std::make_pair(Key.first, Key.first);
Sanjoy Dasb8186762015-02-27 02:24:16 +0000917
918 // We're iterating over RelocateIdxMap so we cannot modify it.
919 auto MaybeBase = RelocateIdxMap.find(BaseKey);
920 if (MaybeBase == RelocateIdxMap.end())
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000921 // TODO: We might want to insert a new base object relocate and gep off
922 // that, if there are enough derived object relocates.
923 continue;
Sanjoy Dasb8186762015-02-27 02:24:16 +0000924
925 RelocateInstMap[MaybeBase->second].push_back(I);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000926 }
927}
928
929// Accepts a GEP and extracts the operands into a vector provided they're all
930// small integer constants
931static bool getGEPSmallConstantIntOffsetV(GetElementPtrInst *GEP,
932 SmallVectorImpl<Value *> &OffsetV) {
933 for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
934 // Only accept small constant integer operands
935 auto Op = dyn_cast<ConstantInt>(GEP->getOperand(i));
936 if (!Op || Op->getZExtValue() > 20)
937 return false;
938 }
939
940 for (unsigned i = 1; i < GEP->getNumOperands(); i++)
941 OffsetV.push_back(GEP->getOperand(i));
942 return true;
943}
944
945// Takes a RelocatedBase (base pointer relocation instruction) and Targets to
946// replace, computes a replacement, and affects it.
947static bool
Manuel Jacob83eefa62016-01-05 04:03:00 +0000948simplifyRelocatesOffABase(GCRelocateInst *RelocatedBase,
949 const SmallVectorImpl<GCRelocateInst *> &Targets) {
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000950 bool MadeChange = false;
Manuel Jacob83eefa62016-01-05 04:03:00 +0000951 for (GCRelocateInst *ToReplace : Targets) {
952 assert(ToReplace->getBasePtrIndex() == RelocatedBase->getBasePtrIndex() &&
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000953 "Not relocating a derived object of the original base object");
Manuel Jacob83eefa62016-01-05 04:03:00 +0000954 if (ToReplace->getBasePtrIndex() == ToReplace->getDerivedPtrIndex()) {
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000955 // A duplicate relocate call. TODO: coalesce duplicates.
956 continue;
957 }
958
Igor Laevskyf637b4a2015-11-03 18:37:40 +0000959 if (RelocatedBase->getParent() != ToReplace->getParent()) {
960 // Base and derived relocates are in different basic blocks.
961 // In this case transform is only valid when base dominates derived
962 // relocate. However it would be too expensive to check dominance
963 // for each such relocate, so we skip the whole transformation.
964 continue;
965 }
966
Manuel Jacob83eefa62016-01-05 04:03:00 +0000967 Value *Base = ToReplace->getBasePtr();
968 auto Derived = dyn_cast<GetElementPtrInst>(ToReplace->getDerivedPtr());
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000969 if (!Derived || Derived->getPointerOperand() != Base)
970 continue;
971
972 SmallVector<Value *, 2> OffsetV;
973 if (!getGEPSmallConstantIntOffsetV(Derived, OffsetV))
974 continue;
975
976 // Create a Builder and replace the target callsite with a gep
Sanjay Patel545a4562016-01-20 18:59:16 +0000977 assert(RelocatedBase->getNextNode() &&
978 "Should always have one since it's not a terminator");
Sanjoy Das3d705e32015-05-11 23:47:30 +0000979
980 // Insert after RelocatedBase
981 IRBuilder<> Builder(RelocatedBase->getNextNode());
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000982 Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc());
Sanjoy Das89c54912015-05-11 18:49:34 +0000983
984 // If gc_relocate does not match the actual type, cast it to the right type.
985 // In theory, there must be a bitcast after gc_relocate if the type does not
986 // match, and we should reuse it to get the derived pointer. But it could be
987 // cases like this:
988 // bb1:
989 // ...
990 // %g1 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
991 // br label %merge
992 //
993 // bb2:
994 // ...
995 // %g2 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
996 // br label %merge
997 //
998 // merge:
999 // %p1 = phi i8 addrspace(1)* [ %g1, %bb1 ], [ %g2, %bb2 ]
1000 // %cast = bitcast i8 addrspace(1)* %p1 in to i32 addrspace(1)*
1001 //
1002 // In this case, we can not find the bitcast any more. So we insert a new bitcast
1003 // no matter there is already one or not. In this way, we can handle all cases, and
1004 // the extra bitcast should be optimized away in later passes.
Manuel Jacob5b90b142015-12-19 18:38:42 +00001005 Value *ActualRelocatedBase = RelocatedBase;
Sanjoy Das89c54912015-05-11 18:49:34 +00001006 if (RelocatedBase->getType() != Base->getType()) {
1007 ActualRelocatedBase =
Manuel Jacob5b90b142015-12-19 18:38:42 +00001008 Builder.CreateBitCast(RelocatedBase, Base->getType());
Sanjoy Das89c54912015-05-11 18:49:34 +00001009 }
David Blaikie68d535c2015-03-24 22:38:16 +00001010 Value *Replacement = Builder.CreateGEP(
Sanjoy Das89c54912015-05-11 18:49:34 +00001011 Derived->getSourceElementType(), ActualRelocatedBase, makeArrayRef(OffsetV));
Ramkumar Ramachandradba73292015-01-14 23:27:07 +00001012 Replacement->takeName(ToReplace);
Sanjoy Das89c54912015-05-11 18:49:34 +00001013 // If the newly generated derived pointer's type does not match the original derived
1014 // pointer's type, cast the new derived pointer to match it. Same reasoning as above.
Manuel Jacob5b90b142015-12-19 18:38:42 +00001015 Value *ActualReplacement = Replacement;
1016 if (Replacement->getType() != ToReplace->getType()) {
Sanjoy Das89c54912015-05-11 18:49:34 +00001017 ActualReplacement =
Manuel Jacob5b90b142015-12-19 18:38:42 +00001018 Builder.CreateBitCast(Replacement, ToReplace->getType());
Sanjoy Das89c54912015-05-11 18:49:34 +00001019 }
1020 ToReplace->replaceAllUsesWith(ActualReplacement);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +00001021 ToReplace->eraseFromParent();
1022
1023 MadeChange = true;
1024 }
1025 return MadeChange;
1026}
1027
1028// Turns this:
1029//
1030// %base = ...
1031// %ptr = gep %base + 15
1032// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
1033// %base' = relocate(%tok, i32 4, i32 4)
1034// %ptr' = relocate(%tok, i32 4, i32 5)
1035// %val = load %ptr'
1036//
1037// into this:
1038//
1039// %base = ...
1040// %ptr = gep %base + 15
1041// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
1042// %base' = gc.relocate(%tok, i32 4, i32 4)
1043// %ptr' = gep %base' + 15
1044// %val = load %ptr'
1045bool CodeGenPrepare::simplifyOffsetableRelocate(Instruction &I) {
1046 bool MadeChange = false;
Manuel Jacob83eefa62016-01-05 04:03:00 +00001047 SmallVector<GCRelocateInst *, 2> AllRelocateCalls;
Ramkumar Ramachandradba73292015-01-14 23:27:07 +00001048
1049 for (auto *U : I.users())
Manuel Jacob83eefa62016-01-05 04:03:00 +00001050 if (GCRelocateInst *Relocate = dyn_cast<GCRelocateInst>(U))
Ramkumar Ramachandradba73292015-01-14 23:27:07 +00001051 // Collect all the relocate calls associated with a statepoint
Manuel Jacob83eefa62016-01-05 04:03:00 +00001052 AllRelocateCalls.push_back(Relocate);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +00001053
1054 // We need atleast one base pointer relocation + one derived pointer
1055 // relocation to mangle
1056 if (AllRelocateCalls.size() < 2)
1057 return false;
1058
1059 // RelocateInstMap is a mapping from the base relocate instruction to the
1060 // corresponding derived relocate instructions
Manuel Jacob83eefa62016-01-05 04:03:00 +00001061 DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>> RelocateInstMap;
Ramkumar Ramachandradba73292015-01-14 23:27:07 +00001062 computeBaseDerivedRelocateMap(AllRelocateCalls, RelocateInstMap);
1063 if (RelocateInstMap.empty())
1064 return false;
1065
1066 for (auto &Item : RelocateInstMap)
1067 // Item.first is the RelocatedBase to offset against
1068 // Item.second is the vector of Targets to replace
1069 MadeChange = simplifyRelocatesOffABase(Item.first, Item.second);
1070 return MadeChange;
1071}
1072
Manuel Jacoba7c48f92014-03-13 13:36:25 +00001073/// SinkCast - Sink the specified cast instruction into its user blocks
1074static bool SinkCast(CastInst *CI) {
Chris Lattnerf2836d12007-03-31 04:06:36 +00001075 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +00001076
Chris Lattnerf2836d12007-03-31 04:06:36 +00001077 /// InsertedCasts - Only insert a cast in each block once.
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001078 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001079
Chris Lattnerf2836d12007-03-31 04:06:36 +00001080 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001081 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
Chris Lattnerf2836d12007-03-31 04:06:36 +00001082 UI != E; ) {
1083 Use &TheUse = UI.getUse();
1084 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +00001085
Chris Lattnerf2836d12007-03-31 04:06:36 +00001086 // Figure out which BB this cast is used in. For PHI's this is the
1087 // appropriate predecessor block.
1088 BasicBlock *UserBB = User->getParent();
1089 if (PHINode *PN = dyn_cast<PHINode>(User)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001090 UserBB = PN->getIncomingBlock(TheUse);
Chris Lattnerf2836d12007-03-31 04:06:36 +00001091 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001092
Chris Lattnerf2836d12007-03-31 04:06:36 +00001093 // Preincrement use iterator so we don't invalidate it.
1094 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001095
David Majnemer0c80e2e2016-04-27 19:36:38 +00001096 // The first insertion point of a block containing an EH pad is after the
1097 // pad. If the pad is the user, we cannot sink the cast past the pad.
1098 if (User->isEHPad())
1099 continue;
1100
Andrew Kaylord0430e82015-11-23 19:16:15 +00001101 // If the block selected to receive the cast is an EH pad that does not
1102 // allow non-PHI instructions before the terminator, we can't sink the
1103 // cast.
1104 if (UserBB->getTerminator()->isEHPad())
1105 continue;
1106
Chris Lattnerf2836d12007-03-31 04:06:36 +00001107 // If this user is in the same block as the cast, don't change the cast.
1108 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001109
Chris Lattnerf2836d12007-03-31 04:06:36 +00001110 // If we have already inserted a cast into this block, use it.
1111 CastInst *&InsertedCast = InsertedCasts[UserBB];
1112
1113 if (!InsertedCast) {
Bill Wendling8ddfc092011-08-16 20:45:24 +00001114 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001115 assert(InsertPt != UserBB->end());
1116 InsertedCast = CastInst::Create(CI->getOpcode(), CI->getOperand(0),
1117 CI->getType(), "", &*InsertPt);
Chris Lattnerf2836d12007-03-31 04:06:36 +00001118 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001119
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001120 // Replace a use of the cast with a use of the new cast.
Chris Lattnerf2836d12007-03-31 04:06:36 +00001121 TheUse = InsertedCast;
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +00001122 MadeChange = true;
Cameron Zwarichced753f2011-01-05 17:27:27 +00001123 ++NumCastUses;
Chris Lattnerf2836d12007-03-31 04:06:36 +00001124 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001125
Chris Lattnerf2836d12007-03-31 04:06:36 +00001126 // If we removed all uses, nuke the cast.
Duncan Sandsafa84da42008-01-20 16:51:46 +00001127 if (CI->use_empty()) {
Chris Lattnerf2836d12007-03-31 04:06:36 +00001128 CI->eraseFromParent();
Duncan Sandsafa84da42008-01-20 16:51:46 +00001129 MadeChange = true;
1130 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001131
Chris Lattnerf2836d12007-03-31 04:06:36 +00001132 return MadeChange;
1133}
1134
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001135/// If the specified cast instruction is a noop copy (e.g. it's casting from
1136/// one pointer type to another, i32->i8 on PPC), sink it into user blocks to
1137/// reduce the number of virtual registers that must be created and coalesced.
Manuel Jacoba7c48f92014-03-13 13:36:25 +00001138///
1139/// Return true if any changes are made.
1140///
Mehdi Amini44ede332015-07-09 02:09:04 +00001141static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI,
1142 const DataLayout &DL) {
Justin Lebar3e50a5b2016-11-21 22:49:15 +00001143 // Sink only "cheap" (or nop) address-space casts. This is a weaker condition
1144 // than sinking only nop casts, but is helpful on some platforms.
1145 if (auto *ASC = dyn_cast<AddrSpaceCastInst>(CI)) {
1146 if (!TLI.isCheapAddrSpaceCast(ASC->getSrcAddressSpace(),
1147 ASC->getDestAddressSpace()))
1148 return false;
1149 }
1150
Manuel Jacoba7c48f92014-03-13 13:36:25 +00001151 // If this is a noop copy,
Mehdi Amini44ede332015-07-09 02:09:04 +00001152 EVT SrcVT = TLI.getValueType(DL, CI->getOperand(0)->getType());
1153 EVT DstVT = TLI.getValueType(DL, CI->getType());
Manuel Jacoba7c48f92014-03-13 13:36:25 +00001154
1155 // This is an fp<->int conversion?
1156 if (SrcVT.isInteger() != DstVT.isInteger())
1157 return false;
1158
1159 // If this is an extension, it will be a zero or sign extension, which
1160 // isn't a noop.
1161 if (SrcVT.bitsLT(DstVT)) return false;
1162
1163 // If these values will be promoted, find out what they will be promoted
1164 // to. This helps us consider truncates on PPC as noop copies when they
1165 // are.
1166 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
1167 TargetLowering::TypePromoteInteger)
1168 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
1169 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
1170 TargetLowering::TypePromoteInteger)
1171 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
1172
1173 // If, after promotion, these are the same types, this is a noop copy.
1174 if (SrcVT != DstVT)
1175 return false;
1176
1177 return SinkCast(CI);
1178}
1179
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001180/// Try to combine CI into a call to the llvm.uadd.with.overflow intrinsic if
1181/// possible.
Sanjoy Dasb6c59142015-04-10 21:07:09 +00001182///
1183/// Return true if any changes were made.
1184static bool CombineUAddWithOverflow(CmpInst *CI) {
1185 Value *A, *B;
1186 Instruction *AddI;
1187 if (!match(CI,
1188 m_UAddWithOverflow(m_Value(A), m_Value(B), m_Instruction(AddI))))
1189 return false;
1190
1191 Type *Ty = AddI->getType();
1192 if (!isa<IntegerType>(Ty))
1193 return false;
1194
1195 // We don't want to move around uses of condition values this late, so we we
1196 // check if it is legal to create the call to the intrinsic in the basic
1197 // block containing the icmp:
1198
1199 if (AddI->getParent() != CI->getParent() && !AddI->hasOneUse())
1200 return false;
1201
1202#ifndef NDEBUG
1203 // Someday m_UAddWithOverflow may get smarter, but this is a safe assumption
1204 // for now:
1205 if (AddI->hasOneUse())
1206 assert(*AddI->user_begin() == CI && "expected!");
1207#endif
1208
Sanjay Patelaf674fb2015-12-14 17:24:23 +00001209 Module *M = CI->getModule();
Sanjoy Dasb6c59142015-04-10 21:07:09 +00001210 Value *F = Intrinsic::getDeclaration(M, Intrinsic::uadd_with_overflow, Ty);
1211
1212 auto *InsertPt = AddI->hasOneUse() ? CI : AddI;
1213
1214 auto *UAddWithOverflow =
1215 CallInst::Create(F, {A, B}, "uadd.overflow", InsertPt);
1216 auto *UAdd = ExtractValueInst::Create(UAddWithOverflow, 0, "uadd", InsertPt);
1217 auto *Overflow =
1218 ExtractValueInst::Create(UAddWithOverflow, 1, "overflow", InsertPt);
1219
1220 CI->replaceAllUsesWith(Overflow);
1221 AddI->replaceAllUsesWith(UAdd);
1222 CI->eraseFromParent();
1223 AddI->eraseFromParent();
1224 return true;
1225}
1226
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001227/// Sink the given CmpInst into user blocks to reduce the number of virtual
1228/// registers that must be created and coalesced. This is a clear win except on
1229/// targets with multiple condition code registers (PowerPC), where it might
1230/// lose; some adjustment may be wanted there.
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001231///
1232/// Return true if any changes are made.
Peter Zotov8efe38a2016-04-03 19:32:13 +00001233static bool SinkCmpExpression(CmpInst *CI, const TargetLowering *TLI) {
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001234 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +00001235
Peter Zotov0b6d7bc2016-04-03 16:36:17 +00001236 // Avoid sinking soft-FP comparisons, since this can move them into a loop.
Peter Zotov8efe38a2016-04-03 19:32:13 +00001237 if (TLI && TLI->useSoftFloat() && isa<FCmpInst>(CI))
Peter Zotov0b6d7bc2016-04-03 16:36:17 +00001238 return false;
1239
1240 // Only insert a cmp in each block once.
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001241 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001242
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001243 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001244 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001245 UI != E; ) {
1246 Use &TheUse = UI.getUse();
1247 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +00001248
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001249 // Preincrement use iterator so we don't invalidate it.
1250 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001251
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001252 // Don't bother for PHI nodes.
1253 if (isa<PHINode>(User))
1254 continue;
1255
1256 // Figure out which BB this cmp is used in.
1257 BasicBlock *UserBB = User->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +00001258
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001259 // If this user is in the same block as the cmp, don't change the cmp.
1260 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001261
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001262 // If we have already inserted a cmp into this block, use it.
1263 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
1264
1265 if (!InsertedCmp) {
Bill Wendling8ddfc092011-08-16 20:45:24 +00001266 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001267 assert(InsertPt != UserBB->end());
Eric Christopherc1ea1492008-09-24 05:32:41 +00001268 InsertedCmp =
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001269 CmpInst::Create(CI->getOpcode(), CI->getPredicate(),
1270 CI->getOperand(0), CI->getOperand(1), "", &*InsertPt);
Wolfgang Piebe51bede2016-10-06 21:43:45 +00001271 // Propagate the debug info.
1272 InsertedCmp->setDebugLoc(CI->getDebugLoc());
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001273 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001274
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001275 // Replace a use of the cmp with a use of the new cmp.
1276 TheUse = InsertedCmp;
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +00001277 MadeChange = true;
Cameron Zwarichced753f2011-01-05 17:27:27 +00001278 ++NumCmpUses;
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001279 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001280
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001281 // If we removed all uses, nuke the cmp.
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +00001282 if (CI->use_empty()) {
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001283 CI->eraseFromParent();
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +00001284 MadeChange = true;
1285 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001286
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001287 return MadeChange;
1288}
1289
Peter Zotovf87e5502016-04-03 17:11:53 +00001290static bool OptimizeCmpExpression(CmpInst *CI, const TargetLowering *TLI) {
Peter Zotov8efe38a2016-04-03 19:32:13 +00001291 if (SinkCmpExpression(CI, TLI))
Sanjoy Dasb6c59142015-04-10 21:07:09 +00001292 return true;
1293
1294 if (CombineUAddWithOverflow(CI))
1295 return true;
1296
1297 return false;
1298}
1299
Geoff Berry5d534b62017-02-21 18:53:14 +00001300/// Duplicate and sink the given 'and' instruction into user blocks where it is
1301/// used in a compare to allow isel to generate better code for targets where
1302/// this operation can be combined.
1303///
1304/// Return true if any changes are made.
1305static bool sinkAndCmp0Expression(Instruction *AndI,
1306 const TargetLowering &TLI,
1307 SetOfInstrs &InsertedInsts) {
1308 // Double-check that we're not trying to optimize an instruction that was
1309 // already optimized by some other part of this pass.
1310 assert(!InsertedInsts.count(AndI) &&
1311 "Attempting to optimize already optimized and instruction");
1312 (void) InsertedInsts;
1313
1314 // Nothing to do for single use in same basic block.
1315 if (AndI->hasOneUse() &&
1316 AndI->getParent() == cast<Instruction>(*AndI->user_begin())->getParent())
1317 return false;
1318
1319 // Try to avoid cases where sinking/duplicating is likely to increase register
1320 // pressure.
1321 if (!isa<ConstantInt>(AndI->getOperand(0)) &&
1322 !isa<ConstantInt>(AndI->getOperand(1)) &&
1323 AndI->getOperand(0)->hasOneUse() && AndI->getOperand(1)->hasOneUse())
1324 return false;
1325
1326 for (auto *U : AndI->users()) {
1327 Instruction *User = cast<Instruction>(U);
1328
1329 // Only sink for and mask feeding icmp with 0.
1330 if (!isa<ICmpInst>(User))
1331 return false;
1332
1333 auto *CmpC = dyn_cast<ConstantInt>(User->getOperand(1));
1334 if (!CmpC || !CmpC->isZero())
1335 return false;
1336 }
1337
1338 if (!TLI.isMaskAndCmp0FoldingBeneficial(*AndI))
1339 return false;
1340
1341 DEBUG(dbgs() << "found 'and' feeding only icmp 0;\n");
1342 DEBUG(AndI->getParent()->dump());
1343
1344 // Push the 'and' into the same block as the icmp 0. There should only be
1345 // one (icmp (and, 0)) in each block, since CSE/GVN should have removed any
1346 // others, so we don't need to keep track of which BBs we insert into.
1347 for (Value::user_iterator UI = AndI->user_begin(), E = AndI->user_end();
1348 UI != E; ) {
1349 Use &TheUse = UI.getUse();
1350 Instruction *User = cast<Instruction>(*UI);
1351
1352 // Preincrement use iterator so we don't invalidate it.
1353 ++UI;
1354
1355 DEBUG(dbgs() << "sinking 'and' use: " << *User << "\n");
1356
1357 // Keep the 'and' in the same place if the use is already in the same block.
1358 Instruction *InsertPt =
1359 User->getParent() == AndI->getParent() ? AndI : User;
1360 Instruction *InsertedAnd =
1361 BinaryOperator::Create(Instruction::And, AndI->getOperand(0),
1362 AndI->getOperand(1), "", InsertPt);
1363 // Propagate the debug info.
1364 InsertedAnd->setDebugLoc(AndI->getDebugLoc());
1365
1366 // Replace a use of the 'and' with a use of the new 'and'.
1367 TheUse = InsertedAnd;
1368 ++NumAndUses;
1369 DEBUG(User->getParent()->dump());
1370 }
1371
1372 // We removed all uses, nuke the and.
1373 AndI->eraseFromParent();
1374 return true;
1375}
1376
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001377/// Check if the candidates could be combined with a shift instruction, which
1378/// includes:
Yi Jiangd069f632014-04-21 19:34:27 +00001379/// 1. Truncate instruction
1380/// 2. And instruction and the imm is a mask of the low bits:
1381/// imm & (imm+1) == 0
Benjamin Kramer322053c2014-04-27 14:54:59 +00001382static bool isExtractBitsCandidateUse(Instruction *User) {
Yi Jiangd069f632014-04-21 19:34:27 +00001383 if (!isa<TruncInst>(User)) {
1384 if (User->getOpcode() != Instruction::And ||
1385 !isa<ConstantInt>(User->getOperand(1)))
1386 return false;
1387
Quentin Colombetd4f44692014-04-22 01:20:34 +00001388 const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue();
Yi Jiangd069f632014-04-21 19:34:27 +00001389
Quentin Colombetd4f44692014-04-22 01:20:34 +00001390 if ((Cimm & (Cimm + 1)).getBoolValue())
Yi Jiangd069f632014-04-21 19:34:27 +00001391 return false;
1392 }
1393 return true;
1394}
1395
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001396/// Sink both shift and truncate instruction to the use of truncate's BB.
Benjamin Kramer322053c2014-04-27 14:54:59 +00001397static bool
Yi Jiangd069f632014-04-21 19:34:27 +00001398SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI,
1399 DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts,
Mehdi Amini44ede332015-07-09 02:09:04 +00001400 const TargetLowering &TLI, const DataLayout &DL) {
Yi Jiangd069f632014-04-21 19:34:27 +00001401 BasicBlock *UserBB = User->getParent();
1402 DenseMap<BasicBlock *, CastInst *> InsertedTruncs;
1403 TruncInst *TruncI = dyn_cast<TruncInst>(User);
1404 bool MadeChange = false;
1405
1406 for (Value::user_iterator TruncUI = TruncI->user_begin(),
1407 TruncE = TruncI->user_end();
1408 TruncUI != TruncE;) {
1409
1410 Use &TruncTheUse = TruncUI.getUse();
1411 Instruction *TruncUser = cast<Instruction>(*TruncUI);
1412 // Preincrement use iterator so we don't invalidate it.
1413
1414 ++TruncUI;
1415
1416 int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode());
1417 if (!ISDOpcode)
1418 continue;
1419
Tim Northovere2239ff2014-07-29 10:20:22 +00001420 // If the use is actually a legal node, there will not be an
1421 // implicit truncate.
1422 // FIXME: always querying the result type is just an
1423 // approximation; some nodes' legality is determined by the
1424 // operand or other means. There's no good way to find out though.
Ahmed Bougacha0788d492014-11-12 22:16:55 +00001425 if (TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00001426 ISDOpcode, TLI.getValueType(DL, TruncUser->getType(), true)))
Yi Jiangd069f632014-04-21 19:34:27 +00001427 continue;
1428
1429 // Don't bother for PHI nodes.
1430 if (isa<PHINode>(TruncUser))
1431 continue;
1432
1433 BasicBlock *TruncUserBB = TruncUser->getParent();
1434
1435 if (UserBB == TruncUserBB)
1436 continue;
1437
1438 BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB];
1439 CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB];
1440
1441 if (!InsertedShift && !InsertedTrunc) {
1442 BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001443 assert(InsertPt != TruncUserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +00001444 // Sink the shift
1445 if (ShiftI->getOpcode() == Instruction::AShr)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001446 InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
1447 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001448 else
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001449 InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
1450 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001451
1452 // Sink the trunc
1453 BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt();
1454 TruncInsertPt++;
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001455 assert(TruncInsertPt != TruncUserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +00001456
1457 InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift,
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001458 TruncI->getType(), "", &*TruncInsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001459
1460 MadeChange = true;
1461
1462 TruncTheUse = InsertedTrunc;
1463 }
1464 }
1465 return MadeChange;
1466}
1467
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001468/// Sink the shift *right* instruction into user blocks if the uses could
1469/// potentially be combined with this shift instruction and generate BitExtract
1470/// instruction. It will only be applied if the architecture supports BitExtract
1471/// instruction. Here is an example:
Yi Jiangd069f632014-04-21 19:34:27 +00001472/// BB1:
1473/// %x.extract.shift = lshr i64 %arg1, 32
1474/// BB2:
1475/// %x.extract.trunc = trunc i64 %x.extract.shift to i16
1476/// ==>
1477///
1478/// BB2:
1479/// %x.extract.shift.1 = lshr i64 %arg1, 32
1480/// %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16
1481///
1482/// CodeGen will recoginze the pattern in BB2 and generate BitExtract
1483/// instruction.
1484/// Return true if any changes are made.
1485static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI,
Mehdi Amini44ede332015-07-09 02:09:04 +00001486 const TargetLowering &TLI,
1487 const DataLayout &DL) {
Yi Jiangd069f632014-04-21 19:34:27 +00001488 BasicBlock *DefBB = ShiftI->getParent();
1489
1490 /// Only insert instructions in each block once.
1491 DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts;
1492
Mehdi Amini44ede332015-07-09 02:09:04 +00001493 bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(DL, ShiftI->getType()));
Yi Jiangd069f632014-04-21 19:34:27 +00001494
1495 bool MadeChange = false;
1496 for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end();
1497 UI != E;) {
1498 Use &TheUse = UI.getUse();
1499 Instruction *User = cast<Instruction>(*UI);
1500 // Preincrement use iterator so we don't invalidate it.
1501 ++UI;
1502
1503 // Don't bother for PHI nodes.
1504 if (isa<PHINode>(User))
1505 continue;
1506
1507 if (!isExtractBitsCandidateUse(User))
1508 continue;
1509
1510 BasicBlock *UserBB = User->getParent();
1511
1512 if (UserBB == DefBB) {
1513 // If the shift and truncate instruction are in the same BB. The use of
1514 // the truncate(TruncUse) may still introduce another truncate if not
1515 // legal. In this case, we would like to sink both shift and truncate
1516 // instruction to the BB of TruncUse.
1517 // for example:
1518 // BB1:
1519 // i64 shift.result = lshr i64 opnd, imm
1520 // trunc.result = trunc shift.result to i16
1521 //
1522 // BB2:
1523 // ----> We will have an implicit truncate here if the architecture does
1524 // not have i16 compare.
1525 // cmp i16 trunc.result, opnd2
1526 //
1527 if (isa<TruncInst>(User) && shiftIsLegal
1528 // If the type of the truncate is legal, no trucate will be
1529 // introduced in other basic blocks.
Mehdi Amini44ede332015-07-09 02:09:04 +00001530 &&
1531 (!TLI.isTypeLegal(TLI.getValueType(DL, User->getType()))))
Yi Jiangd069f632014-04-21 19:34:27 +00001532 MadeChange =
Mehdi Amini44ede332015-07-09 02:09:04 +00001533 SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI, DL);
Yi Jiangd069f632014-04-21 19:34:27 +00001534
1535 continue;
1536 }
1537 // If we have already inserted a shift into this block, use it.
1538 BinaryOperator *&InsertedShift = InsertedShifts[UserBB];
1539
1540 if (!InsertedShift) {
1541 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001542 assert(InsertPt != UserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +00001543
1544 if (ShiftI->getOpcode() == Instruction::AShr)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001545 InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
1546 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001547 else
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001548 InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
1549 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001550
1551 MadeChange = true;
1552 }
1553
1554 // Replace a use of the shift with a use of the new shift.
1555 TheUse = InsertedShift;
1556 }
1557
1558 // If we removed all uses, nuke the shift.
1559 if (ShiftI->use_empty())
1560 ShiftI->eraseFromParent();
1561
1562 return MadeChange;
1563}
1564
Sanjay Patel4699b8a2015-11-19 16:37:10 +00001565/// If counting leading or trailing zeros is an expensive operation and a zero
1566/// input is defined, add a check for zero to avoid calling the intrinsic.
1567///
1568/// We want to transform:
1569/// %z = call i64 @llvm.cttz.i64(i64 %A, i1 false)
1570///
1571/// into:
1572/// entry:
1573/// %cmpz = icmp eq i64 %A, 0
1574/// br i1 %cmpz, label %cond.end, label %cond.false
1575/// cond.false:
1576/// %z = call i64 @llvm.cttz.i64(i64 %A, i1 true)
1577/// br label %cond.end
1578/// cond.end:
1579/// %ctz = phi i64 [ 64, %entry ], [ %z, %cond.false ]
1580///
1581/// If the transform is performed, return true and set ModifiedDT to true.
1582static bool despeculateCountZeros(IntrinsicInst *CountZeros,
1583 const TargetLowering *TLI,
1584 const DataLayout *DL,
1585 bool &ModifiedDT) {
1586 if (!TLI || !DL)
1587 return false;
1588
1589 // If a zero input is undefined, it doesn't make sense to despeculate that.
1590 if (match(CountZeros->getOperand(1), m_One()))
1591 return false;
1592
1593 // If it's cheap to speculate, there's nothing to do.
1594 auto IntrinsicID = CountZeros->getIntrinsicID();
1595 if ((IntrinsicID == Intrinsic::cttz && TLI->isCheapToSpeculateCttz()) ||
1596 (IntrinsicID == Intrinsic::ctlz && TLI->isCheapToSpeculateCtlz()))
1597 return false;
1598
1599 // Only handle legal scalar cases. Anything else requires too much work.
1600 Type *Ty = CountZeros->getType();
1601 unsigned SizeInBits = Ty->getPrimitiveSizeInBits();
Jun Bum Limbe11bdc2016-05-13 18:38:35 +00001602 if (Ty->isVectorTy() || SizeInBits > DL->getLargestLegalIntTypeSizeInBits())
Sanjay Patel4699b8a2015-11-19 16:37:10 +00001603 return false;
1604
1605 // The intrinsic will be sunk behind a compare against zero and branch.
1606 BasicBlock *StartBlock = CountZeros->getParent();
1607 BasicBlock *CallBlock = StartBlock->splitBasicBlock(CountZeros, "cond.false");
1608
1609 // Create another block after the count zero intrinsic. A PHI will be added
1610 // in this block to select the result of the intrinsic or the bit-width
1611 // constant if the input to the intrinsic is zero.
1612 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(CountZeros));
1613 BasicBlock *EndBlock = CallBlock->splitBasicBlock(SplitPt, "cond.end");
1614
1615 // Set up a builder to create a compare, conditional branch, and PHI.
1616 IRBuilder<> Builder(CountZeros->getContext());
1617 Builder.SetInsertPoint(StartBlock->getTerminator());
1618 Builder.SetCurrentDebugLocation(CountZeros->getDebugLoc());
1619
1620 // Replace the unconditional branch that was created by the first split with
1621 // a compare against zero and a conditional branch.
1622 Value *Zero = Constant::getNullValue(Ty);
1623 Value *Cmp = Builder.CreateICmpEQ(CountZeros->getOperand(0), Zero, "cmpz");
1624 Builder.CreateCondBr(Cmp, EndBlock, CallBlock);
1625 StartBlock->getTerminator()->eraseFromParent();
1626
1627 // Create a PHI in the end block to select either the output of the intrinsic
1628 // or the bit width of the operand.
1629 Builder.SetInsertPoint(&EndBlock->front());
1630 PHINode *PN = Builder.CreatePHI(Ty, 2, "ctz");
1631 CountZeros->replaceAllUsesWith(PN);
1632 Value *BitWidth = Builder.getInt(APInt(SizeInBits, SizeInBits));
1633 PN->addIncoming(BitWidth, StartBlock);
1634 PN->addIncoming(CountZeros, CallBlock);
1635
1636 // We are explicitly handling the zero case, so we can set the intrinsic's
1637 // undefined zero argument to 'true'. This will also prevent reprocessing the
1638 // intrinsic; we only despeculate when a zero input is defined.
1639 CountZeros->setArgOperand(1, Builder.getTrue());
1640 ModifiedDT = true;
1641 return true;
1642}
1643
Zaara Syeda3a7578c2017-05-31 17:12:38 +00001644// This class provides helper functions to expand a memcmp library call into an
1645// inline expansion.
1646class MemCmpExpansion {
1647 struct ResultBlock {
1648 BasicBlock *BB;
1649 PHINode *PhiSrc1;
1650 PHINode *PhiSrc2;
1651 ResultBlock();
1652 };
1653
1654 CallInst *CI;
1655 ResultBlock ResBlock;
1656 unsigned MaxLoadSize;
1657 unsigned NumBlocks;
1658 unsigned NumBlocksNonOneByte;
1659 unsigned NumLoadsPerBlock;
1660 std::vector<BasicBlock *> LoadCmpBlocks;
1661 BasicBlock *EndBlock;
1662 PHINode *PhiRes;
1663 bool IsUsedForZeroCmp;
1664 int calculateNumBlocks(unsigned Size);
1665 void createLoadCmpBlocks();
1666 void createResultBlock();
1667 void setupResultBlockPHINodes();
1668 void setupEndBlockPHINodes();
1669 void emitLoadCompareBlock(unsigned Index, int LoadSize, int GEPIndex,
1670 bool IsLittleEndian);
Sanjay Patel60070002017-06-07 13:33:00 +00001671 Value *getCompareLoadPairs(unsigned Index, unsigned Size,
1672 unsigned &NumBytesProcessed, IRBuilder<> &Builder);
Zaara Syeda3a7578c2017-05-31 17:12:38 +00001673 void emitLoadCompareBlockMultipleLoads(unsigned Index, unsigned Size,
1674 unsigned &NumBytesProcessed);
1675 void emitLoadCompareByteBlock(unsigned Index, int GEPIndex);
1676 void emitMemCmpResultBlock(bool IsLittleEndian);
1677 Value *getMemCmpExpansionZeroCase(unsigned Size, bool IsLittleEndian);
1678 unsigned getLoadSize(unsigned Size);
1679 unsigned getNumLoads(unsigned Size);
1680
1681public:
1682 MemCmpExpansion(CallInst *CI, unsigned MaxLoadSize,
1683 unsigned NumLoadsPerBlock);
Sanjay Patelaf515d92017-06-07 14:45:49 +00001684 Value *getMemCmpExpansion(uint64_t Size, bool IsLittleEndian);
Zaara Syeda3a7578c2017-05-31 17:12:38 +00001685};
1686
1687MemCmpExpansion::ResultBlock::ResultBlock()
1688 : BB(nullptr), PhiSrc1(nullptr), PhiSrc2(nullptr) {}
1689
1690// Initialize the basic block structure required for expansion of memcmp call
1691// with given maximum load size and memcmp size parameter.
1692// This structure includes:
1693// 1. A list of load compare blocks - LoadCmpBlocks.
1694// 2. An EndBlock, split from original instruction point, which is the block to
1695// return from.
1696// 3. ResultBlock, block to branch to for early exit when a
1697// LoadCmpBlock finds a difference.
1698MemCmpExpansion::MemCmpExpansion(CallInst *CI, unsigned MaxLoadSize,
1699 unsigned NumLoadsPerBlock)
1700 : CI(CI), MaxLoadSize(MaxLoadSize), NumLoadsPerBlock(NumLoadsPerBlock) {
1701
1702 IRBuilder<> Builder(CI->getContext());
1703
1704 BasicBlock *StartBlock = CI->getParent();
1705 EndBlock = StartBlock->splitBasicBlock(CI, "endblock");
1706 setupEndBlockPHINodes();
1707 IsUsedForZeroCmp = isOnlyUsedInZeroEqualityComparison(CI);
1708
1709 ConstantInt *SizeCast = dyn_cast<ConstantInt>(CI->getArgOperand(2));
1710 uint64_t Size = SizeCast->getZExtValue();
1711
1712 // Calculate how many load compare blocks are required for an expansion of
1713 // given Size.
1714 NumBlocks = calculateNumBlocks(Size);
1715 createResultBlock();
1716
1717 // If return value of memcmp is not used in a zero equality, we need to
1718 // calculate which source was larger. The calculation requires the
1719 // two loaded source values of each load compare block.
1720 // These will be saved in the phi nodes created by setupResultBlockPHINodes.
1721 if (!IsUsedForZeroCmp)
1722 setupResultBlockPHINodes();
1723
1724 // Create the number of required load compare basic blocks.
1725 createLoadCmpBlocks();
1726
1727 // Update the terminator added by splitBasicBlock to branch to the first
1728 // LoadCmpBlock.
1729 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1730 StartBlock->getTerminator()->setSuccessor(0, LoadCmpBlocks[0]);
1731}
1732
1733void MemCmpExpansion::createLoadCmpBlocks() {
1734 for (unsigned i = 0; i < NumBlocks; i++) {
1735 BasicBlock *BB = BasicBlock::Create(CI->getContext(), "loadbb",
1736 EndBlock->getParent(), EndBlock);
1737 LoadCmpBlocks.push_back(BB);
1738 }
1739}
1740
1741void MemCmpExpansion::createResultBlock() {
1742 ResBlock.BB = BasicBlock::Create(CI->getContext(), "res_block",
1743 EndBlock->getParent(), EndBlock);
1744}
1745
1746// This function creates the IR instructions for loading and comparing 1 byte.
Sanjay Patelab0ecc02017-06-07 12:44:36 +00001747// It loads 1 byte from each source of the memcmp parameters with the given
Zaara Syeda3a7578c2017-05-31 17:12:38 +00001748// GEPIndex. It then subtracts the two loaded values and adds this result to the
1749// final phi node for selecting the memcmp result.
1750void MemCmpExpansion::emitLoadCompareByteBlock(unsigned Index, int GEPIndex) {
1751 IRBuilder<> Builder(CI->getContext());
1752
1753 Value *Source1 = CI->getArgOperand(0);
1754 Value *Source2 = CI->getArgOperand(1);
1755
1756 Builder.SetInsertPoint(LoadCmpBlocks[Index]);
1757 Type *LoadSizeType = Type::getInt8Ty(CI->getContext());
Sanjay Patelb4b7df92017-06-06 20:30:47 +00001758 // Cast source to LoadSizeType*.
Zaara Syeda3a7578c2017-05-31 17:12:38 +00001759 if (Source1->getType() != LoadSizeType)
1760 Source1 = Builder.CreateBitCast(Source1, LoadSizeType->getPointerTo());
1761 if (Source2->getType() != LoadSizeType)
1762 Source2 = Builder.CreateBitCast(Source2, LoadSizeType->getPointerTo());
1763
Sanjay Patelb4b7df92017-06-06 20:30:47 +00001764 // Get the base address using the GEPIndex.
Zaara Syeda3a7578c2017-05-31 17:12:38 +00001765 if (GEPIndex != 0) {
1766 Source1 = Builder.CreateGEP(LoadSizeType, Source1,
1767 ConstantInt::get(LoadSizeType, GEPIndex));
1768 Source2 = Builder.CreateGEP(LoadSizeType, Source2,
1769 ConstantInt::get(LoadSizeType, GEPIndex));
1770 }
1771
1772 Value *LoadSrc1 = Builder.CreateLoad(LoadSizeType, Source1);
1773 Value *LoadSrc2 = Builder.CreateLoad(LoadSizeType, Source2);
1774
1775 LoadSrc1 = Builder.CreateZExt(LoadSrc1, Type::getInt32Ty(CI->getContext()));
1776 LoadSrc2 = Builder.CreateZExt(LoadSrc2, Type::getInt32Ty(CI->getContext()));
1777 Value *Diff = Builder.CreateSub(LoadSrc1, LoadSrc2);
1778
1779 PhiRes->addIncoming(Diff, LoadCmpBlocks[Index]);
1780
1781 if (Index < (LoadCmpBlocks.size() - 1)) {
Sanjay Patelb4b7df92017-06-06 20:30:47 +00001782 // Early exit branch if difference found to EndBlock. Otherwise, continue to
1783 // next LoadCmpBlock,
Zaara Syeda3a7578c2017-05-31 17:12:38 +00001784 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_NE, Diff,
1785 ConstantInt::get(Diff->getType(), 0));
1786 BranchInst *CmpBr =
1787 BranchInst::Create(EndBlock, LoadCmpBlocks[Index + 1], Cmp);
1788 Builder.Insert(CmpBr);
1789 } else {
Sanjay Patelb4b7df92017-06-06 20:30:47 +00001790 // The last block has an unconditional branch to EndBlock.
Zaara Syeda3a7578c2017-05-31 17:12:38 +00001791 BranchInst *CmpBr = BranchInst::Create(EndBlock);
1792 Builder.Insert(CmpBr);
1793 }
1794}
1795
1796unsigned MemCmpExpansion::getNumLoads(unsigned Size) {
1797 return (Size / MaxLoadSize) + countPopulation(Size % MaxLoadSize);
1798}
1799
1800unsigned MemCmpExpansion::getLoadSize(unsigned Size) {
1801 return MinAlign(PowerOf2Floor(Size), MaxLoadSize);
1802}
1803
Sanjay Patel60070002017-06-07 13:33:00 +00001804/// Generate an equality comparison for one or more pairs of loaded values.
1805/// This is used in the case where the memcmp() call is compared equal or not
1806/// equal to zero.
1807Value *MemCmpExpansion::getCompareLoadPairs(unsigned Index, unsigned Size,
1808 unsigned &NumBytesProcessed,
1809 IRBuilder<> &Builder) {
Zaara Syeda3a7578c2017-05-31 17:12:38 +00001810 std::vector<Value *> XorList, OrList;
1811 Value *Diff;
1812
1813 unsigned RemainingBytes = Size - NumBytesProcessed;
1814 unsigned NumLoadsRemaining = getNumLoads(RemainingBytes);
1815 unsigned NumLoads = std::min(NumLoadsRemaining, NumLoadsPerBlock);
1816
1817 Builder.SetInsertPoint(LoadCmpBlocks[Index]);
Sanjay Patelf57015d2017-06-07 00:17:08 +00001818 Value *Cmp = nullptr;
Zaara Syeda3a7578c2017-05-31 17:12:38 +00001819 for (unsigned i = 0; i < NumLoads; ++i) {
1820 unsigned LoadSize = getLoadSize(RemainingBytes);
1821 unsigned GEPIndex = NumBytesProcessed / LoadSize;
1822 NumBytesProcessed += LoadSize;
1823 RemainingBytes -= LoadSize;
1824
1825 Type *LoadSizeType = IntegerType::get(CI->getContext(), LoadSize * 8);
1826 Type *MaxLoadType = IntegerType::get(CI->getContext(), MaxLoadSize * 8);
1827
1828 Value *Source1 = CI->getArgOperand(0);
1829 Value *Source2 = CI->getArgOperand(1);
1830
Sanjay Patelb4b7df92017-06-06 20:30:47 +00001831 // Cast source to LoadSizeType*.
Zaara Syeda3a7578c2017-05-31 17:12:38 +00001832 if (Source1->getType() != LoadSizeType)
1833 Source1 = Builder.CreateBitCast(Source1, LoadSizeType->getPointerTo());
1834 if (Source2->getType() != LoadSizeType)
1835 Source2 = Builder.CreateBitCast(Source2, LoadSizeType->getPointerTo());
1836
Sanjay Patelb4b7df92017-06-06 20:30:47 +00001837 // Get the base address using the GEPIndex.
Zaara Syeda3a7578c2017-05-31 17:12:38 +00001838 if (GEPIndex != 0) {
1839 Source1 = Builder.CreateGEP(LoadSizeType, Source1,
1840 ConstantInt::get(LoadSizeType, GEPIndex));
1841 Source2 = Builder.CreateGEP(LoadSizeType, Source2,
1842 ConstantInt::get(LoadSizeType, GEPIndex));
1843 }
1844
Sanjay Patelb4b7df92017-06-06 20:30:47 +00001845 // Load LoadSizeType from the base address.
Zaara Syeda3a7578c2017-05-31 17:12:38 +00001846 Value *LoadSrc1 = Builder.CreateLoad(LoadSizeType, Source1);
1847 Value *LoadSrc2 = Builder.CreateLoad(LoadSizeType, Source2);
1848 if (LoadSizeType != MaxLoadType) {
1849 LoadSrc1 = Builder.CreateZExtOrTrunc(LoadSrc1, MaxLoadType);
1850 LoadSrc2 = Builder.CreateZExtOrTrunc(LoadSrc2, MaxLoadType);
1851 }
Sanjay Patelf57015d2017-06-07 00:17:08 +00001852 if (NumLoads != 1) {
1853 // If we have multiple loads per block, we need to generate a composite
1854 // comparison using xor+or.
1855 Diff = Builder.CreateXor(LoadSrc1, LoadSrc2);
1856 Diff = Builder.CreateZExtOrTrunc(Diff, MaxLoadType);
1857 XorList.push_back(Diff);
1858 } else {
1859 // If there's only one load per block, we just compare the loaded values.
1860 Cmp = Builder.CreateICmpNE(LoadSrc1, LoadSrc2);
1861 }
Zaara Syeda3a7578c2017-05-31 17:12:38 +00001862 }
1863
1864 auto pairWiseOr = [&](std::vector<Value *> &InList) -> std::vector<Value *> {
1865 std::vector<Value *> OutList;
1866 for (unsigned i = 0; i < InList.size() - 1; i = i + 2) {
1867 Value *Or = Builder.CreateOr(InList[i], InList[i + 1]);
1868 OutList.push_back(Or);
1869 }
1870 if (InList.size() % 2 != 0)
1871 OutList.push_back(InList.back());
1872 return OutList;
1873 };
1874
Sanjay Patelf57015d2017-06-07 00:17:08 +00001875 if (!Cmp) {
1876 // Pairwise OR the XOR results.
1877 OrList = pairWiseOr(XorList);
Zaara Syeda3a7578c2017-05-31 17:12:38 +00001878
Sanjay Patelf57015d2017-06-07 00:17:08 +00001879 // Pairwise OR the OR results until one result left.
1880 while (OrList.size() != 1) {
1881 OrList = pairWiseOr(OrList);
1882 }
1883 Cmp = Builder.CreateICmpNE(OrList[0], ConstantInt::get(Diff->getType(), 0));
Zaara Syeda3a7578c2017-05-31 17:12:38 +00001884 }
1885
Sanjay Patel60070002017-06-07 13:33:00 +00001886 return Cmp;
1887}
1888
1889void MemCmpExpansion::emitLoadCompareBlockMultipleLoads(
1890 unsigned Index, unsigned Size, unsigned &NumBytesProcessed) {
1891 IRBuilder<> Builder(CI->getContext());
1892 Value *Cmp = getCompareLoadPairs(Index, Size, NumBytesProcessed, Builder);
1893
Zaara Syeda3a7578c2017-05-31 17:12:38 +00001894 BasicBlock *NextBB = (Index == (LoadCmpBlocks.size() - 1))
1895 ? EndBlock
1896 : LoadCmpBlocks[Index + 1];
Sanjay Patelb4b7df92017-06-06 20:30:47 +00001897 // Early exit branch if difference found to ResultBlock. Otherwise,
1898 // continue to next LoadCmpBlock or EndBlock.
Zaara Syeda3a7578c2017-05-31 17:12:38 +00001899 BranchInst *CmpBr = BranchInst::Create(ResBlock.BB, NextBB, Cmp);
1900 Builder.Insert(CmpBr);
1901
1902 // Add a phi edge for the last LoadCmpBlock to Endblock with a value of 0
1903 // since early exit to ResultBlock was not taken (no difference was found in
Sanjay Patelb4b7df92017-06-06 20:30:47 +00001904 // any of the bytes).
Zaara Syeda3a7578c2017-05-31 17:12:38 +00001905 if (Index == LoadCmpBlocks.size() - 1) {
1906 Value *Zero = ConstantInt::get(Type::getInt32Ty(CI->getContext()), 0);
1907 PhiRes->addIncoming(Zero, LoadCmpBlocks[Index]);
1908 }
1909}
1910
1911// This function creates the IR intructions for loading and comparing using the
1912// given LoadSize. It loads the number of bytes specified by LoadSize from each
1913// source of the memcmp parameters. It then does a subtract to see if there was
1914// a difference in the loaded values. If a difference is found, it branches
1915// with an early exit to the ResultBlock for calculating which source was
1916// larger. Otherwise, it falls through to the either the next LoadCmpBlock or
1917// the EndBlock if this is the last LoadCmpBlock. Loading 1 byte is handled with
1918// a special case through emitLoadCompareByteBlock. The special handling can
1919// simply subtract the loaded values and add it to the result phi node.
1920void MemCmpExpansion::emitLoadCompareBlock(unsigned Index, int LoadSize,
1921 int GEPIndex, bool IsLittleEndian) {
1922 if (LoadSize == 1) {
1923 MemCmpExpansion::emitLoadCompareByteBlock(Index, GEPIndex);
1924 return;
1925 }
1926
1927 IRBuilder<> Builder(CI->getContext());
1928
1929 Type *LoadSizeType = IntegerType::get(CI->getContext(), LoadSize * 8);
1930 Type *MaxLoadType = IntegerType::get(CI->getContext(), MaxLoadSize * 8);
1931
1932 Value *Source1 = CI->getArgOperand(0);
1933 Value *Source2 = CI->getArgOperand(1);
1934
1935 Builder.SetInsertPoint(LoadCmpBlocks[Index]);
Sanjay Patelb4b7df92017-06-06 20:30:47 +00001936 // Cast source to LoadSizeType*.
Zaara Syeda3a7578c2017-05-31 17:12:38 +00001937 if (Source1->getType() != LoadSizeType)
1938 Source1 = Builder.CreateBitCast(Source1, LoadSizeType->getPointerTo());
1939 if (Source2->getType() != LoadSizeType)
1940 Source2 = Builder.CreateBitCast(Source2, LoadSizeType->getPointerTo());
1941
Sanjay Patelb4b7df92017-06-06 20:30:47 +00001942 // Get the base address using the GEPIndex.
Zaara Syeda3a7578c2017-05-31 17:12:38 +00001943 if (GEPIndex != 0) {
1944 Source1 = Builder.CreateGEP(LoadSizeType, Source1,
1945 ConstantInt::get(LoadSizeType, GEPIndex));
1946 Source2 = Builder.CreateGEP(LoadSizeType, Source2,
1947 ConstantInt::get(LoadSizeType, GEPIndex));
1948 }
1949
Sanjay Patelb4b7df92017-06-06 20:30:47 +00001950 // Load LoadSizeType from the base address.
Zaara Syeda3a7578c2017-05-31 17:12:38 +00001951 Value *LoadSrc1 = Builder.CreateLoad(LoadSizeType, Source1);
1952 Value *LoadSrc2 = Builder.CreateLoad(LoadSizeType, Source2);
1953
1954 if (IsLittleEndian) {
1955 Function *F = LoadCmpBlocks[Index]->getParent();
1956
1957 Function *Bswap = Intrinsic::getDeclaration(F->getParent(),
1958 Intrinsic::bswap, LoadSizeType);
1959 LoadSrc1 = Builder.CreateCall(Bswap, LoadSrc1);
1960 LoadSrc2 = Builder.CreateCall(Bswap, LoadSrc2);
1961 }
1962
1963 if (LoadSizeType != MaxLoadType) {
1964 LoadSrc1 = Builder.CreateZExtOrTrunc(LoadSrc1, MaxLoadType);
1965 LoadSrc2 = Builder.CreateZExtOrTrunc(LoadSrc2, MaxLoadType);
1966 }
1967
1968 // Add the loaded values to the phi nodes for calculating memcmp result only
1969 // if result is not used in a zero equality.
1970 if (!IsUsedForZeroCmp) {
1971 ResBlock.PhiSrc1->addIncoming(LoadSrc1, LoadCmpBlocks[Index]);
1972 ResBlock.PhiSrc2->addIncoming(LoadSrc2, LoadCmpBlocks[Index]);
1973 }
1974
1975 Value *Diff = Builder.CreateSub(LoadSrc1, LoadSrc2);
1976
1977 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_NE, Diff,
1978 ConstantInt::get(Diff->getType(), 0));
1979 BasicBlock *NextBB = (Index == (LoadCmpBlocks.size() - 1))
1980 ? EndBlock
1981 : LoadCmpBlocks[Index + 1];
Sanjay Patelb4b7df92017-06-06 20:30:47 +00001982 // Early exit branch if difference found to ResultBlock. Otherwise, continue
1983 // to next LoadCmpBlock or EndBlock.
Zaara Syeda3a7578c2017-05-31 17:12:38 +00001984 BranchInst *CmpBr = BranchInst::Create(ResBlock.BB, NextBB, Cmp);
1985 Builder.Insert(CmpBr);
1986
1987 // Add a phi edge for the last LoadCmpBlock to Endblock with a value of 0
1988 // since early exit to ResultBlock was not taken (no difference was found in
Sanjay Patelb4b7df92017-06-06 20:30:47 +00001989 // any of the bytes).
Zaara Syeda3a7578c2017-05-31 17:12:38 +00001990 if (Index == LoadCmpBlocks.size() - 1) {
1991 Value *Zero = ConstantInt::get(Type::getInt32Ty(CI->getContext()), 0);
1992 PhiRes->addIncoming(Zero, LoadCmpBlocks[Index]);
1993 }
1994}
1995
1996// This function populates the ResultBlock with a sequence to calculate the
1997// memcmp result. It compares the two loaded source values and returns -1 if
1998// src1 < src2 and 1 if src1 > src2.
1999void MemCmpExpansion::emitMemCmpResultBlock(bool IsLittleEndian) {
2000 IRBuilder<> Builder(CI->getContext());
2001
2002 // Special case: if memcmp result is used in a zero equality, result does not
2003 // need to be calculated and can simply return 1.
2004 if (IsUsedForZeroCmp) {
2005 BasicBlock::iterator InsertPt = ResBlock.BB->getFirstInsertionPt();
2006 Builder.SetInsertPoint(ResBlock.BB, InsertPt);
2007 Value *Res = ConstantInt::get(Type::getInt32Ty(CI->getContext()), 1);
2008 PhiRes->addIncoming(Res, ResBlock.BB);
2009 BranchInst *NewBr = BranchInst::Create(EndBlock);
2010 Builder.Insert(NewBr);
2011 return;
2012 }
2013 BasicBlock::iterator InsertPt = ResBlock.BB->getFirstInsertionPt();
2014 Builder.SetInsertPoint(ResBlock.BB, InsertPt);
2015
2016 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_ULT, ResBlock.PhiSrc1,
2017 ResBlock.PhiSrc2);
2018
2019 Value *Res =
2020 Builder.CreateSelect(Cmp, ConstantInt::get(Builder.getInt32Ty(), -1),
2021 ConstantInt::get(Builder.getInt32Ty(), 1));
2022
2023 BranchInst *NewBr = BranchInst::Create(EndBlock);
2024 Builder.Insert(NewBr);
2025 PhiRes->addIncoming(Res, ResBlock.BB);
2026}
2027
2028int MemCmpExpansion::calculateNumBlocks(unsigned Size) {
2029 int NumBlocks = 0;
Sanjay Patelab0ecc02017-06-07 12:44:36 +00002030 bool HaveOneByteLoad = false;
Zaara Syeda3a7578c2017-05-31 17:12:38 +00002031 unsigned RemainingSize = Size;
2032 unsigned LoadSize = MaxLoadSize;
2033 while (RemainingSize) {
2034 if (LoadSize == 1)
Sanjay Patelab0ecc02017-06-07 12:44:36 +00002035 HaveOneByteLoad = true;
Zaara Syeda3a7578c2017-05-31 17:12:38 +00002036 NumBlocks += RemainingSize / LoadSize;
2037 RemainingSize = RemainingSize % LoadSize;
2038 LoadSize = LoadSize / 2;
2039 }
Sanjay Patelab0ecc02017-06-07 12:44:36 +00002040 NumBlocksNonOneByte = HaveOneByteLoad ? (NumBlocks - 1) : NumBlocks;
Zaara Syeda3a7578c2017-05-31 17:12:38 +00002041
2042 if (IsUsedForZeroCmp)
2043 NumBlocks = NumBlocks / NumLoadsPerBlock +
2044 (NumBlocks % NumLoadsPerBlock != 0 ? 1 : 0);
2045
2046 return NumBlocks;
2047}
2048
2049void MemCmpExpansion::setupResultBlockPHINodes() {
2050 IRBuilder<> Builder(CI->getContext());
2051 Type *MaxLoadType = IntegerType::get(CI->getContext(), MaxLoadSize * 8);
2052 Builder.SetInsertPoint(ResBlock.BB);
2053 ResBlock.PhiSrc1 =
2054 Builder.CreatePHI(MaxLoadType, NumBlocksNonOneByte, "phi.src1");
2055 ResBlock.PhiSrc2 =
2056 Builder.CreatePHI(MaxLoadType, NumBlocksNonOneByte, "phi.src2");
2057}
2058
2059void MemCmpExpansion::setupEndBlockPHINodes() {
2060 IRBuilder<> Builder(CI->getContext());
2061
2062 Builder.SetInsertPoint(&EndBlock->front());
2063 PhiRes = Builder.CreatePHI(Type::getInt32Ty(CI->getContext()), 2, "phi.res");
2064}
2065
2066Value *MemCmpExpansion::getMemCmpExpansionZeroCase(unsigned Size,
2067 bool IsLittleEndian) {
2068 unsigned NumBytesProcessed = 0;
Sanjay Patelb4b7df92017-06-06 20:30:47 +00002069 // This loop populates each of the LoadCmpBlocks with the IR sequence to
2070 // handle multiple loads per block.
Sanjay Patelab0ecc02017-06-07 12:44:36 +00002071 for (unsigned i = 0; i < NumBlocks; ++i)
Zaara Syeda3a7578c2017-05-31 17:12:38 +00002072 emitLoadCompareBlockMultipleLoads(i, Size, NumBytesProcessed);
Zaara Syeda3a7578c2017-05-31 17:12:38 +00002073
2074 emitMemCmpResultBlock(IsLittleEndian);
2075 return PhiRes;
2076}
2077
2078// This function expands the memcmp call into an inline expansion and returns
2079// the memcmp result.
Sanjay Patelaf515d92017-06-07 14:45:49 +00002080Value *MemCmpExpansion::getMemCmpExpansion(uint64_t Size, bool IsLittleEndian) {
Sanjay Patelab0ecc02017-06-07 12:44:36 +00002081 if (IsUsedForZeroCmp)
Zaara Syeda3a7578c2017-05-31 17:12:38 +00002082 return getMemCmpExpansionZeroCase(Size, IsLittleEndian);
Zaara Syeda3a7578c2017-05-31 17:12:38 +00002083
Sanjay Patelaf515d92017-06-07 14:45:49 +00002084 // This loop calls emitLoadCompareBlock for comparing Size bytes of the two
Sanjay Patelb4b7df92017-06-06 20:30:47 +00002085 // memcmp sources. It starts with loading using the maximum load size set by
Zaara Syeda3a7578c2017-05-31 17:12:38 +00002086 // the target. It processes any remaining bytes using a load size which is the
2087 // next smallest power of 2.
Sanjay Patelaf515d92017-06-07 14:45:49 +00002088 int LoadSize = MaxLoadSize;
2089 int NumBytesToBeProcessed = Size;
2090 unsigned Index = 0;
Zaara Syeda3a7578c2017-05-31 17:12:38 +00002091 while (NumBytesToBeProcessed) {
Sanjay Patelaf515d92017-06-07 14:45:49 +00002092 // Calculate how many blocks we can create with the current load size.
Zaara Syeda3a7578c2017-05-31 17:12:38 +00002093 int NumBlocks = NumBytesToBeProcessed / LoadSize;
2094 int GEPIndex = (Size - NumBytesToBeProcessed) / LoadSize;
2095 NumBytesToBeProcessed = NumBytesToBeProcessed % LoadSize;
2096
2097 // For each NumBlocks, populate the instruction sequence for loading and
Sanjay Patelb4b7df92017-06-06 20:30:47 +00002098 // comparing LoadSize bytes.
Zaara Syeda3a7578c2017-05-31 17:12:38 +00002099 while (NumBlocks--) {
2100 emitLoadCompareBlock(Index, LoadSize, GEPIndex, IsLittleEndian);
2101 Index++;
2102 GEPIndex++;
2103 }
Sanjay Patelb4b7df92017-06-06 20:30:47 +00002104 // Get the next LoadSize to use.
Zaara Syeda3a7578c2017-05-31 17:12:38 +00002105 LoadSize = LoadSize / 2;
2106 }
2107
2108 emitMemCmpResultBlock(IsLittleEndian);
2109 return PhiRes;
2110}
2111
2112// This function checks to see if an expansion of memcmp can be generated.
2113// It checks for constant compare size that is less than the max inline size.
2114// If an expansion cannot occur, returns false to leave as a library call.
Sanjay Patelb4b7df92017-06-06 20:30:47 +00002115// Otherwise, the library call is replaced with a new IR instruction sequence.
Zaara Syeda3a7578c2017-05-31 17:12:38 +00002116/// We want to transform:
2117/// %call = call signext i32 @memcmp(i8* %0, i8* %1, i64 15)
2118/// To:
2119/// loadbb:
2120/// %0 = bitcast i32* %buffer2 to i8*
2121/// %1 = bitcast i32* %buffer1 to i8*
2122/// %2 = bitcast i8* %1 to i64*
2123/// %3 = bitcast i8* %0 to i64*
2124/// %4 = load i64, i64* %2
2125/// %5 = load i64, i64* %3
2126/// %6 = call i64 @llvm.bswap.i64(i64 %4)
2127/// %7 = call i64 @llvm.bswap.i64(i64 %5)
2128/// %8 = sub i64 %6, %7
2129/// %9 = icmp ne i64 %8, 0
2130/// br i1 %9, label %res_block, label %loadbb1
2131/// res_block: ; preds = %loadbb2,
2132/// %loadbb1, %loadbb
2133/// %phi.src1 = phi i64 [ %6, %loadbb ], [ %22, %loadbb1 ], [ %36, %loadbb2 ]
2134/// %phi.src2 = phi i64 [ %7, %loadbb ], [ %23, %loadbb1 ], [ %37, %loadbb2 ]
2135/// %10 = icmp ult i64 %phi.src1, %phi.src2
2136/// %11 = select i1 %10, i32 -1, i32 1
2137/// br label %endblock
2138/// loadbb1: ; preds = %loadbb
2139/// %12 = bitcast i32* %buffer2 to i8*
2140/// %13 = bitcast i32* %buffer1 to i8*
2141/// %14 = bitcast i8* %13 to i32*
2142/// %15 = bitcast i8* %12 to i32*
2143/// %16 = getelementptr i32, i32* %14, i32 2
2144/// %17 = getelementptr i32, i32* %15, i32 2
2145/// %18 = load i32, i32* %16
2146/// %19 = load i32, i32* %17
2147/// %20 = call i32 @llvm.bswap.i32(i32 %18)
2148/// %21 = call i32 @llvm.bswap.i32(i32 %19)
2149/// %22 = zext i32 %20 to i64
2150/// %23 = zext i32 %21 to i64
2151/// %24 = sub i64 %22, %23
2152/// %25 = icmp ne i64 %24, 0
2153/// br i1 %25, label %res_block, label %loadbb2
2154/// loadbb2: ; preds = %loadbb1
2155/// %26 = bitcast i32* %buffer2 to i8*
2156/// %27 = bitcast i32* %buffer1 to i8*
2157/// %28 = bitcast i8* %27 to i16*
2158/// %29 = bitcast i8* %26 to i16*
2159/// %30 = getelementptr i16, i16* %28, i16 6
2160/// %31 = getelementptr i16, i16* %29, i16 6
2161/// %32 = load i16, i16* %30
2162/// %33 = load i16, i16* %31
2163/// %34 = call i16 @llvm.bswap.i16(i16 %32)
2164/// %35 = call i16 @llvm.bswap.i16(i16 %33)
2165/// %36 = zext i16 %34 to i64
2166/// %37 = zext i16 %35 to i64
2167/// %38 = sub i64 %36, %37
2168/// %39 = icmp ne i64 %38, 0
2169/// br i1 %39, label %res_block, label %loadbb3
2170/// loadbb3: ; preds = %loadbb2
2171/// %40 = bitcast i32* %buffer2 to i8*
2172/// %41 = bitcast i32* %buffer1 to i8*
2173/// %42 = getelementptr i8, i8* %41, i8 14
2174/// %43 = getelementptr i8, i8* %40, i8 14
2175/// %44 = load i8, i8* %42
2176/// %45 = load i8, i8* %43
2177/// %46 = zext i8 %44 to i32
2178/// %47 = zext i8 %45 to i32
2179/// %48 = sub i32 %46, %47
2180/// br label %endblock
2181/// endblock: ; preds = %res_block,
2182/// %loadbb3
2183/// %phi.res = phi i32 [ %48, %loadbb3 ], [ %11, %res_block ]
2184/// ret i32 %phi.res
2185static bool expandMemCmp(CallInst *CI, const TargetTransformInfo *TTI,
2186 const TargetLowering *TLI, const DataLayout *DL) {
2187 NumMemCmpCalls++;
2188 IRBuilder<> Builder(CI->getContext());
2189
Sanjay Patelb4b7df92017-06-06 20:30:47 +00002190 // TTI call to check if target would like to expand memcmp. Also, get the
2191 // MaxLoadSize.
Zaara Syeda3a7578c2017-05-31 17:12:38 +00002192 unsigned MaxLoadSize;
2193 if (!TTI->expandMemCmp(CI, MaxLoadSize))
2194 return false;
2195
Sanjay Patelb4b7df92017-06-06 20:30:47 +00002196 // Early exit from expansion if -Oz.
Sanjay Patel4137d512017-06-07 14:29:52 +00002197 if (CI->getFunction()->optForMinSize())
Zaara Syeda3a7578c2017-05-31 17:12:38 +00002198 return false;
Zaara Syeda3a7578c2017-05-31 17:12:38 +00002199
Sanjay Patelb4b7df92017-06-06 20:30:47 +00002200 // Early exit from expansion if size is not a constant.
Zaara Syeda3a7578c2017-05-31 17:12:38 +00002201 ConstantInt *SizeCast = dyn_cast<ConstantInt>(CI->getArgOperand(2));
2202 if (!SizeCast) {
2203 NumMemCmpNotConstant++;
2204 return false;
2205 }
2206
Sanjay Patelb4b7df92017-06-06 20:30:47 +00002207 // Early exit from expansion if size greater than max bytes to load.
Zaara Syeda3a7578c2017-05-31 17:12:38 +00002208 uint64_t SizeVal = SizeCast->getZExtValue();
2209
2210 unsigned NumLoads = 0;
2211 unsigned RemainingSize = SizeVal;
2212 unsigned LoadSize = MaxLoadSize;
2213 while (RemainingSize) {
2214 NumLoads += RemainingSize / LoadSize;
2215 RemainingSize = RemainingSize % LoadSize;
2216 LoadSize = LoadSize / 2;
2217 }
2218
Sanjay Patel4137d512017-06-07 14:29:52 +00002219 if (NumLoads > TLI->getMaxExpandSizeMemcmp(CI->getFunction()->optForSize())) {
Zaara Syeda3a7578c2017-05-31 17:12:38 +00002220 NumMemCmpGreaterThanMax++;
2221 return false;
2222 }
2223
2224 NumMemCmpInlined++;
2225
Sanjay Patelb4b7df92017-06-06 20:30:47 +00002226 // MemCmpHelper object creates and sets up basic blocks required for
2227 // expanding memcmp with size SizeVal.
Zaara Syeda3a7578c2017-05-31 17:12:38 +00002228 unsigned NumLoadsPerBlock = MemCmpNumLoadsPerBlock;
2229 MemCmpExpansion MemCmpHelper(CI, MaxLoadSize, NumLoadsPerBlock);
2230
Sanjay Patelaf515d92017-06-07 14:45:49 +00002231 Value *Res = MemCmpHelper.getMemCmpExpansion(SizeVal, DL->isLittleEndian());
Zaara Syeda3a7578c2017-05-31 17:12:38 +00002232
Sanjay Patelb4b7df92017-06-06 20:30:47 +00002233 // Replace call with result of expansion and erase call.
Zaara Syeda3a7578c2017-05-31 17:12:38 +00002234 CI->replaceAllUsesWith(Res);
2235 CI->eraseFromParent();
2236
2237 return true;
2238}
2239
Sanjay Patelfc580a62015-09-21 23:03:16 +00002240bool CodeGenPrepare::optimizeCallInst(CallInst *CI, bool& ModifiedDT) {
Chris Lattner7a277142011-01-15 07:14:54 +00002241 BasicBlock *BB = CI->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +00002242
Chris Lattner7a277142011-01-15 07:14:54 +00002243 // Lower inline assembly if we can.
2244 // If we found an inline asm expession, and if the target knows how to
2245 // lower it to normal LLVM code, do so now.
2246 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
2247 if (TLI->ExpandInlineAsm(CI)) {
2248 // Avoid invalidating the iterator.
2249 CurInstIterator = BB->begin();
2250 // Avoid processing instructions out of order, which could cause
2251 // reuse before a value is defined.
2252 SunkAddrs.clear();
2253 return true;
2254 }
2255 // Sink address computing for memory operands into the block.
Sanjay Patelfc580a62015-09-21 23:03:16 +00002256 if (optimizeInlineAsmInst(CI))
Chris Lattner7a277142011-01-15 07:14:54 +00002257 return true;
2258 }
Nadav Rotem465834c2012-07-24 10:51:42 +00002259
John Brawn0dbcd652015-03-18 12:01:59 +00002260 // Align the pointer arguments to this call if the target thinks it's a good
2261 // idea
2262 unsigned MinSize, PrefAlign;
Mehdi Amini4fe37982015-07-07 18:45:17 +00002263 if (TLI && TLI->shouldAlignPointerArgs(CI, MinSize, PrefAlign)) {
John Brawn0dbcd652015-03-18 12:01:59 +00002264 for (auto &Arg : CI->arg_operands()) {
2265 // We want to align both objects whose address is used directly and
2266 // objects whose address is used in casts and GEPs, though it only makes
2267 // sense for GEPs if the offset is a multiple of the desired alignment and
2268 // if size - offset meets the size threshold.
2269 if (!Arg->getType()->isPointerTy())
2270 continue;
Mehdi Amini4fe37982015-07-07 18:45:17 +00002271 APInt Offset(DL->getPointerSizeInBits(
2272 cast<PointerType>(Arg->getType())->getAddressSpace()),
2273 0);
2274 Value *Val = Arg->stripAndAccumulateInBoundsConstantOffsets(*DL, Offset);
John Brawn0dbcd652015-03-18 12:01:59 +00002275 uint64_t Offset2 = Offset.getLimitedValue();
John Brawne8fd6c82015-04-13 10:47:39 +00002276 if ((Offset2 & (PrefAlign-1)) != 0)
2277 continue;
John Brawn0dbcd652015-03-18 12:01:59 +00002278 AllocaInst *AI;
Mehdi Amini4fe37982015-07-07 18:45:17 +00002279 if ((AI = dyn_cast<AllocaInst>(Val)) && AI->getAlignment() < PrefAlign &&
2280 DL->getTypeAllocSize(AI->getAllocatedType()) >= MinSize + Offset2)
John Brawn0dbcd652015-03-18 12:01:59 +00002281 AI->setAlignment(PrefAlign);
John Brawne8fd6c82015-04-13 10:47:39 +00002282 // Global variables can only be aligned if they are defined in this
2283 // object (i.e. they are uniquely initialized in this object), and
2284 // over-aligning global variables that have an explicit section is
2285 // forbidden.
2286 GlobalVariable *GV;
James Y Knightac03dca2016-01-15 16:33:06 +00002287 if ((GV = dyn_cast<GlobalVariable>(Val)) && GV->canIncreaseAlignment() &&
Tim Northover918f0502016-07-18 18:28:52 +00002288 GV->getPointerAlignment(*DL) < PrefAlign &&
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00002289 DL->getTypeAllocSize(GV->getValueType()) >=
Mehdi Amini4fe37982015-07-07 18:45:17 +00002290 MinSize + Offset2)
John Brawne8fd6c82015-04-13 10:47:39 +00002291 GV->setAlignment(PrefAlign);
John Brawn0dbcd652015-03-18 12:01:59 +00002292 }
2293 // If this is a memcpy (or similar) then we may be able to improve the
2294 // alignment
2295 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(CI)) {
Mehdi Amini4fe37982015-07-07 18:45:17 +00002296 unsigned Align = getKnownAlignment(MI->getDest(), *DL);
John Brawn0dbcd652015-03-18 12:01:59 +00002297 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
Mehdi Amini4fe37982015-07-07 18:45:17 +00002298 Align = std::min(Align, getKnownAlignment(MTI->getSource(), *DL));
Pete Cooper67cf9a72015-11-19 05:56:52 +00002299 if (Align > MI->getAlignment())
2300 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(), Align));
John Brawn0dbcd652015-03-18 12:01:59 +00002301 }
2302 }
2303
Philip Reamesac115ed2016-03-09 23:13:12 +00002304 // If we have a cold call site, try to sink addressing computation into the
2305 // cold block. This interacts with our handling for loads and stores to
2306 // ensure that we can fold all uses of a potential addressing computation
2307 // into their uses. TODO: generalize this to work over profiling data
2308 if (!OptSize && CI->hasFnAttr(Attribute::Cold))
2309 for (auto &Arg : CI->arg_operands()) {
2310 if (!Arg->getType()->isPointerTy())
2311 continue;
2312 unsigned AS = Arg->getType()->getPointerAddressSpace();
2313 return optimizeMemoryInst(CI, Arg, Arg->getType(), AS);
2314 }
Junmo Park6098cbb2016-03-11 07:05:32 +00002315
Eric Christopher4b7948e2010-03-11 02:41:03 +00002316 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00002317 if (II) {
2318 switch (II->getIntrinsicID()) {
2319 default: break;
2320 case Intrinsic::objectsize: {
2321 // Lower all uses of llvm.objectsize.*
George Burgess IV3f089142016-12-20 23:46:36 +00002322 ConstantInt *RetVal =
2323 lowerObjectSizeCall(II, *DL, TLInfo, /*MustSucceed=*/true);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00002324 // Substituting this can cause recursive simplifications, which can
Sanjoy Dase6bca0e2017-05-01 17:07:49 +00002325 // invalidate our iterator. Use a WeakTrackingVH to hold onto it in case
2326 // this
Sanjoy Das2cbeb002017-04-26 16:37:05 +00002327 // happens.
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00002328 Value *CurValue = &*CurInstIterator;
Sanjoy Dase6bca0e2017-05-01 17:07:49 +00002329 WeakTrackingVH IterHandle(CurValue);
Nadav Rotem465834c2012-07-24 10:51:42 +00002330
Sanjay Patel545a4562016-01-20 18:59:16 +00002331 replaceAndRecursivelySimplify(CI, RetVal, TLInfo, nullptr);
Chris Lattner1b93be52011-01-15 07:25:29 +00002332
Elena Demikhovsky87700a72014-12-28 08:54:45 +00002333 // If the iterator instruction was recursively deleted, start over at the
2334 // start of the block.
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00002335 if (IterHandle != CurValue) {
Elena Demikhovsky87700a72014-12-28 08:54:45 +00002336 CurInstIterator = BB->begin();
2337 SunkAddrs.clear();
2338 }
2339 return true;
Chris Lattner86d56c62011-01-18 20:53:04 +00002340 }
Ahmed Bougacha236f9042015-05-22 21:37:17 +00002341 case Intrinsic::aarch64_stlxr:
2342 case Intrinsic::aarch64_stxr: {
2343 ZExtInst *ExtVal = dyn_cast<ZExtInst>(CI->getArgOperand(0));
2344 if (!ExtVal || !ExtVal->hasOneUse() ||
2345 ExtVal->getParent() == CI->getParent())
2346 return false;
2347 // Sink a zext feeding stlxr/stxr before it, so it can be folded into it.
2348 ExtVal->moveBefore(CI);
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002349 // Mark this instruction as "inserted by CGP", so that other
2350 // optimizations don't touch it.
2351 InsertedInsts.insert(ExtVal);
Ahmed Bougacha236f9042015-05-22 21:37:17 +00002352 return true;
2353 }
Piotr Padlewski6c15ec42015-09-15 18:32:14 +00002354 case Intrinsic::invariant_group_barrier:
2355 II->replaceAllUsesWith(II->getArgOperand(0));
2356 II->eraseFromParent();
2357 return true;
Sanjay Patel4699b8a2015-11-19 16:37:10 +00002358
2359 case Intrinsic::cttz:
2360 case Intrinsic::ctlz:
2361 // If counting zeros is expensive, try to avoid it.
2362 return despeculateCountZeros(II, TLI, DL, ModifiedDT);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00002363 }
Eric Christopher4b7948e2010-03-11 02:41:03 +00002364
Elena Demikhovsky87700a72014-12-28 08:54:45 +00002365 if (TLI) {
2366 SmallVector<Value*, 2> PtrOps;
2367 Type *AccessTy;
Matt Arsenault1672b1b2017-02-08 07:09:03 +00002368 if (TLI->getAddrModeArguments(II, PtrOps, AccessTy))
2369 while (!PtrOps.empty()) {
2370 Value *PtrVal = PtrOps.pop_back_val();
2371 unsigned AS = PtrVal->getType()->getPointerAddressSpace();
2372 if (optimizeMemoryInst(II, PtrVal, AccessTy, AS))
Elena Demikhovsky87700a72014-12-28 08:54:45 +00002373 return true;
Matt Arsenault1672b1b2017-02-08 07:09:03 +00002374 }
Elena Demikhovsky87700a72014-12-28 08:54:45 +00002375 }
Pete Cooper615fd892012-03-13 20:59:56 +00002376 }
2377
Eric Christopher4b7948e2010-03-11 02:41:03 +00002378 // From here on out we're working with named functions.
Craig Topperc0196b12014-04-14 00:51:57 +00002379 if (!CI->getCalledFunction()) return false;
Devang Patel0da52502011-05-26 21:51:06 +00002380
Benjamin Kramer7b88a492010-03-12 09:27:41 +00002381 // Lower all default uses of _chk calls. This is very similar
2382 // to what InstCombineCalls does, but here we are only lowering calls
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002383 // to fortified library functions (e.g. __memcpy_chk) that have the default
2384 // "don't know" as the objectsize. Anything else should be left alone.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002385 FortifiedLibCallSimplifier Simplifier(TLInfo, true);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002386 if (Value *V = Simplifier.optimizeCall(CI)) {
2387 CI->replaceAllUsesWith(V);
2388 CI->eraseFromParent();
2389 return true;
2390 }
Zaara Syeda3a7578c2017-05-31 17:12:38 +00002391
2392 LibFunc Func;
2393 if (TLInfo->getLibFunc(*CI->getCalledFunction(), Func) &&
2394 Func == LibFunc_memcmp) {
2395 if (expandMemCmp(CI, TTI, TLI, DL)) {
2396 ModifiedDT = true;
2397 return true;
2398 }
2399 }
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002400 return false;
Eric Christopher4b7948e2010-03-11 02:41:03 +00002401}
Chris Lattner1b93be52011-01-15 07:25:29 +00002402
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002403/// Look for opportunities to duplicate return instructions to the predecessor
2404/// to enable tail call optimizations. The case it is currently looking for is:
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00002405/// @code
Evan Cheng0663f232011-03-21 01:19:09 +00002406/// bb0:
2407/// %tmp0 = tail call i32 @f0()
2408/// br label %return
2409/// bb1:
2410/// %tmp1 = tail call i32 @f1()
2411/// br label %return
2412/// bb2:
2413/// %tmp2 = tail call i32 @f2()
2414/// br label %return
2415/// return:
2416/// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
2417/// ret i32 %retval
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00002418/// @endcode
Evan Cheng0663f232011-03-21 01:19:09 +00002419///
2420/// =>
2421///
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00002422/// @code
Evan Cheng0663f232011-03-21 01:19:09 +00002423/// bb0:
2424/// %tmp0 = tail call i32 @f0()
2425/// ret i32 %tmp0
2426/// bb1:
2427/// %tmp1 = tail call i32 @f1()
2428/// ret i32 %tmp1
2429/// bb2:
2430/// %tmp2 = tail call i32 @f2()
2431/// ret i32 %tmp2
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00002432/// @endcode
Sanjay Patelfc580a62015-09-21 23:03:16 +00002433bool CodeGenPrepare::dupRetToEnableTailCallOpts(BasicBlock *BB) {
Cameron Zwarich47e71752011-03-24 04:51:51 +00002434 if (!TLI)
2435 return false;
2436
Michael Kuperstein71321562016-09-07 20:29:49 +00002437 ReturnInst *RetI = dyn_cast<ReturnInst>(BB->getTerminator());
2438 if (!RetI)
Benjamin Kramer455fa352012-11-23 19:17:06 +00002439 return false;
2440
Craig Topperc0196b12014-04-14 00:51:57 +00002441 PHINode *PN = nullptr;
2442 BitCastInst *BCI = nullptr;
Michael Kuperstein71321562016-09-07 20:29:49 +00002443 Value *V = RetI->getReturnValue();
Evan Cheng249716e2012-07-27 21:21:26 +00002444 if (V) {
2445 BCI = dyn_cast<BitCastInst>(V);
2446 if (BCI)
2447 V = BCI->getOperand(0);
2448
2449 PN = dyn_cast<PHINode>(V);
2450 if (!PN)
2451 return false;
2452 }
Evan Cheng0663f232011-03-21 01:19:09 +00002453
Cameron Zwarich4649f172011-03-24 04:52:10 +00002454 if (PN && PN->getParent() != BB)
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002455 return false;
Evan Cheng0663f232011-03-21 01:19:09 +00002456
Cameron Zwarich4649f172011-03-24 04:52:10 +00002457 // Make sure there are no instructions between the PHI and return, or that the
2458 // return is the first instruction in the block.
2459 if (PN) {
2460 BasicBlock::iterator BI = BB->begin();
2461 do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
Evan Cheng249716e2012-07-27 21:21:26 +00002462 if (&*BI == BCI)
2463 // Also skip over the bitcast.
2464 ++BI;
Michael Kuperstein71321562016-09-07 20:29:49 +00002465 if (&*BI != RetI)
Cameron Zwarich4649f172011-03-24 04:52:10 +00002466 return false;
2467 } else {
Cameron Zwarich74157ab2011-03-24 16:34:59 +00002468 BasicBlock::iterator BI = BB->begin();
2469 while (isa<DbgInfoIntrinsic>(BI)) ++BI;
Michael Kuperstein71321562016-09-07 20:29:49 +00002470 if (&*BI != RetI)
Cameron Zwarich4649f172011-03-24 04:52:10 +00002471 return false;
2472 }
Evan Cheng0663f232011-03-21 01:19:09 +00002473
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002474 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
2475 /// call.
Michael Kupersteinf79af6f2016-09-08 00:48:37 +00002476 const Function *F = BB->getParent();
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002477 SmallVector<CallInst*, 4> TailCalls;
Cameron Zwarich4649f172011-03-24 04:52:10 +00002478 if (PN) {
2479 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
2480 CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
2481 // Make sure the phi value is indeed produced by the tail call.
2482 if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
Michael Kupersteinf79af6f2016-09-08 00:48:37 +00002483 TLI->mayBeEmittedAsTailCall(CI) &&
2484 attributesPermitTailCall(F, CI, RetI, *TLI))
Cameron Zwarich4649f172011-03-24 04:52:10 +00002485 TailCalls.push_back(CI);
2486 }
2487 } else {
2488 SmallPtrSet<BasicBlock*, 4> VisitedBBs;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00002489 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
David Blaikie70573dc2014-11-19 07:49:26 +00002490 if (!VisitedBBs.insert(*PI).second)
Cameron Zwarich4649f172011-03-24 04:52:10 +00002491 continue;
2492
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00002493 BasicBlock::InstListType &InstList = (*PI)->getInstList();
Cameron Zwarich4649f172011-03-24 04:52:10 +00002494 BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
2495 BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
Cameron Zwarich74157ab2011-03-24 16:34:59 +00002496 do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
2497 if (RI == RE)
Cameron Zwarich4649f172011-03-24 04:52:10 +00002498 continue;
Cameron Zwarich74157ab2011-03-24 16:34:59 +00002499
Cameron Zwarich4649f172011-03-24 04:52:10 +00002500 CallInst *CI = dyn_cast<CallInst>(&*RI);
Michael Kupersteinf79af6f2016-09-08 00:48:37 +00002501 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI) &&
2502 attributesPermitTailCall(F, CI, RetI, *TLI))
Cameron Zwarich4649f172011-03-24 04:52:10 +00002503 TailCalls.push_back(CI);
2504 }
Evan Cheng0663f232011-03-21 01:19:09 +00002505 }
2506
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002507 bool Changed = false;
2508 for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
2509 CallInst *CI = TailCalls[i];
2510 CallSite CS(CI);
2511
2512 // Conservatively require the attributes of the call to match those of the
2513 // return. Ignore noalias because it doesn't affect the call sequence.
Reid Klecknerb5180542017-03-21 16:57:19 +00002514 AttributeList CalleeAttrs = CS.getAttributes();
2515 if (AttrBuilder(CalleeAttrs, AttributeList::ReturnIndex)
2516 .removeAttribute(Attribute::NoAlias) !=
2517 AttrBuilder(CalleeAttrs, AttributeList::ReturnIndex)
2518 .removeAttribute(Attribute::NoAlias))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002519 continue;
2520
2521 // Make sure the call instruction is followed by an unconditional branch to
2522 // the return block.
2523 BasicBlock *CallBB = CI->getParent();
2524 BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
2525 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
2526 continue;
2527
2528 // Duplicate the return into CallBB.
Michael Kuperstein71321562016-09-07 20:29:49 +00002529 (void)FoldReturnIntoUncondBranch(RetI, BB, CallBB);
Devang Patel8f606d72011-03-24 15:35:25 +00002530 ModifiedDT = Changed = true;
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002531 ++NumRetsDup;
2532 }
2533
2534 // If we eliminated all predecessors of the block, delete the block now.
Evan Cheng64a223a2012-09-28 23:58:57 +00002535 if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002536 BB->eraseFromParent();
2537
2538 return Changed;
Evan Cheng0663f232011-03-21 01:19:09 +00002539}
2540
Chris Lattner728f9022008-11-25 07:09:13 +00002541//===----------------------------------------------------------------------===//
Chris Lattner728f9022008-11-25 07:09:13 +00002542// Memory Optimization
2543//===----------------------------------------------------------------------===//
2544
Chandler Carruthc8925912013-01-05 02:09:22 +00002545namespace {
2546
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002547/// This is an extended version of TargetLowering::AddrMode
Chandler Carruthc8925912013-01-05 02:09:22 +00002548/// which holds actual Value*'s for register values.
Chandler Carruth95f83e02013-01-07 15:14:13 +00002549struct ExtAddrMode : public TargetLowering::AddrMode {
Chandler Carruthc8925912013-01-05 02:09:22 +00002550 Value *BaseReg;
2551 Value *ScaledReg;
Craig Topperc0196b12014-04-14 00:51:57 +00002552 ExtAddrMode() : BaseReg(nullptr), ScaledReg(nullptr) {}
Chandler Carruthc8925912013-01-05 02:09:22 +00002553 void print(raw_ostream &OS) const;
2554 void dump() const;
Stephen Lin837bba12013-07-15 17:55:02 +00002555
Chandler Carruthc8925912013-01-05 02:09:22 +00002556 bool operator==(const ExtAddrMode& O) const {
2557 return (BaseReg == O.BaseReg) && (ScaledReg == O.ScaledReg) &&
2558 (BaseGV == O.BaseGV) && (BaseOffs == O.BaseOffs) &&
2559 (HasBaseReg == O.HasBaseReg) && (Scale == O.Scale);
2560 }
2561};
2562
Eli Friedmanc1f1f852013-09-10 23:09:24 +00002563#ifndef NDEBUG
2564static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
2565 AM.print(OS);
2566 return OS;
2567}
2568#endif
2569
Chandler Carruthc8925912013-01-05 02:09:22 +00002570void ExtAddrMode::print(raw_ostream &OS) const {
2571 bool NeedPlus = false;
2572 OS << "[";
2573 if (BaseGV) {
2574 OS << (NeedPlus ? " + " : "")
2575 << "GV:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00002576 BaseGV->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00002577 NeedPlus = true;
2578 }
2579
Richard Trieuc0f91212014-05-30 03:15:17 +00002580 if (BaseOffs) {
2581 OS << (NeedPlus ? " + " : "")
2582 << BaseOffs;
2583 NeedPlus = true;
2584 }
Chandler Carruthc8925912013-01-05 02:09:22 +00002585
2586 if (BaseReg) {
2587 OS << (NeedPlus ? " + " : "")
2588 << "Base:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00002589 BaseReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00002590 NeedPlus = true;
2591 }
2592 if (Scale) {
2593 OS << (NeedPlus ? " + " : "")
2594 << Scale << "*";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00002595 ScaledReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00002596 }
2597
2598 OS << ']';
2599}
2600
2601#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Yaron Kereneb2a2542016-01-29 20:50:44 +00002602LLVM_DUMP_METHOD void ExtAddrMode::dump() const {
Chandler Carruthc8925912013-01-05 02:09:22 +00002603 print(dbgs());
2604 dbgs() << '\n';
2605}
2606#endif
2607
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002608/// \brief This class provides transaction based operation on the IR.
2609/// Every change made through this class is recorded in the internal state and
2610/// can be undone (rollback) until commit is called.
2611class TypePromotionTransaction {
2612
2613 /// \brief This represents the common interface of the individual transaction.
2614 /// Each class implements the logic for doing one specific modification on
2615 /// the IR via the TypePromotionTransaction.
2616 class TypePromotionAction {
2617 protected:
2618 /// The Instruction modified.
2619 Instruction *Inst;
2620
2621 public:
2622 /// \brief Constructor of the action.
2623 /// The constructor performs the related action on the IR.
2624 TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
2625
2626 virtual ~TypePromotionAction() {}
2627
2628 /// \brief Undo the modification done by this action.
2629 /// When this method is called, the IR must be in the same state as it was
2630 /// before this action was applied.
2631 /// \pre Undoing the action works if and only if the IR is in the exact same
2632 /// state as it was directly after this action was applied.
2633 virtual void undo() = 0;
2634
2635 /// \brief Advocate every change made by this action.
2636 /// When the results on the IR of the action are to be kept, it is important
2637 /// to call this function, otherwise hidden information may be kept forever.
2638 virtual void commit() {
2639 // Nothing to be done, this action is not doing anything.
2640 }
2641 };
2642
2643 /// \brief Utility to remember the position of an instruction.
2644 class InsertionHandler {
2645 /// Position of an instruction.
2646 /// Either an instruction:
2647 /// - Is the first in a basic block: BB is used.
2648 /// - Has a previous instructon: PrevInst is used.
2649 union {
2650 Instruction *PrevInst;
2651 BasicBlock *BB;
2652 } Point;
2653 /// Remember whether or not the instruction had a previous instruction.
2654 bool HasPrevInstruction;
2655
2656 public:
2657 /// \brief Record the position of \p Inst.
2658 InsertionHandler(Instruction *Inst) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002659 BasicBlock::iterator It = Inst->getIterator();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002660 HasPrevInstruction = (It != (Inst->getParent()->begin()));
2661 if (HasPrevInstruction)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002662 Point.PrevInst = &*--It;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002663 else
2664 Point.BB = Inst->getParent();
2665 }
2666
2667 /// \brief Insert \p Inst at the recorded position.
2668 void insert(Instruction *Inst) {
2669 if (HasPrevInstruction) {
2670 if (Inst->getParent())
2671 Inst->removeFromParent();
2672 Inst->insertAfter(Point.PrevInst);
2673 } else {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002674 Instruction *Position = &*Point.BB->getFirstInsertionPt();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002675 if (Inst->getParent())
2676 Inst->moveBefore(Position);
2677 else
2678 Inst->insertBefore(Position);
2679 }
2680 }
2681 };
2682
2683 /// \brief Move an instruction before another.
2684 class InstructionMoveBefore : public TypePromotionAction {
2685 /// Original position of the instruction.
2686 InsertionHandler Position;
2687
2688 public:
2689 /// \brief Move \p Inst before \p Before.
2690 InstructionMoveBefore(Instruction *Inst, Instruction *Before)
2691 : TypePromotionAction(Inst), Position(Inst) {
2692 DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before << "\n");
2693 Inst->moveBefore(Before);
2694 }
2695
2696 /// \brief Move the instruction back to its original position.
Craig Topper4584cd52014-03-07 09:26:03 +00002697 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002698 DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n");
2699 Position.insert(Inst);
2700 }
2701 };
2702
2703 /// \brief Set the operand of an instruction with a new value.
2704 class OperandSetter : public TypePromotionAction {
2705 /// Original operand of the instruction.
2706 Value *Origin;
2707 /// Index of the modified instruction.
2708 unsigned Idx;
2709
2710 public:
2711 /// \brief Set \p Idx operand of \p Inst with \p NewVal.
2712 OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
2713 : TypePromotionAction(Inst), Idx(Idx) {
2714 DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"
2715 << "for:" << *Inst << "\n"
2716 << "with:" << *NewVal << "\n");
2717 Origin = Inst->getOperand(Idx);
2718 Inst->setOperand(Idx, NewVal);
2719 }
2720
2721 /// \brief Restore the original value of the instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002722 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002723 DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"
2724 << "for: " << *Inst << "\n"
2725 << "with: " << *Origin << "\n");
2726 Inst->setOperand(Idx, Origin);
2727 }
2728 };
2729
2730 /// \brief Hide the operands of an instruction.
2731 /// Do as if this instruction was not using any of its operands.
2732 class OperandsHider : public TypePromotionAction {
2733 /// The list of original operands.
2734 SmallVector<Value *, 4> OriginalValues;
2735
2736 public:
2737 /// \brief Remove \p Inst from the uses of the operands of \p Inst.
2738 OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
2739 DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n");
2740 unsigned NumOpnds = Inst->getNumOperands();
2741 OriginalValues.reserve(NumOpnds);
2742 for (unsigned It = 0; It < NumOpnds; ++It) {
2743 // Save the current operand.
2744 Value *Val = Inst->getOperand(It);
2745 OriginalValues.push_back(Val);
2746 // Set a dummy one.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00002747 // We could use OperandSetter here, but that would imply an overhead
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002748 // that we are not willing to pay.
2749 Inst->setOperand(It, UndefValue::get(Val->getType()));
2750 }
2751 }
2752
2753 /// \brief Restore the original list of uses.
Craig Topper4584cd52014-03-07 09:26:03 +00002754 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002755 DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n");
2756 for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
2757 Inst->setOperand(It, OriginalValues[It]);
2758 }
2759 };
2760
2761 /// \brief Build a truncate instruction.
2762 class TruncBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00002763 Value *Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002764 public:
2765 /// \brief Build a truncate instruction of \p Opnd producing a \p Ty
2766 /// result.
2767 /// trunc Opnd to Ty.
2768 TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
2769 IRBuilder<> Builder(Opnd);
Quentin Colombetac55b152014-09-16 22:36:07 +00002770 Val = Builder.CreateTrunc(Opnd, Ty, "promoted");
2771 DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002772 }
2773
Quentin Colombetac55b152014-09-16 22:36:07 +00002774 /// \brief Get the built value.
2775 Value *getBuiltValue() { return Val; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002776
2777 /// \brief Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002778 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00002779 DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n");
2780 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2781 IVal->eraseFromParent();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002782 }
2783 };
2784
2785 /// \brief Build a sign extension instruction.
2786 class SExtBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00002787 Value *Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002788 public:
2789 /// \brief Build a sign extension instruction of \p Opnd producing a \p Ty
2790 /// result.
2791 /// sext Opnd to Ty.
2792 SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
Quentin Colombetac55b152014-09-16 22:36:07 +00002793 : TypePromotionAction(InsertPt) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002794 IRBuilder<> Builder(InsertPt);
Quentin Colombetac55b152014-09-16 22:36:07 +00002795 Val = Builder.CreateSExt(Opnd, Ty, "promoted");
2796 DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002797 }
2798
Quentin Colombetac55b152014-09-16 22:36:07 +00002799 /// \brief Get the built value.
2800 Value *getBuiltValue() { return Val; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002801
2802 /// \brief Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002803 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00002804 DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n");
2805 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2806 IVal->eraseFromParent();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002807 }
2808 };
2809
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002810 /// \brief Build a zero extension instruction.
2811 class ZExtBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00002812 Value *Val;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002813 public:
2814 /// \brief Build a zero extension instruction of \p Opnd producing a \p Ty
2815 /// result.
2816 /// zext Opnd to Ty.
2817 ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
Quentin Colombetac55b152014-09-16 22:36:07 +00002818 : TypePromotionAction(InsertPt) {
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002819 IRBuilder<> Builder(InsertPt);
Quentin Colombetac55b152014-09-16 22:36:07 +00002820 Val = Builder.CreateZExt(Opnd, Ty, "promoted");
2821 DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n");
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002822 }
2823
Quentin Colombetac55b152014-09-16 22:36:07 +00002824 /// \brief Get the built value.
2825 Value *getBuiltValue() { return Val; }
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002826
2827 /// \brief Remove the built instruction.
2828 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00002829 DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n");
2830 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2831 IVal->eraseFromParent();
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002832 }
2833 };
2834
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002835 /// \brief Mutate an instruction to another type.
2836 class TypeMutator : public TypePromotionAction {
2837 /// Record the original type.
2838 Type *OrigTy;
2839
2840 public:
2841 /// \brief Mutate the type of \p Inst into \p NewTy.
2842 TypeMutator(Instruction *Inst, Type *NewTy)
2843 : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
2844 DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy
2845 << "\n");
2846 Inst->mutateType(NewTy);
2847 }
2848
2849 /// \brief Mutate the instruction back to its original type.
Craig Topper4584cd52014-03-07 09:26:03 +00002850 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002851 DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy
2852 << "\n");
2853 Inst->mutateType(OrigTy);
2854 }
2855 };
2856
2857 /// \brief Replace the uses of an instruction by another instruction.
2858 class UsesReplacer : public TypePromotionAction {
2859 /// Helper structure to keep track of the replaced uses.
2860 struct InstructionAndIdx {
2861 /// The instruction using the instruction.
2862 Instruction *Inst;
2863 /// The index where this instruction is used for Inst.
2864 unsigned Idx;
2865 InstructionAndIdx(Instruction *Inst, unsigned Idx)
2866 : Inst(Inst), Idx(Idx) {}
2867 };
2868
2869 /// Keep track of the original uses (pair Instruction, Index).
2870 SmallVector<InstructionAndIdx, 4> OriginalUses;
2871 typedef SmallVectorImpl<InstructionAndIdx>::iterator use_iterator;
2872
2873 public:
2874 /// \brief Replace all the use of \p Inst by \p New.
2875 UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) {
2876 DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New
2877 << "\n");
2878 // Record the original uses.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002879 for (Use &U : Inst->uses()) {
2880 Instruction *UserI = cast<Instruction>(U.getUser());
2881 OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo()));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002882 }
2883 // Now, we can replace the uses.
2884 Inst->replaceAllUsesWith(New);
2885 }
2886
2887 /// \brief Reassign the original uses of Inst to Inst.
Craig Topper4584cd52014-03-07 09:26:03 +00002888 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002889 DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n");
2890 for (use_iterator UseIt = OriginalUses.begin(),
2891 EndIt = OriginalUses.end();
2892 UseIt != EndIt; ++UseIt) {
2893 UseIt->Inst->setOperand(UseIt->Idx, Inst);
2894 }
2895 }
2896 };
2897
2898 /// \brief Remove an instruction from the IR.
2899 class InstructionRemover : public TypePromotionAction {
2900 /// Original position of the instruction.
2901 InsertionHandler Inserter;
2902 /// Helper structure to hide all the link to the instruction. In other
2903 /// words, this helps to do as if the instruction was removed.
2904 OperandsHider Hider;
2905 /// Keep track of the uses replaced, if any.
2906 UsesReplacer *Replacer;
Jun Bum Limdee55652017-04-03 19:20:07 +00002907 /// Keep track of instructions removed.
2908 SetOfInstrs &RemovedInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002909
2910 public:
2911 /// \brief Remove all reference of \p Inst and optinally replace all its
2912 /// uses with New.
Jun Bum Limdee55652017-04-03 19:20:07 +00002913 /// \p RemovedInsts Keep track of the instructions removed by this Action.
Craig Topperc0196b12014-04-14 00:51:57 +00002914 /// \pre If !Inst->use_empty(), then New != nullptr
Jun Bum Limdee55652017-04-03 19:20:07 +00002915 InstructionRemover(Instruction *Inst, SetOfInstrs &RemovedInsts,
2916 Value *New = nullptr)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002917 : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
Jun Bum Limdee55652017-04-03 19:20:07 +00002918 Replacer(nullptr), RemovedInsts(RemovedInsts) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002919 if (New)
2920 Replacer = new UsesReplacer(Inst, New);
2921 DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n");
Jun Bum Limdee55652017-04-03 19:20:07 +00002922 RemovedInsts.insert(Inst);
2923 /// The instructions removed here will be freed after completing
2924 /// optimizeBlock() for all blocks as we need to keep track of the
2925 /// removed instructions during promotion.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002926 Inst->removeFromParent();
2927 }
2928
Alexander Kornienkof817c1c2015-04-11 02:11:45 +00002929 ~InstructionRemover() override { delete Replacer; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002930
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002931 /// \brief Resurrect the instruction and reassign it to the proper uses if
2932 /// new value was provided when build this action.
Craig Topper4584cd52014-03-07 09:26:03 +00002933 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002934 DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n");
2935 Inserter.insert(Inst);
2936 if (Replacer)
2937 Replacer->undo();
2938 Hider.undo();
Jun Bum Limdee55652017-04-03 19:20:07 +00002939 RemovedInsts.erase(Inst);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002940 }
2941 };
2942
2943public:
2944 /// Restoration point.
2945 /// The restoration point is a pointer to an action instead of an iterator
2946 /// because the iterator may be invalidated but not the pointer.
2947 typedef const TypePromotionAction *ConstRestorationPt;
Jun Bum Limdee55652017-04-03 19:20:07 +00002948
2949 TypePromotionTransaction(SetOfInstrs &RemovedInsts)
2950 : RemovedInsts(RemovedInsts) {}
2951
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002952 /// Advocate every changes made in that transaction.
2953 void commit();
2954 /// Undo all the changes made after the given point.
2955 void rollback(ConstRestorationPt Point);
2956 /// Get the current restoration point.
2957 ConstRestorationPt getRestorationPoint() const;
2958
2959 /// \name API for IR modification with state keeping to support rollback.
2960 /// @{
2961 /// Same as Instruction::setOperand.
2962 void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
2963 /// Same as Instruction::eraseFromParent.
Craig Topperc0196b12014-04-14 00:51:57 +00002964 void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002965 /// Same as Value::replaceAllUsesWith.
2966 void replaceAllUsesWith(Instruction *Inst, Value *New);
2967 /// Same as Value::mutateType.
2968 void mutateType(Instruction *Inst, Type *NewTy);
2969 /// Same as IRBuilder::createTrunc.
Quentin Colombetac55b152014-09-16 22:36:07 +00002970 Value *createTrunc(Instruction *Opnd, Type *Ty);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002971 /// Same as IRBuilder::createSExt.
Quentin Colombetac55b152014-09-16 22:36:07 +00002972 Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002973 /// Same as IRBuilder::createZExt.
Quentin Colombetac55b152014-09-16 22:36:07 +00002974 Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002975 /// Same as Instruction::moveBefore.
2976 void moveBefore(Instruction *Inst, Instruction *Before);
2977 /// @}
2978
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002979private:
2980 /// The ordered list of actions made so far.
David Blaikie7620b312014-04-15 06:17:44 +00002981 SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions;
2982 typedef SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator CommitPt;
Jun Bum Limdee55652017-04-03 19:20:07 +00002983 SetOfInstrs &RemovedInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002984};
2985
2986void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
2987 Value *NewVal) {
2988 Actions.push_back(
David Blaikie7620b312014-04-15 06:17:44 +00002989 make_unique<TypePromotionTransaction::OperandSetter>(Inst, Idx, NewVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002990}
2991
2992void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
2993 Value *NewVal) {
2994 Actions.push_back(
Jun Bum Limdee55652017-04-03 19:20:07 +00002995 make_unique<TypePromotionTransaction::InstructionRemover>(Inst,
2996 RemovedInsts, NewVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002997}
2998
2999void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
3000 Value *New) {
David Blaikie7620b312014-04-15 06:17:44 +00003001 Actions.push_back(make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003002}
3003
3004void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
David Blaikie7620b312014-04-15 06:17:44 +00003005 Actions.push_back(make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003006}
3007
Quentin Colombetac55b152014-09-16 22:36:07 +00003008Value *TypePromotionTransaction::createTrunc(Instruction *Opnd,
3009 Type *Ty) {
David Blaikie7620b312014-04-15 06:17:44 +00003010 std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00003011 Value *Val = Ptr->getBuiltValue();
David Blaikie7620b312014-04-15 06:17:44 +00003012 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00003013 return Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003014}
3015
Quentin Colombetac55b152014-09-16 22:36:07 +00003016Value *TypePromotionTransaction::createSExt(Instruction *Inst,
3017 Value *Opnd, Type *Ty) {
David Blaikie7620b312014-04-15 06:17:44 +00003018 std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00003019 Value *Val = Ptr->getBuiltValue();
David Blaikie7620b312014-04-15 06:17:44 +00003020 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00003021 return Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003022}
3023
Quentin Colombetac55b152014-09-16 22:36:07 +00003024Value *TypePromotionTransaction::createZExt(Instruction *Inst,
3025 Value *Opnd, Type *Ty) {
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003026 std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00003027 Value *Val = Ptr->getBuiltValue();
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003028 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00003029 return Val;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003030}
3031
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003032void TypePromotionTransaction::moveBefore(Instruction *Inst,
3033 Instruction *Before) {
3034 Actions.push_back(
David Blaikie7620b312014-04-15 06:17:44 +00003035 make_unique<TypePromotionTransaction::InstructionMoveBefore>(Inst, Before));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003036}
3037
3038TypePromotionTransaction::ConstRestorationPt
3039TypePromotionTransaction::getRestorationPoint() const {
David Blaikie7620b312014-04-15 06:17:44 +00003040 return !Actions.empty() ? Actions.back().get() : nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003041}
3042
3043void TypePromotionTransaction::commit() {
3044 for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt;
David Blaikie7620b312014-04-15 06:17:44 +00003045 ++It)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003046 (*It)->commit();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003047 Actions.clear();
3048}
3049
3050void TypePromotionTransaction::rollback(
3051 TypePromotionTransaction::ConstRestorationPt Point) {
David Blaikie7620b312014-04-15 06:17:44 +00003052 while (!Actions.empty() && Point != Actions.back().get()) {
3053 std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003054 Curr->undo();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003055 }
3056}
3057
Chandler Carruthc8925912013-01-05 02:09:22 +00003058/// \brief A helper class for matching addressing modes.
3059///
3060/// This encapsulates the logic for matching the target-legal addressing modes.
3061class AddressingModeMatcher {
3062 SmallVectorImpl<Instruction*> &AddrModeInsts;
3063 const TargetLowering &TLI;
Igor Laevsky3be81ba2017-02-07 13:27:20 +00003064 const TargetRegisterInfo &TRI;
Mehdi Amini4fe37982015-07-07 18:45:17 +00003065 const DataLayout &DL;
Chandler Carruthc8925912013-01-05 02:09:22 +00003066
3067 /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
3068 /// the memory instruction that we're computing this address for.
3069 Type *AccessTy;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003070 unsigned AddrSpace;
Chandler Carruthc8925912013-01-05 02:09:22 +00003071 Instruction *MemoryInst;
Stephen Lin837bba12013-07-15 17:55:02 +00003072
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003073 /// This is the addressing mode that we're building up. This is
Chandler Carruthc8925912013-01-05 02:09:22 +00003074 /// part of the return value of this addressing mode matching stuff.
3075 ExtAddrMode &AddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00003076
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003077 /// The instructions inserted by other CodeGenPrepare optimizations.
3078 const SetOfInstrs &InsertedInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003079 /// A map from the instructions to their type before promotion.
3080 InstrToOrigTy &PromotedInsts;
3081 /// The ongoing transaction where every action should be registered.
3082 TypePromotionTransaction &TPT;
3083
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003084 /// This is set to true when we should not do profitability checks.
3085 /// When true, IsProfitableToFoldIntoAddressingMode always returns true.
Chandler Carruthc8925912013-01-05 02:09:22 +00003086 bool IgnoreProfitability;
Stephen Lin837bba12013-07-15 17:55:02 +00003087
Eric Christopherd75c00c2015-02-26 22:38:34 +00003088 AddressingModeMatcher(SmallVectorImpl<Instruction *> &AMI,
Igor Laevsky3be81ba2017-02-07 13:27:20 +00003089 const TargetLowering &TLI,
3090 const TargetRegisterInfo &TRI,
3091 Type *AT, unsigned AS,
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003092 Instruction *MI, ExtAddrMode &AM,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003093 const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003094 InstrToOrigTy &PromotedInsts,
3095 TypePromotionTransaction &TPT)
Igor Laevsky3be81ba2017-02-07 13:27:20 +00003096 : AddrModeInsts(AMI), TLI(TLI), TRI(TRI),
Mehdi Amini4fe37982015-07-07 18:45:17 +00003097 DL(MI->getModule()->getDataLayout()), AccessTy(AT), AddrSpace(AS),
3098 MemoryInst(MI), AddrMode(AM), InsertedInsts(InsertedInsts),
3099 PromotedInsts(PromotedInsts), TPT(TPT) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003100 IgnoreProfitability = false;
3101 }
3102public:
Stephen Lin837bba12013-07-15 17:55:02 +00003103
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003104 /// Find the maximal addressing mode that a load/store of V can fold,
Chandler Carruthc8925912013-01-05 02:09:22 +00003105 /// give an access type of AccessTy. This returns a list of involved
3106 /// instructions in AddrModeInsts.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003107 /// \p InsertedInsts The instructions inserted by other CodeGenPrepare
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003108 /// optimizations.
3109 /// \p PromotedInsts maps the instructions to their type before promotion.
3110 /// \p The ongoing transaction where every action should be registered.
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003111 static ExtAddrMode Match(Value *V, Type *AccessTy, unsigned AS,
Chandler Carruthc8925912013-01-05 02:09:22 +00003112 Instruction *MemoryInst,
3113 SmallVectorImpl<Instruction*> &AddrModeInsts,
Igor Laevsky3be81ba2017-02-07 13:27:20 +00003114 const TargetLowering &TLI,
3115 const TargetRegisterInfo &TRI,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003116 const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003117 InstrToOrigTy &PromotedInsts,
3118 TypePromotionTransaction &TPT) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003119 ExtAddrMode Result;
3120
Igor Laevsky3be81ba2017-02-07 13:27:20 +00003121 bool Success = AddressingModeMatcher(AddrModeInsts, TLI, TRI,
3122 AccessTy, AS,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003123 MemoryInst, Result, InsertedInsts,
Sanjay Patelfc580a62015-09-21 23:03:16 +00003124 PromotedInsts, TPT).matchAddr(V, 0);
Chandler Carruthc8925912013-01-05 02:09:22 +00003125 (void)Success; assert(Success && "Couldn't select *anything*?");
3126 return Result;
3127 }
3128private:
Sanjay Patelfc580a62015-09-21 23:03:16 +00003129 bool matchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
3130 bool matchAddr(Value *V, unsigned Depth);
3131 bool matchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth,
Craig Topperc0196b12014-04-14 00:51:57 +00003132 bool *MovedAway = nullptr);
Sanjay Patelfc580a62015-09-21 23:03:16 +00003133 bool isProfitableToFoldIntoAddressingMode(Instruction *I,
Chandler Carruthc8925912013-01-05 02:09:22 +00003134 ExtAddrMode &AMBefore,
3135 ExtAddrMode &AMAfter);
Sanjay Patelfc580a62015-09-21 23:03:16 +00003136 bool valueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
3137 bool isPromotionProfitable(unsigned NewCost, unsigned OldCost,
Quentin Colombet867c5502014-02-14 22:23:22 +00003138 Value *PromotedOperand) const;
Chandler Carruthc8925912013-01-05 02:09:22 +00003139};
3140
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003141/// Try adding ScaleReg*Scale to the current addressing mode.
Chandler Carruthc8925912013-01-05 02:09:22 +00003142/// Return true and update AddrMode if this addr mode is legal for the target,
3143/// false if not.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003144bool AddressingModeMatcher::matchScaledValue(Value *ScaleReg, int64_t Scale,
Chandler Carruthc8925912013-01-05 02:09:22 +00003145 unsigned Depth) {
3146 // If Scale is 1, then this is the same as adding ScaleReg to the addressing
3147 // mode. Just process that directly.
3148 if (Scale == 1)
Sanjay Patelfc580a62015-09-21 23:03:16 +00003149 return matchAddr(ScaleReg, Depth);
Stephen Lin837bba12013-07-15 17:55:02 +00003150
Chandler Carruthc8925912013-01-05 02:09:22 +00003151 // If the scale is 0, it takes nothing to add this.
3152 if (Scale == 0)
3153 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003154
Chandler Carruthc8925912013-01-05 02:09:22 +00003155 // If we already have a scale of this value, we can add to it, otherwise, we
3156 // need an available scale field.
3157 if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
3158 return false;
3159
3160 ExtAddrMode TestAddrMode = AddrMode;
3161
3162 // Add scale to turn X*4+X*3 -> X*7. This could also do things like
3163 // [A+B + A*7] -> [B+A*8].
3164 TestAddrMode.Scale += Scale;
3165 TestAddrMode.ScaledReg = ScaleReg;
3166
3167 // If the new address isn't legal, bail out.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003168 if (!TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003169 return false;
3170
3171 // It was legal, so commit it.
3172 AddrMode = TestAddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00003173
Chandler Carruthc8925912013-01-05 02:09:22 +00003174 // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
3175 // to see if ScaleReg is actually X+C. If so, we can turn this into adding
3176 // X*Scale + C*Scale to addr mode.
Craig Topperc0196b12014-04-14 00:51:57 +00003177 ConstantInt *CI = nullptr; Value *AddLHS = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003178 if (isa<Instruction>(ScaleReg) && // not a constant expr.
3179 match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
3180 TestAddrMode.ScaledReg = AddLHS;
3181 TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00003182
Chandler Carruthc8925912013-01-05 02:09:22 +00003183 // If this addressing mode is legal, commit it and remember that we folded
3184 // this instruction.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003185 if (TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003186 AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
3187 AddrMode = TestAddrMode;
3188 return true;
3189 }
3190 }
3191
3192 // Otherwise, not (x+c)*scale, just return what we have.
3193 return true;
3194}
3195
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003196/// This is a little filter, which returns true if an addressing computation
3197/// involving I might be folded into a load/store accessing it.
3198/// This doesn't need to be perfect, but needs to accept at least
Chandler Carruthc8925912013-01-05 02:09:22 +00003199/// the set of instructions that MatchOperationAddr can.
3200static bool MightBeFoldableInst(Instruction *I) {
3201 switch (I->getOpcode()) {
3202 case Instruction::BitCast:
Eli Benderskyf13a0562014-05-22 00:02:52 +00003203 case Instruction::AddrSpaceCast:
Chandler Carruthc8925912013-01-05 02:09:22 +00003204 // Don't touch identity bitcasts.
3205 if (I->getType() == I->getOperand(0)->getType())
3206 return false;
3207 return I->getType()->isPointerTy() || I->getType()->isIntegerTy();
3208 case Instruction::PtrToInt:
3209 // PtrToInt is always a noop, as we know that the int type is pointer sized.
3210 return true;
3211 case Instruction::IntToPtr:
3212 // We know the input is intptr_t, so this is foldable.
3213 return true;
3214 case Instruction::Add:
3215 return true;
3216 case Instruction::Mul:
3217 case Instruction::Shl:
3218 // Can only handle X*C and X << C.
3219 return isa<ConstantInt>(I->getOperand(1));
3220 case Instruction::GetElementPtr:
3221 return true;
3222 default:
3223 return false;
3224 }
3225}
3226
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003227/// \brief Check whether or not \p Val is a legal instruction for \p TLI.
3228/// \note \p Val is assumed to be the product of some type promotion.
3229/// Therefore if \p Val has an undefined state in \p TLI, this is assumed
3230/// to be legal, as the non-promoted value would have had the same state.
Mehdi Amini44ede332015-07-09 02:09:04 +00003231static bool isPromotedInstructionLegal(const TargetLowering &TLI,
3232 const DataLayout &DL, Value *Val) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003233 Instruction *PromotedInst = dyn_cast<Instruction>(Val);
3234 if (!PromotedInst)
3235 return false;
3236 int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode());
3237 // If the ISDOpcode is undefined, it was undefined before the promotion.
3238 if (!ISDOpcode)
3239 return true;
3240 // Otherwise, check if the promoted instruction is legal or not.
3241 return TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00003242 ISDOpcode, TLI.getValueType(DL, PromotedInst->getType()));
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003243}
3244
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003245/// \brief Hepler class to perform type promotion.
3246class TypePromotionHelper {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003247 /// \brief Utility function to check whether or not a sign or zero extension
3248 /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by
3249 /// either using the operands of \p Inst or promoting \p Inst.
3250 /// The type of the extension is defined by \p IsSExt.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003251 /// In other words, check if:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003252 /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003253 /// #1 Promotion applies:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003254 /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...).
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003255 /// #2 Operand reuses:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003256 /// ext opnd1 to ConsideredExtType.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003257 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003258 static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType,
3259 const InstrToOrigTy &PromotedInsts, bool IsSExt);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003260
3261 /// \brief Utility function to determine if \p OpIdx should be promoted when
3262 /// promoting \p Inst.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003263 static bool shouldExtOperand(const Instruction *Inst, int OpIdx) {
Rafael Espindola84921b92015-10-24 23:11:13 +00003264 return !(isa<SelectInst>(Inst) && OpIdx == 0);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003265 }
3266
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003267 /// \brief Utility function to promote the operand of \p Ext when this
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003268 /// operand is a promotable trunc or sext or zext.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003269 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003270 /// \p CreatedInstsCost[out] contains the cost of all instructions
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003271 /// created to promote the operand of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003272 /// Newly added extensions are inserted in \p Exts.
3273 /// Newly added truncates are inserted in \p Truncs.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003274 /// Should never be called directly.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003275 /// \return The promoted value which is used instead of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003276 static Value *promoteOperandForTruncAndAnyExt(
3277 Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003278 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003279 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003280 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003281
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003282 /// \brief Utility function to promote the operand of \p Ext when this
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003283 /// operand is promotable and is not a supported trunc or sext.
3284 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003285 /// \p CreatedInstsCost[out] contains the cost of all the instructions
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003286 /// created to promote the operand of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003287 /// Newly added extensions are inserted in \p Exts.
3288 /// Newly added truncates are inserted in \p Truncs.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003289 /// Should never be called directly.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003290 /// \return The promoted value which is used instead of Ext.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003291 static Value *promoteOperandForOther(Instruction *Ext,
3292 TypePromotionTransaction &TPT,
3293 InstrToOrigTy &PromotedInsts,
3294 unsigned &CreatedInstsCost,
3295 SmallVectorImpl<Instruction *> *Exts,
3296 SmallVectorImpl<Instruction *> *Truncs,
3297 const TargetLowering &TLI, bool IsSExt);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003298
3299 /// \see promoteOperandForOther.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003300 static Value *signExtendOperandForOther(
3301 Instruction *Ext, TypePromotionTransaction &TPT,
3302 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
3303 SmallVectorImpl<Instruction *> *Exts,
3304 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
3305 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
3306 Exts, Truncs, TLI, true);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003307 }
3308
3309 /// \see promoteOperandForOther.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003310 static Value *zeroExtendOperandForOther(
3311 Instruction *Ext, TypePromotionTransaction &TPT,
3312 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
3313 SmallVectorImpl<Instruction *> *Exts,
3314 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
3315 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
3316 Exts, Truncs, TLI, false);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003317 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003318
3319public:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003320 /// Type for the utility function that promotes the operand of Ext.
3321 typedef Value *(*Action)(Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003322 InstrToOrigTy &PromotedInsts,
3323 unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003324 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003325 SmallVectorImpl<Instruction *> *Truncs,
3326 const TargetLowering &TLI);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003327 /// \brief Given a sign/zero extend instruction \p Ext, return the approriate
3328 /// action to promote the operand of \p Ext instead of using Ext.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003329 /// \return NULL if no promotable action is possible with the current
3330 /// sign extension.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003331 /// \p InsertedInsts keeps track of all the instructions inserted by the
3332 /// other CodeGenPrepare optimizations. This information is important
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003333 /// because we do not want to promote these instructions as CodeGenPrepare
3334 /// will reinsert them later. Thus creating an infinite loop: create/remove.
3335 /// \p PromotedInsts maps the instructions to their type before promotion.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003336 static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003337 const TargetLowering &TLI,
3338 const InstrToOrigTy &PromotedInsts);
3339};
3340
3341bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003342 Type *ConsideredExtType,
3343 const InstrToOrigTy &PromotedInsts,
3344 bool IsSExt) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003345 // The promotion helper does not know how to deal with vector types yet.
3346 // To be able to fix that, we would need to fix the places where we
3347 // statically extend, e.g., constants and such.
3348 if (Inst->getType()->isVectorTy())
3349 return false;
3350
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003351 // We can always get through zext.
3352 if (isa<ZExtInst>(Inst))
3353 return true;
3354
3355 // sext(sext) is ok too.
3356 if (IsSExt && isa<SExtInst>(Inst))
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003357 return true;
3358
3359 // We can get through binary operator, if it is legal. In other words, the
3360 // binary operator must have a nuw or nsw flag.
3361 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
3362 if (BinOp && isa<OverflowingBinaryOperator>(BinOp) &&
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003363 ((!IsSExt && BinOp->hasNoUnsignedWrap()) ||
3364 (IsSExt && BinOp->hasNoSignedWrap())))
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003365 return true;
3366
3367 // Check if we can do the following simplification.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003368 // ext(trunc(opnd)) --> ext(opnd)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003369 if (!isa<TruncInst>(Inst))
3370 return false;
3371
3372 Value *OpndVal = Inst->getOperand(0);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003373 // Check if we can use this operand in the extension.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003374 // If the type is larger than the result type of the extension, we cannot.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003375 if (!OpndVal->getType()->isIntegerTy() ||
3376 OpndVal->getType()->getIntegerBitWidth() >
3377 ConsideredExtType->getIntegerBitWidth())
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003378 return false;
3379
3380 // If the operand of the truncate is not an instruction, we will not have
3381 // any information on the dropped bits.
3382 // (Actually we could for constant but it is not worth the extra logic).
3383 Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
3384 if (!Opnd)
3385 return false;
3386
3387 // Check if the source of the type is narrow enough.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003388 // I.e., check that trunc just drops extended bits of the same kind of
3389 // the extension.
3390 // #1 get the type of the operand and check the kind of the extended bits.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003391 const Type *OpndType;
3392 InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
Benjamin Kramer4cd5faa2015-07-31 17:00:39 +00003393 if (It != PromotedInsts.end() && It->second.getInt() == IsSExt)
3394 OpndType = It->second.getPointer();
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003395 else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd)))
3396 OpndType = Opnd->getOperand(0)->getType();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003397 else
3398 return false;
3399
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003400 // #2 check that the truncate just drops extended bits.
Rafael Espindola84921b92015-10-24 23:11:13 +00003401 return Inst->getType()->getIntegerBitWidth() >=
3402 OpndType->getIntegerBitWidth();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003403}
3404
3405TypePromotionHelper::Action TypePromotionHelper::getAction(
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003406 Instruction *Ext, const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003407 const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003408 assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
3409 "Unexpected instruction type");
3410 Instruction *ExtOpnd = dyn_cast<Instruction>(Ext->getOperand(0));
3411 Type *ExtTy = Ext->getType();
3412 bool IsSExt = isa<SExtInst>(Ext);
3413 // If the operand of the extension is not an instruction, we cannot
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003414 // get through.
3415 // If it, check we can get through.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003416 if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt))
Craig Topperc0196b12014-04-14 00:51:57 +00003417 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003418
3419 // Do not promote if the operand has been added by codegenprepare.
3420 // Otherwise, it means we are undoing an optimization that is likely to be
3421 // redone, thus causing potential infinite loop.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003422 if (isa<TruncInst>(ExtOpnd) && InsertedInsts.count(ExtOpnd))
Craig Topperc0196b12014-04-14 00:51:57 +00003423 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003424
3425 // SExt or Trunc instructions.
3426 // Return the related handler.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003427 if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) ||
3428 isa<ZExtInst>(ExtOpnd))
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003429 return promoteOperandForTruncAndAnyExt;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003430
3431 // Regular instruction.
3432 // Abort early if we will have to insert non-free instructions.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003433 if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(ExtTy, ExtOpnd->getType()))
Craig Topperc0196b12014-04-14 00:51:57 +00003434 return nullptr;
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003435 return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003436}
3437
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003438Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt(
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003439 llvm::Instruction *SExt, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003440 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003441 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003442 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003443 // By construction, the operand of SExt is an instruction. Otherwise we cannot
3444 // get through it and this method should not be called.
3445 Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
Quentin Colombetac55b152014-09-16 22:36:07 +00003446 Value *ExtVal = SExt;
Quentin Colombet1b274f92015-03-10 21:48:15 +00003447 bool HasMergedNonFreeExt = false;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003448 if (isa<ZExtInst>(SExtOpnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003449 // Replace s|zext(zext(opnd))
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003450 // => zext(opnd).
Quentin Colombet1b274f92015-03-10 21:48:15 +00003451 HasMergedNonFreeExt = !TLI.isExtFree(SExtOpnd);
Quentin Colombetac55b152014-09-16 22:36:07 +00003452 Value *ZExt =
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003453 TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType());
3454 TPT.replaceAllUsesWith(SExt, ZExt);
3455 TPT.eraseInstruction(SExt);
Quentin Colombetac55b152014-09-16 22:36:07 +00003456 ExtVal = ZExt;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003457 } else {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003458 // Replace z|sext(trunc(opnd)) or sext(sext(opnd))
3459 // => z|sext(opnd).
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003460 TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
3461 }
Quentin Colombet1b274f92015-03-10 21:48:15 +00003462 CreatedInstsCost = 0;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003463
3464 // Remove dead code.
3465 if (SExtOpnd->use_empty())
3466 TPT.eraseInstruction(SExtOpnd);
3467
Quentin Colombet9dcb7242014-09-15 18:26:58 +00003468 // Check if the extension is still needed.
Quentin Colombetac55b152014-09-16 22:36:07 +00003469 Instruction *ExtInst = dyn_cast<Instruction>(ExtVal);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003470 if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType()) {
Quentin Colombet1b274f92015-03-10 21:48:15 +00003471 if (ExtInst) {
3472 if (Exts)
3473 Exts->push_back(ExtInst);
3474 CreatedInstsCost = !TLI.isExtFree(ExtInst) && !HasMergedNonFreeExt;
3475 }
Quentin Colombetac55b152014-09-16 22:36:07 +00003476 return ExtVal;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003477 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003478
Quentin Colombet9dcb7242014-09-15 18:26:58 +00003479 // At this point we have: ext ty opnd to ty.
3480 // Reassign the uses of ExtInst to the opnd and remove ExtInst.
3481 Value *NextVal = ExtInst->getOperand(0);
3482 TPT.eraseInstruction(ExtInst, NextVal);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003483 return NextVal;
3484}
3485
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003486Value *TypePromotionHelper::promoteOperandForOther(
3487 Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003488 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003489 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003490 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI,
3491 bool IsSExt) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003492 // By construction, the operand of Ext is an instruction. Otherwise we cannot
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003493 // get through it and this method should not be called.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003494 Instruction *ExtOpnd = cast<Instruction>(Ext->getOperand(0));
Quentin Colombet1b274f92015-03-10 21:48:15 +00003495 CreatedInstsCost = 0;
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003496 if (!ExtOpnd->hasOneUse()) {
3497 // ExtOpnd will be promoted.
3498 // All its uses, but Ext, will need to use a truncated value of the
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003499 // promoted version.
3500 // Create the truncate now.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003501 Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->getType());
Quentin Colombetac55b152014-09-16 22:36:07 +00003502 if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) {
3503 ITrunc->removeFromParent();
3504 // Insert it just after the definition.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003505 ITrunc->insertAfter(ExtOpnd);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003506 if (Truncs)
3507 Truncs->push_back(ITrunc);
Quentin Colombetac55b152014-09-16 22:36:07 +00003508 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003509
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003510 TPT.replaceAllUsesWith(ExtOpnd, Trunc);
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003511 // Restore the operand of Ext (which has been replaced by the previous call
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003512 // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003513 TPT.setOperand(Ext, 0, ExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003514 }
3515
3516 // Get through the Instruction:
3517 // 1. Update its type.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003518 // 2. Replace the uses of Ext by Inst.
3519 // 3. Extend each operand that needs to be extended.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003520
3521 // Remember the original type of the instruction before promotion.
3522 // This is useful to know that the high bits are sign extended bits.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003523 PromotedInsts.insert(std::pair<Instruction *, TypeIsSExt>(
3524 ExtOpnd, TypeIsSExt(ExtOpnd->getType(), IsSExt)));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003525 // Step #1.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003526 TPT.mutateType(ExtOpnd, Ext->getType());
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003527 // Step #2.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003528 TPT.replaceAllUsesWith(Ext, ExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003529 // Step #3.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003530 Instruction *ExtForOpnd = Ext;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003531
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003532 DEBUG(dbgs() << "Propagate Ext to operands\n");
3533 for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003534 ++OpIdx) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003535 DEBUG(dbgs() << "Operand:\n" << *(ExtOpnd->getOperand(OpIdx)) << '\n');
3536 if (ExtOpnd->getOperand(OpIdx)->getType() == Ext->getType() ||
3537 !shouldExtOperand(ExtOpnd, OpIdx)) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003538 DEBUG(dbgs() << "No need to propagate\n");
3539 continue;
3540 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003541 // Check if we can statically extend the operand.
3542 Value *Opnd = ExtOpnd->getOperand(OpIdx);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003543 if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003544 DEBUG(dbgs() << "Statically extend\n");
3545 unsigned BitWidth = Ext->getType()->getIntegerBitWidth();
3546 APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth)
3547 : Cst->getValue().zext(BitWidth);
3548 TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->getType(), CstVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003549 continue;
3550 }
3551 // UndefValue are typed, so we have to statically sign extend them.
3552 if (isa<UndefValue>(Opnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003553 DEBUG(dbgs() << "Statically extend\n");
3554 TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->getType()));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003555 continue;
3556 }
3557
3558 // Otherwise we have to explicity sign extend the operand.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003559 // Check if Ext was reused to extend an operand.
3560 if (!ExtForOpnd) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003561 // If yes, create a new one.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003562 DEBUG(dbgs() << "More operands to ext\n");
Quentin Colombet84f89cc2014-12-22 18:11:52 +00003563 Value *ValForExtOpnd = IsSExt ? TPT.createSExt(Ext, Opnd, Ext->getType())
3564 : TPT.createZExt(Ext, Opnd, Ext->getType());
3565 if (!isa<Instruction>(ValForExtOpnd)) {
3566 TPT.setOperand(ExtOpnd, OpIdx, ValForExtOpnd);
3567 continue;
3568 }
3569 ExtForOpnd = cast<Instruction>(ValForExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003570 }
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003571 if (Exts)
3572 Exts->push_back(ExtForOpnd);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003573 TPT.setOperand(ExtForOpnd, 0, Opnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003574
3575 // Move the sign extension before the insertion point.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003576 TPT.moveBefore(ExtForOpnd, ExtOpnd);
3577 TPT.setOperand(ExtOpnd, OpIdx, ExtForOpnd);
Quentin Colombet1b274f92015-03-10 21:48:15 +00003578 CreatedInstsCost += !TLI.isExtFree(ExtForOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003579 // If more sext are required, new instructions will have to be created.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003580 ExtForOpnd = nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003581 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003582 if (ExtForOpnd == Ext) {
3583 DEBUG(dbgs() << "Extension is useless now\n");
3584 TPT.eraseInstruction(Ext);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003585 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003586 return ExtOpnd;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003587}
3588
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003589/// Check whether or not promoting an instruction to a wider type is profitable.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003590/// \p NewCost gives the cost of extension instructions created by the
3591/// promotion.
3592/// \p OldCost gives the cost of extension instructions before the promotion
3593/// plus the number of instructions that have been
3594/// matched in the addressing mode the promotion.
Quentin Colombet867c5502014-02-14 22:23:22 +00003595/// \p PromotedOperand is the value that has been promoted.
3596/// \return True if the promotion is profitable, false otherwise.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003597bool AddressingModeMatcher::isPromotionProfitable(
Quentin Colombet1b274f92015-03-10 21:48:15 +00003598 unsigned NewCost, unsigned OldCost, Value *PromotedOperand) const {
3599 DEBUG(dbgs() << "OldCost: " << OldCost << "\tNewCost: " << NewCost << '\n');
3600 // The cost of the new extensions is greater than the cost of the
3601 // old extension plus what we folded.
Quentin Colombet867c5502014-02-14 22:23:22 +00003602 // This is not profitable.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003603 if (NewCost > OldCost)
Quentin Colombet867c5502014-02-14 22:23:22 +00003604 return false;
Quentin Colombet1b274f92015-03-10 21:48:15 +00003605 if (NewCost < OldCost)
Quentin Colombet867c5502014-02-14 22:23:22 +00003606 return true;
3607 // The promotion is neutral but it may help folding the sign extension in
3608 // loads for instance.
3609 // Check that we did not create an illegal instruction.
Mehdi Amini44ede332015-07-09 02:09:04 +00003610 return isPromotedInstructionLegal(TLI, DL, PromotedOperand);
Quentin Colombet867c5502014-02-14 22:23:22 +00003611}
3612
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003613/// Given an instruction or constant expr, see if we can fold the operation
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003614/// into the addressing mode. If so, update the addressing mode and return
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003615/// true, otherwise return false without modifying AddrMode.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003616/// If \p MovedAway is not NULL, it contains the information of whether or
3617/// not AddrInst has to be folded into the addressing mode on success.
3618/// If \p MovedAway == true, \p AddrInst will not be part of the addressing
3619/// because it has been moved away.
3620/// Thus AddrInst must not be added in the matched instructions.
3621/// This state can happen when AddrInst is a sext, since it may be moved away.
3622/// Therefore, AddrInst may not be valid when MovedAway is true and it must
3623/// not be referenced anymore.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003624bool AddressingModeMatcher::matchOperationAddr(User *AddrInst, unsigned Opcode,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003625 unsigned Depth,
3626 bool *MovedAway) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003627 // Avoid exponential behavior on extremely deep expression trees.
3628 if (Depth >= 5) return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003629
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003630 // By default, all matched instructions stay in place.
3631 if (MovedAway)
3632 *MovedAway = false;
3633
Chandler Carruthc8925912013-01-05 02:09:22 +00003634 switch (Opcode) {
3635 case Instruction::PtrToInt:
3636 // PtrToInt is always a noop, as we know that the int type is pointer sized.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003637 return matchAddr(AddrInst->getOperand(0), Depth);
Mehdi Amini44ede332015-07-09 02:09:04 +00003638 case Instruction::IntToPtr: {
3639 auto AS = AddrInst->getType()->getPointerAddressSpace();
3640 auto PtrTy = MVT::getIntegerVT(DL.getPointerSizeInBits(AS));
Chandler Carruthc8925912013-01-05 02:09:22 +00003641 // This inttoptr is a no-op if the integer type is pointer sized.
Mehdi Amini44ede332015-07-09 02:09:04 +00003642 if (TLI.getValueType(DL, AddrInst->getOperand(0)->getType()) == PtrTy)
Sanjay Patelfc580a62015-09-21 23:03:16 +00003643 return matchAddr(AddrInst->getOperand(0), Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00003644 return false;
Mehdi Amini44ede332015-07-09 02:09:04 +00003645 }
Chandler Carruthc8925912013-01-05 02:09:22 +00003646 case Instruction::BitCast:
3647 // BitCast is always a noop, and we can handle it as long as it is
3648 // int->int or pointer->pointer (we don't want int<->fp or something).
3649 if ((AddrInst->getOperand(0)->getType()->isPointerTy() ||
3650 AddrInst->getOperand(0)->getType()->isIntegerTy()) &&
3651 // Don't touch identity bitcasts. These were probably put here by LSR,
3652 // and we don't want to mess around with them. Assume it knows what it
3653 // is doing.
3654 AddrInst->getOperand(0)->getType() != AddrInst->getType())
Sanjay Patelfc580a62015-09-21 23:03:16 +00003655 return matchAddr(AddrInst->getOperand(0), Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00003656 return false;
Matt Arsenaultf05b0232015-05-26 16:59:43 +00003657 case Instruction::AddrSpaceCast: {
3658 unsigned SrcAS
3659 = AddrInst->getOperand(0)->getType()->getPointerAddressSpace();
3660 unsigned DestAS = AddrInst->getType()->getPointerAddressSpace();
3661 if (TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
Sanjay Patelfc580a62015-09-21 23:03:16 +00003662 return matchAddr(AddrInst->getOperand(0), Depth);
Matt Arsenaultf05b0232015-05-26 16:59:43 +00003663 return false;
3664 }
Chandler Carruthc8925912013-01-05 02:09:22 +00003665 case Instruction::Add: {
3666 // Check to see if we can merge in the RHS then the LHS. If so, we win.
3667 ExtAddrMode BackupAddrMode = AddrMode;
3668 unsigned OldSize = AddrModeInsts.size();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003669 // Start a transaction at this point.
3670 // The LHS may match but not the RHS.
3671 // Therefore, we need a higher level restoration point to undo partially
3672 // matched operation.
3673 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3674 TPT.getRestorationPoint();
3675
Sanjay Patelfc580a62015-09-21 23:03:16 +00003676 if (matchAddr(AddrInst->getOperand(1), Depth+1) &&
3677 matchAddr(AddrInst->getOperand(0), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00003678 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003679
Chandler Carruthc8925912013-01-05 02:09:22 +00003680 // Restore the old addr mode info.
3681 AddrMode = BackupAddrMode;
3682 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003683 TPT.rollback(LastKnownGood);
Stephen Lin837bba12013-07-15 17:55:02 +00003684
Chandler Carruthc8925912013-01-05 02:09:22 +00003685 // Otherwise this was over-aggressive. Try merging in the LHS then the RHS.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003686 if (matchAddr(AddrInst->getOperand(0), Depth+1) &&
3687 matchAddr(AddrInst->getOperand(1), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00003688 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003689
Chandler Carruthc8925912013-01-05 02:09:22 +00003690 // Otherwise we definitely can't merge the ADD in.
3691 AddrMode = BackupAddrMode;
3692 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003693 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003694 break;
3695 }
3696 //case Instruction::Or:
3697 // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
3698 //break;
3699 case Instruction::Mul:
3700 case Instruction::Shl: {
3701 // Can only handle X*C and X << C.
3702 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
Sanjay Pateld3bbfa12014-07-16 22:40:28 +00003703 if (!RHS)
3704 return false;
Chandler Carruthc8925912013-01-05 02:09:22 +00003705 int64_t Scale = RHS->getSExtValue();
3706 if (Opcode == Instruction::Shl)
3707 Scale = 1LL << Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00003708
Sanjay Patelfc580a62015-09-21 23:03:16 +00003709 return matchScaledValue(AddrInst->getOperand(0), Scale, Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00003710 }
3711 case Instruction::GetElementPtr: {
3712 // Scan the GEP. We check it if it contains constant offsets and at most
3713 // one variable offset.
3714 int VariableOperand = -1;
3715 unsigned VariableScale = 0;
Stephen Lin837bba12013-07-15 17:55:02 +00003716
Chandler Carruthc8925912013-01-05 02:09:22 +00003717 int64_t ConstantOffset = 0;
Chandler Carruthc8925912013-01-05 02:09:22 +00003718 gep_type_iterator GTI = gep_type_begin(AddrInst);
3719 for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
Peter Collingbourneab85225b2016-12-02 02:24:42 +00003720 if (StructType *STy = GTI.getStructTypeOrNull()) {
Mehdi Amini4fe37982015-07-07 18:45:17 +00003721 const StructLayout *SL = DL.getStructLayout(STy);
Chandler Carruthc8925912013-01-05 02:09:22 +00003722 unsigned Idx =
3723 cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
3724 ConstantOffset += SL->getElementOffset(Idx);
3725 } else {
Mehdi Amini4fe37982015-07-07 18:45:17 +00003726 uint64_t TypeSize = DL.getTypeAllocSize(GTI.getIndexedType());
Chandler Carruthc8925912013-01-05 02:09:22 +00003727 if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
3728 ConstantOffset += CI->getSExtValue()*TypeSize;
3729 } else if (TypeSize) { // Scales of zero don't do anything.
3730 // We only allow one variable index at the moment.
3731 if (VariableOperand != -1)
3732 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003733
Chandler Carruthc8925912013-01-05 02:09:22 +00003734 // Remember the variable index.
3735 VariableOperand = i;
3736 VariableScale = TypeSize;
3737 }
3738 }
3739 }
Stephen Lin837bba12013-07-15 17:55:02 +00003740
Chandler Carruthc8925912013-01-05 02:09:22 +00003741 // A common case is for the GEP to only do a constant offset. In this case,
3742 // just add it to the disp field and check validity.
3743 if (VariableOperand == -1) {
3744 AddrMode.BaseOffs += ConstantOffset;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003745 if (ConstantOffset == 0 ||
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003746 TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003747 // Check to see if we can fold the base pointer in too.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003748 if (matchAddr(AddrInst->getOperand(0), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00003749 return true;
3750 }
3751 AddrMode.BaseOffs -= ConstantOffset;
3752 return false;
3753 }
3754
3755 // Save the valid addressing mode in case we can't match.
3756 ExtAddrMode BackupAddrMode = AddrMode;
3757 unsigned OldSize = AddrModeInsts.size();
3758
3759 // See if the scale and offset amount is valid for this target.
3760 AddrMode.BaseOffs += ConstantOffset;
3761
3762 // Match the base operand of the GEP.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003763 if (!matchAddr(AddrInst->getOperand(0), Depth+1)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003764 // If it couldn't be matched, just stuff the value in a register.
3765 if (AddrMode.HasBaseReg) {
3766 AddrMode = BackupAddrMode;
3767 AddrModeInsts.resize(OldSize);
3768 return false;
3769 }
3770 AddrMode.HasBaseReg = true;
3771 AddrMode.BaseReg = AddrInst->getOperand(0);
3772 }
3773
3774 // Match the remaining variable portion of the GEP.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003775 if (!matchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
Chandler Carruthc8925912013-01-05 02:09:22 +00003776 Depth)) {
3777 // If it couldn't be matched, try stuffing the base into a register
3778 // instead of matching it, and retrying the match of the scale.
3779 AddrMode = BackupAddrMode;
3780 AddrModeInsts.resize(OldSize);
3781 if (AddrMode.HasBaseReg)
3782 return false;
3783 AddrMode.HasBaseReg = true;
3784 AddrMode.BaseReg = AddrInst->getOperand(0);
3785 AddrMode.BaseOffs += ConstantOffset;
Sanjay Patelfc580a62015-09-21 23:03:16 +00003786 if (!matchScaledValue(AddrInst->getOperand(VariableOperand),
Chandler Carruthc8925912013-01-05 02:09:22 +00003787 VariableScale, Depth)) {
3788 // If even that didn't work, bail.
3789 AddrMode = BackupAddrMode;
3790 AddrModeInsts.resize(OldSize);
3791 return false;
3792 }
3793 }
3794
3795 return true;
3796 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003797 case Instruction::SExt:
3798 case Instruction::ZExt: {
3799 Instruction *Ext = dyn_cast<Instruction>(AddrInst);
3800 if (!Ext)
Sanjay Pateld3bbfa12014-07-16 22:40:28 +00003801 return false;
Sanjay Patelab60d042014-07-16 21:08:10 +00003802
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003803 // Try to move this ext out of the way of the addressing mode.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003804 // Ask for a method for doing so.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003805 TypePromotionHelper::Action TPH =
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003806 TypePromotionHelper::getAction(Ext, InsertedInsts, TLI, PromotedInsts);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003807 if (!TPH)
3808 return false;
3809
3810 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3811 TPT.getRestorationPoint();
Quentin Colombet1b274f92015-03-10 21:48:15 +00003812 unsigned CreatedInstsCost = 0;
3813 unsigned ExtCost = !TLI.isExtFree(Ext);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003814 Value *PromotedOperand =
Quentin Colombet1b274f92015-03-10 21:48:15 +00003815 TPH(Ext, TPT, PromotedInsts, CreatedInstsCost, nullptr, nullptr, TLI);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003816 // SExt has been moved away.
3817 // Thus either it will be rematched later in the recursive calls or it is
3818 // gone. Anyway, we must not fold it into the addressing mode at this point.
3819 // E.g.,
3820 // op = add opnd, 1
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003821 // idx = ext op
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003822 // addr = gep base, idx
3823 // is now:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003824 // promotedOpnd = ext opnd <- no match here
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003825 // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls)
3826 // addr = gep base, op <- match
3827 if (MovedAway)
3828 *MovedAway = true;
3829
3830 assert(PromotedOperand &&
3831 "TypePromotionHelper should have filtered out those cases");
3832
3833 ExtAddrMode BackupAddrMode = AddrMode;
3834 unsigned OldSize = AddrModeInsts.size();
3835
Sanjay Patelfc580a62015-09-21 23:03:16 +00003836 if (!matchAddr(PromotedOperand, Depth) ||
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003837 // The total of the new cost is equal to the cost of the created
Quentin Colombet1b274f92015-03-10 21:48:15 +00003838 // instructions.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003839 // The total of the old cost is equal to the cost of the extension plus
Quentin Colombet1b274f92015-03-10 21:48:15 +00003840 // what we have saved in the addressing mode.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003841 !isPromotionProfitable(CreatedInstsCost,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003842 ExtCost + (AddrModeInsts.size() - OldSize),
Quentin Colombet867c5502014-02-14 22:23:22 +00003843 PromotedOperand)) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003844 AddrMode = BackupAddrMode;
3845 AddrModeInsts.resize(OldSize);
3846 DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
3847 TPT.rollback(LastKnownGood);
3848 return false;
3849 }
3850 return true;
3851 }
Chandler Carruthc8925912013-01-05 02:09:22 +00003852 }
3853 return false;
3854}
3855
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003856/// If we can, try to add the value of 'Addr' into the current addressing mode.
3857/// If Addr can't be added to AddrMode this returns false and leaves AddrMode
3858/// unmodified. This assumes that Addr is either a pointer type or intptr_t
3859/// for the target.
Chandler Carruthc8925912013-01-05 02:09:22 +00003860///
Sanjay Patelfc580a62015-09-21 23:03:16 +00003861bool AddressingModeMatcher::matchAddr(Value *Addr, unsigned Depth) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003862 // Start a transaction at this point that we will rollback if the matching
3863 // fails.
3864 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3865 TPT.getRestorationPoint();
Chandler Carruthc8925912013-01-05 02:09:22 +00003866 if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
3867 // Fold in immediates if legal for the target.
3868 AddrMode.BaseOffs += CI->getSExtValue();
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003869 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003870 return true;
3871 AddrMode.BaseOffs -= CI->getSExtValue();
3872 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
3873 // If this is a global variable, try to fold it into the addressing mode.
Craig Topperc0196b12014-04-14 00:51:57 +00003874 if (!AddrMode.BaseGV) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003875 AddrMode.BaseGV = GV;
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003876 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003877 return true;
Craig Topperc0196b12014-04-14 00:51:57 +00003878 AddrMode.BaseGV = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003879 }
3880 } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
3881 ExtAddrMode BackupAddrMode = AddrMode;
3882 unsigned OldSize = AddrModeInsts.size();
3883
3884 // Check to see if it is possible to fold this operation.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003885 bool MovedAway = false;
Sanjay Patelfc580a62015-09-21 23:03:16 +00003886 if (matchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003887 // This instruction may have been moved away. If so, there is nothing
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003888 // to check here.
3889 if (MovedAway)
3890 return true;
Chandler Carruthc8925912013-01-05 02:09:22 +00003891 // Okay, it's possible to fold this. Check to see if it is actually
3892 // *profitable* to do so. We use a simple cost model to avoid increasing
3893 // register pressure too much.
3894 if (I->hasOneUse() ||
Sanjay Patelfc580a62015-09-21 23:03:16 +00003895 isProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003896 AddrModeInsts.push_back(I);
3897 return true;
3898 }
Stephen Lin837bba12013-07-15 17:55:02 +00003899
Chandler Carruthc8925912013-01-05 02:09:22 +00003900 // It isn't profitable to do this, roll back.
3901 //cerr << "NOT FOLDING: " << *I;
3902 AddrMode = BackupAddrMode;
3903 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003904 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003905 }
3906 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
Sanjay Patelfc580a62015-09-21 23:03:16 +00003907 if (matchOperationAddr(CE, CE->getOpcode(), Depth))
Chandler Carruthc8925912013-01-05 02:09:22 +00003908 return true;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003909 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003910 } else if (isa<ConstantPointerNull>(Addr)) {
3911 // Null pointer gets folded without affecting the addressing mode.
3912 return true;
3913 }
3914
3915 // Worse case, the target should support [reg] addressing modes. :)
3916 if (!AddrMode.HasBaseReg) {
3917 AddrMode.HasBaseReg = true;
3918 AddrMode.BaseReg = Addr;
3919 // Still check for legality in case the target supports [imm] but not [i+r].
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003920 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003921 return true;
3922 AddrMode.HasBaseReg = false;
Craig Topperc0196b12014-04-14 00:51:57 +00003923 AddrMode.BaseReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003924 }
3925
3926 // If the base register is already taken, see if we can do [r+r].
3927 if (AddrMode.Scale == 0) {
3928 AddrMode.Scale = 1;
3929 AddrMode.ScaledReg = Addr;
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003930 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003931 return true;
3932 AddrMode.Scale = 0;
Craig Topperc0196b12014-04-14 00:51:57 +00003933 AddrMode.ScaledReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003934 }
3935 // Couldn't match.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003936 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003937 return false;
3938}
3939
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003940/// Check to see if all uses of OpVal by the specified inline asm call are due
3941/// to memory operands. If so, return true, otherwise return false.
Chandler Carruthc8925912013-01-05 02:09:22 +00003942static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
Igor Laevsky3be81ba2017-02-07 13:27:20 +00003943 const TargetLowering &TLI,
3944 const TargetRegisterInfo &TRI) {
Sanjay Patel4137d512017-06-07 14:29:52 +00003945 const Function *F = CI->getFunction();
Eric Christopherd75c00c2015-02-26 22:38:34 +00003946 TargetLowering::AsmOperandInfoVector TargetConstraints =
Igor Laevsky3be81ba2017-02-07 13:27:20 +00003947 TLI.ParseConstraints(F->getParent()->getDataLayout(), &TRI,
Mehdi Amini8ac7a9d2015-07-07 19:07:19 +00003948 ImmutableCallSite(CI));
Igor Laevsky3be81ba2017-02-07 13:27:20 +00003949
Chandler Carruthc8925912013-01-05 02:09:22 +00003950 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
3951 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Stephen Lin837bba12013-07-15 17:55:02 +00003952
Chandler Carruthc8925912013-01-05 02:09:22 +00003953 // Compute the constraint code and ConstraintType to use.
Igor Laevsky3be81ba2017-02-07 13:27:20 +00003954 TLI.ComputeConstraintToUse(OpInfo, SDValue());
Chandler Carruthc8925912013-01-05 02:09:22 +00003955
3956 // If this asm operand is our Value*, and if it isn't an indirect memory
3957 // operand, we can't fold it!
3958 if (OpInfo.CallOperandVal == OpVal &&
3959 (OpInfo.ConstraintType != TargetLowering::C_Memory ||
3960 !OpInfo.isIndirect))
3961 return false;
3962 }
3963
3964 return true;
3965}
3966
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003967/// Recursively walk all the uses of I until we find a memory use.
3968/// If we find an obviously non-foldable instruction, return true.
Chandler Carruthc8925912013-01-05 02:09:22 +00003969/// Add the ultimately found memory instructions to MemoryUses.
Eric Christopher11e4df72015-02-26 22:38:43 +00003970static bool FindAllMemoryUses(
3971 Instruction *I,
3972 SmallVectorImpl<std::pair<Instruction *, unsigned>> &MemoryUses,
Igor Laevsky3be81ba2017-02-07 13:27:20 +00003973 SmallPtrSetImpl<Instruction *> &ConsideredInsts,
3974 const TargetLowering &TLI, const TargetRegisterInfo &TRI) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003975 // If we already considered this instruction, we're done.
David Blaikie70573dc2014-11-19 07:49:26 +00003976 if (!ConsideredInsts.insert(I).second)
Chandler Carruthc8925912013-01-05 02:09:22 +00003977 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003978
Chandler Carruthc8925912013-01-05 02:09:22 +00003979 // If this is an obviously unfoldable instruction, bail out.
3980 if (!MightBeFoldableInst(I))
3981 return true;
3982
Philip Reamesac115ed2016-03-09 23:13:12 +00003983 const bool OptSize = I->getFunction()->optForSize();
3984
Chandler Carruthc8925912013-01-05 02:09:22 +00003985 // Loop over all the uses, recursively processing them.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003986 for (Use &U : I->uses()) {
3987 Instruction *UserI = cast<Instruction>(U.getUser());
Chandler Carruthc8925912013-01-05 02:09:22 +00003988
Chandler Carruthcdf47882014-03-09 03:16:01 +00003989 if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
3990 MemoryUses.push_back(std::make_pair(LI, U.getOperandNo()));
Chandler Carruthc8925912013-01-05 02:09:22 +00003991 continue;
3992 }
Stephen Lin837bba12013-07-15 17:55:02 +00003993
Chandler Carruthcdf47882014-03-09 03:16:01 +00003994 if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
3995 unsigned opNo = U.getOperandNo();
Matt Arsenault02d915b2017-03-15 22:35:20 +00003996 if (opNo != StoreInst::getPointerOperandIndex())
3997 return true; // Storing addr, not into addr.
Chandler Carruthc8925912013-01-05 02:09:22 +00003998 MemoryUses.push_back(std::make_pair(SI, opNo));
3999 continue;
4000 }
Stephen Lin837bba12013-07-15 17:55:02 +00004001
Matt Arsenault02d915b2017-03-15 22:35:20 +00004002 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(UserI)) {
4003 unsigned opNo = U.getOperandNo();
4004 if (opNo != AtomicRMWInst::getPointerOperandIndex())
4005 return true; // Storing addr, not into addr.
4006 MemoryUses.push_back(std::make_pair(RMW, opNo));
4007 continue;
4008 }
4009
4010 if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(UserI)) {
4011 unsigned opNo = U.getOperandNo();
4012 if (opNo != AtomicCmpXchgInst::getPointerOperandIndex())
4013 return true; // Storing addr, not into addr.
4014 MemoryUses.push_back(std::make_pair(CmpX, opNo));
4015 continue;
4016 }
4017
Chandler Carruthcdf47882014-03-09 03:16:01 +00004018 if (CallInst *CI = dyn_cast<CallInst>(UserI)) {
Philip Reamesac115ed2016-03-09 23:13:12 +00004019 // If this is a cold call, we can sink the addressing calculation into
4020 // the cold path. See optimizeCallInst
4021 if (!OptSize && CI->hasFnAttr(Attribute::Cold))
4022 continue;
Junmo Park6098cbb2016-03-11 07:05:32 +00004023
Chandler Carruthc8925912013-01-05 02:09:22 +00004024 InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
4025 if (!IA) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00004026
Chandler Carruthc8925912013-01-05 02:09:22 +00004027 // If this is a memory operand, we're cool, otherwise bail out.
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004028 if (!IsOperandAMemoryOperand(CI, IA, I, TLI, TRI))
Chandler Carruthc8925912013-01-05 02:09:22 +00004029 return true;
4030 continue;
4031 }
Stephen Lin837bba12013-07-15 17:55:02 +00004032
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004033 if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TLI, TRI))
Chandler Carruthc8925912013-01-05 02:09:22 +00004034 return true;
4035 }
4036
4037 return false;
4038}
4039
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00004040/// Return true if Val is already known to be live at the use site that we're
4041/// folding it into. If so, there is no cost to include it in the addressing
4042/// mode. KnownLive1 and KnownLive2 are two values that we know are live at the
4043/// instruction already.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004044bool AddressingModeMatcher::valueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
Chandler Carruthc8925912013-01-05 02:09:22 +00004045 Value *KnownLive2) {
4046 // If Val is either of the known-live values, we know it is live!
Craig Topperc0196b12014-04-14 00:51:57 +00004047 if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2)
Chandler Carruthc8925912013-01-05 02:09:22 +00004048 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00004049
Chandler Carruthc8925912013-01-05 02:09:22 +00004050 // All values other than instructions and arguments (e.g. constants) are live.
4051 if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00004052
Chandler Carruthc8925912013-01-05 02:09:22 +00004053 // If Val is a constant sized alloca in the entry block, it is live, this is
4054 // true because it is just a reference to the stack/frame pointer, which is
4055 // live for the whole function.
4056 if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
4057 if (AI->isStaticAlloca())
4058 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00004059
Chandler Carruthc8925912013-01-05 02:09:22 +00004060 // Check to see if this value is already used in the memory instruction's
4061 // block. If so, it's already live into the block at the very least, so we
4062 // can reasonably fold it.
4063 return Val->isUsedInBasicBlock(MemoryInst->getParent());
4064}
4065
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004066/// It is possible for the addressing mode of the machine to fold the specified
4067/// instruction into a load or store that ultimately uses it.
4068/// However, the specified instruction has multiple uses.
4069/// Given this, it may actually increase register pressure to fold it
4070/// into the load. For example, consider this code:
Chandler Carruthc8925912013-01-05 02:09:22 +00004071///
4072/// X = ...
4073/// Y = X+1
4074/// use(Y) -> nonload/store
4075/// Z = Y+1
4076/// load Z
4077///
4078/// In this case, Y has multiple uses, and can be folded into the load of Z
4079/// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to
4080/// be live at the use(Y) line. If we don't fold Y into load Z, we use one
4081/// fewer register. Since Y can't be folded into "use(Y)" we don't increase the
4082/// number of computations either.
4083///
4084/// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If
4085/// X was live across 'load Z' for other reasons, we actually *would* want to
4086/// fold the addressing mode in the Z case. This would make Y die earlier.
4087bool AddressingModeMatcher::
Sanjay Patelfc580a62015-09-21 23:03:16 +00004088isProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
Chandler Carruthc8925912013-01-05 02:09:22 +00004089 ExtAddrMode &AMAfter) {
4090 if (IgnoreProfitability) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00004091
Chandler Carruthc8925912013-01-05 02:09:22 +00004092 // AMBefore is the addressing mode before this instruction was folded into it,
4093 // and AMAfter is the addressing mode after the instruction was folded. Get
4094 // the set of registers referenced by AMAfter and subtract out those
4095 // referenced by AMBefore: this is the set of values which folding in this
4096 // address extends the lifetime of.
4097 //
4098 // Note that there are only two potential values being referenced here,
4099 // BaseReg and ScaleReg (global addresses are always available, as are any
4100 // folded immediates).
4101 Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
Stephen Lin837bba12013-07-15 17:55:02 +00004102
Chandler Carruthc8925912013-01-05 02:09:22 +00004103 // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
4104 // lifetime wasn't extended by adding this instruction.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004105 if (valueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
Craig Topperc0196b12014-04-14 00:51:57 +00004106 BaseReg = nullptr;
Sanjay Patelfc580a62015-09-21 23:03:16 +00004107 if (valueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
Craig Topperc0196b12014-04-14 00:51:57 +00004108 ScaledReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00004109
4110 // If folding this instruction (and it's subexprs) didn't extend any live
4111 // ranges, we're ok with it.
Craig Topperc0196b12014-04-14 00:51:57 +00004112 if (!BaseReg && !ScaledReg)
Chandler Carruthc8925912013-01-05 02:09:22 +00004113 return true;
4114
Philip Reamesac115ed2016-03-09 23:13:12 +00004115 // If all uses of this instruction can have the address mode sunk into them,
4116 // we can remove the addressing mode and effectively trade one live register
4117 // for another (at worst.) In this context, folding an addressing mode into
Junmo Park6098cbb2016-03-11 07:05:32 +00004118 // the use is just a particularly nice way of sinking it.
Chandler Carruthc8925912013-01-05 02:09:22 +00004119 SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
4120 SmallPtrSet<Instruction*, 16> ConsideredInsts;
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004121 if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TLI, TRI))
Chandler Carruthc8925912013-01-05 02:09:22 +00004122 return false; // Has a non-memory, non-foldable use!
Stephen Lin837bba12013-07-15 17:55:02 +00004123
Chandler Carruthc8925912013-01-05 02:09:22 +00004124 // Now that we know that all uses of this instruction are part of a chain of
4125 // computation involving only operations that could theoretically be folded
Philip Reamesac115ed2016-03-09 23:13:12 +00004126 // into a memory use, loop over each of these memory operation uses and see
4127 // if they could *actually* fold the instruction. The assumption is that
4128 // addressing modes are cheap and that duplicating the computation involved
4129 // many times is worthwhile, even on a fastpath. For sinking candidates
4130 // (i.e. cold call sites), this serves as a way to prevent excessive code
4131 // growth since most architectures have some reasonable small and fast way to
4132 // compute an effective address. (i.e LEA on x86)
Chandler Carruthc8925912013-01-05 02:09:22 +00004133 SmallVector<Instruction*, 32> MatchedAddrModeInsts;
4134 for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
4135 Instruction *User = MemoryUses[i].first;
4136 unsigned OpNo = MemoryUses[i].second;
Stephen Lin837bba12013-07-15 17:55:02 +00004137
Chandler Carruthc8925912013-01-05 02:09:22 +00004138 // Get the access type of this use. If the use isn't a pointer, we don't
4139 // know what it accesses.
4140 Value *Address = User->getOperand(OpNo);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00004141 PointerType *AddrTy = dyn_cast<PointerType>(Address->getType());
4142 if (!AddrTy)
Chandler Carruthc8925912013-01-05 02:09:22 +00004143 return false;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00004144 Type *AddressAccessTy = AddrTy->getElementType();
4145 unsigned AS = AddrTy->getAddressSpace();
Stephen Lin837bba12013-07-15 17:55:02 +00004146
Chandler Carruthc8925912013-01-05 02:09:22 +00004147 // Do a match against the root of this address, ignoring profitability. This
4148 // will tell us if the addressing mode for the memory operation will
4149 // *actually* cover the shared instruction.
4150 ExtAddrMode Result;
Quentin Colombet5a69dda2014-02-11 01:59:02 +00004151 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4152 TPT.getRestorationPoint();
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004153 AddressingModeMatcher Matcher(MatchedAddrModeInsts, TLI, TRI,
4154 AddressAccessTy, AS,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00004155 MemoryInst, Result, InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004156 PromotedInsts, TPT);
Chandler Carruthc8925912013-01-05 02:09:22 +00004157 Matcher.IgnoreProfitability = true;
Sanjay Patelfc580a62015-09-21 23:03:16 +00004158 bool Success = Matcher.matchAddr(Address, 0);
Chandler Carruthc8925912013-01-05 02:09:22 +00004159 (void)Success; assert(Success && "Couldn't select *anything*?");
4160
Quentin Colombet5a69dda2014-02-11 01:59:02 +00004161 // The match was to check the profitability, the changes made are not
4162 // part of the original matcher. Therefore, they should be dropped
4163 // otherwise the original matcher will not present the right state.
4164 TPT.rollback(LastKnownGood);
4165
Chandler Carruthc8925912013-01-05 02:09:22 +00004166 // If the match didn't cover I, then it won't be shared by it.
David Majnemer0d955d02016-08-11 22:21:41 +00004167 if (!is_contained(MatchedAddrModeInsts, I))
Chandler Carruthc8925912013-01-05 02:09:22 +00004168 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00004169
Chandler Carruthc8925912013-01-05 02:09:22 +00004170 MatchedAddrModeInsts.clear();
4171 }
Stephen Lin837bba12013-07-15 17:55:02 +00004172
Chandler Carruthc8925912013-01-05 02:09:22 +00004173 return true;
4174}
4175
4176} // end anonymous namespace
4177
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004178/// Return true if the specified values are defined in a
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004179/// different basic block than BB.
4180static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
4181 if (Instruction *I = dyn_cast<Instruction>(V))
4182 return I->getParent() != BB;
4183 return false;
4184}
4185
Philip Reamesac115ed2016-03-09 23:13:12 +00004186/// Sink addressing mode computation immediate before MemoryInst if doing so
4187/// can be done without increasing register pressure. The need for the
4188/// register pressure constraint means this can end up being an all or nothing
4189/// decision for all uses of the same addressing computation.
4190///
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004191/// Load and Store Instructions often have addressing modes that can do
4192/// significant amounts of computation. As such, instruction selection will try
4193/// to get the load or store to do as much computation as possible for the
4194/// program. The problem is that isel can only see within a single block. As
4195/// such, we sink as much legal addressing mode work into the block as possible.
Chris Lattner728f9022008-11-25 07:09:13 +00004196///
4197/// This method is used to optimize both load/store and inline asms with memory
Philip Reamesac115ed2016-03-09 23:13:12 +00004198/// operands. It's also used to sink addressing computations feeding into cold
4199/// call sites into their (cold) basic block.
4200///
4201/// The motivation for handling sinking into cold blocks is that doing so can
4202/// both enable other address mode sinking (by satisfying the register pressure
4203/// constraint above), and reduce register pressure globally (by removing the
4204/// addressing mode computation from the fast path entirely.).
Sanjay Patelfc580a62015-09-21 23:03:16 +00004205bool CodeGenPrepare::optimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00004206 Type *AccessTy, unsigned AddrSpace) {
Owen Anderson8ba5f392010-11-27 08:15:55 +00004207 Value *Repl = Addr;
Nadav Rotem465834c2012-07-24 10:51:42 +00004208
4209 // Try to collapse single-value PHI nodes. This is necessary to undo
Owen Andersondfb8c3b2010-11-19 22:15:03 +00004210 // unprofitable PRE transformations.
Cameron Zwarich43cecb12011-01-03 06:33:01 +00004211 SmallVector<Value*, 8> worklist;
4212 SmallPtrSet<Value*, 16> Visited;
Owen Anderson8ba5f392010-11-27 08:15:55 +00004213 worklist.push_back(Addr);
Nadav Rotem465834c2012-07-24 10:51:42 +00004214
Owen Anderson8ba5f392010-11-27 08:15:55 +00004215 // Use a worklist to iteratively look through PHI nodes, and ensure that
4216 // the addressing mode obtained from the non-PHI roots of the graph
4217 // are equivalent.
Craig Topperc0196b12014-04-14 00:51:57 +00004218 Value *Consensus = nullptr;
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00004219 unsigned NumUsesConsensus = 0;
Cameron Zwarich13c885d2011-03-05 08:12:26 +00004220 bool IsNumUsesConsensusValid = false;
Owen Anderson8ba5f392010-11-27 08:15:55 +00004221 SmallVector<Instruction*, 16> AddrModeInsts;
4222 ExtAddrMode AddrMode;
Jun Bum Limdee55652017-04-03 19:20:07 +00004223 TypePromotionTransaction TPT(RemovedInsts);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004224 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4225 TPT.getRestorationPoint();
Owen Anderson8ba5f392010-11-27 08:15:55 +00004226 while (!worklist.empty()) {
4227 Value *V = worklist.back();
4228 worklist.pop_back();
Nadav Rotem465834c2012-07-24 10:51:42 +00004229
Owen Anderson8ba5f392010-11-27 08:15:55 +00004230 // Break use-def graph loops.
David Blaikie70573dc2014-11-19 07:49:26 +00004231 if (!Visited.insert(V).second) {
Craig Topperc0196b12014-04-14 00:51:57 +00004232 Consensus = nullptr;
Owen Anderson8ba5f392010-11-27 08:15:55 +00004233 break;
Owen Andersondfb8c3b2010-11-19 22:15:03 +00004234 }
Nadav Rotem465834c2012-07-24 10:51:42 +00004235
Owen Anderson8ba5f392010-11-27 08:15:55 +00004236 // For a PHI node, push all of its incoming values.
4237 if (PHINode *P = dyn_cast<PHINode>(V)) {
Pete Cooper833f34d2015-05-12 20:05:31 +00004238 for (Value *IncValue : P->incoming_values())
4239 worklist.push_back(IncValue);
Owen Anderson8ba5f392010-11-27 08:15:55 +00004240 continue;
4241 }
Nadav Rotem465834c2012-07-24 10:51:42 +00004242
Philip Reamesac115ed2016-03-09 23:13:12 +00004243 // For non-PHIs, determine the addressing mode being computed. Note that
4244 // the result may differ depending on what other uses our candidate
4245 // addressing instructions might have.
Owen Anderson8ba5f392010-11-27 08:15:55 +00004246 SmallVector<Instruction*, 16> NewAddrModeInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004247 ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004248 V, AccessTy, AddrSpace, MemoryInst, NewAddrModeInsts, *TLI, *TRI,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00004249 InsertedInsts, PromotedInsts, TPT);
Cameron Zwarich13c885d2011-03-05 08:12:26 +00004250
4251 // This check is broken into two cases with very similar code to avoid using
4252 // getNumUses() as much as possible. Some values have a lot of uses, so
4253 // calling getNumUses() unconditionally caused a significant compile-time
4254 // regression.
4255 if (!Consensus) {
4256 Consensus = V;
4257 AddrMode = NewAddrMode;
4258 AddrModeInsts = NewAddrModeInsts;
4259 continue;
4260 } else if (NewAddrMode == AddrMode) {
4261 if (!IsNumUsesConsensusValid) {
4262 NumUsesConsensus = Consensus->getNumUses();
4263 IsNumUsesConsensusValid = true;
4264 }
4265
4266 // Ensure that the obtained addressing mode is equivalent to that obtained
4267 // for all other roots of the PHI traversal. Also, when choosing one
4268 // such root as representative, select the one with the most uses in order
4269 // to keep the cost modeling heuristics in AddressingModeMatcher
4270 // applicable.
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00004271 unsigned NumUses = V->getNumUses();
4272 if (NumUses > NumUsesConsensus) {
Owen Anderson8ba5f392010-11-27 08:15:55 +00004273 Consensus = V;
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00004274 NumUsesConsensus = NumUses;
Owen Anderson8ba5f392010-11-27 08:15:55 +00004275 AddrModeInsts = NewAddrModeInsts;
4276 }
4277 continue;
4278 }
Nadav Rotem465834c2012-07-24 10:51:42 +00004279
Craig Topperc0196b12014-04-14 00:51:57 +00004280 Consensus = nullptr;
Owen Anderson8ba5f392010-11-27 08:15:55 +00004281 break;
Owen Andersondfb8c3b2010-11-19 22:15:03 +00004282 }
Nadav Rotem465834c2012-07-24 10:51:42 +00004283
Owen Anderson8ba5f392010-11-27 08:15:55 +00004284 // If the addressing mode couldn't be determined, or if multiple different
4285 // ones were determined, bail out now.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004286 if (!Consensus) {
4287 TPT.rollback(LastKnownGood);
4288 return false;
4289 }
4290 TPT.commit();
Nadav Rotem465834c2012-07-24 10:51:42 +00004291
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004292 // If all the instructions matched are already in this BB, don't do anything.
Justin Lebar838c7f52016-11-21 22:49:11 +00004293 if (none_of(AddrModeInsts, [&](Value *V) {
4294 return IsNonLocalValue(V, MemoryInst->getParent());
4295 })) {
David Greene74e2d492010-01-05 01:27:11 +00004296 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004297 return false;
4298 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00004299
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004300 // Insert this computation right after this user. Since our caller is
4301 // scanning from the top of the BB to the bottom, reuse of the expr are
4302 // guaranteed to happen later.
Devang Patelc10e52a2011-09-06 18:49:53 +00004303 IRBuilder<> Builder(MemoryInst);
Eric Christopherc1ea1492008-09-24 05:32:41 +00004304
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004305 // Now that we determined the addressing expression we want to use and know
4306 // that we have to sink it into this block. Check to see if we have already
4307 // done this for some other load/store instr in this block. If so, reuse the
4308 // computation.
4309 Value *&SunkAddr = SunkAddrs[Addr];
4310 if (SunkAddr) {
David Greene74e2d492010-01-05 01:27:11 +00004311 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00004312 << *MemoryInst << "\n");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004313 if (SunkAddr->getType() != Addr->getType())
Eli Friedmanc12a5a72017-02-24 20:51:36 +00004314 SunkAddr = Builder.CreatePointerCast(SunkAddr, Addr->getType());
Eric Christopherfccff372015-01-27 01:01:38 +00004315 } else if (AddrSinkUsingGEPs ||
4316 (!AddrSinkUsingGEPs.getNumOccurrences() && TM &&
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004317 SubtargetInfo->useAA())) {
Hal Finkelc3998302014-04-12 00:59:48 +00004318 // By default, we use the GEP-based method when AA is used later. This
4319 // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities.
4320 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00004321 << *MemoryInst << "\n");
Mehdi Amini4fe37982015-07-07 18:45:17 +00004322 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
Craig Topperc0196b12014-04-14 00:51:57 +00004323 Value *ResultPtr = nullptr, *ResultIndex = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00004324
4325 // First, find the pointer.
4326 if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) {
4327 ResultPtr = AddrMode.BaseReg;
Craig Topperc0196b12014-04-14 00:51:57 +00004328 AddrMode.BaseReg = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00004329 }
4330
4331 if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) {
4332 // We can't add more than one pointer together, nor can we scale a
4333 // pointer (both of which seem meaningless).
4334 if (ResultPtr || AddrMode.Scale != 1)
4335 return false;
4336
4337 ResultPtr = AddrMode.ScaledReg;
4338 AddrMode.Scale = 0;
4339 }
4340
4341 if (AddrMode.BaseGV) {
4342 if (ResultPtr)
4343 return false;
4344
4345 ResultPtr = AddrMode.BaseGV;
4346 }
4347
4348 // If the real base value actually came from an inttoptr, then the matcher
4349 // will look through it and provide only the integer value. In that case,
4350 // use it here.
4351 if (!ResultPtr && AddrMode.BaseReg) {
4352 ResultPtr =
4353 Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(), "sunkaddr");
Craig Topperc0196b12014-04-14 00:51:57 +00004354 AddrMode.BaseReg = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00004355 } else if (!ResultPtr && AddrMode.Scale == 1) {
4356 ResultPtr =
4357 Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(), "sunkaddr");
4358 AddrMode.Scale = 0;
4359 }
4360
4361 if (!ResultPtr &&
4362 !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) {
4363 SunkAddr = Constant::getNullValue(Addr->getType());
4364 } else if (!ResultPtr) {
4365 return false;
4366 } else {
4367 Type *I8PtrTy =
David Blaikie3909da72015-03-30 20:42:56 +00004368 Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace());
4369 Type *I8Ty = Builder.getInt8Ty();
Hal Finkelc3998302014-04-12 00:59:48 +00004370
4371 // Start with the base register. Do this first so that subsequent address
4372 // matching finds it last, which will prevent it from trying to match it
4373 // as the scaled value in case it happens to be a mul. That would be
4374 // problematic if we've sunk a different mul for the scale, because then
4375 // we'd end up sinking both muls.
4376 if (AddrMode.BaseReg) {
4377 Value *V = AddrMode.BaseReg;
4378 if (V->getType() != IntPtrTy)
4379 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
4380
4381 ResultIndex = V;
4382 }
4383
4384 // Add the scale value.
4385 if (AddrMode.Scale) {
4386 Value *V = AddrMode.ScaledReg;
4387 if (V->getType() == IntPtrTy) {
4388 // done.
4389 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
4390 cast<IntegerType>(V->getType())->getBitWidth()) {
4391 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
4392 } else {
4393 // It is only safe to sign extend the BaseReg if we know that the math
4394 // required to create it did not overflow before we extend it. Since
4395 // the original IR value was tossed in favor of a constant back when
4396 // the AddrMode was created we need to bail out gracefully if widths
4397 // do not match instead of extending it.
4398 Instruction *I = dyn_cast_or_null<Instruction>(ResultIndex);
4399 if (I && (ResultIndex != AddrMode.BaseReg))
4400 I->eraseFromParent();
4401 return false;
4402 }
4403
4404 if (AddrMode.Scale != 1)
4405 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
4406 "sunkaddr");
4407 if (ResultIndex)
4408 ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr");
4409 else
4410 ResultIndex = V;
4411 }
4412
4413 // Add in the Base Offset if present.
4414 if (AddrMode.BaseOffs) {
4415 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
4416 if (ResultIndex) {
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00004417 // We need to add this separately from the scale above to help with
4418 // SDAG consecutive load/store merging.
Hal Finkelc3998302014-04-12 00:59:48 +00004419 if (ResultPtr->getType() != I8PtrTy)
Eli Friedmanc12a5a72017-02-24 20:51:36 +00004420 ResultPtr = Builder.CreatePointerCast(ResultPtr, I8PtrTy);
David Blaikie3909da72015-03-30 20:42:56 +00004421 ResultPtr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
Hal Finkelc3998302014-04-12 00:59:48 +00004422 }
4423
4424 ResultIndex = V;
4425 }
4426
4427 if (!ResultIndex) {
4428 SunkAddr = ResultPtr;
4429 } else {
4430 if (ResultPtr->getType() != I8PtrTy)
Eli Friedmanc12a5a72017-02-24 20:51:36 +00004431 ResultPtr = Builder.CreatePointerCast(ResultPtr, I8PtrTy);
David Blaikie3909da72015-03-30 20:42:56 +00004432 SunkAddr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
Hal Finkelc3998302014-04-12 00:59:48 +00004433 }
4434
4435 if (SunkAddr->getType() != Addr->getType())
Eli Friedmanc12a5a72017-02-24 20:51:36 +00004436 SunkAddr = Builder.CreatePointerCast(SunkAddr, Addr->getType());
Hal Finkelc3998302014-04-12 00:59:48 +00004437 }
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004438 } else {
David Greene74e2d492010-01-05 01:27:11 +00004439 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00004440 << *MemoryInst << "\n");
Mehdi Amini4fe37982015-07-07 18:45:17 +00004441 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
Craig Topperc0196b12014-04-14 00:51:57 +00004442 Value *Result = nullptr;
Dan Gohmanca194452010-01-19 22:45:06 +00004443
4444 // Start with the base register. Do this first so that subsequent address
4445 // matching finds it last, which will prevent it from trying to match it
4446 // as the scaled value in case it happens to be a mul. That would be
4447 // problematic if we've sunk a different mul for the scale, because then
4448 // we'd end up sinking both muls.
4449 if (AddrMode.BaseReg) {
4450 Value *V = AddrMode.BaseReg;
Duncan Sands19d0b472010-02-16 11:11:14 +00004451 if (V->getType()->isPointerTy())
Devang Patelc10e52a2011-09-06 18:49:53 +00004452 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00004453 if (V->getType() != IntPtrTy)
Devang Patelc10e52a2011-09-06 18:49:53 +00004454 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00004455 Result = V;
4456 }
4457
4458 // Add the scale value.
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004459 if (AddrMode.Scale) {
4460 Value *V = AddrMode.ScaledReg;
4461 if (V->getType() == IntPtrTy) {
4462 // done.
Duncan Sands19d0b472010-02-16 11:11:14 +00004463 } else if (V->getType()->isPointerTy()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00004464 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004465 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
4466 cast<IntegerType>(V->getType())->getBitWidth()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00004467 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004468 } else {
Jim Grosbached2cd392014-03-26 17:27:01 +00004469 // It is only safe to sign extend the BaseReg if we know that the math
4470 // required to create it did not overflow before we extend it. Since
4471 // the original IR value was tossed in favor of a constant back when
4472 // the AddrMode was created we need to bail out gracefully if widths
4473 // do not match instead of extending it.
Joey Gouly12a8bf02014-05-13 15:42:45 +00004474 Instruction *I = dyn_cast_or_null<Instruction>(Result);
Jim Grosbach83b44e12014-04-10 00:27:45 +00004475 if (I && (Result != AddrMode.BaseReg))
4476 I->eraseFromParent();
Jim Grosbached2cd392014-03-26 17:27:01 +00004477 return false;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004478 }
4479 if (AddrMode.Scale != 1)
Devang Patelc10e52a2011-09-06 18:49:53 +00004480 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
4481 "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004482 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00004483 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004484 else
4485 Result = V;
4486 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00004487
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004488 // Add in the BaseGV if present.
4489 if (AddrMode.BaseGV) {
Devang Patelc10e52a2011-09-06 18:49:53 +00004490 Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004491 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00004492 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004493 else
4494 Result = V;
4495 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00004496
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004497 // Add in the Base Offset if present.
4498 if (AddrMode.BaseOffs) {
Owen Andersonedb4a702009-07-24 23:12:02 +00004499 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004500 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00004501 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004502 else
4503 Result = V;
4504 }
4505
Craig Topperc0196b12014-04-14 00:51:57 +00004506 if (!Result)
Owen Anderson5a1acd92009-07-31 20:28:14 +00004507 SunkAddr = Constant::getNullValue(Addr->getType());
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004508 else
Devang Patelc10e52a2011-09-06 18:49:53 +00004509 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004510 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00004511
Owen Andersondfb8c3b2010-11-19 22:15:03 +00004512 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
Eric Christopherc1ea1492008-09-24 05:32:41 +00004513
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004514 // If we have no uses, recursively delete the value and all dead instructions
4515 // using it.
Owen Andersondfb8c3b2010-11-19 22:15:03 +00004516 if (Repl->use_empty()) {
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004517 // This can cause recursive deletion, which can invalidate our iterator.
Sanjoy Dase6bca0e2017-05-01 17:07:49 +00004518 // Use a WeakTrackingVH to hold onto it in case this happens.
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00004519 Value *CurValue = &*CurInstIterator;
Sanjoy Dase6bca0e2017-05-01 17:07:49 +00004520 WeakTrackingVH IterHandle(CurValue);
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004521 BasicBlock *BB = CurInstIterator->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +00004522
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00004523 RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004524
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00004525 if (IterHandle != CurValue) {
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004526 // If the iterator instruction was recursively deleted, start over at the
4527 // start of the block.
4528 CurInstIterator = BB->begin();
4529 SunkAddrs.clear();
Nadav Rotem465834c2012-07-24 10:51:42 +00004530 }
Dale Johannesenb67a6e662010-03-31 20:37:15 +00004531 }
Cameron Zwarichced753f2011-01-05 17:27:27 +00004532 ++NumMemoryInsts;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004533 return true;
4534}
4535
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004536/// If there are any memory operands, use OptimizeMemoryInst to sink their
4537/// address computing into the block when possible / profitable.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004538bool CodeGenPrepare::optimizeInlineAsmInst(CallInst *CS) {
Evan Cheng1da25002008-02-26 02:42:37 +00004539 bool MadeChange = false;
Evan Cheng1da25002008-02-26 02:42:37 +00004540
Eric Christopher11e4df72015-02-26 22:38:43 +00004541 const TargetRegisterInfo *TRI =
Sanjay Patel4137d512017-06-07 14:29:52 +00004542 TM->getSubtargetImpl(*CS->getFunction())->getRegisterInfo();
Mehdi Amini8ac7a9d2015-07-07 19:07:19 +00004543 TargetLowering::AsmOperandInfoVector TargetConstraints =
4544 TLI->ParseConstraints(*DL, TRI, CS);
Dale Johannesenf95f59a2010-09-16 18:30:55 +00004545 unsigned ArgNo = 0;
John Thompson1094c802010-09-13 18:15:37 +00004546 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
4547 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Nadav Rotem465834c2012-07-24 10:51:42 +00004548
Evan Cheng1da25002008-02-26 02:42:37 +00004549 // Compute the constraint code and ConstraintType to use.
Dale Johannesence97d552010-06-25 21:55:36 +00004550 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Evan Cheng1da25002008-02-26 02:42:37 +00004551
Eli Friedman666bbe32008-02-26 18:37:49 +00004552 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
4553 OpInfo.isIndirect) {
Chris Lattner7a277142011-01-15 07:14:54 +00004554 Value *OpVal = CS->getArgOperand(ArgNo++);
Sanjay Patelfc580a62015-09-21 23:03:16 +00004555 MadeChange |= optimizeMemoryInst(CS, OpVal, OpVal->getType(), ~0u);
Dale Johannesenf95f59a2010-09-16 18:30:55 +00004556 } else if (OpInfo.Type == InlineAsm::isInput)
4557 ArgNo++;
Evan Cheng1da25002008-02-26 02:42:37 +00004558 }
4559
4560 return MadeChange;
4561}
4562
Jun Bum Lim42301012017-03-17 19:05:21 +00004563/// \brief Check if all the uses of \p Val are equivalent (or free) zero or
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004564/// sign extensions.
Jun Bum Lim42301012017-03-17 19:05:21 +00004565static bool hasSameExtUse(Value *Val, const TargetLowering &TLI) {
4566 assert(!Val->use_empty() && "Input must have at least one use");
4567 const Instruction *FirstUser = cast<Instruction>(*Val->user_begin());
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004568 bool IsSExt = isa<SExtInst>(FirstUser);
4569 Type *ExtTy = FirstUser->getType();
Jun Bum Lim42301012017-03-17 19:05:21 +00004570 for (const User *U : Val->users()) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004571 const Instruction *UI = cast<Instruction>(U);
4572 if ((IsSExt && !isa<SExtInst>(UI)) || (!IsSExt && !isa<ZExtInst>(UI)))
4573 return false;
4574 Type *CurTy = UI->getType();
4575 // Same input and output types: Same instruction after CSE.
4576 if (CurTy == ExtTy)
4577 continue;
4578
4579 // If IsSExt is true, we are in this situation:
Jun Bum Lim42301012017-03-17 19:05:21 +00004580 // a = Val
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004581 // b = sext ty1 a to ty2
4582 // c = sext ty1 a to ty3
4583 // Assuming ty2 is shorter than ty3, this could be turned into:
Jun Bum Lim42301012017-03-17 19:05:21 +00004584 // a = Val
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004585 // b = sext ty1 a to ty2
4586 // c = sext ty2 b to ty3
4587 // However, the last sext is not free.
4588 if (IsSExt)
4589 return false;
4590
4591 // This is a ZExt, maybe this is free to extend from one type to another.
4592 // In that case, we would not account for a different use.
4593 Type *NarrowTy;
4594 Type *LargeTy;
4595 if (ExtTy->getScalarType()->getIntegerBitWidth() >
4596 CurTy->getScalarType()->getIntegerBitWidth()) {
4597 NarrowTy = CurTy;
4598 LargeTy = ExtTy;
4599 } else {
4600 NarrowTy = ExtTy;
4601 LargeTy = CurTy;
4602 }
4603
4604 if (!TLI.isZExtFree(NarrowTy, LargeTy))
4605 return false;
4606 }
4607 // All uses are the same or can be derived from one another for free.
4608 return true;
4609}
4610
Jun Bum Lim42301012017-03-17 19:05:21 +00004611/// \brief Try to speculatively promote extensions in \p Exts and continue
4612/// promoting through newly promoted operands recursively as far as doing so is
4613/// profitable. Save extensions profitably moved up, in \p ProfitablyMovedExts.
4614/// When some promotion happened, \p TPT contains the proper state to revert
4615/// them.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004616///
Jun Bum Lim42301012017-03-17 19:05:21 +00004617/// \return true if some promotion happened, false otherwise.
Jun Bum Lim42301012017-03-17 19:05:21 +00004618bool CodeGenPrepare::tryToPromoteExts(
4619 TypePromotionTransaction &TPT, const SmallVectorImpl<Instruction *> &Exts,
4620 SmallVectorImpl<Instruction *> &ProfitablyMovedExts,
4621 unsigned CreatedInstsCost) {
4622 bool Promoted = false;
4623
4624 // Iterate over all the extensions to try to promote them.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004625 for (auto I : Exts) {
Jun Bum Lim42301012017-03-17 19:05:21 +00004626 // Early check if we directly have ext(load).
4627 if (isa<LoadInst>(I->getOperand(0))) {
4628 ProfitablyMovedExts.push_back(I);
4629 continue;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004630 }
Jun Bum Lim42301012017-03-17 19:05:21 +00004631
4632 // Check whether or not we want to do any promotion. The reason we have
4633 // this check inside the for loop is to catch the case where an extension
4634 // is directly fed by a load because in such case the extension can be moved
4635 // up without any promotion on its operands.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004636 if (!TLI || !TLI->enableExtLdPromotion() || DisableExtLdPromotion)
Jun Bum Lim42301012017-03-17 19:05:21 +00004637 return false;
4638
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004639 // Get the action to perform the promotion.
Jun Bum Lim42301012017-03-17 19:05:21 +00004640 TypePromotionHelper::Action TPH =
4641 TypePromotionHelper::getAction(I, InsertedInsts, *TLI, PromotedInsts);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004642 // Check if we can promote.
Jun Bum Lim42301012017-03-17 19:05:21 +00004643 if (!TPH) {
4644 // Save the current extension as we cannot move up through its operand.
4645 ProfitablyMovedExts.push_back(I);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004646 continue;
Jun Bum Lim42301012017-03-17 19:05:21 +00004647 }
4648
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004649 // Save the current state.
4650 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4651 TPT.getRestorationPoint();
4652 SmallVector<Instruction *, 4> NewExts;
Quentin Colombet1b274f92015-03-10 21:48:15 +00004653 unsigned NewCreatedInstsCost = 0;
4654 unsigned ExtCost = !TLI->isExtFree(I);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004655 // Promote.
Quentin Colombet1b274f92015-03-10 21:48:15 +00004656 Value *PromotedVal = TPH(I, TPT, PromotedInsts, NewCreatedInstsCost,
4657 &NewExts, nullptr, *TLI);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004658 assert(PromotedVal &&
4659 "TypePromotionHelper should have filtered out those cases");
4660
4661 // We would be able to merge only one extension in a load.
4662 // Therefore, if we have more than 1 new extension we heuristically
4663 // cut this search path, because it means we degrade the code quality.
4664 // With exactly 2, the transformation is neutral, because we will merge
4665 // one extension but leave one. However, we optimistically keep going,
4666 // because the new extension may be removed too.
Quentin Colombet1b274f92015-03-10 21:48:15 +00004667 long long TotalCreatedInstsCost = CreatedInstsCost + NewCreatedInstsCost;
Jun Bum Limb99a06b2017-01-27 17:16:37 +00004668 // FIXME: It would be possible to propagate a negative value instead of
Jun Bum Lim42301012017-03-17 19:05:21 +00004669 // conservatively ceiling it to 0.
Jun Bum Limb99a06b2017-01-27 17:16:37 +00004670 TotalCreatedInstsCost =
4671 std::max((long long)0, (TotalCreatedInstsCost - ExtCost));
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004672 if (!StressExtLdPromotion &&
Quentin Colombet1b274f92015-03-10 21:48:15 +00004673 (TotalCreatedInstsCost > 1 ||
Mehdi Amini44ede332015-07-09 02:09:04 +00004674 !isPromotedInstructionLegal(*TLI, *DL, PromotedVal))) {
Jun Bum Lim42301012017-03-17 19:05:21 +00004675 // This promotion is not profitable, rollback to the previous state, and
4676 // save the current extension in ProfitablyMovedExts as the latest
4677 // speculative promotion turned out to be unprofitable.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004678 TPT.rollback(LastKnownGood);
Jun Bum Lim42301012017-03-17 19:05:21 +00004679 ProfitablyMovedExts.push_back(I);
4680 continue;
4681 }
4682 // Continue promoting NewExts as far as doing so is profitable.
4683 SmallVector<Instruction *, 2> NewlyMovedExts;
4684 (void)tryToPromoteExts(TPT, NewExts, NewlyMovedExts, TotalCreatedInstsCost);
4685 bool NewPromoted = false;
4686 for (auto ExtInst : NewlyMovedExts) {
4687 Instruction *MovedExt = cast<Instruction>(ExtInst);
4688 Value *ExtOperand = MovedExt->getOperand(0);
4689 // If we have reached to a load, we need this extra profitability check
4690 // as it could potentially be merged into an ext(load).
4691 if (isa<LoadInst>(ExtOperand) &&
4692 !(StressExtLdPromotion || NewCreatedInstsCost <= ExtCost ||
4693 (ExtOperand->hasOneUse() || hasSameExtUse(ExtOperand, *TLI))))
4694 continue;
4695
4696 ProfitablyMovedExts.push_back(MovedExt);
4697 NewPromoted = true;
4698 }
4699
4700 // If none of speculative promotions for NewExts is profitable, rollback
4701 // and save the current extension (I) as the last profitable extension.
4702 if (!NewPromoted) {
4703 TPT.rollback(LastKnownGood);
4704 ProfitablyMovedExts.push_back(I);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004705 continue;
4706 }
4707 // The promotion is profitable.
Jun Bum Lim42301012017-03-17 19:05:21 +00004708 Promoted = true;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004709 }
Jun Bum Lim42301012017-03-17 19:05:21 +00004710 return Promoted;
4711}
4712
Jun Bum Limdee55652017-04-03 19:20:07 +00004713/// Merging redundant sexts when one is dominating the other.
4714bool CodeGenPrepare::mergeSExts(Function &F) {
4715 DominatorTree DT(F);
4716 bool Changed = false;
4717 for (auto &Entry : ValToSExtendedUses) {
4718 SExts &Insts = Entry.second;
4719 SExts CurPts;
4720 for (Instruction *Inst : Insts) {
4721 if (RemovedInsts.count(Inst) || !isa<SExtInst>(Inst) ||
4722 Inst->getOperand(0) != Entry.first)
4723 continue;
4724 bool inserted = false;
4725 for (auto &Pt : CurPts) {
4726 if (DT.dominates(Inst, Pt)) {
4727 Pt->replaceAllUsesWith(Inst);
4728 RemovedInsts.insert(Pt);
4729 Pt->removeFromParent();
4730 Pt = Inst;
4731 inserted = true;
4732 Changed = true;
4733 break;
4734 }
4735 if (!DT.dominates(Pt, Inst))
4736 // Give up if we need to merge in a common dominator as the
4737 // expermients show it is not profitable.
4738 continue;
4739 Inst->replaceAllUsesWith(Pt);
4740 RemovedInsts.insert(Inst);
4741 Inst->removeFromParent();
4742 inserted = true;
4743 Changed = true;
4744 break;
4745 }
4746 if (!inserted)
4747 CurPts.push_back(Inst);
4748 }
4749 }
4750 return Changed;
4751}
4752
Jun Bum Lim42301012017-03-17 19:05:21 +00004753/// Return true, if an ext(load) can be formed from an extension in
4754/// \p MovedExts.
4755bool CodeGenPrepare::canFormExtLd(
4756 const SmallVectorImpl<Instruction *> &MovedExts, LoadInst *&LI,
4757 Instruction *&Inst, bool HasPromoted) {
4758 for (auto *MovedExtInst : MovedExts) {
4759 if (isa<LoadInst>(MovedExtInst->getOperand(0))) {
4760 LI = cast<LoadInst>(MovedExtInst->getOperand(0));
4761 Inst = MovedExtInst;
4762 break;
4763 }
4764 }
4765 if (!LI)
4766 return false;
4767
4768 // If they're already in the same block, there's nothing to do.
4769 // Make the cheap checks first if we did not promote.
4770 // If we promoted, we need to check if it is indeed profitable.
4771 if (!HasPromoted && LI->getParent() == Inst->getParent())
4772 return false;
4773
4774 EVT VT = TLI->getValueType(*DL, Inst->getType());
4775 EVT LoadVT = TLI->getValueType(*DL, LI->getType());
4776
4777 // If the load has other users and the truncate is not free, this probably
4778 // isn't worthwhile.
4779 if (!LI->hasOneUse() && (TLI->isTypeLegal(LoadVT) || !TLI->isTypeLegal(VT)) &&
4780 !TLI->isTruncateFree(Inst->getType(), LI->getType()))
4781 return false;
4782
4783 // Check whether the target supports casts folded into loads.
4784 unsigned LType;
4785 if (isa<ZExtInst>(Inst))
4786 LType = ISD::ZEXTLOAD;
4787 else {
4788 assert(isa<SExtInst>(Inst) && "Unexpected ext type!");
4789 LType = ISD::SEXTLOAD;
4790 }
4791
4792 return TLI->isLoadExtLegal(LType, VT, LoadVT);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004793}
4794
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004795/// Move a zext or sext fed by a load into the same basic block as the load,
4796/// unless conditions are unfavorable. This allows SelectionDAG to fold the
4797/// extend into the load.
Dan Gohman99429a02009-10-16 20:59:35 +00004798///
Jun Bum Limdee55652017-04-03 19:20:07 +00004799/// E.g.,
4800/// \code
4801/// %ld = load i32* %addr
4802/// %add = add nuw i32 %ld, 4
4803/// %zext = zext i32 %add to i64
4804// \endcode
4805/// =>
4806/// \code
4807/// %ld = load i32* %addr
4808/// %zext = zext i32 %ld to i64
4809/// %add = add nuw i64 %zext, 4
4810/// \encode
4811/// Note that the promotion in %add to i64 is done in tryToPromoteExts(), which
4812/// allow us to match zext(load i32*) to i64.
4813///
4814/// Also, try to promote the computations used to obtain a sign extended
4815/// value used into memory accesses.
4816/// E.g.,
4817/// \code
4818/// a = add nsw i32 b, 3
4819/// d = sext i32 a to i64
4820/// e = getelementptr ..., i64 d
4821/// \endcode
4822/// =>
4823/// \code
4824/// f = sext i32 b to i64
4825/// a = add nsw i64 f, 3
4826/// e = getelementptr ..., i64 a
4827/// \endcode
4828///
4829/// \p Inst[in/out] the extension may be modified during the process if some
4830/// promotions apply.
4831bool CodeGenPrepare::optimizeExt(Instruction *&Inst) {
4832 // ExtLoad formation and address type promotion infrastructure requires TLI to
4833 // be effective.
Chandler Carruth0f139b42016-11-04 06:54:00 +00004834 if (!TLI)
4835 return false;
4836
Jun Bum Limdee55652017-04-03 19:20:07 +00004837 bool AllowPromotionWithoutCommonHeader = false;
4838 /// See if it is an interesting sext operations for the address type
4839 /// promotion before trying to promote it, e.g., the ones with the right
4840 /// type and used in memory accesses.
4841 bool ATPConsiderable = TTI->shouldConsiderAddressTypePromotion(
4842 *Inst, AllowPromotionWithoutCommonHeader);
4843 TypePromotionTransaction TPT(RemovedInsts);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004844 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
Jun Bum Lim42301012017-03-17 19:05:21 +00004845 TPT.getRestorationPoint();
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004846 SmallVector<Instruction *, 1> Exts;
Jun Bum Limdee55652017-04-03 19:20:07 +00004847 SmallVector<Instruction *, 2> SpeculativelyMovedExts;
4848 Exts.push_back(Inst);
Jun Bum Lim42301012017-03-17 19:05:21 +00004849
Jun Bum Limdee55652017-04-03 19:20:07 +00004850 bool HasPromoted = tryToPromoteExts(TPT, Exts, SpeculativelyMovedExts);
Jun Bum Lim42301012017-03-17 19:05:21 +00004851
Dan Gohman99429a02009-10-16 20:59:35 +00004852 // Look for a load being extended.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004853 LoadInst *LI = nullptr;
Jun Bum Limdee55652017-04-03 19:20:07 +00004854 Instruction *ExtFedByLoad;
4855
4856 // Try to promote a chain of computation if it allows to form an extended
4857 // load.
4858 if (canFormExtLd(SpeculativelyMovedExts, LI, ExtFedByLoad, HasPromoted)) {
4859 assert(LI && ExtFedByLoad && "Expect a valid load and extension");
4860 TPT.commit();
4861 // Move the extend into the same block as the load
4862 ExtFedByLoad->removeFromParent();
4863 ExtFedByLoad->insertAfter(LI);
4864 // CGP does not check if the zext would be speculatively executed when moved
4865 // to the same basic block as the load. Preserving its original location
4866 // would pessimize the debugging experience, as well as negatively impact
4867 // the quality of sample pgo. We don't want to use "line 0" as that has a
4868 // size cost in the line-table section and logically the zext can be seen as
4869 // part of the load. Therefore we conservatively reuse the same debug
4870 // location for the load and the zext.
4871 ExtFedByLoad->setDebugLoc(LI->getDebugLoc());
4872 ++NumExtsMoved;
4873 Inst = ExtFedByLoad;
4874 return true;
4875 }
4876
4877 // Continue promoting SExts if known as considerable depending on targets.
4878 if (ATPConsiderable &&
4879 performAddressTypePromotion(Inst, AllowPromotionWithoutCommonHeader,
4880 HasPromoted, TPT, SpeculativelyMovedExts))
4881 return true;
4882
4883 TPT.rollback(LastKnownGood);
4884 return false;
4885}
4886
4887// Perform address type promotion if doing so is profitable.
4888// If AllowPromotionWithoutCommonHeader == false, we should find other sext
4889// instructions that sign extended the same initial value. However, if
4890// AllowPromotionWithoutCommonHeader == true, we expect promoting the
4891// extension is just profitable.
4892bool CodeGenPrepare::performAddressTypePromotion(
4893 Instruction *&Inst, bool AllowPromotionWithoutCommonHeader,
4894 bool HasPromoted, TypePromotionTransaction &TPT,
4895 SmallVectorImpl<Instruction *> &SpeculativelyMovedExts) {
4896 bool Promoted = false;
4897 SmallPtrSet<Instruction *, 1> UnhandledExts;
4898 bool AllSeenFirst = true;
4899 for (auto I : SpeculativelyMovedExts) {
4900 Value *HeadOfChain = I->getOperand(0);
4901 DenseMap<Value *, Instruction *>::iterator AlreadySeen =
4902 SeenChainsForSExt.find(HeadOfChain);
4903 // If there is an unhandled SExt which has the same header, try to promote
4904 // it as well.
4905 if (AlreadySeen != SeenChainsForSExt.end()) {
4906 if (AlreadySeen->second != nullptr)
4907 UnhandledExts.insert(AlreadySeen->second);
4908 AllSeenFirst = false;
4909 }
4910 }
4911
4912 if (!AllSeenFirst || (AllowPromotionWithoutCommonHeader &&
4913 SpeculativelyMovedExts.size() == 1)) {
4914 TPT.commit();
4915 if (HasPromoted)
4916 Promoted = true;
4917 for (auto I : SpeculativelyMovedExts) {
4918 Value *HeadOfChain = I->getOperand(0);
4919 SeenChainsForSExt[HeadOfChain] = nullptr;
4920 ValToSExtendedUses[HeadOfChain].push_back(I);
4921 }
4922 // Update Inst as promotion happen.
4923 Inst = SpeculativelyMovedExts.pop_back_val();
4924 } else {
4925 // This is the first chain visited from the header, keep the current chain
4926 // as unhandled. Defer to promote this until we encounter another SExt
4927 // chain derived from the same header.
4928 for (auto I : SpeculativelyMovedExts) {
4929 Value *HeadOfChain = I->getOperand(0);
4930 SeenChainsForSExt[HeadOfChain] = Inst;
4931 }
Dan Gohman99429a02009-10-16 20:59:35 +00004932 return false;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004933 }
Dan Gohman99429a02009-10-16 20:59:35 +00004934
Jun Bum Limdee55652017-04-03 19:20:07 +00004935 if (!AllSeenFirst && !UnhandledExts.empty())
4936 for (auto VisitedSExt : UnhandledExts) {
4937 if (RemovedInsts.count(VisitedSExt))
4938 continue;
4939 TypePromotionTransaction TPT(RemovedInsts);
4940 SmallVector<Instruction *, 1> Exts;
4941 SmallVector<Instruction *, 2> Chains;
4942 Exts.push_back(VisitedSExt);
4943 bool HasPromoted = tryToPromoteExts(TPT, Exts, Chains);
4944 TPT.commit();
4945 if (HasPromoted)
4946 Promoted = true;
4947 for (auto I : Chains) {
4948 Value *HeadOfChain = I->getOperand(0);
4949 // Mark this as handled.
4950 SeenChainsForSExt[HeadOfChain] = nullptr;
4951 ValToSExtendedUses[HeadOfChain].push_back(I);
4952 }
4953 }
4954 return Promoted;
Dan Gohman99429a02009-10-16 20:59:35 +00004955}
4956
Sanjay Patelfc580a62015-09-21 23:03:16 +00004957bool CodeGenPrepare::optimizeExtUses(Instruction *I) {
Evan Chengd3d80172007-12-05 23:58:20 +00004958 BasicBlock *DefBB = I->getParent();
4959
Bob Wilsonff714f92010-09-21 21:44:14 +00004960 // If the result of a {s|z}ext and its source are both live out, rewrite all
Evan Chengd3d80172007-12-05 23:58:20 +00004961 // other uses of the source with result of extension.
4962 Value *Src = I->getOperand(0);
4963 if (Src->hasOneUse())
4964 return false;
4965
Evan Cheng2011df42007-12-13 07:50:36 +00004966 // Only do this xform if truncating is free.
Gabor Greifaa261722008-02-26 19:13:21 +00004967 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
Evan Cheng37c36ed2007-12-13 03:32:53 +00004968 return false;
4969
Evan Cheng7bc89422007-12-12 00:51:06 +00004970 // Only safe to perform the optimization if the source is also defined in
Evan Cheng63d33cf2007-12-12 02:53:41 +00004971 // this block.
4972 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
Evan Cheng7bc89422007-12-12 00:51:06 +00004973 return false;
4974
Evan Chengd3d80172007-12-05 23:58:20 +00004975 bool DefIsLiveOut = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00004976 for (User *U : I->users()) {
4977 Instruction *UI = cast<Instruction>(U);
Evan Chengd3d80172007-12-05 23:58:20 +00004978
4979 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004980 BasicBlock *UserBB = UI->getParent();
Evan Chengd3d80172007-12-05 23:58:20 +00004981 if (UserBB == DefBB) continue;
4982 DefIsLiveOut = true;
4983 break;
4984 }
4985 if (!DefIsLiveOut)
4986 return false;
4987
Jim Grosbach0f38c1e2013-04-15 17:40:48 +00004988 // Make sure none of the uses are PHI nodes.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004989 for (User *U : Src->users()) {
4990 Instruction *UI = cast<Instruction>(U);
4991 BasicBlock *UserBB = UI->getParent();
Evan Cheng37c36ed2007-12-13 03:32:53 +00004992 if (UserBB == DefBB) continue;
4993 // Be conservative. We don't want this xform to end up introducing
4994 // reloads just before load / store instructions.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004995 if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI))
Evan Cheng63d33cf2007-12-12 02:53:41 +00004996 return false;
4997 }
4998
Evan Chengd3d80172007-12-05 23:58:20 +00004999 // InsertedTruncs - Only insert one trunc in each block once.
5000 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
5001
5002 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00005003 for (Use &U : Src->uses()) {
5004 Instruction *User = cast<Instruction>(U.getUser());
Evan Chengd3d80172007-12-05 23:58:20 +00005005
5006 // Figure out which BB this ext is used in.
5007 BasicBlock *UserBB = User->getParent();
5008 if (UserBB == DefBB) continue;
5009
5010 // Both src and def are live in this block. Rewrite the use.
5011 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
5012
5013 if (!InsertedTrunc) {
Bill Wendling8ddfc092011-08-16 20:45:24 +00005014 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00005015 assert(InsertPt != UserBB->end());
5016 InsertedTrunc = new TruncInst(I, Src->getType(), "", &*InsertPt);
Ahmed Bougachaf3299142015-06-17 20:44:32 +00005017 InsertedInsts.insert(InsertedTrunc);
Evan Chengd3d80172007-12-05 23:58:20 +00005018 }
5019
5020 // Replace a use of the {s|z}ext source with a use of the result.
Chandler Carruthcdf47882014-03-09 03:16:01 +00005021 U = InsertedTrunc;
Cameron Zwarichced753f2011-01-05 17:27:27 +00005022 ++NumExtUses;
Evan Chengd3d80172007-12-05 23:58:20 +00005023 MadeChange = true;
5024 }
5025
5026 return MadeChange;
5027}
5028
Geoff Berry5256fca2015-11-20 22:34:39 +00005029// Find loads whose uses only use some of the loaded value's bits. Add an "and"
5030// just after the load if the target can fold this into one extload instruction,
5031// with the hope of eliminating some of the other later "and" instructions using
5032// the loaded value. "and"s that are made trivially redundant by the insertion
5033// of the new "and" are removed by this function, while others (e.g. those whose
5034// path from the load goes through a phi) are left for isel to potentially
5035// remove.
5036//
5037// For example:
5038//
5039// b0:
5040// x = load i32
5041// ...
5042// b1:
5043// y = and x, 0xff
5044// z = use y
5045//
5046// becomes:
5047//
5048// b0:
5049// x = load i32
5050// x' = and x, 0xff
5051// ...
5052// b1:
5053// z = use x'
5054//
5055// whereas:
5056//
5057// b0:
5058// x1 = load i32
5059// ...
5060// b1:
5061// x2 = load i32
5062// ...
5063// b2:
5064// x = phi x1, x2
5065// y = and x, 0xff
5066//
5067// becomes (after a call to optimizeLoadExt for each load):
5068//
5069// b0:
5070// x1 = load i32
5071// x1' = and x1, 0xff
5072// ...
5073// b1:
5074// x2 = load i32
5075// x2' = and x2, 0xff
5076// ...
5077// b2:
5078// x = phi x1', x2'
5079// y = and x, 0xff
5080//
5081
5082bool CodeGenPrepare::optimizeLoadExt(LoadInst *Load) {
5083
5084 if (!Load->isSimple() ||
5085 !(Load->getType()->isIntegerTy() || Load->getType()->isPointerTy()))
5086 return false;
5087
Geoff Berry5d534b62017-02-21 18:53:14 +00005088 // Skip loads we've already transformed.
5089 if (Load->hasOneUse() &&
5090 InsertedInsts.count(cast<Instruction>(*Load->user_begin())))
5091 return false;
Geoff Berry5256fca2015-11-20 22:34:39 +00005092
5093 // Look at all uses of Load, looking through phis, to determine how many bits
5094 // of the loaded value are needed.
5095 SmallVector<Instruction *, 8> WorkList;
5096 SmallPtrSet<Instruction *, 16> Visited;
5097 SmallVector<Instruction *, 8> AndsToMaybeRemove;
5098 for (auto *U : Load->users())
5099 WorkList.push_back(cast<Instruction>(U));
5100
5101 EVT LoadResultVT = TLI->getValueType(*DL, Load->getType());
5102 unsigned BitWidth = LoadResultVT.getSizeInBits();
5103 APInt DemandBits(BitWidth, 0);
5104 APInt WidestAndBits(BitWidth, 0);
5105
5106 while (!WorkList.empty()) {
5107 Instruction *I = WorkList.back();
5108 WorkList.pop_back();
5109
5110 // Break use-def graph loops.
5111 if (!Visited.insert(I).second)
5112 continue;
5113
5114 // For a PHI node, push all of its users.
5115 if (auto *Phi = dyn_cast<PHINode>(I)) {
5116 for (auto *U : Phi->users())
5117 WorkList.push_back(cast<Instruction>(U));
5118 continue;
5119 }
5120
5121 switch (I->getOpcode()) {
5122 case llvm::Instruction::And: {
5123 auto *AndC = dyn_cast<ConstantInt>(I->getOperand(1));
5124 if (!AndC)
5125 return false;
5126 APInt AndBits = AndC->getValue();
5127 DemandBits |= AndBits;
5128 // Keep track of the widest and mask we see.
5129 if (AndBits.ugt(WidestAndBits))
5130 WidestAndBits = AndBits;
5131 if (AndBits == WidestAndBits && I->getOperand(0) == Load)
5132 AndsToMaybeRemove.push_back(I);
5133 break;
5134 }
5135
5136 case llvm::Instruction::Shl: {
5137 auto *ShlC = dyn_cast<ConstantInt>(I->getOperand(1));
5138 if (!ShlC)
5139 return false;
5140 uint64_t ShiftAmt = ShlC->getLimitedValue(BitWidth - 1);
Craig Topperfc947bc2017-04-18 17:14:21 +00005141 DemandBits.setLowBits(BitWidth - ShiftAmt);
Geoff Berry5256fca2015-11-20 22:34:39 +00005142 break;
5143 }
5144
5145 case llvm::Instruction::Trunc: {
5146 EVT TruncVT = TLI->getValueType(*DL, I->getType());
5147 unsigned TruncBitWidth = TruncVT.getSizeInBits();
Craig Topperfc947bc2017-04-18 17:14:21 +00005148 DemandBits.setLowBits(TruncBitWidth);
Geoff Berry5256fca2015-11-20 22:34:39 +00005149 break;
5150 }
5151
5152 default:
5153 return false;
5154 }
5155 }
5156
5157 uint32_t ActiveBits = DemandBits.getActiveBits();
5158 // Avoid hoisting (and (load x) 1) since it is unlikely to be folded by the
5159 // target even if isLoadExtLegal says an i1 EXTLOAD is valid. For example,
5160 // for the AArch64 target isLoadExtLegal(ZEXTLOAD, i32, i1) returns true, but
5161 // (and (load x) 1) is not matched as a single instruction, rather as a LDR
5162 // followed by an AND.
5163 // TODO: Look into removing this restriction by fixing backends to either
5164 // return false for isLoadExtLegal for i1 or have them select this pattern to
5165 // a single instruction.
5166 //
5167 // Also avoid hoisting if we didn't see any ands with the exact DemandBits
5168 // mask, since these are the only ands that will be removed by isel.
Craig Topperd33ee1b2017-04-03 16:34:59 +00005169 if (ActiveBits <= 1 || !DemandBits.isMask(ActiveBits) ||
Geoff Berry5256fca2015-11-20 22:34:39 +00005170 WidestAndBits != DemandBits)
5171 return false;
5172
5173 LLVMContext &Ctx = Load->getType()->getContext();
5174 Type *TruncTy = Type::getIntNTy(Ctx, ActiveBits);
5175 EVT TruncVT = TLI->getValueType(*DL, TruncTy);
5176
5177 // Reject cases that won't be matched as extloads.
5178 if (!LoadResultVT.bitsGT(TruncVT) || !TruncVT.isRound() ||
5179 !TLI->isLoadExtLegal(ISD::ZEXTLOAD, LoadResultVT, TruncVT))
5180 return false;
5181
5182 IRBuilder<> Builder(Load->getNextNode());
5183 auto *NewAnd = dyn_cast<Instruction>(
5184 Builder.CreateAnd(Load, ConstantInt::get(Ctx, DemandBits)));
Geoff Berry5d534b62017-02-21 18:53:14 +00005185 // Mark this instruction as "inserted by CGP", so that other
5186 // optimizations don't touch it.
5187 InsertedInsts.insert(NewAnd);
Geoff Berry5256fca2015-11-20 22:34:39 +00005188
5189 // Replace all uses of load with new and (except for the use of load in the
5190 // new and itself).
5191 Load->replaceAllUsesWith(NewAnd);
5192 NewAnd->setOperand(0, Load);
5193
5194 // Remove any and instructions that are now redundant.
5195 for (auto *And : AndsToMaybeRemove)
5196 // Check that the and mask is the same as the one we decided to put on the
5197 // new and.
5198 if (cast<ConstantInt>(And->getOperand(1))->getValue() == DemandBits) {
5199 And->replaceAllUsesWith(NewAnd);
5200 if (&*CurInstIterator == And)
5201 CurInstIterator = std::next(And->getIterator());
5202 And->eraseFromParent();
5203 ++NumAndUses;
5204 }
5205
5206 ++NumAndsAdded;
5207 return true;
5208}
5209
Sanjay Patel69a50a12015-10-19 21:59:12 +00005210/// Check if V (an operand of a select instruction) is an expensive instruction
5211/// that is only used once.
5212static bool sinkSelectOperand(const TargetTransformInfo *TTI, Value *V) {
5213 auto *I = dyn_cast<Instruction>(V);
5214 // If it's safe to speculatively execute, then it should not have side
5215 // effects; therefore, it's safe to sink and possibly *not* execute.
Rafael Espindola84921b92015-10-24 23:11:13 +00005216 return I && I->hasOneUse() && isSafeToSpeculativelyExecute(I) &&
5217 TTI->getUserCost(I) >= TargetTransformInfo::TCC_Expensive;
Sanjay Patel69a50a12015-10-19 21:59:12 +00005218}
5219
Sanjay Patel4ac6b112015-09-21 22:47:23 +00005220/// Returns true if a SelectInst should be turned into an explicit branch.
Sanjay Patel69a50a12015-10-19 21:59:12 +00005221static bool isFormingBranchFromSelectProfitable(const TargetTransformInfo *TTI,
Sanjay Pateld66607b2016-04-26 17:11:17 +00005222 const TargetLowering *TLI,
Sanjay Patel69a50a12015-10-19 21:59:12 +00005223 SelectInst *SI) {
Sanjay Pateld66607b2016-04-26 17:11:17 +00005224 // If even a predictable select is cheap, then a branch can't be cheaper.
5225 if (!TLI->isPredictableSelectExpensive())
5226 return false;
5227
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005228 // FIXME: This should use the same heuristics as IfConversion to determine
Sanjay Pateld66607b2016-04-26 17:11:17 +00005229 // whether a select is better represented as a branch.
5230
5231 // If metadata tells us that the select condition is obviously predictable,
5232 // then we want to replace the select with a branch.
5233 uint64_t TrueWeight, FalseWeight;
5234 if (SI->extractProfMetadata(TrueWeight, FalseWeight)) {
5235 uint64_t Max = std::max(TrueWeight, FalseWeight);
5236 uint64_t Sum = TrueWeight + FalseWeight;
Sanjay Patelc7b91e62016-05-09 17:31:55 +00005237 if (Sum != 0) {
5238 auto Probability = BranchProbability::getBranchProbability(Max, Sum);
5239 if (Probability > TLI->getPredictableBranchThreshold())
5240 return true;
5241 }
Sanjay Pateld66607b2016-04-26 17:11:17 +00005242 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005243
5244 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
5245
Sanjay Patel4e652762015-09-28 22:14:51 +00005246 // If a branch is predictable, an out-of-order CPU can avoid blocking on its
5247 // comparison condition. If the compare has more than one use, there's
5248 // probably another cmov or setcc around, so it's not worth emitting a branch.
Sanjay Patel5e5f0e92015-09-28 21:44:46 +00005249 if (!Cmp || !Cmp->hasOneUse())
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005250 return false;
5251
Sanjay Patel69a50a12015-10-19 21:59:12 +00005252 // If either operand of the select is expensive and only needed on one side
5253 // of the select, we should form a branch.
5254 if (sinkSelectOperand(TTI, SI->getTrueValue()) ||
5255 sinkSelectOperand(TTI, SI->getFalseValue()))
5256 return true;
5257
5258 return false;
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005259}
5260
Dehao Chen9bbb9412016-09-12 20:23:28 +00005261/// If \p isTrue is true, return the true value of \p SI, otherwise return
5262/// false value of \p SI. If the true/false value of \p SI is defined by any
5263/// select instructions in \p Selects, look through the defining select
5264/// instruction until the true/false value is not defined in \p Selects.
5265static Value *getTrueOrFalseValue(
5266 SelectInst *SI, bool isTrue,
5267 const SmallPtrSet<const Instruction *, 2> &Selects) {
5268 Value *V;
5269
5270 for (SelectInst *DefSI = SI; DefSI != nullptr && Selects.count(DefSI);
5271 DefSI = dyn_cast<SelectInst>(V)) {
Dehao Chenc32d7122016-09-12 20:29:54 +00005272 assert(DefSI->getCondition() == SI->getCondition() &&
Dehao Chen9bbb9412016-09-12 20:23:28 +00005273 "The condition of DefSI does not match with SI");
5274 V = (isTrue ? DefSI->getTrueValue() : DefSI->getFalseValue());
5275 }
5276 return V;
5277}
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005278
Nadav Rotem9d832022012-09-02 12:10:19 +00005279/// If we have a SelectInst that will likely profit from branch prediction,
5280/// turn it into a branch.
Sanjay Patelfc580a62015-09-21 23:03:16 +00005281bool CodeGenPrepare::optimizeSelectInst(SelectInst *SI) {
Dehao Chen9bbb9412016-09-12 20:23:28 +00005282 // Find all consecutive select instructions that share the same condition.
5283 SmallVector<SelectInst *, 2> ASI;
5284 ASI.push_back(SI);
5285 for (BasicBlock::iterator It = ++BasicBlock::iterator(SI);
5286 It != SI->getParent()->end(); ++It) {
5287 SelectInst *I = dyn_cast<SelectInst>(&*It);
5288 if (I && SI->getCondition() == I->getCondition()) {
5289 ASI.push_back(I);
5290 } else {
5291 break;
5292 }
5293 }
5294
5295 SelectInst *LastSI = ASI.back();
5296 // Increment the current iterator to skip all the rest of select instructions
5297 // because they will be either "not lowered" or "all lowered" to branch.
5298 CurInstIterator = std::next(LastSI->getIterator());
5299
Nadav Rotem9d832022012-09-02 12:10:19 +00005300 bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
5301
5302 // Can we convert the 'select' to CF ?
Sanjay Patela31b0c02016-04-26 00:47:39 +00005303 if (DisableSelectToBranch || OptSize || !TLI || VectorCond ||
5304 SI->getMetadata(LLVMContext::MD_unpredictable))
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005305 return false;
5306
Nadav Rotem9d832022012-09-02 12:10:19 +00005307 TargetLowering::SelectSupportKind SelectKind;
5308 if (VectorCond)
5309 SelectKind = TargetLowering::VectorMaskSelect;
5310 else if (SI->getType()->isVectorTy())
5311 SelectKind = TargetLowering::ScalarCondVectorVal;
5312 else
5313 SelectKind = TargetLowering::ScalarValSelect;
5314
Sanjay Pateld66607b2016-04-26 17:11:17 +00005315 if (TLI->isSelectSupported(SelectKind) &&
5316 !isFormingBranchFromSelectProfitable(TTI, TLI, SI))
5317 return false;
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005318
5319 ModifiedDT = true;
5320
Sanjay Patel69a50a12015-10-19 21:59:12 +00005321 // Transform a sequence like this:
5322 // start:
5323 // %cmp = cmp uge i32 %a, %b
5324 // %sel = select i1 %cmp, i32 %c, i32 %d
5325 //
5326 // Into:
5327 // start:
5328 // %cmp = cmp uge i32 %a, %b
5329 // br i1 %cmp, label %select.true, label %select.false
5330 // select.true:
5331 // br label %select.end
5332 // select.false:
5333 // br label %select.end
5334 // select.end:
5335 // %sel = phi i32 [ %c, %select.true ], [ %d, %select.false ]
5336 //
5337 // In addition, we may sink instructions that produce %c or %d from
5338 // the entry block into the destination(s) of the new branch.
5339 // If the true or false blocks do not contain a sunken instruction, that
5340 // block and its branch may be optimized away. In that case, one side of the
5341 // first branch will point directly to select.end, and the corresponding PHI
5342 // predecessor block will be the start block.
5343
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005344 // First, we split the block containing the select into 2 blocks.
5345 BasicBlock *StartBlock = SI->getParent();
Dehao Chen9bbb9412016-09-12 20:23:28 +00005346 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(LastSI));
Sanjay Patel69a50a12015-10-19 21:59:12 +00005347 BasicBlock *EndBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005348
Sanjay Patel69a50a12015-10-19 21:59:12 +00005349 // Delete the unconditional branch that was just created by the split.
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005350 StartBlock->getTerminator()->eraseFromParent();
Sanjay Patel69a50a12015-10-19 21:59:12 +00005351
5352 // These are the new basic blocks for the conditional branch.
5353 // At least one will become an actual new basic block.
5354 BasicBlock *TrueBlock = nullptr;
5355 BasicBlock *FalseBlock = nullptr;
Dehao Chen9bbb9412016-09-12 20:23:28 +00005356 BranchInst *TrueBranch = nullptr;
5357 BranchInst *FalseBranch = nullptr;
Sanjay Patel69a50a12015-10-19 21:59:12 +00005358
5359 // Sink expensive instructions into the conditional blocks to avoid executing
5360 // them speculatively.
Dehao Chen9bbb9412016-09-12 20:23:28 +00005361 for (SelectInst *SI : ASI) {
5362 if (sinkSelectOperand(TTI, SI->getTrueValue())) {
5363 if (TrueBlock == nullptr) {
5364 TrueBlock = BasicBlock::Create(SI->getContext(), "select.true.sink",
5365 EndBlock->getParent(), EndBlock);
5366 TrueBranch = BranchInst::Create(EndBlock, TrueBlock);
5367 }
5368 auto *TrueInst = cast<Instruction>(SI->getTrueValue());
5369 TrueInst->moveBefore(TrueBranch);
5370 }
5371 if (sinkSelectOperand(TTI, SI->getFalseValue())) {
5372 if (FalseBlock == nullptr) {
5373 FalseBlock = BasicBlock::Create(SI->getContext(), "select.false.sink",
5374 EndBlock->getParent(), EndBlock);
5375 FalseBranch = BranchInst::Create(EndBlock, FalseBlock);
5376 }
5377 auto *FalseInst = cast<Instruction>(SI->getFalseValue());
5378 FalseInst->moveBefore(FalseBranch);
5379 }
Sanjay Patel69a50a12015-10-19 21:59:12 +00005380 }
5381
5382 // If there was nothing to sink, then arbitrarily choose the 'false' side
5383 // for a new input value to the PHI.
5384 if (TrueBlock == FalseBlock) {
5385 assert(TrueBlock == nullptr &&
5386 "Unexpected basic block transform while optimizing select");
5387
5388 FalseBlock = BasicBlock::Create(SI->getContext(), "select.false",
5389 EndBlock->getParent(), EndBlock);
5390 BranchInst::Create(EndBlock, FalseBlock);
5391 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005392
5393 // Insert the real conditional branch based on the original condition.
Sanjay Patel69a50a12015-10-19 21:59:12 +00005394 // If we did not create a new block for one of the 'true' or 'false' paths
5395 // of the condition, it means that side of the branch goes to the end block
5396 // directly and the path originates from the start block from the point of
5397 // view of the new PHI.
Xinliang David Li241e6c72016-09-03 21:26:36 +00005398 BasicBlock *TT, *FT;
Sanjay Patel69a50a12015-10-19 21:59:12 +00005399 if (TrueBlock == nullptr) {
Xinliang David Li241e6c72016-09-03 21:26:36 +00005400 TT = EndBlock;
5401 FT = FalseBlock;
Sanjay Patel69a50a12015-10-19 21:59:12 +00005402 TrueBlock = StartBlock;
5403 } else if (FalseBlock == nullptr) {
Xinliang David Li241e6c72016-09-03 21:26:36 +00005404 TT = TrueBlock;
5405 FT = EndBlock;
Sanjay Patel69a50a12015-10-19 21:59:12 +00005406 FalseBlock = StartBlock;
5407 } else {
Xinliang David Li241e6c72016-09-03 21:26:36 +00005408 TT = TrueBlock;
5409 FT = FalseBlock;
Sanjay Patel69a50a12015-10-19 21:59:12 +00005410 }
Xinliang David Li241e6c72016-09-03 21:26:36 +00005411 IRBuilder<>(SI).CreateCondBr(SI->getCondition(), TT, FT, SI);
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005412
Dehao Chen9bbb9412016-09-12 20:23:28 +00005413 SmallPtrSet<const Instruction *, 2> INS;
5414 INS.insert(ASI.begin(), ASI.end());
5415 // Use reverse iterator because later select may use the value of the
5416 // earlier select, and we need to propagate value through earlier select
5417 // to get the PHI operand.
5418 for (auto It = ASI.rbegin(); It != ASI.rend(); ++It) {
5419 SelectInst *SI = *It;
5420 // The select itself is replaced with a PHI Node.
5421 PHINode *PN = PHINode::Create(SI->getType(), 2, "", &EndBlock->front());
5422 PN->takeName(SI);
5423 PN->addIncoming(getTrueOrFalseValue(SI, true, INS), TrueBlock);
5424 PN->addIncoming(getTrueOrFalseValue(SI, false, INS), FalseBlock);
Sanjay Patel69a50a12015-10-19 21:59:12 +00005425
Dehao Chen9bbb9412016-09-12 20:23:28 +00005426 SI->replaceAllUsesWith(PN);
5427 SI->eraseFromParent();
5428 INS.erase(SI);
5429 ++NumSelectsExpanded;
5430 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005431
5432 // Instruct OptimizeBlock to skip to the next block.
5433 CurInstIterator = StartBlock->end();
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005434 return true;
5435}
5436
Benjamin Kramer573ff362014-03-01 17:24:40 +00005437static bool isBroadcastShuffle(ShuffleVectorInst *SVI) {
Tim Northoveraeb8e062014-02-19 10:02:43 +00005438 SmallVector<int, 16> Mask(SVI->getShuffleMask());
5439 int SplatElem = -1;
5440 for (unsigned i = 0; i < Mask.size(); ++i) {
5441 if (SplatElem != -1 && Mask[i] != -1 && Mask[i] != SplatElem)
5442 return false;
5443 SplatElem = Mask[i];
5444 }
5445
5446 return true;
5447}
5448
5449/// Some targets have expensive vector shifts if the lanes aren't all the same
5450/// (e.g. x86 only introduced "vpsllvd" and friends with AVX2). In these cases
5451/// it's often worth sinking a shufflevector splat down to its use so that
5452/// codegen can spot all lanes are identical.
Sanjay Patelfc580a62015-09-21 23:03:16 +00005453bool CodeGenPrepare::optimizeShuffleVectorInst(ShuffleVectorInst *SVI) {
Tim Northoveraeb8e062014-02-19 10:02:43 +00005454 BasicBlock *DefBB = SVI->getParent();
5455
5456 // Only do this xform if variable vector shifts are particularly expensive.
5457 if (!TLI || !TLI->isVectorShiftByScalarCheap(SVI->getType()))
5458 return false;
5459
5460 // We only expect better codegen by sinking a shuffle if we can recognise a
5461 // constant splat.
5462 if (!isBroadcastShuffle(SVI))
5463 return false;
5464
5465 // InsertedShuffles - Only insert a shuffle in each block once.
5466 DenseMap<BasicBlock*, Instruction*> InsertedShuffles;
5467
5468 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00005469 for (User *U : SVI->users()) {
5470 Instruction *UI = cast<Instruction>(U);
Tim Northoveraeb8e062014-02-19 10:02:43 +00005471
5472 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00005473 BasicBlock *UserBB = UI->getParent();
Tim Northoveraeb8e062014-02-19 10:02:43 +00005474 if (UserBB == DefBB) continue;
5475
5476 // For now only apply this when the splat is used by a shift instruction.
Chandler Carruthcdf47882014-03-09 03:16:01 +00005477 if (!UI->isShift()) continue;
Tim Northoveraeb8e062014-02-19 10:02:43 +00005478
5479 // Everything checks out, sink the shuffle if the user's block doesn't
5480 // already have a copy.
5481 Instruction *&InsertedShuffle = InsertedShuffles[UserBB];
5482
5483 if (!InsertedShuffle) {
5484 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00005485 assert(InsertPt != UserBB->end());
5486 InsertedShuffle =
5487 new ShuffleVectorInst(SVI->getOperand(0), SVI->getOperand(1),
5488 SVI->getOperand(2), "", &*InsertPt);
Tim Northoveraeb8e062014-02-19 10:02:43 +00005489 }
5490
Chandler Carruthcdf47882014-03-09 03:16:01 +00005491 UI->replaceUsesOfWith(SVI, InsertedShuffle);
Tim Northoveraeb8e062014-02-19 10:02:43 +00005492 MadeChange = true;
5493 }
5494
5495 // If we removed all uses, nuke the shuffle.
5496 if (SVI->use_empty()) {
5497 SVI->eraseFromParent();
5498 MadeChange = true;
5499 }
5500
5501 return MadeChange;
5502}
5503
Sanjay Patel0ed9aea2015-11-02 23:22:49 +00005504bool CodeGenPrepare::optimizeSwitchInst(SwitchInst *SI) {
5505 if (!TLI || !DL)
5506 return false;
5507
5508 Value *Cond = SI->getCondition();
5509 Type *OldType = Cond->getType();
5510 LLVMContext &Context = Cond->getContext();
5511 MVT RegType = TLI->getRegisterType(Context, TLI->getValueType(*DL, OldType));
5512 unsigned RegWidth = RegType.getSizeInBits();
5513
5514 if (RegWidth <= cast<IntegerType>(OldType)->getBitWidth())
5515 return false;
5516
5517 // If the register width is greater than the type width, expand the condition
5518 // of the switch instruction and each case constant to the width of the
5519 // register. By widening the type of the switch condition, subsequent
5520 // comparisons (for case comparisons) will not need to be extended to the
5521 // preferred register width, so we will potentially eliminate N-1 extends,
5522 // where N is the number of cases in the switch.
5523 auto *NewType = Type::getIntNTy(Context, RegWidth);
5524
5525 // Zero-extend the switch condition and case constants unless the switch
5526 // condition is a function argument that is already being sign-extended.
5527 // In that case, we can avoid an unnecessary mask/extension by sign-extending
5528 // everything instead.
5529 Instruction::CastOps ExtType = Instruction::ZExt;
5530 if (auto *Arg = dyn_cast<Argument>(Cond))
5531 if (Arg->hasSExtAttr())
5532 ExtType = Instruction::SExt;
5533
5534 auto *ExtInst = CastInst::Create(ExtType, Cond, NewType);
5535 ExtInst->insertBefore(SI);
5536 SI->setCondition(ExtInst);
Chandler Carruth927d8e62017-04-12 07:27:28 +00005537 for (auto Case : SI->cases()) {
Sanjay Patel0ed9aea2015-11-02 23:22:49 +00005538 APInt NarrowConst = Case.getCaseValue()->getValue();
5539 APInt WideConst = (ExtType == Instruction::ZExt) ?
5540 NarrowConst.zext(RegWidth) : NarrowConst.sext(RegWidth);
5541 Case.setValue(ConstantInt::get(Context, WideConst));
5542 }
5543
5544 return true;
5545}
5546
Zaara Syeda3a7578c2017-05-31 17:12:38 +00005547
Quentin Colombetc32615d2014-10-31 17:52:53 +00005548namespace {
5549/// \brief Helper class to promote a scalar operation to a vector one.
5550/// This class is used to move downward extractelement transition.
5551/// E.g.,
5552/// a = vector_op <2 x i32>
5553/// b = extractelement <2 x i32> a, i32 0
5554/// c = scalar_op b
5555/// store c
5556///
5557/// =>
5558/// a = vector_op <2 x i32>
5559/// c = vector_op a (equivalent to scalar_op on the related lane)
5560/// * d = extractelement <2 x i32> c, i32 0
5561/// * store d
5562/// Assuming both extractelement and store can be combine, we get rid of the
5563/// transition.
5564class VectorPromoteHelper {
Mehdi Amini44ede332015-07-09 02:09:04 +00005565 /// DataLayout associated with the current module.
5566 const DataLayout &DL;
5567
Quentin Colombetc32615d2014-10-31 17:52:53 +00005568 /// Used to perform some checks on the legality of vector operations.
5569 const TargetLowering &TLI;
5570
5571 /// Used to estimated the cost of the promoted chain.
5572 const TargetTransformInfo &TTI;
5573
5574 /// The transition being moved downwards.
5575 Instruction *Transition;
5576 /// The sequence of instructions to be promoted.
5577 SmallVector<Instruction *, 4> InstsToBePromoted;
5578 /// Cost of combining a store and an extract.
5579 unsigned StoreExtractCombineCost;
5580 /// Instruction that will be combined with the transition.
5581 Instruction *CombineInst;
5582
5583 /// \brief The instruction that represents the current end of the transition.
5584 /// Since we are faking the promotion until we reach the end of the chain
5585 /// of computation, we need a way to get the current end of the transition.
5586 Instruction *getEndOfTransition() const {
5587 if (InstsToBePromoted.empty())
5588 return Transition;
5589 return InstsToBePromoted.back();
5590 }
5591
5592 /// \brief Return the index of the original value in the transition.
5593 /// E.g., for "extractelement <2 x i32> c, i32 1" the original value,
5594 /// c, is at index 0.
5595 unsigned getTransitionOriginalValueIdx() const {
5596 assert(isa<ExtractElementInst>(Transition) &&
5597 "Other kind of transitions are not supported yet");
5598 return 0;
5599 }
5600
5601 /// \brief Return the index of the index in the transition.
5602 /// E.g., for "extractelement <2 x i32> c, i32 0" the index
5603 /// is at index 1.
5604 unsigned getTransitionIdx() const {
5605 assert(isa<ExtractElementInst>(Transition) &&
5606 "Other kind of transitions are not supported yet");
5607 return 1;
5608 }
5609
5610 /// \brief Get the type of the transition.
5611 /// This is the type of the original value.
5612 /// E.g., for "extractelement <2 x i32> c, i32 1" the type of the
5613 /// transition is <2 x i32>.
5614 Type *getTransitionType() const {
5615 return Transition->getOperand(getTransitionOriginalValueIdx())->getType();
5616 }
5617
5618 /// \brief Promote \p ToBePromoted by moving \p Def downward through.
5619 /// I.e., we have the following sequence:
5620 /// Def = Transition <ty1> a to <ty2>
5621 /// b = ToBePromoted <ty2> Def, ...
5622 /// =>
5623 /// b = ToBePromoted <ty1> a, ...
5624 /// Def = Transition <ty1> ToBePromoted to <ty2>
5625 void promoteImpl(Instruction *ToBePromoted);
5626
5627 /// \brief Check whether or not it is profitable to promote all the
5628 /// instructions enqueued to be promoted.
5629 bool isProfitableToPromote() {
5630 Value *ValIdx = Transition->getOperand(getTransitionOriginalValueIdx());
5631 unsigned Index = isa<ConstantInt>(ValIdx)
5632 ? cast<ConstantInt>(ValIdx)->getZExtValue()
5633 : -1;
5634 Type *PromotedType = getTransitionType();
5635
5636 StoreInst *ST = cast<StoreInst>(CombineInst);
5637 unsigned AS = ST->getPointerAddressSpace();
5638 unsigned Align = ST->getAlignment();
5639 // Check if this store is supported.
5640 if (!TLI.allowsMisalignedMemoryAccesses(
Mehdi Amini44ede332015-07-09 02:09:04 +00005641 TLI.getValueType(DL, ST->getValueOperand()->getType()), AS,
5642 Align)) {
Quentin Colombetc32615d2014-10-31 17:52:53 +00005643 // If this is not supported, there is no way we can combine
5644 // the extract with the store.
5645 return false;
5646 }
5647
5648 // The scalar chain of computation has to pay for the transition
5649 // scalar to vector.
5650 // The vector chain has to account for the combining cost.
5651 uint64_t ScalarCost =
5652 TTI.getVectorInstrCost(Transition->getOpcode(), PromotedType, Index);
5653 uint64_t VectorCost = StoreExtractCombineCost;
5654 for (const auto &Inst : InstsToBePromoted) {
5655 // Compute the cost.
5656 // By construction, all instructions being promoted are arithmetic ones.
5657 // Moreover, one argument is a constant that can be viewed as a splat
5658 // constant.
5659 Value *Arg0 = Inst->getOperand(0);
5660 bool IsArg0Constant = isa<UndefValue>(Arg0) || isa<ConstantInt>(Arg0) ||
5661 isa<ConstantFP>(Arg0);
5662 TargetTransformInfo::OperandValueKind Arg0OVK =
5663 IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
5664 : TargetTransformInfo::OK_AnyValue;
5665 TargetTransformInfo::OperandValueKind Arg1OVK =
5666 !IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
5667 : TargetTransformInfo::OK_AnyValue;
5668 ScalarCost += TTI.getArithmeticInstrCost(
5669 Inst->getOpcode(), Inst->getType(), Arg0OVK, Arg1OVK);
5670 VectorCost += TTI.getArithmeticInstrCost(Inst->getOpcode(), PromotedType,
5671 Arg0OVK, Arg1OVK);
5672 }
5673 DEBUG(dbgs() << "Estimated cost of computation to be promoted:\nScalar: "
5674 << ScalarCost << "\nVector: " << VectorCost << '\n');
5675 return ScalarCost > VectorCost;
5676 }
5677
5678 /// \brief Generate a constant vector with \p Val with the same
5679 /// number of elements as the transition.
5680 /// \p UseSplat defines whether or not \p Val should be replicated
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00005681 /// across the whole vector.
Quentin Colombetc32615d2014-10-31 17:52:53 +00005682 /// In other words, if UseSplat == true, we generate <Val, Val, ..., Val>,
5683 /// otherwise we generate a vector with as many undef as possible:
5684 /// <undef, ..., undef, Val, undef, ..., undef> where \p Val is only
5685 /// used at the index of the extract.
5686 Value *getConstantVector(Constant *Val, bool UseSplat) const {
5687 unsigned ExtractIdx = UINT_MAX;
5688 if (!UseSplat) {
5689 // If we cannot determine where the constant must be, we have to
5690 // use a splat constant.
5691 Value *ValExtractIdx = Transition->getOperand(getTransitionIdx());
5692 if (ConstantInt *CstVal = dyn_cast<ConstantInt>(ValExtractIdx))
5693 ExtractIdx = CstVal->getSExtValue();
5694 else
5695 UseSplat = true;
5696 }
5697
5698 unsigned End = getTransitionType()->getVectorNumElements();
5699 if (UseSplat)
5700 return ConstantVector::getSplat(End, Val);
5701
5702 SmallVector<Constant *, 4> ConstVec;
5703 UndefValue *UndefVal = UndefValue::get(Val->getType());
5704 for (unsigned Idx = 0; Idx != End; ++Idx) {
5705 if (Idx == ExtractIdx)
5706 ConstVec.push_back(Val);
5707 else
5708 ConstVec.push_back(UndefVal);
5709 }
5710 return ConstantVector::get(ConstVec);
5711 }
5712
5713 /// \brief Check if promoting to a vector type an operand at \p OperandIdx
5714 /// in \p Use can trigger undefined behavior.
5715 static bool canCauseUndefinedBehavior(const Instruction *Use,
5716 unsigned OperandIdx) {
5717 // This is not safe to introduce undef when the operand is on
5718 // the right hand side of a division-like instruction.
5719 if (OperandIdx != 1)
5720 return false;
5721 switch (Use->getOpcode()) {
5722 default:
5723 return false;
5724 case Instruction::SDiv:
5725 case Instruction::UDiv:
5726 case Instruction::SRem:
5727 case Instruction::URem:
5728 return true;
5729 case Instruction::FDiv:
5730 case Instruction::FRem:
5731 return !Use->hasNoNaNs();
5732 }
5733 llvm_unreachable(nullptr);
5734 }
5735
5736public:
Mehdi Amini44ede332015-07-09 02:09:04 +00005737 VectorPromoteHelper(const DataLayout &DL, const TargetLowering &TLI,
5738 const TargetTransformInfo &TTI, Instruction *Transition,
5739 unsigned CombineCost)
5740 : DL(DL), TLI(TLI), TTI(TTI), Transition(Transition),
Quentin Colombetc32615d2014-10-31 17:52:53 +00005741 StoreExtractCombineCost(CombineCost), CombineInst(nullptr) {
5742 assert(Transition && "Do not know how to promote null");
5743 }
5744
5745 /// \brief Check if we can promote \p ToBePromoted to \p Type.
5746 bool canPromote(const Instruction *ToBePromoted) const {
5747 // We could support CastInst too.
5748 return isa<BinaryOperator>(ToBePromoted);
5749 }
5750
5751 /// \brief Check if it is profitable to promote \p ToBePromoted
5752 /// by moving downward the transition through.
5753 bool shouldPromote(const Instruction *ToBePromoted) const {
5754 // Promote only if all the operands can be statically expanded.
5755 // Indeed, we do not want to introduce any new kind of transitions.
5756 for (const Use &U : ToBePromoted->operands()) {
5757 const Value *Val = U.get();
5758 if (Val == getEndOfTransition()) {
5759 // If the use is a division and the transition is on the rhs,
5760 // we cannot promote the operation, otherwise we may create a
5761 // division by zero.
5762 if (canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()))
5763 return false;
5764 continue;
5765 }
5766 if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) &&
5767 !isa<ConstantFP>(Val))
5768 return false;
5769 }
5770 // Check that the resulting operation is legal.
5771 int ISDOpcode = TLI.InstructionOpcodeToISD(ToBePromoted->getOpcode());
5772 if (!ISDOpcode)
5773 return false;
5774 return StressStoreExtract ||
Ahmed Bougacha026600d2014-11-12 23:05:03 +00005775 TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00005776 ISDOpcode, TLI.getValueType(DL, getTransitionType(), true));
Quentin Colombetc32615d2014-10-31 17:52:53 +00005777 }
5778
5779 /// \brief Check whether or not \p Use can be combined
5780 /// with the transition.
5781 /// I.e., is it possible to do Use(Transition) => AnotherUse?
5782 bool canCombine(const Instruction *Use) { return isa<StoreInst>(Use); }
5783
5784 /// \brief Record \p ToBePromoted as part of the chain to be promoted.
5785 void enqueueForPromotion(Instruction *ToBePromoted) {
5786 InstsToBePromoted.push_back(ToBePromoted);
5787 }
5788
5789 /// \brief Set the instruction that will be combined with the transition.
5790 void recordCombineInstruction(Instruction *ToBeCombined) {
5791 assert(canCombine(ToBeCombined) && "Unsupported instruction to combine");
5792 CombineInst = ToBeCombined;
5793 }
5794
5795 /// \brief Promote all the instructions enqueued for promotion if it is
5796 /// is profitable.
5797 /// \return True if the promotion happened, false otherwise.
5798 bool promote() {
5799 // Check if there is something to promote.
5800 // Right now, if we do not have anything to combine with,
5801 // we assume the promotion is not profitable.
5802 if (InstsToBePromoted.empty() || !CombineInst)
5803 return false;
5804
5805 // Check cost.
5806 if (!StressStoreExtract && !isProfitableToPromote())
5807 return false;
5808
5809 // Promote.
5810 for (auto &ToBePromoted : InstsToBePromoted)
5811 promoteImpl(ToBePromoted);
5812 InstsToBePromoted.clear();
5813 return true;
5814 }
5815};
5816} // End of anonymous namespace.
5817
5818void VectorPromoteHelper::promoteImpl(Instruction *ToBePromoted) {
5819 // At this point, we know that all the operands of ToBePromoted but Def
5820 // can be statically promoted.
5821 // For Def, we need to use its parameter in ToBePromoted:
5822 // b = ToBePromoted ty1 a
5823 // Def = Transition ty1 b to ty2
5824 // Move the transition down.
5825 // 1. Replace all uses of the promoted operation by the transition.
5826 // = ... b => = ... Def.
5827 assert(ToBePromoted->getType() == Transition->getType() &&
5828 "The type of the result of the transition does not match "
5829 "the final type");
5830 ToBePromoted->replaceAllUsesWith(Transition);
5831 // 2. Update the type of the uses.
5832 // b = ToBePromoted ty2 Def => b = ToBePromoted ty1 Def.
5833 Type *TransitionTy = getTransitionType();
5834 ToBePromoted->mutateType(TransitionTy);
5835 // 3. Update all the operands of the promoted operation with promoted
5836 // operands.
5837 // b = ToBePromoted ty1 Def => b = ToBePromoted ty1 a.
5838 for (Use &U : ToBePromoted->operands()) {
5839 Value *Val = U.get();
5840 Value *NewVal = nullptr;
5841 if (Val == Transition)
5842 NewVal = Transition->getOperand(getTransitionOriginalValueIdx());
5843 else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) ||
5844 isa<ConstantFP>(Val)) {
5845 // Use a splat constant if it is not safe to use undef.
5846 NewVal = getConstantVector(
5847 cast<Constant>(Val),
5848 isa<UndefValue>(Val) ||
5849 canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()));
5850 } else
Craig Topperd3c02f12015-01-05 10:15:49 +00005851 llvm_unreachable("Did you modified shouldPromote and forgot to update "
5852 "this?");
Quentin Colombetc32615d2014-10-31 17:52:53 +00005853 ToBePromoted->setOperand(U.getOperandNo(), NewVal);
5854 }
5855 Transition->removeFromParent();
5856 Transition->insertAfter(ToBePromoted);
5857 Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted);
5858}
5859
5860/// Some targets can do store(extractelement) with one instruction.
5861/// Try to push the extractelement towards the stores when the target
5862/// has this feature and this is profitable.
Sanjay Patelfc580a62015-09-21 23:03:16 +00005863bool CodeGenPrepare::optimizeExtractElementInst(Instruction *Inst) {
Quentin Colombetc32615d2014-10-31 17:52:53 +00005864 unsigned CombineCost = UINT_MAX;
5865 if (DisableStoreExtract || !TLI ||
5866 (!StressStoreExtract &&
5867 !TLI->canCombineStoreAndExtract(Inst->getOperand(0)->getType(),
5868 Inst->getOperand(1), CombineCost)))
5869 return false;
5870
5871 // At this point we know that Inst is a vector to scalar transition.
5872 // Try to move it down the def-use chain, until:
5873 // - We can combine the transition with its single use
5874 // => we got rid of the transition.
5875 // - We escape the current basic block
5876 // => we would need to check that we are moving it at a cheaper place and
5877 // we do not do that for now.
5878 BasicBlock *Parent = Inst->getParent();
5879 DEBUG(dbgs() << "Found an interesting transition: " << *Inst << '\n');
Mehdi Amini44ede332015-07-09 02:09:04 +00005880 VectorPromoteHelper VPH(*DL, *TLI, *TTI, Inst, CombineCost);
Quentin Colombetc32615d2014-10-31 17:52:53 +00005881 // If the transition has more than one use, assume this is not going to be
5882 // beneficial.
5883 while (Inst->hasOneUse()) {
5884 Instruction *ToBePromoted = cast<Instruction>(*Inst->user_begin());
5885 DEBUG(dbgs() << "Use: " << *ToBePromoted << '\n');
5886
5887 if (ToBePromoted->getParent() != Parent) {
5888 DEBUG(dbgs() << "Instruction to promote is in a different block ("
5889 << ToBePromoted->getParent()->getName()
5890 << ") than the transition (" << Parent->getName() << ").\n");
5891 return false;
5892 }
5893
5894 if (VPH.canCombine(ToBePromoted)) {
5895 DEBUG(dbgs() << "Assume " << *Inst << '\n'
5896 << "will be combined with: " << *ToBePromoted << '\n');
5897 VPH.recordCombineInstruction(ToBePromoted);
5898 bool Changed = VPH.promote();
5899 NumStoreExtractExposed += Changed;
5900 return Changed;
5901 }
5902
5903 DEBUG(dbgs() << "Try promoting.\n");
5904 if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted))
5905 return false;
5906
5907 DEBUG(dbgs() << "Promoting is possible... Enqueue for promotion!\n");
5908
5909 VPH.enqueueForPromotion(ToBePromoted);
5910 Inst = ToBePromoted;
5911 }
5912 return false;
5913}
5914
Wei Mia2f0b592016-12-22 19:44:45 +00005915/// For the instruction sequence of store below, F and I values
5916/// are bundled together as an i64 value before being stored into memory.
5917/// Sometimes it is more efficent to generate separate stores for F and I,
5918/// which can remove the bitwise instructions or sink them to colder places.
5919///
5920/// (store (or (zext (bitcast F to i32) to i64),
5921/// (shl (zext I to i64), 32)), addr) -->
5922/// (store F, addr) and (store I, addr+4)
5923///
5924/// Similarly, splitting for other merged store can also be beneficial, like:
5925/// For pair of {i32, i32}, i64 store --> two i32 stores.
5926/// For pair of {i32, i16}, i64 store --> two i32 stores.
5927/// For pair of {i16, i16}, i32 store --> two i16 stores.
5928/// For pair of {i16, i8}, i32 store --> two i16 stores.
5929/// For pair of {i8, i8}, i16 store --> two i8 stores.
5930///
5931/// We allow each target to determine specifically which kind of splitting is
5932/// supported.
5933///
5934/// The store patterns are commonly seen from the simple code snippet below
5935/// if only std::make_pair(...) is sroa transformed before inlined into hoo.
5936/// void goo(const std::pair<int, float> &);
5937/// hoo() {
5938/// ...
5939/// goo(std::make_pair(tmp, ftmp));
5940/// ...
5941/// }
5942///
5943/// Although we already have similar splitting in DAG Combine, we duplicate
5944/// it in CodeGenPrepare to catch the case in which pattern is across
5945/// multiple BBs. The logic in DAG Combine is kept to catch case generated
5946/// during code expansion.
5947static bool splitMergedValStore(StoreInst &SI, const DataLayout &DL,
5948 const TargetLowering &TLI) {
5949 // Handle simple but common cases only.
5950 Type *StoreType = SI.getValueOperand()->getType();
5951 if (DL.getTypeStoreSizeInBits(StoreType) != DL.getTypeSizeInBits(StoreType) ||
5952 DL.getTypeSizeInBits(StoreType) == 0)
5953 return false;
5954
5955 unsigned HalfValBitSize = DL.getTypeSizeInBits(StoreType) / 2;
5956 Type *SplitStoreType = Type::getIntNTy(SI.getContext(), HalfValBitSize);
5957 if (DL.getTypeStoreSizeInBits(SplitStoreType) !=
5958 DL.getTypeSizeInBits(SplitStoreType))
5959 return false;
5960
5961 // Match the following patterns:
5962 // (store (or (zext LValue to i64),
5963 // (shl (zext HValue to i64), 32)), HalfValBitSize)
5964 // or
5965 // (store (or (shl (zext HValue to i64), 32)), HalfValBitSize)
5966 // (zext LValue to i64),
5967 // Expect both operands of OR and the first operand of SHL have only
5968 // one use.
5969 Value *LValue, *HValue;
5970 if (!match(SI.getValueOperand(),
5971 m_c_Or(m_OneUse(m_ZExt(m_Value(LValue))),
5972 m_OneUse(m_Shl(m_OneUse(m_ZExt(m_Value(HValue))),
5973 m_SpecificInt(HalfValBitSize))))))
5974 return false;
5975
5976 // Check LValue and HValue are int with size less or equal than 32.
5977 if (!LValue->getType()->isIntegerTy() ||
5978 DL.getTypeSizeInBits(LValue->getType()) > HalfValBitSize ||
5979 !HValue->getType()->isIntegerTy() ||
5980 DL.getTypeSizeInBits(HValue->getType()) > HalfValBitSize)
5981 return false;
5982
5983 // If LValue/HValue is a bitcast instruction, use the EVT before bitcast
5984 // as the input of target query.
5985 auto *LBC = dyn_cast<BitCastInst>(LValue);
5986 auto *HBC = dyn_cast<BitCastInst>(HValue);
5987 EVT LowTy = LBC ? EVT::getEVT(LBC->getOperand(0)->getType())
5988 : EVT::getEVT(LValue->getType());
5989 EVT HighTy = HBC ? EVT::getEVT(HBC->getOperand(0)->getType())
5990 : EVT::getEVT(HValue->getType());
5991 if (!ForceSplitStore && !TLI.isMultiStoresCheaperThanBitsMerge(LowTy, HighTy))
5992 return false;
5993
5994 // Start to split store.
5995 IRBuilder<> Builder(SI.getContext());
5996 Builder.SetInsertPoint(&SI);
5997
5998 // If LValue/HValue is a bitcast in another BB, create a new one in current
5999 // BB so it may be merged with the splitted stores by dag combiner.
6000 if (LBC && LBC->getParent() != SI.getParent())
6001 LValue = Builder.CreateBitCast(LBC->getOperand(0), LBC->getType());
6002 if (HBC && HBC->getParent() != SI.getParent())
6003 HValue = Builder.CreateBitCast(HBC->getOperand(0), HBC->getType());
6004
6005 auto CreateSplitStore = [&](Value *V, bool Upper) {
6006 V = Builder.CreateZExtOrBitCast(V, SplitStoreType);
6007 Value *Addr = Builder.CreateBitCast(
6008 SI.getOperand(1),
6009 SplitStoreType->getPointerTo(SI.getPointerAddressSpace()));
6010 if (Upper)
6011 Addr = Builder.CreateGEP(
6012 SplitStoreType, Addr,
6013 ConstantInt::get(Type::getInt32Ty(SI.getContext()), 1));
6014 Builder.CreateAlignedStore(
6015 V, Addr, Upper ? SI.getAlignment() / 2 : SI.getAlignment());
6016 };
6017
6018 CreateSplitStore(LValue, false);
6019 CreateSplitStore(HValue, true);
6020
6021 // Delete the old store.
6022 SI.eraseFromParent();
6023 return true;
6024}
6025
Sanjay Patelfc580a62015-09-21 23:03:16 +00006026bool CodeGenPrepare::optimizeInst(Instruction *I, bool& ModifiedDT) {
Ahmed Bougachaf3299142015-06-17 20:44:32 +00006027 // Bail out if we inserted the instruction to prevent optimizations from
6028 // stepping on each other's toes.
6029 if (InsertedInsts.count(I))
6030 return false;
6031
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006032 if (PHINode *P = dyn_cast<PHINode>(I)) {
6033 // It is possible for very late stage optimizations (such as SimplifyCFG)
6034 // to introduce PHI nodes too late to be cleaned up. If we detect such a
6035 // trivial PHI, go ahead and zap it here.
Daniel Berlin4d0fe642017-04-28 19:55:38 +00006036 if (Value *V = SimplifyInstruction(P, {*DL, TLInfo})) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006037 P->replaceAllUsesWith(V);
6038 P->eraseFromParent();
6039 ++NumPHIsElim;
Chris Lattneree588de2011-01-15 07:29:01 +00006040 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006041 }
Chris Lattneree588de2011-01-15 07:29:01 +00006042 return false;
6043 }
Nadav Rotem465834c2012-07-24 10:51:42 +00006044
Chris Lattneree588de2011-01-15 07:29:01 +00006045 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006046 // If the source of the cast is a constant, then this should have
6047 // already been constant folded. The only reason NOT to constant fold
6048 // it is if something (e.g. LSR) was careful to place the constant
6049 // evaluation in a block other than then one that uses it (e.g. to hoist
6050 // the address of globals out of a loop). If this is the case, we don't
6051 // want to forward-subst the cast.
6052 if (isa<Constant>(CI->getOperand(0)))
6053 return false;
6054
Mehdi Amini44ede332015-07-09 02:09:04 +00006055 if (TLI && OptimizeNoopCopyExpression(CI, *TLI, *DL))
Chris Lattneree588de2011-01-15 07:29:01 +00006056 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006057
Chris Lattneree588de2011-01-15 07:29:01 +00006058 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +00006059 /// Sink a zext or sext into its user blocks if the target type doesn't
6060 /// fit in one register
Mehdi Amini44ede332015-07-09 02:09:04 +00006061 if (TLI &&
6062 TLI->getTypeAction(CI->getContext(),
6063 TLI->getValueType(*DL, CI->getType())) ==
6064 TargetLowering::TypeExpandInteger) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +00006065 return SinkCast(CI);
6066 } else {
Jun Bum Limdee55652017-04-03 19:20:07 +00006067 bool MadeChange = optimizeExt(I);
Sanjay Patelfc580a62015-09-21 23:03:16 +00006068 return MadeChange | optimizeExtUses(I);
Manuel Jacoba7c48f92014-03-13 13:36:25 +00006069 }
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006070 }
Chris Lattneree588de2011-01-15 07:29:01 +00006071 return false;
6072 }
Nadav Rotem465834c2012-07-24 10:51:42 +00006073
Chris Lattneree588de2011-01-15 07:29:01 +00006074 if (CmpInst *CI = dyn_cast<CmpInst>(I))
Hal Finkeldecb0242014-01-02 21:13:43 +00006075 if (!TLI || !TLI->hasMultipleConditionRegisters())
Peter Zotovf87e5502016-04-03 17:11:53 +00006076 return OptimizeCmpExpression(CI, TLI);
Nadav Rotem465834c2012-07-24 10:51:42 +00006077
Chris Lattneree588de2011-01-15 07:29:01 +00006078 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Sanjoy Das00757272016-12-16 20:29:39 +00006079 LI->setMetadata(LLVMContext::MD_invariant_group, nullptr);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00006080 if (TLI) {
Geoff Berry5256fca2015-11-20 22:34:39 +00006081 bool Modified = optimizeLoadExt(LI);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00006082 unsigned AS = LI->getPointerAddressSpace();
Geoff Berry5256fca2015-11-20 22:34:39 +00006083 Modified |= optimizeMemoryInst(I, I->getOperand(0), LI->getType(), AS);
6084 return Modified;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00006085 }
Hans Wennborgf3254832012-10-30 11:23:25 +00006086 return false;
Chris Lattneree588de2011-01-15 07:29:01 +00006087 }
Nadav Rotem465834c2012-07-24 10:51:42 +00006088
Chris Lattneree588de2011-01-15 07:29:01 +00006089 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Wei Mia2f0b592016-12-22 19:44:45 +00006090 if (TLI && splitMergedValStore(*SI, *DL, *TLI))
6091 return true;
Sanjoy Das00757272016-12-16 20:29:39 +00006092 SI->setMetadata(LLVMContext::MD_invariant_group, nullptr);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00006093 if (TLI) {
6094 unsigned AS = SI->getPointerAddressSpace();
Sanjay Patelfc580a62015-09-21 23:03:16 +00006095 return optimizeMemoryInst(I, SI->getOperand(1),
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00006096 SI->getOperand(0)->getType(), AS);
6097 }
Chris Lattneree588de2011-01-15 07:29:01 +00006098 return false;
6099 }
Nadav Rotem465834c2012-07-24 10:51:42 +00006100
Matt Arsenault02d915b2017-03-15 22:35:20 +00006101 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
6102 unsigned AS = RMW->getPointerAddressSpace();
6103 return optimizeMemoryInst(I, RMW->getPointerOperand(),
6104 RMW->getType(), AS);
6105 }
6106
6107 if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(I)) {
6108 unsigned AS = CmpX->getPointerAddressSpace();
6109 return optimizeMemoryInst(I, CmpX->getPointerOperand(),
6110 CmpX->getCompareOperand()->getType(), AS);
6111 }
6112
Yi Jiangd069f632014-04-21 19:34:27 +00006113 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I);
6114
Geoff Berry5d534b62017-02-21 18:53:14 +00006115 if (BinOp && (BinOp->getOpcode() == Instruction::And) &&
6116 EnableAndCmpSinking && TLI)
6117 return sinkAndCmp0Expression(BinOp, *TLI, InsertedInsts);
6118
Yi Jiangd069f632014-04-21 19:34:27 +00006119 if (BinOp && (BinOp->getOpcode() == Instruction::AShr ||
6120 BinOp->getOpcode() == Instruction::LShr)) {
6121 ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1));
6122 if (TLI && CI && TLI->hasExtractBitsInsn())
Mehdi Amini44ede332015-07-09 02:09:04 +00006123 return OptimizeExtractBits(BinOp, CI, *TLI, *DL);
Yi Jiangd069f632014-04-21 19:34:27 +00006124
6125 return false;
6126 }
6127
Chris Lattneree588de2011-01-15 07:29:01 +00006128 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00006129 if (GEPI->hasAllZeroIndices()) {
6130 /// The GEP operand must be a pointer, so must its result -> BitCast
6131 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
6132 GEPI->getName(), GEPI);
6133 GEPI->replaceAllUsesWith(NC);
6134 GEPI->eraseFromParent();
6135 ++NumGEPsElim;
Sanjay Patelfc580a62015-09-21 23:03:16 +00006136 optimizeInst(NC, ModifiedDT);
Chris Lattneree588de2011-01-15 07:29:01 +00006137 return true;
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00006138 }
Chris Lattneree588de2011-01-15 07:29:01 +00006139 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006140 }
Nadav Rotem465834c2012-07-24 10:51:42 +00006141
Chris Lattneree588de2011-01-15 07:29:01 +00006142 if (CallInst *CI = dyn_cast<CallInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00006143 return optimizeCallInst(CI, ModifiedDT);
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006144
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00006145 if (SelectInst *SI = dyn_cast<SelectInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00006146 return optimizeSelectInst(SI);
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00006147
Tim Northoveraeb8e062014-02-19 10:02:43 +00006148 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00006149 return optimizeShuffleVectorInst(SVI);
Tim Northoveraeb8e062014-02-19 10:02:43 +00006150
Sanjay Patel0ed9aea2015-11-02 23:22:49 +00006151 if (auto *Switch = dyn_cast<SwitchInst>(I))
6152 return optimizeSwitchInst(Switch);
6153
Quentin Colombetc32615d2014-10-31 17:52:53 +00006154 if (isa<ExtractElementInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00006155 return optimizeExtractElementInst(I);
Quentin Colombetc32615d2014-10-31 17:52:53 +00006156
Chris Lattneree588de2011-01-15 07:29:01 +00006157 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006158}
6159
James Molloyf01488e2016-01-15 09:20:19 +00006160/// Given an OR instruction, check to see if this is a bitreverse
6161/// idiom. If so, insert the new intrinsic and return true.
6162static bool makeBitReverse(Instruction &I, const DataLayout &DL,
6163 const TargetLowering &TLI) {
6164 if (!I.getType()->isIntegerTy() ||
6165 !TLI.isOperationLegalOrCustom(ISD::BITREVERSE,
6166 TLI.getValueType(DL, I.getType(), true)))
6167 return false;
6168
6169 SmallVector<Instruction*, 4> Insts;
Chad Rosiera00df492016-05-25 16:22:14 +00006170 if (!recognizeBSwapOrBitReverseIdiom(&I, false, true, Insts))
James Molloyf01488e2016-01-15 09:20:19 +00006171 return false;
6172 Instruction *LastInst = Insts.back();
6173 I.replaceAllUsesWith(LastInst);
6174 RecursivelyDeleteTriviallyDeadInstructions(&I);
6175 return true;
6176}
6177
Chris Lattnerf2836d12007-03-31 04:06:36 +00006178// In this pass we look for GEP and cast instructions that are used
6179// across basic blocks and rewrite them to improve basic-block-at-a-time
6180// selection.
Sanjay Patelfc580a62015-09-21 23:03:16 +00006181bool CodeGenPrepare::optimizeBlock(BasicBlock &BB, bool& ModifiedDT) {
Cameron Zwarichce3b9302011-01-06 00:42:50 +00006182 SunkAddrs.clear();
Cameron Zwarich5dd2aa22011-03-02 03:31:46 +00006183 bool MadeChange = false;
Eric Christopherc1ea1492008-09-24 05:32:41 +00006184
Chris Lattner7a277142011-01-15 07:14:54 +00006185 CurInstIterator = BB.begin();
Elena Demikhovsky87700a72014-12-28 08:54:45 +00006186 while (CurInstIterator != BB.end()) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00006187 MadeChange |= optimizeInst(&*CurInstIterator++, ModifiedDT);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00006188 if (ModifiedDT)
6189 return true;
6190 }
Benjamin Kramer455fa352012-11-23 19:17:06 +00006191
James Molloyf01488e2016-01-15 09:20:19 +00006192 bool MadeBitReverse = true;
6193 while (TLI && MadeBitReverse) {
6194 MadeBitReverse = false;
6195 for (auto &I : reverse(BB)) {
6196 if (makeBitReverse(I, *DL, *TLI)) {
6197 MadeBitReverse = MadeChange = true;
George Burgess IVd4febd12016-03-22 21:25:08 +00006198 ModifiedDT = true;
James Molloyf01488e2016-01-15 09:20:19 +00006199 break;
6200 }
6201 }
6202 }
James Molloy3ef84c42016-01-15 10:36:01 +00006203 MadeChange |= dupRetToEnableTailCallOpts(&BB);
Junmo Park7d6c5f12016-01-28 09:42:39 +00006204
Chris Lattnerf2836d12007-03-31 04:06:36 +00006205 return MadeChange;
6206}
Devang Patel53771ba2011-08-18 00:50:51 +00006207
6208// llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotem465834c2012-07-24 10:51:42 +00006209// handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patel53771ba2011-08-18 00:50:51 +00006210// find a node corresponding to the value.
Sanjay Patelfc580a62015-09-21 23:03:16 +00006211bool CodeGenPrepare::placeDbgValues(Function &F) {
Devang Patel53771ba2011-08-18 00:50:51 +00006212 bool MadeChange = false;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +00006213 for (BasicBlock &BB : F) {
Craig Topperc0196b12014-04-14 00:51:57 +00006214 Instruction *PrevNonDbgInst = nullptr;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +00006215 for (BasicBlock::iterator BI = BB.begin(), BE = BB.end(); BI != BE;) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00006216 Instruction *Insn = &*BI++;
Devang Patel53771ba2011-08-18 00:50:51 +00006217 DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
Adrian Prantl32da8892014-04-25 20:49:25 +00006218 // Leave dbg.values that refer to an alloca alone. These
6219 // instrinsics describe the address of a variable (= the alloca)
6220 // being taken. They should not be moved next to the alloca
6221 // (and to the beginning of the scope), but rather stay close to
6222 // where said address is used.
6223 if (!DVI || (DVI->getValue() && isa<AllocaInst>(DVI->getValue()))) {
Devang Patel53771ba2011-08-18 00:50:51 +00006224 PrevNonDbgInst = Insn;
6225 continue;
6226 }
6227
6228 Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
6229 if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
Reid Kleckner8de1fe22015-12-08 23:00:03 +00006230 // If VI is a phi in a block with an EHPad terminator, we can't insert
6231 // after it.
6232 if (isa<PHINode>(VI) && VI->getParent()->getTerminator()->isEHPad())
6233 continue;
Devang Patel53771ba2011-08-18 00:50:51 +00006234 DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
6235 DVI->removeFromParent();
Reid Klecknere18f92b2015-12-08 22:33:23 +00006236 if (isa<PHINode>(VI))
6237 DVI->insertBefore(&*VI->getParent()->getFirstInsertionPt());
6238 else
6239 DVI->insertAfter(VI);
Devang Patel53771ba2011-08-18 00:50:51 +00006240 MadeChange = true;
6241 ++NumDbgValueMoved;
6242 }
6243 }
6244 }
6245 return MadeChange;
6246}
Tim Northovercea0abb2014-03-29 08:22:29 +00006247
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006248/// \brief Scale down both weights to fit into uint32_t.
6249static void scaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) {
6250 uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
6251 uint32_t Scale = (NewMax / UINT32_MAX) + 1;
6252 NewTrue = NewTrue / Scale;
6253 NewFalse = NewFalse / Scale;
6254}
6255
6256/// \brief Some targets prefer to split a conditional branch like:
6257/// \code
6258/// %0 = icmp ne i32 %a, 0
6259/// %1 = icmp ne i32 %b, 0
6260/// %or.cond = or i1 %0, %1
6261/// br i1 %or.cond, label %TrueBB, label %FalseBB
6262/// \endcode
6263/// into multiple branch instructions like:
6264/// \code
6265/// bb1:
6266/// %0 = icmp ne i32 %a, 0
6267/// br i1 %0, label %TrueBB, label %bb2
6268/// bb2:
6269/// %1 = icmp ne i32 %b, 0
6270/// br i1 %1, label %TrueBB, label %FalseBB
6271/// \endcode
6272/// This usually allows instruction selection to do even further optimizations
6273/// and combine the compare with the branch instruction. Currently this is
6274/// applied for targets which have "cheap" jump instructions.
6275///
6276/// FIXME: Remove the (equivalent?) implementation in SelectionDAG.
6277///
6278bool CodeGenPrepare::splitBranchCondition(Function &F) {
David Blaikiedc3f01e2015-03-09 01:57:13 +00006279 if (!TM || !TM->Options.EnableFastISel || !TLI || TLI->isJumpExpensive())
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006280 return false;
6281
6282 bool MadeChange = false;
6283 for (auto &BB : F) {
6284 // Does this BB end with the following?
6285 // %cond1 = icmp|fcmp|binary instruction ...
6286 // %cond2 = icmp|fcmp|binary instruction ...
6287 // %cond.or = or|and i1 %cond1, cond2
6288 // br i1 %cond.or label %dest1, label %dest2"
6289 BinaryOperator *LogicOp;
6290 BasicBlock *TBB, *FBB;
6291 if (!match(BB.getTerminator(), m_Br(m_OneUse(m_BinOp(LogicOp)), TBB, FBB)))
6292 continue;
6293
Sanjay Patel42574202015-09-02 19:23:23 +00006294 auto *Br1 = cast<BranchInst>(BB.getTerminator());
6295 if (Br1->getMetadata(LLVMContext::MD_unpredictable))
6296 continue;
6297
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006298 unsigned Opc;
Juergen Ributzka8bda7382014-12-09 17:50:10 +00006299 Value *Cond1, *Cond2;
6300 if (match(LogicOp, m_And(m_OneUse(m_Value(Cond1)),
6301 m_OneUse(m_Value(Cond2)))))
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006302 Opc = Instruction::And;
Juergen Ributzka8bda7382014-12-09 17:50:10 +00006303 else if (match(LogicOp, m_Or(m_OneUse(m_Value(Cond1)),
6304 m_OneUse(m_Value(Cond2)))))
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006305 Opc = Instruction::Or;
6306 else
6307 continue;
6308
6309 if (!match(Cond1, m_CombineOr(m_Cmp(), m_BinOp())) ||
6310 !match(Cond2, m_CombineOr(m_Cmp(), m_BinOp())) )
6311 continue;
6312
6313 DEBUG(dbgs() << "Before branch condition splitting\n"; BB.dump());
6314
6315 // Create a new BB.
Duncan P. N. Exon Smitha848c472016-02-21 19:52:15 +00006316 auto TmpBB =
6317 BasicBlock::Create(BB.getContext(), BB.getName() + ".cond.split",
6318 BB.getParent(), BB.getNextNode());
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006319
6320 // Update original basic block by using the first condition directly by the
6321 // branch instruction and removing the no longer needed and/or instruction.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006322 Br1->setCondition(Cond1);
6323 LogicOp->eraseFromParent();
Juergen Ributzka8bda7382014-12-09 17:50:10 +00006324
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006325 // Depending on the conditon we have to either replace the true or the false
6326 // successor of the original branch instruction.
6327 if (Opc == Instruction::And)
6328 Br1->setSuccessor(0, TmpBB);
6329 else
6330 Br1->setSuccessor(1, TmpBB);
6331
6332 // Fill in the new basic block.
6333 auto *Br2 = IRBuilder<>(TmpBB).CreateCondBr(Cond2, TBB, FBB);
Juergen Ributzka8bda7382014-12-09 17:50:10 +00006334 if (auto *I = dyn_cast<Instruction>(Cond2)) {
6335 I->removeFromParent();
6336 I->insertBefore(Br2);
6337 }
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006338
6339 // Update PHI nodes in both successors. The original BB needs to be
6340 // replaced in one succesor's PHI nodes, because the branch comes now from
6341 // the newly generated BB (NewBB). In the other successor we need to add one
6342 // incoming edge to the PHI nodes, because both branch instructions target
6343 // now the same successor. Depending on the original branch condition
6344 // (and/or) we have to swap the successors (TrueDest, FalseDest), so that
Simon Pilgrimf2fbf432016-11-20 13:47:59 +00006345 // we perform the correct update for the PHI nodes.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006346 // This doesn't change the successor order of the just created branch
6347 // instruction (or any other instruction).
6348 if (Opc == Instruction::Or)
6349 std::swap(TBB, FBB);
6350
6351 // Replace the old BB with the new BB.
6352 for (auto &I : *TBB) {
6353 PHINode *PN = dyn_cast<PHINode>(&I);
6354 if (!PN)
6355 break;
6356 int i;
6357 while ((i = PN->getBasicBlockIndex(&BB)) >= 0)
6358 PN->setIncomingBlock(i, TmpBB);
6359 }
6360
6361 // Add another incoming edge form the new BB.
6362 for (auto &I : *FBB) {
6363 PHINode *PN = dyn_cast<PHINode>(&I);
6364 if (!PN)
6365 break;
6366 auto *Val = PN->getIncomingValueForBlock(&BB);
6367 PN->addIncoming(Val, TmpBB);
6368 }
6369
6370 // Update the branch weights (from SelectionDAGBuilder::
6371 // FindMergedConditions).
6372 if (Opc == Instruction::Or) {
6373 // Codegen X | Y as:
6374 // BB1:
6375 // jmp_if_X TBB
6376 // jmp TmpBB
6377 // TmpBB:
6378 // jmp_if_Y TBB
6379 // jmp FBB
6380 //
6381
6382 // We have flexibility in setting Prob for BB1 and Prob for NewBB.
6383 // The requirement is that
6384 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
6385 // = TrueProb for orignal BB.
6386 // Assuming the orignal weights are A and B, one choice is to set BB1's
6387 // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice
6388 // assumes that
6389 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
6390 // Another choice is to assume TrueProb for BB1 equals to TrueProb for
6391 // TmpBB, but the math is more complicated.
6392 uint64_t TrueWeight, FalseWeight;
Sanjay Pateldc88bd62016-04-23 20:01:22 +00006393 if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) {
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006394 uint64_t NewTrueWeight = TrueWeight;
6395 uint64_t NewFalseWeight = TrueWeight + 2 * FalseWeight;
6396 scaleWeights(NewTrueWeight, NewFalseWeight);
6397 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
6398 .createBranchWeights(TrueWeight, FalseWeight));
6399
6400 NewTrueWeight = TrueWeight;
6401 NewFalseWeight = 2 * FalseWeight;
6402 scaleWeights(NewTrueWeight, NewFalseWeight);
6403 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
6404 .createBranchWeights(TrueWeight, FalseWeight));
6405 }
6406 } else {
6407 // Codegen X & Y as:
6408 // BB1:
6409 // jmp_if_X TmpBB
6410 // jmp FBB
6411 // TmpBB:
6412 // jmp_if_Y TBB
6413 // jmp FBB
6414 //
6415 // This requires creation of TmpBB after CurBB.
6416
6417 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
6418 // The requirement is that
6419 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
6420 // = FalseProb for orignal BB.
6421 // Assuming the orignal weights are A and B, one choice is to set BB1's
6422 // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice
6423 // assumes that
6424 // FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB.
6425 uint64_t TrueWeight, FalseWeight;
Sanjay Pateldc88bd62016-04-23 20:01:22 +00006426 if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) {
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006427 uint64_t NewTrueWeight = 2 * TrueWeight + FalseWeight;
6428 uint64_t NewFalseWeight = FalseWeight;
6429 scaleWeights(NewTrueWeight, NewFalseWeight);
6430 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
6431 .createBranchWeights(TrueWeight, FalseWeight));
6432
6433 NewTrueWeight = 2 * TrueWeight;
6434 NewFalseWeight = FalseWeight;
6435 scaleWeights(NewTrueWeight, NewFalseWeight);
6436 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
6437 .createBranchWeights(TrueWeight, FalseWeight));
6438 }
6439 }
6440
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006441 // Note: No point in getting fancy here, since the DT info is never
Quentin Colombet7bdd50d2015-03-18 23:17:28 +00006442 // available to CodeGenPrepare.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006443 ModifiedDT = true;
6444
6445 MadeChange = true;
6446
6447 DEBUG(dbgs() << "After branch condition splitting\n"; BB.dump();
6448 TmpBB->dump());
6449 }
6450 return MadeChange;
6451}