blob: 3afbb3cf3de329a46def90cc0bbb6893036cc114 [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
Eugene Zelenko900b6332017-08-29 22:32:07 +000016#include "llvm/ADT/APInt.h"
17#include "llvm/ADT/ArrayRef.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000018#include "llvm/ADT/DenseMap.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000019#include "llvm/ADT/PointerIntPair.h"
20#include "llvm/ADT/STLExtras.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000021#include "llvm/ADT/SmallPtrSet.h"
22#include "llvm/ADT/SmallVector.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000023#include "llvm/ADT/Statistic.h"
Jun Bum Lim90b6b502016-12-16 20:38:39 +000024#include "llvm/Analysis/BlockFrequencyInfo.h"
25#include "llvm/Analysis/BranchProbabilityInfo.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000026#include "llvm/Analysis/ConstantFolding.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000027#include "llvm/Analysis/InstructionSimplify.h"
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +000028#include "llvm/Analysis/LoopInfo.h"
Zaara Syeda3a7578c2017-05-31 17:12:38 +000029#include "llvm/Analysis/MemoryBuiltins.h"
Dehao Chen302b69c2016-10-18 20:42:47 +000030#include "llvm/Analysis/ProfileSummaryInfo.h"
Chandler Carruth62d42152015-01-15 02:16:27 +000031#include "llvm/Analysis/TargetLibraryInfo.h"
Quentin Colombetc32615d2014-10-31 17:52:53 +000032#include "llvm/Analysis/TargetTransformInfo.h"
Sanjay Patel69a50a12015-10-19 21:59:12 +000033#include "llvm/Analysis/ValueTracking.h"
Michael Kupersteinf79af6f2016-09-08 00:48:37 +000034#include "llvm/CodeGen/Analysis.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000035#include "llvm/CodeGen/ISDOpcodes.h"
36#include "llvm/CodeGen/MachineValueType.h"
37#include "llvm/CodeGen/SelectionDAGNodes.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000038#include "llvm/CodeGen/TargetLowering.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000039#include "llvm/CodeGen/TargetPassConfig.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000040#include "llvm/CodeGen/TargetSubtargetInfo.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000041#include "llvm/CodeGen/ValueTypes.h"
42#include "llvm/IR/Argument.h"
43#include "llvm/IR/Attributes.h"
44#include "llvm/IR/BasicBlock.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000045#include "llvm/IR/CallSite.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000046#include "llvm/IR/Constant.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000047#include "llvm/IR/Constants.h"
48#include "llvm/IR/DataLayout.h"
49#include "llvm/IR/DerivedTypes.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000050#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000051#include "llvm/IR/Function.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000052#include "llvm/IR/GetElementPtrTypeIterator.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000053#include "llvm/IR/GlobalValue.h"
54#include "llvm/IR/GlobalVariable.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000055#include "llvm/IR/IRBuilder.h"
56#include "llvm/IR/InlineAsm.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000057#include "llvm/IR/InstrTypes.h"
58#include "llvm/IR/Instruction.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000059#include "llvm/IR/Instructions.h"
60#include "llvm/IR/IntrinsicInst.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000061#include "llvm/IR/Intrinsics.h"
62#include "llvm/IR/LLVMContext.h"
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +000063#include "llvm/IR/MDBuilder.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000064#include "llvm/IR/Module.h"
65#include "llvm/IR/Operator.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000066#include "llvm/IR/PatternMatch.h"
Ramkumar Ramachandradba73292015-01-14 23:27:07 +000067#include "llvm/IR/Statepoint.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000068#include "llvm/IR/Type.h"
69#include "llvm/IR/Use.h"
70#include "llvm/IR/User.h"
71#include "llvm/IR/Value.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +000072#include "llvm/IR/ValueHandle.h"
Chandler Carrutha4ea2692014-03-04 11:26:31 +000073#include "llvm/IR/ValueMap.h"
Chris Lattnerf2836d12007-03-31 04:06:36 +000074#include "llvm/Pass.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000075#include "llvm/Support/BlockFrequency.h"
Sanjay Pateld66607b2016-04-26 17:11:17 +000076#include "llvm/Support/BranchProbability.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000077#include "llvm/Support/Casting.h"
Evan Cheng8b637b12010-08-17 01:34:49 +000078#include "llvm/Support/CommandLine.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000079#include "llvm/Support/Compiler.h"
Evan Chengd3d80172007-12-05 23:58:20 +000080#include "llvm/Support/Debug.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000081#include "llvm/Support/ErrorHandling.h"
82#include "llvm/Support/MathExtras.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000083#include "llvm/Support/raw_ostream.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000084#include "llvm/Target/TargetMachine.h"
85#include "llvm/Target/TargetOptions.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000086#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Preston Gurdcdf540d2012-09-04 18:22:17 +000087#include "llvm/Transforms/Utils/BypassSlowDivision.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000088#include "llvm/Transforms/Utils/Local.h"
Ahmed Bougachae03bef72015-01-12 17:22:43 +000089#include "llvm/Transforms/Utils/SimplifyLibCalls.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000090#include <algorithm>
91#include <cassert>
92#include <cstdint>
93#include <iterator>
94#include <limits>
95#include <memory>
96#include <utility>
97#include <vector>
Zaara Syeda3a7578c2017-05-31 17:12:38 +000098
Chris Lattnerf2836d12007-03-31 04:06:36 +000099using namespace llvm;
Chris Lattnerd616ef52008-11-25 04:42:10 +0000100using namespace llvm::PatternMatch;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000101
Chandler Carruth1b9dde02014-04-22 02:02:50 +0000102#define DEBUG_TYPE "codegenprepare"
103
Cameron Zwarichced753f2011-01-05 17:27:27 +0000104STATISTIC(NumBlocksElim, "Number of blocks eliminated");
Evan Cheng0663f232011-03-21 01:19:09 +0000105STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated");
106STATISTIC(NumGEPsElim, "Number of GEPs converted to casts");
Cameron Zwarichced753f2011-01-05 17:27:27 +0000107STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "
108 "sunken Cmps");
109STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
110 "of sunken Casts");
111STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "
112 "computations were sunk");
Serguei Katkovd5d8d542017-11-05 05:50:33 +0000113STATISTIC(NumMemoryInstsPhiCreated,
114 "Number of phis created when address "
115 "computations were sunk to memory instructions");
116STATISTIC(NumMemoryInstsSelectCreated,
117 "Number of select created when address "
118 "computations were sunk to memory instructions");
Evan Cheng0663f232011-03-21 01:19:09 +0000119STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads");
120STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized");
Geoff Berry5256fca2015-11-20 22:34:39 +0000121STATISTIC(NumAndsAdded,
122 "Number of and mask instructions added to form ext loads");
123STATISTIC(NumAndUses, "Number of uses of and mask instructions optimized");
Evan Cheng0663f232011-03-21 01:19:09 +0000124STATISTIC(NumRetsDup, "Number of return instructions duplicated");
Devang Patel53771ba2011-08-18 00:50:51 +0000125STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved");
Benjamin Kramer047d7ca2012-05-05 12:49:22 +0000126STATISTIC(NumSelectsExpanded, "Number of selects turned into branches");
Quentin Colombetc32615d2014-10-31 17:52:53 +0000127STATISTIC(NumStoreExtractExposed, "Number of store(extractelement) exposed");
Jakob Stoklund Oleseneb12f492010-09-30 20:51:52 +0000128
Cameron Zwarich338d3622011-03-11 21:52:04 +0000129static cl::opt<bool> DisableBranchOpts(
130 "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
131 cl::desc("Disable branch optimizations in CodeGenPrepare"));
132
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000133static cl::opt<bool>
134 DisableGCOpts("disable-cgp-gc-opts", cl::Hidden, cl::init(false),
135 cl::desc("Disable GC optimizations in CodeGenPrepare"));
136
Benjamin Kramer3d38c172012-05-06 14:25:16 +0000137static cl::opt<bool> DisableSelectToBranch(
138 "disable-cgp-select2branch", cl::Hidden, cl::init(false),
139 cl::desc("Disable select to branch conversion."));
Benjamin Kramer047d7ca2012-05-05 12:49:22 +0000140
Hal Finkelc3998302014-04-12 00:59:48 +0000141static cl::opt<bool> AddrSinkUsingGEPs(
Eli Friedman5fba1e52017-04-06 22:42:18 +0000142 "addr-sink-using-gep", cl::Hidden, cl::init(true),
Hal Finkelc3998302014-04-12 00:59:48 +0000143 cl::desc("Address sinking in CGP using GEPs."));
144
Tim Northovercea0abb2014-03-29 08:22:29 +0000145static cl::opt<bool> EnableAndCmpSinking(
146 "enable-andcmp-sinking", cl::Hidden, cl::init(true),
147 cl::desc("Enable sinkinig and/cmp into branches."));
148
Quentin Colombetc32615d2014-10-31 17:52:53 +0000149static cl::opt<bool> DisableStoreExtract(
150 "disable-cgp-store-extract", cl::Hidden, cl::init(false),
151 cl::desc("Disable store(extract) optimizations in CodeGenPrepare"));
152
153static cl::opt<bool> StressStoreExtract(
154 "stress-cgp-store-extract", cl::Hidden, cl::init(false),
155 cl::desc("Stress test store(extract) optimizations in CodeGenPrepare"));
156
Quentin Colombetfc2201e2014-12-17 01:36:17 +0000157static cl::opt<bool> DisableExtLdPromotion(
158 "disable-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
159 cl::desc("Disable ext(promotable(ld)) -> promoted(ext(ld)) optimization in "
160 "CodeGenPrepare"));
161
162static cl::opt<bool> StressExtLdPromotion(
163 "stress-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
164 cl::desc("Stress test ext(promotable(ld)) -> promoted(ext(ld)) "
165 "optimization in CodeGenPrepare"));
166
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000167static cl::opt<bool> DisablePreheaderProtect(
168 "disable-preheader-prot", cl::Hidden, cl::init(false),
169 cl::desc("Disable protection against removing loop preheaders"));
170
Dehao Chen302b69c2016-10-18 20:42:47 +0000171static cl::opt<bool> ProfileGuidedSectionPrefix(
David Callahan5960d9b12017-06-14 20:35:33 +0000172 "profile-guided-section-prefix", cl::Hidden, cl::init(true), cl::ZeroOrMore,
Dehao Chen302b69c2016-10-18 20:42:47 +0000173 cl::desc("Use profile info to add section prefix for hot/cold functions"));
174
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000175static cl::opt<unsigned> FreqRatioToSkipMerge(
176 "cgp-freq-ratio-to-skip-merge", cl::Hidden, cl::init(2),
177 cl::desc("Skip merging empty blocks if (frequency of empty block) / "
178 "(frequency of destination block) is greater than this ratio"));
179
Wei Mia2f0b592016-12-22 19:44:45 +0000180static cl::opt<bool> ForceSplitStore(
181 "force-split-store", cl::Hidden, cl::init(false),
182 cl::desc("Force store splitting no matter what the target query says."));
183
Jun Bum Limdee55652017-04-03 19:20:07 +0000184static cl::opt<bool>
185EnableTypePromotionMerge("cgp-type-promotion-merge", cl::Hidden,
186 cl::desc("Enable merging of redundant sexts when one is dominating"
187 " the other."), cl::init(true));
188
Serguei Katkovd5d8d542017-11-05 05:50:33 +0000189static cl::opt<bool> DisableComplexAddrModes(
Serguei Katkovd4df7442017-11-29 09:48:50 +0000190 "disable-complex-addr-modes", cl::Hidden, cl::init(false),
Serguei Katkovd5d8d542017-11-05 05:50:33 +0000191 cl::desc("Disables combining addressing modes with different parts "
192 "in optimizeMemoryInst."));
193
194static cl::opt<bool>
195AddrSinkNewPhis("addr-sink-new-phis", cl::Hidden, cl::init(false),
196 cl::desc("Allow creation of Phis in Address sinking."));
197
198static cl::opt<bool>
Serguei Katkov9fe05242018-01-26 06:26:56 +0000199AddrSinkNewSelects("addr-sink-new-select", cl::Hidden, cl::init(true),
Serguei Katkovd5d8d542017-11-05 05:50:33 +0000200 cl::desc("Allow creation of selects in Address sinking."));
201
John Brawn70cdb5b2017-11-24 14:10:45 +0000202static cl::opt<bool> AddrSinkCombineBaseReg(
203 "addr-sink-combine-base-reg", cl::Hidden, cl::init(true),
204 cl::desc("Allow combining of BaseReg field in Address sinking."));
205
206static cl::opt<bool> AddrSinkCombineBaseGV(
207 "addr-sink-combine-base-gv", cl::Hidden, cl::init(true),
208 cl::desc("Allow combining of BaseGV field in Address sinking."));
209
210static cl::opt<bool> AddrSinkCombineBaseOffs(
211 "addr-sink-combine-base-offs", cl::Hidden, cl::init(true),
212 cl::desc("Allow combining of BaseOffs field in Address sinking."));
213
214static cl::opt<bool> AddrSinkCombineScaledReg(
215 "addr-sink-combine-scaled-reg", cl::Hidden, cl::init(true),
216 cl::desc("Allow combining of ScaledReg field in Address sinking."));
217
Eric Christopherc1ea1492008-09-24 05:32:41 +0000218namespace {
Eugene Zelenko900b6332017-08-29 22:32:07 +0000219
220using SetOfInstrs = SmallPtrSet<Instruction *, 16>;
221using TypeIsSExt = PointerIntPair<Type *, 1, bool>;
222using InstrToOrigTy = DenseMap<Instruction *, TypeIsSExt>;
223using SExts = SmallVector<Instruction *, 16>;
224using ValueToSExts = DenseMap<Value *, SExts>;
225
Quentin Colombetfc2201e2014-12-17 01:36:17 +0000226class TypePromotionTransaction;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000227
Chris Lattner2dd09db2009-09-02 06:11:42 +0000228 class CodeGenPrepare : public FunctionPass {
Eugene Zelenko900b6332017-08-29 22:32:07 +0000229 const TargetMachine *TM = nullptr;
Igor Laevsky3be81ba2017-02-07 13:27:20 +0000230 const TargetSubtargetInfo *SubtargetInfo;
Eugene Zelenko900b6332017-08-29 22:32:07 +0000231 const TargetLowering *TLI = nullptr;
Igor Laevsky3be81ba2017-02-07 13:27:20 +0000232 const TargetRegisterInfo *TRI;
Eugene Zelenko900b6332017-08-29 22:32:07 +0000233 const TargetTransformInfo *TTI = nullptr;
Chad Rosierc24b86f2011-12-01 03:08:23 +0000234 const TargetLibraryInfo *TLInfo;
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000235 const LoopInfo *LI;
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000236 std::unique_ptr<BlockFrequencyInfo> BFI;
237 std::unique_ptr<BranchProbabilityInfo> BPI;
Nadav Rotem465834c2012-07-24 10:51:42 +0000238
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000239 /// As we scan instructions optimizing them, this is the next instruction
240 /// to optimize. Transforms that can invalidate this should update it.
Chris Lattner7a277142011-01-15 07:14:54 +0000241 BasicBlock::iterator CurInstIterator;
Evan Cheng3b3de7c2008-12-19 18:03:11 +0000242
Evan Cheng0663f232011-03-21 01:19:09 +0000243 /// Keeps track of non-local addresses that have been sunk into a block.
244 /// This allows us to avoid inserting duplicate code for blocks with
Simon Dardis230f4532017-11-24 16:45:28 +0000245 /// multiple load/stores of the same address. The usage of WeakTrackingVH
246 /// enables SunkAddrs to be treated as a cache whose entries can be
247 /// invalidated if a sunken address computation has been erased.
248 ValueMap<Value*, WeakTrackingVH> SunkAddrs;
Cameron Zwarichce3b9302011-01-06 00:42:50 +0000249
Ahmed Bougachaf3299142015-06-17 20:44:32 +0000250 /// Keeps track of all instructions inserted for the current function.
251 SetOfInstrs InsertedInsts;
Eugene Zelenko900b6332017-08-29 22:32:07 +0000252
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000253 /// Keeps track of the type of the related instruction before their
254 /// promotion for the current function.
255 InstrToOrigTy PromotedInsts;
256
Jun Bum Limdee55652017-04-03 19:20:07 +0000257 /// Keep track of instructions removed during promotion.
258 SetOfInstrs RemovedInsts;
259
260 /// Keep track of sext chains based on their initial value.
261 DenseMap<Value *, Instruction *> SeenChainsForSExt;
262
263 /// Keep track of SExt promoted.
264 ValueToSExts ValToSExtendedUses;
265
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000266 /// True if CFG is modified in any way.
Devang Patel8f606d72011-03-24 15:35:25 +0000267 bool ModifiedDT;
Evan Cheng0663f232011-03-21 01:19:09 +0000268
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000269 /// True if optimizing for size.
Benjamin Kramer047d7ca2012-05-05 12:49:22 +0000270 bool OptSize;
271
Mehdi Amini4fe37982015-07-07 18:45:17 +0000272 /// DataLayout for the Function being processed.
Eugene Zelenko900b6332017-08-29 22:32:07 +0000273 const DataLayout *DL = nullptr;
Mehdi Amini4fe37982015-07-07 18:45:17 +0000274
Chris Lattnerf2836d12007-03-31 04:06:36 +0000275 public:
Nick Lewyckye7da2d62007-05-06 13:37:16 +0000276 static char ID; // Pass identification, replacement for typeid
Eugene Zelenko900b6332017-08-29 22:32:07 +0000277
278 CodeGenPrepare() : FunctionPass(ID) {
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000279 initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
280 }
Eugene Zelenko900b6332017-08-29 22:32:07 +0000281
Craig Topper4584cd52014-03-07 09:26:03 +0000282 bool runOnFunction(Function &F) override;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000283
Mehdi Amini117296c2016-10-01 02:56:57 +0000284 StringRef getPassName() const override { return "CodeGen Prepare"; }
Evan Cheng99cafb12012-12-21 01:48:14 +0000285
Craig Topper4584cd52014-03-07 09:26:03 +0000286 void getAnalysisUsage(AnalysisUsage &AU) const override {
George Burgess IVd4febd12016-03-22 21:25:08 +0000287 // FIXME: When we can selectively preserve passes, preserve the domtree.
Dehao Chen302b69c2016-10-18 20:42:47 +0000288 AU.addRequired<ProfileSummaryInfoWrapperPass>();
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000289 AU.addRequired<TargetLibraryInfoWrapperPass>();
Chandler Carruth705b1852015-01-31 03:43:40 +0000290 AU.addRequired<TargetTransformInfoWrapperPass>();
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000291 AU.addRequired<LoopInfoWrapperPass>();
Andreas Neustifterf8cb7582009-09-16 09:26:52 +0000292 }
293
Chris Lattnerf2836d12007-03-31 04:06:36 +0000294 private:
Sanjay Patelfc580a62015-09-21 23:03:16 +0000295 bool eliminateFallThrough(Function &F);
296 bool eliminateMostlyEmptyBlocks(Function &F);
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000297 BasicBlock *findDestBlockOfMergeableEmptyBlock(BasicBlock *BB);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000298 bool canMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
299 void eliminateMostlyEmptyBlock(BasicBlock *BB);
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000300 bool isMergingEmptyBlockProfitable(BasicBlock *BB, BasicBlock *DestBB,
301 bool isPreheader);
Sanjay Patel3b8974b2017-06-08 20:00:09 +0000302 bool optimizeBlock(BasicBlock &BB, bool &ModifiedDT);
303 bool optimizeInst(Instruction *I, bool &ModifiedDT);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000304 bool optimizeMemoryInst(Instruction *I, Value *Addr,
Matt Arsenaultf72b49b2015-06-04 16:17:38 +0000305 Type *AccessTy, unsigned AS);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000306 bool optimizeInlineAsmInst(CallInst *CS);
Sanjay Patel3b8974b2017-06-08 20:00:09 +0000307 bool optimizeCallInst(CallInst *CI, bool &ModifiedDT);
Jun Bum Limdee55652017-04-03 19:20:07 +0000308 bool optimizeExt(Instruction *&I);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000309 bool optimizeExtUses(Instruction *I);
Geoff Berry5256fca2015-11-20 22:34:39 +0000310 bool optimizeLoadExt(LoadInst *I);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000311 bool optimizeSelectInst(SelectInst *SI);
312 bool optimizeShuffleVectorInst(ShuffleVectorInst *SI);
Sanjay Patel0ed9aea2015-11-02 23:22:49 +0000313 bool optimizeSwitchInst(SwitchInst *CI);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000314 bool optimizeExtractElementInst(Instruction *Inst);
315 bool dupRetToEnableTailCallOpts(BasicBlock *BB);
316 bool placeDbgValues(Function &F);
Jun Bum Lim42301012017-03-17 19:05:21 +0000317 bool canFormExtLd(const SmallVectorImpl<Instruction *> &MovedExts,
318 LoadInst *&LI, Instruction *&Inst, bool HasPromoted);
319 bool tryToPromoteExts(TypePromotionTransaction &TPT,
320 const SmallVectorImpl<Instruction *> &Exts,
321 SmallVectorImpl<Instruction *> &ProfitablyMovedExts,
322 unsigned CreatedInstsCost = 0);
Jun Bum Limdee55652017-04-03 19:20:07 +0000323 bool mergeSExts(Function &F);
324 bool performAddressTypePromotion(
325 Instruction *&Inst,
326 bool AllowPromotionWithoutCommonHeader,
327 bool HasPromoted, TypePromotionTransaction &TPT,
328 SmallVectorImpl<Instruction *> &SpeculativelyMovedExts);
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +0000329 bool splitBranchCondition(Function &F);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000330 bool simplifyOffsetableRelocate(Instruction &I);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000331 };
Eugene Zelenko900b6332017-08-29 22:32:07 +0000332
333} // end anonymous namespace
Devang Patel09f162c2007-05-01 21:15:47 +0000334
Devang Patel8c78a0b2007-05-03 01:11:54 +0000335char CodeGenPrepare::ID = 0;
Eugene Zelenko900b6332017-08-29 22:32:07 +0000336
Matthias Braun1527baa2017-05-25 21:26:32 +0000337INITIALIZE_PASS_BEGIN(CodeGenPrepare, DEBUG_TYPE,
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000338 "Optimize for code generation", false, false)
Dehao Chen302b69c2016-10-18 20:42:47 +0000339INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
Matthias Braun1527baa2017-05-25 21:26:32 +0000340INITIALIZE_PASS_END(CodeGenPrepare, DEBUG_TYPE,
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000341 "Optimize for code generation", false, false)
Chris Lattnerf2836d12007-03-31 04:06:36 +0000342
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000343FunctionPass *llvm::createCodeGenPreparePass() { return new CodeGenPrepare(); }
Chris Lattnerf2836d12007-03-31 04:06:36 +0000344
Chris Lattnerf2836d12007-03-31 04:06:36 +0000345bool CodeGenPrepare::runOnFunction(Function &F) {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000346 if (skipFunction(F))
Paul Robinson7c99ec52014-03-31 17:43:35 +0000347 return false;
348
Mehdi Amini4fe37982015-07-07 18:45:17 +0000349 DL = &F.getParent()->getDataLayout();
350
Chris Lattnerf2836d12007-03-31 04:06:36 +0000351 bool EverMadeChange = false;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000352 // Clear per function information.
Ahmed Bougachaf3299142015-06-17 20:44:32 +0000353 InsertedInsts.clear();
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000354 PromotedInsts.clear();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000355
Devang Patel8f606d72011-03-24 15:35:25 +0000356 ModifiedDT = false;
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000357 if (auto *TPC = getAnalysisIfAvailable<TargetPassConfig>()) {
358 TM = &TPC->getTM<TargetMachine>();
Igor Laevsky3be81ba2017-02-07 13:27:20 +0000359 SubtargetInfo = TM->getSubtargetImpl(F);
360 TLI = SubtargetInfo->getTargetLowering();
361 TRI = SubtargetInfo->getRegisterInfo();
362 }
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000363 TLInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Chandler Carruthfdb9c572015-02-01 12:01:35 +0000364 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000365 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Teresa Johnsona4ce3bf2017-12-20 17:53:10 +0000366 BPI.reset(new BranchProbabilityInfo(F, *LI));
367 BFI.reset(new BlockFrequencyInfo(F, *BPI, *LI));
Sanjay Patel82d91dd2015-08-11 19:39:36 +0000368 OptSize = F.optForSize();
Evan Cheng0663f232011-03-21 01:19:09 +0000369
Easwaran Raman0d55b552017-11-14 19:31:51 +0000370 ProfileSummaryInfo *PSI =
371 getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
Dehao Chen302b69c2016-10-18 20:42:47 +0000372 if (ProfileGuidedSectionPrefix) {
Teresa Johnsona4ce3bf2017-12-20 17:53:10 +0000373 if (PSI->isFunctionHotInCallGraph(&F, *BFI))
Dehao Chen302b69c2016-10-18 20:42:47 +0000374 F.setSectionPrefix(".hot");
Teresa Johnsona4ce3bf2017-12-20 17:53:10 +0000375 else if (PSI->isFunctionColdInCallGraph(&F, *BFI))
Teresa Johnson720d9b42017-05-09 01:43:24 +0000376 F.setSectionPrefix(".unlikely");
Dehao Chen302b69c2016-10-18 20:42:47 +0000377 }
378
Preston Gurdcdf540d2012-09-04 18:22:17 +0000379 /// This optimization identifies DIV instructions that can be
380 /// profitably bypassed and carried out with a shorter, faster divide.
Easwaran Raman0d55b552017-11-14 19:31:51 +0000381 if (!OptSize && !PSI->hasHugeWorkingSetSize() && TLI &&
382 TLI->isSlowDivBypassed()) {
Preston Gurd0d67f512012-10-04 21:33:40 +0000383 const DenseMap<unsigned int, unsigned int> &BypassWidths =
384 TLI->getBypassSlowDivWidths();
Eric Christopher49a7d6c2016-01-04 23:18:58 +0000385 BasicBlock* BB = &*F.begin();
386 while (BB != nullptr) {
387 // bypassSlowDivision may create new BBs, but we don't want to reapply the
388 // optimization to those blocks.
389 BasicBlock* Next = BB->getNextNode();
390 EverMadeChange |= bypassSlowDivision(BB, BypassWidths);
391 BB = Next;
392 }
Preston Gurdcdf540d2012-09-04 18:22:17 +0000393 }
394
395 // Eliminate blocks that contain only PHI nodes and an
Chris Lattnerc3748562007-04-02 01:35:34 +0000396 // unconditional branch.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000397 EverMadeChange |= eliminateMostlyEmptyBlocks(F);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000398
Devang Patel53771ba2011-08-18 00:50:51 +0000399 // llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotem465834c2012-07-24 10:51:42 +0000400 // handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patel53771ba2011-08-18 00:50:51 +0000401 // find a node corresponding to the value.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000402 EverMadeChange |= placeDbgValues(F);
Devang Patel53771ba2011-08-18 00:50:51 +0000403
Geoff Berry5d534b62017-02-21 18:53:14 +0000404 if (!DisableBranchOpts)
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +0000405 EverMadeChange |= splitBranchCondition(F);
Tim Northovercea0abb2014-03-29 08:22:29 +0000406
Michael Kuperstein13bf8a22017-02-28 00:11:34 +0000407 // Split some critical edges where one of the sources is an indirect branch,
408 // to help generate sane code for PHIs involving such edges.
Hiroshi Yamauchi9364fa32017-12-04 20:36:01 +0000409 EverMadeChange |= SplitIndirectBrCriticalEdges(F);
Michael Kuperstein13bf8a22017-02-28 00:11:34 +0000410
Chris Lattnerc3748562007-04-02 01:35:34 +0000411 bool MadeChange = true;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000412 while (MadeChange) {
413 MadeChange = false;
Jun Bum Limdee55652017-04-03 19:20:07 +0000414 SeenChainsForSExt.clear();
415 ValToSExtendedUses.clear();
416 RemovedInsts.clear();
Hans Wennborg02fbc712012-09-19 07:48:16 +0000417 for (Function::iterator I = F.begin(); I != F.end(); ) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000418 BasicBlock *BB = &*I++;
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000419 bool ModifiedDTOnIteration = false;
Sanjay Patelfc580a62015-09-21 23:03:16 +0000420 MadeChange |= optimizeBlock(*BB, ModifiedDTOnIteration);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000421
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000422 // Restart BB iteration if the dominator tree of the Function was changed
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000423 if (ModifiedDTOnIteration)
424 break;
Evan Cheng0663f232011-03-21 01:19:09 +0000425 }
Jun Bum Limdee55652017-04-03 19:20:07 +0000426 if (EnableTypePromotionMerge && !ValToSExtendedUses.empty())
427 MadeChange |= mergeSExts(F);
428
429 // Really free removed instructions during promotion.
430 for (Instruction *I : RemovedInsts)
Reid Kleckner96ab8722017-05-18 17:24:10 +0000431 I->deleteValue();
Jun Bum Limdee55652017-04-03 19:20:07 +0000432
Chris Lattnerf2836d12007-03-31 04:06:36 +0000433 EverMadeChange |= MadeChange;
434 }
Cameron Zwarichce3b9302011-01-06 00:42:50 +0000435
436 SunkAddrs.clear();
437
Cameron Zwarich338d3622011-03-11 21:52:04 +0000438 if (!DisableBranchOpts) {
439 MadeChange = false;
Bill Wendling97b93592012-03-04 10:46:01 +0000440 SmallPtrSet<BasicBlock*, 8> WorkList;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +0000441 for (BasicBlock &BB : F) {
442 SmallVector<BasicBlock *, 2> Successors(succ_begin(&BB), succ_end(&BB));
443 MadeChange |= ConstantFoldTerminator(&BB, true);
Bill Wendling97b93592012-03-04 10:46:01 +0000444 if (!MadeChange) continue;
445
446 for (SmallVectorImpl<BasicBlock*>::iterator
447 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
448 if (pred_begin(*II) == pred_end(*II))
449 WorkList.insert(*II);
450 }
451
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000452 // Delete the dead blocks and any of their dead successors.
Bill Wendlingab417b62012-12-06 00:30:20 +0000453 MadeChange |= !WorkList.empty();
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000454 while (!WorkList.empty()) {
455 BasicBlock *BB = *WorkList.begin();
456 WorkList.erase(BB);
457 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
458
459 DeleteDeadBlock(BB);
Stephen Lin837bba12013-07-15 17:55:02 +0000460
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000461 for (SmallVectorImpl<BasicBlock*>::iterator
462 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
463 if (pred_begin(*II) == pred_end(*II))
464 WorkList.insert(*II);
465 }
Cameron Zwarich338d3622011-03-11 21:52:04 +0000466
Nadav Rotem70409992012-08-14 05:19:07 +0000467 // Merge pairs of basic blocks with unconditional branches, connected by
468 // a single edge.
469 if (EverMadeChange || MadeChange)
Sanjay Patelfc580a62015-09-21 23:03:16 +0000470 MadeChange |= eliminateFallThrough(F);
Nadav Rotem70409992012-08-14 05:19:07 +0000471
Cameron Zwarich338d3622011-03-11 21:52:04 +0000472 EverMadeChange |= MadeChange;
473 }
474
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000475 if (!DisableGCOpts) {
476 SmallVector<Instruction *, 2> Statepoints;
477 for (BasicBlock &BB : F)
478 for (Instruction &I : BB)
479 if (isStatepoint(I))
480 Statepoints.push_back(&I);
481 for (auto &I : Statepoints)
482 EverMadeChange |= simplifyOffsetableRelocate(*I);
483 }
484
Chris Lattnerf2836d12007-03-31 04:06:36 +0000485 return EverMadeChange;
486}
487
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000488/// Merge basic blocks which are connected by a single edge, where one of the
489/// basic blocks has a single successor pointing to the other basic block,
490/// which has a single predecessor.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000491bool CodeGenPrepare::eliminateFallThrough(Function &F) {
Nadav Rotem70409992012-08-14 05:19:07 +0000492 bool Changed = false;
493 // Scan all of the blocks in the function, except for the entry block.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000494 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000495 BasicBlock *BB = &*I++;
Nadav Rotem70409992012-08-14 05:19:07 +0000496 // If the destination block has a single pred, then this is a trivial
497 // edge, just collapse it.
498 BasicBlock *SinglePred = BB->getSinglePredecessor();
499
Evan Cheng64a223a2012-09-28 23:58:57 +0000500 // Don't merge if BB's address is taken.
501 if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue;
Nadav Rotem70409992012-08-14 05:19:07 +0000502
503 BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
504 if (Term && !Term->isConditional()) {
505 Changed = true;
Michael Liao6e12d122012-08-21 05:55:22 +0000506 DEBUG(dbgs() << "To merge:\n"<< *SinglePred << "\n\n\n");
Nadav Rotem70409992012-08-14 05:19:07 +0000507 // Remember if SinglePred was the entry block of the function.
508 // If so, we will need to move BB back to the entry position.
509 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Quentin Colombet7bdd50d2015-03-18 23:17:28 +0000510 MergeBasicBlockIntoOnlyPred(BB, nullptr);
Nadav Rotem70409992012-08-14 05:19:07 +0000511
512 if (isEntry && BB != &BB->getParent()->getEntryBlock())
513 BB->moveBefore(&BB->getParent()->getEntryBlock());
514
515 // We have erased a block. Update the iterator.
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000516 I = BB->getIterator();
Nadav Rotem70409992012-08-14 05:19:07 +0000517 }
518 }
519 return Changed;
520}
521
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000522/// Find a destination block from BB if BB is mergeable empty block.
523BasicBlock *CodeGenPrepare::findDestBlockOfMergeableEmptyBlock(BasicBlock *BB) {
524 // If this block doesn't end with an uncond branch, ignore it.
525 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
526 if (!BI || !BI->isUnconditional())
527 return nullptr;
528
529 // If the instruction before the branch (skipping debug info) isn't a phi
530 // node, then other stuff is happening here.
531 BasicBlock::iterator BBI = BI->getIterator();
532 if (BBI != BB->begin()) {
533 --BBI;
534 while (isa<DbgInfoIntrinsic>(BBI)) {
535 if (BBI == BB->begin())
536 break;
537 --BBI;
538 }
539 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
540 return nullptr;
541 }
542
543 // Do not break infinite loops.
544 BasicBlock *DestBB = BI->getSuccessor(0);
545 if (DestBB == BB)
546 return nullptr;
547
548 if (!canMergeBlocks(BB, DestBB))
549 DestBB = nullptr;
550
551 return DestBB;
552}
553
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000554/// Eliminate blocks that contain only PHI nodes, debug info directives, and an
555/// unconditional branch. Passes before isel (e.g. LSR/loopsimplify) often split
556/// edges in ways that are non-optimal for isel. Start by eliminating these
557/// blocks so we can split them the way we want them.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000558bool CodeGenPrepare::eliminateMostlyEmptyBlocks(Function &F) {
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000559 SmallPtrSet<BasicBlock *, 16> Preheaders;
560 SmallVector<Loop *, 16> LoopList(LI->begin(), LI->end());
561 while (!LoopList.empty()) {
562 Loop *L = LoopList.pop_back_val();
563 LoopList.insert(LoopList.end(), L->begin(), L->end());
564 if (BasicBlock *Preheader = L->getLoopPreheader())
565 Preheaders.insert(Preheader);
566 }
567
Chris Lattnerc3748562007-04-02 01:35:34 +0000568 bool MadeChange = false;
569 // Note that this intentionally skips the entry block.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000570 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000571 BasicBlock *BB = &*I++;
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000572 BasicBlock *DestBB = findDestBlockOfMergeableEmptyBlock(BB);
573 if (!DestBB ||
574 !isMergingEmptyBlockProfitable(BB, DestBB, Preheaders.count(BB)))
Chris Lattnerc3748562007-04-02 01:35:34 +0000575 continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000576
Sanjay Patelfc580a62015-09-21 23:03:16 +0000577 eliminateMostlyEmptyBlock(BB);
Chris Lattnerc3748562007-04-02 01:35:34 +0000578 MadeChange = true;
579 }
580 return MadeChange;
581}
582
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000583bool CodeGenPrepare::isMergingEmptyBlockProfitable(BasicBlock *BB,
584 BasicBlock *DestBB,
585 bool isPreheader) {
586 // Do not delete loop preheaders if doing so would create a critical edge.
587 // Loop preheaders can be good locations to spill registers. If the
588 // preheader is deleted and we create a critical edge, registers may be
589 // spilled in the loop body instead.
590 if (!DisablePreheaderProtect && isPreheader &&
591 !(BB->getSinglePredecessor() &&
592 BB->getSinglePredecessor()->getSingleSuccessor()))
593 return false;
594
595 // Try to skip merging if the unique predecessor of BB is terminated by a
596 // switch or indirect branch instruction, and BB is used as an incoming block
597 // of PHIs in DestBB. In such case, merging BB and DestBB would cause ISel to
598 // add COPY instructions in the predecessor of BB instead of BB (if it is not
599 // merged). Note that the critical edge created by merging such blocks wont be
600 // split in MachineSink because the jump table is not analyzable. By keeping
601 // such empty block (BB), ISel will place COPY instructions in BB, not in the
602 // predecessor of BB.
603 BasicBlock *Pred = BB->getUniquePredecessor();
604 if (!Pred ||
605 !(isa<SwitchInst>(Pred->getTerminator()) ||
606 isa<IndirectBrInst>(Pred->getTerminator())))
607 return true;
608
609 if (BB->getTerminator() != BB->getFirstNonPHI())
610 return true;
611
612 // We use a simple cost heuristic which determine skipping merging is
613 // profitable if the cost of skipping merging is less than the cost of
614 // merging : Cost(skipping merging) < Cost(merging BB), where the
615 // Cost(skipping merging) is Freq(BB) * (Cost(Copy) + Cost(Branch)), and
616 // the Cost(merging BB) is Freq(Pred) * Cost(Copy).
617 // Assuming Cost(Copy) == Cost(Branch), we could simplify it to :
618 // Freq(Pred) / Freq(BB) > 2.
619 // Note that if there are multiple empty blocks sharing the same incoming
620 // value for the PHIs in the DestBB, we consider them together. In such
621 // case, Cost(merging BB) will be the sum of their frequencies.
622
623 if (!isa<PHINode>(DestBB->begin()))
624 return true;
625
626 SmallPtrSet<BasicBlock *, 16> SameIncomingValueBBs;
627
628 // Find all other incoming blocks from which incoming values of all PHIs in
629 // DestBB are the same as the ones from BB.
630 for (pred_iterator PI = pred_begin(DestBB), E = pred_end(DestBB); PI != E;
631 ++PI) {
632 BasicBlock *DestBBPred = *PI;
633 if (DestBBPred == BB)
634 continue;
635
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000636 if (llvm::all_of(DestBB->phis(), [&](const PHINode &DestPN) {
637 return DestPN.getIncomingValueForBlock(BB) ==
638 DestPN.getIncomingValueForBlock(DestBBPred);
639 }))
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000640 SameIncomingValueBBs.insert(DestBBPred);
641 }
642
643 // See if all BB's incoming values are same as the value from Pred. In this
644 // case, no reason to skip merging because COPYs are expected to be place in
645 // Pred already.
646 if (SameIncomingValueBBs.count(Pred))
647 return true;
648
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000649 BlockFrequency PredFreq = BFI->getBlockFreq(Pred);
650 BlockFrequency BBFreq = BFI->getBlockFreq(BB);
651
652 for (auto SameValueBB : SameIncomingValueBBs)
653 if (SameValueBB->getUniquePredecessor() == Pred &&
654 DestBB == findDestBlockOfMergeableEmptyBlock(SameValueBB))
655 BBFreq += BFI->getBlockFreq(SameValueBB);
656
657 return PredFreq.getFrequency() <=
658 BBFreq.getFrequency() * FreqRatioToSkipMerge;
659}
660
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000661/// Return true if we can merge BB into DestBB if there is a single
662/// unconditional branch between them, and BB contains no other non-phi
Chris Lattnerc3748562007-04-02 01:35:34 +0000663/// instructions.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000664bool CodeGenPrepare::canMergeBlocks(const BasicBlock *BB,
Chris Lattnerc3748562007-04-02 01:35:34 +0000665 const BasicBlock *DestBB) const {
666 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
667 // the successor. If there are more complex condition (e.g. preheaders),
668 // don't mess around with them.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000669 for (const PHINode &PN : BB->phis()) {
670 for (const User *U : PN.users()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000671 const Instruction *UI = cast<Instruction>(U);
672 if (UI->getParent() != DestBB || !isa<PHINode>(UI))
Chris Lattnerc3748562007-04-02 01:35:34 +0000673 return false;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000674 // If User is inside DestBB block and it is a PHINode then check
675 // incoming value. If incoming value is not from BB then this is
Devang Pateld3208522007-04-25 00:37:04 +0000676 // a complex condition (e.g. preheaders) we want to avoid here.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000677 if (UI->getParent() == DestBB) {
678 if (const PHINode *UPN = dyn_cast<PHINode>(UI))
Devang Pateld3208522007-04-25 00:37:04 +0000679 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
680 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
681 if (Insn && Insn->getParent() == BB &&
682 Insn->getParent() != UPN->getIncomingBlock(I))
683 return false;
684 }
685 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000686 }
687 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000688
Chris Lattnerc3748562007-04-02 01:35:34 +0000689 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
690 // and DestBB may have conflicting incoming values for the block. If so, we
691 // can't merge the block.
692 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
693 if (!DestBBPN) return true; // no conflict.
Eric Christopherc1ea1492008-09-24 05:32:41 +0000694
Chris Lattnerc3748562007-04-02 01:35:34 +0000695 // Collect the preds of BB.
Chris Lattner8201a9b2007-11-06 22:07:40 +0000696 SmallPtrSet<const BasicBlock*, 16> BBPreds;
Chris Lattnerc3748562007-04-02 01:35:34 +0000697 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
698 // It is faster to get preds from a PHI than with pred_iterator.
699 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
700 BBPreds.insert(BBPN->getIncomingBlock(i));
701 } else {
702 BBPreds.insert(pred_begin(BB), pred_end(BB));
703 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000704
Chris Lattnerc3748562007-04-02 01:35:34 +0000705 // Walk the preds of DestBB.
706 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
707 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
708 if (BBPreds.count(Pred)) { // Common predecessor?
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000709 for (const PHINode &PN : DestBB->phis()) {
710 const Value *V1 = PN.getIncomingValueForBlock(Pred);
711 const Value *V2 = PN.getIncomingValueForBlock(BB);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000712
Chris Lattnerc3748562007-04-02 01:35:34 +0000713 // If V2 is a phi node in BB, look up what the mapped value will be.
714 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
715 if (V2PN->getParent() == BB)
716 V2 = V2PN->getIncomingValueForBlock(Pred);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000717
Chris Lattnerc3748562007-04-02 01:35:34 +0000718 // If there is a conflict, bail out.
719 if (V1 != V2) return false;
720 }
721 }
722 }
723
724 return true;
725}
726
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000727/// Eliminate a basic block that has only phi's and an unconditional branch in
728/// it.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000729void CodeGenPrepare::eliminateMostlyEmptyBlock(BasicBlock *BB) {
Chris Lattnerc3748562007-04-02 01:35:34 +0000730 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
731 BasicBlock *DestBB = BI->getSuccessor(0);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000732
David Greene74e2d492010-01-05 01:27:11 +0000733 DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000734
Chris Lattnerc3748562007-04-02 01:35:34 +0000735 // If the destination block has a single pred, then this is a trivial edge,
736 // just collapse it.
Chris Lattner4059f432008-11-27 19:29:14 +0000737 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
Chris Lattner8a172da2008-11-28 19:54:49 +0000738 if (SinglePred != DestBB) {
739 // Remember if SinglePred was the entry block of the function. If so, we
740 // will need to move BB back to the entry position.
741 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Balaram Makam32bcb5d2017-10-27 00:35:18 +0000742 MergeBasicBlockIntoOnlyPred(DestBB, nullptr);
Chris Lattner4059f432008-11-27 19:29:14 +0000743
Chris Lattner8a172da2008-11-28 19:54:49 +0000744 if (isEntry && BB != &BB->getParent()->getEntryBlock())
745 BB->moveBefore(&BB->getParent()->getEntryBlock());
Nadav Rotem465834c2012-07-24 10:51:42 +0000746
David Greene74e2d492010-01-05 01:27:11 +0000747 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattner8a172da2008-11-28 19:54:49 +0000748 return;
749 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000750 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000751
Chris Lattnerc3748562007-04-02 01:35:34 +0000752 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
753 // to handle the new incoming edges it is about to have.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000754 for (PHINode &PN : DestBB->phis()) {
Chris Lattnerc3748562007-04-02 01:35:34 +0000755 // Remove the incoming value for BB, and remember it.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000756 Value *InVal = PN.removeIncomingValue(BB, false);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000757
Chris Lattnerc3748562007-04-02 01:35:34 +0000758 // Two options: either the InVal is a phi node defined in BB or it is some
759 // value that dominates BB.
760 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
761 if (InValPhi && InValPhi->getParent() == BB) {
762 // Add all of the input values of the input PHI as inputs of this phi.
763 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000764 PN.addIncoming(InValPhi->getIncomingValue(i),
765 InValPhi->getIncomingBlock(i));
Chris Lattnerc3748562007-04-02 01:35:34 +0000766 } else {
767 // Otherwise, add one instance of the dominating value for each edge that
768 // we will be adding.
769 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
770 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000771 PN.addIncoming(InVal, BBPN->getIncomingBlock(i));
Chris Lattnerc3748562007-04-02 01:35:34 +0000772 } else {
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000773 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000774 PN.addIncoming(InVal, *PI);
Chris Lattnerc3748562007-04-02 01:35:34 +0000775 }
776 }
777 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000778
Chris Lattnerc3748562007-04-02 01:35:34 +0000779 // The PHIs are now updated, change everything that refers to BB to use
780 // DestBB and remove BB.
781 BB->replaceAllUsesWith(DestBB);
782 BB->eraseFromParent();
Cameron Zwarichced753f2011-01-05 17:27:27 +0000783 ++NumBlocksElim;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000784
David Greene74e2d492010-01-05 01:27:11 +0000785 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerc3748562007-04-02 01:35:34 +0000786}
787
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000788// Computes a map of base pointer relocation instructions to corresponding
789// derived pointer relocation instructions given a vector of all relocate calls
790static void computeBaseDerivedRelocateMap(
Manuel Jacob83eefa62016-01-05 04:03:00 +0000791 const SmallVectorImpl<GCRelocateInst *> &AllRelocateCalls,
792 DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>>
793 &RelocateInstMap) {
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000794 // Collect information in two maps: one primarily for locating the base object
795 // while filling the second map; the second map is the final structure holding
796 // a mapping between Base and corresponding Derived relocate calls
Manuel Jacob83eefa62016-01-05 04:03:00 +0000797 DenseMap<std::pair<unsigned, unsigned>, GCRelocateInst *> RelocateIdxMap;
798 for (auto *ThisRelocate : AllRelocateCalls) {
799 auto K = std::make_pair(ThisRelocate->getBasePtrIndex(),
800 ThisRelocate->getDerivedPtrIndex());
801 RelocateIdxMap.insert(std::make_pair(K, ThisRelocate));
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000802 }
803 for (auto &Item : RelocateIdxMap) {
804 std::pair<unsigned, unsigned> Key = Item.first;
805 if (Key.first == Key.second)
806 // Base relocation: nothing to insert
807 continue;
808
Manuel Jacob83eefa62016-01-05 04:03:00 +0000809 GCRelocateInst *I = Item.second;
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000810 auto BaseKey = std::make_pair(Key.first, Key.first);
Sanjoy Dasb8186762015-02-27 02:24:16 +0000811
812 // We're iterating over RelocateIdxMap so we cannot modify it.
813 auto MaybeBase = RelocateIdxMap.find(BaseKey);
814 if (MaybeBase == RelocateIdxMap.end())
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000815 // TODO: We might want to insert a new base object relocate and gep off
816 // that, if there are enough derived object relocates.
817 continue;
Sanjoy Dasb8186762015-02-27 02:24:16 +0000818
819 RelocateInstMap[MaybeBase->second].push_back(I);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000820 }
821}
822
823// Accepts a GEP and extracts the operands into a vector provided they're all
824// small integer constants
825static bool getGEPSmallConstantIntOffsetV(GetElementPtrInst *GEP,
826 SmallVectorImpl<Value *> &OffsetV) {
827 for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
828 // Only accept small constant integer operands
829 auto Op = dyn_cast<ConstantInt>(GEP->getOperand(i));
830 if (!Op || Op->getZExtValue() > 20)
831 return false;
832 }
833
834 for (unsigned i = 1; i < GEP->getNumOperands(); i++)
835 OffsetV.push_back(GEP->getOperand(i));
836 return true;
837}
838
839// Takes a RelocatedBase (base pointer relocation instruction) and Targets to
840// replace, computes a replacement, and affects it.
841static bool
Manuel Jacob83eefa62016-01-05 04:03:00 +0000842simplifyRelocatesOffABase(GCRelocateInst *RelocatedBase,
843 const SmallVectorImpl<GCRelocateInst *> &Targets) {
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000844 bool MadeChange = false;
Serguei Katkov9e5604d2017-08-17 05:48:30 +0000845 // We must ensure the relocation of derived pointer is defined after
846 // relocation of base pointer. If we find a relocation corresponding to base
847 // defined earlier than relocation of base then we move relocation of base
848 // right before found relocation. We consider only relocation in the same
849 // basic block as relocation of base. Relocations from other basic block will
850 // be skipped by optimization and we do not care about them.
851 for (auto R = RelocatedBase->getParent()->getFirstInsertionPt();
852 &*R != RelocatedBase; ++R)
853 if (auto RI = dyn_cast<GCRelocateInst>(R))
854 if (RI->getStatepoint() == RelocatedBase->getStatepoint())
855 if (RI->getBasePtrIndex() == RelocatedBase->getBasePtrIndex()) {
856 RelocatedBase->moveBefore(RI);
857 break;
858 }
859
Manuel Jacob83eefa62016-01-05 04:03:00 +0000860 for (GCRelocateInst *ToReplace : Targets) {
861 assert(ToReplace->getBasePtrIndex() == RelocatedBase->getBasePtrIndex() &&
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000862 "Not relocating a derived object of the original base object");
Manuel Jacob83eefa62016-01-05 04:03:00 +0000863 if (ToReplace->getBasePtrIndex() == ToReplace->getDerivedPtrIndex()) {
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000864 // A duplicate relocate call. TODO: coalesce duplicates.
865 continue;
866 }
867
Igor Laevskyf637b4a2015-11-03 18:37:40 +0000868 if (RelocatedBase->getParent() != ToReplace->getParent()) {
869 // Base and derived relocates are in different basic blocks.
870 // In this case transform is only valid when base dominates derived
871 // relocate. However it would be too expensive to check dominance
872 // for each such relocate, so we skip the whole transformation.
873 continue;
874 }
875
Manuel Jacob83eefa62016-01-05 04:03:00 +0000876 Value *Base = ToReplace->getBasePtr();
877 auto Derived = dyn_cast<GetElementPtrInst>(ToReplace->getDerivedPtr());
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000878 if (!Derived || Derived->getPointerOperand() != Base)
879 continue;
880
881 SmallVector<Value *, 2> OffsetV;
882 if (!getGEPSmallConstantIntOffsetV(Derived, OffsetV))
883 continue;
884
885 // Create a Builder and replace the target callsite with a gep
Sanjay Patel545a4562016-01-20 18:59:16 +0000886 assert(RelocatedBase->getNextNode() &&
887 "Should always have one since it's not a terminator");
Sanjoy Das3d705e32015-05-11 23:47:30 +0000888
889 // Insert after RelocatedBase
890 IRBuilder<> Builder(RelocatedBase->getNextNode());
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000891 Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc());
Sanjoy Das89c54912015-05-11 18:49:34 +0000892
893 // If gc_relocate does not match the actual type, cast it to the right type.
894 // In theory, there must be a bitcast after gc_relocate if the type does not
895 // match, and we should reuse it to get the derived pointer. But it could be
896 // cases like this:
897 // bb1:
898 // ...
899 // %g1 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
900 // br label %merge
901 //
902 // bb2:
903 // ...
904 // %g2 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
905 // br label %merge
906 //
907 // merge:
908 // %p1 = phi i8 addrspace(1)* [ %g1, %bb1 ], [ %g2, %bb2 ]
909 // %cast = bitcast i8 addrspace(1)* %p1 in to i32 addrspace(1)*
910 //
911 // In this case, we can not find the bitcast any more. So we insert a new bitcast
912 // no matter there is already one or not. In this way, we can handle all cases, and
913 // the extra bitcast should be optimized away in later passes.
Manuel Jacob5b90b142015-12-19 18:38:42 +0000914 Value *ActualRelocatedBase = RelocatedBase;
Sanjoy Das89c54912015-05-11 18:49:34 +0000915 if (RelocatedBase->getType() != Base->getType()) {
916 ActualRelocatedBase =
Manuel Jacob5b90b142015-12-19 18:38:42 +0000917 Builder.CreateBitCast(RelocatedBase, Base->getType());
Sanjoy Das89c54912015-05-11 18:49:34 +0000918 }
David Blaikie68d535c2015-03-24 22:38:16 +0000919 Value *Replacement = Builder.CreateGEP(
Sanjoy Das89c54912015-05-11 18:49:34 +0000920 Derived->getSourceElementType(), ActualRelocatedBase, makeArrayRef(OffsetV));
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000921 Replacement->takeName(ToReplace);
Sanjoy Das89c54912015-05-11 18:49:34 +0000922 // If the newly generated derived pointer's type does not match the original derived
923 // pointer's type, cast the new derived pointer to match it. Same reasoning as above.
Manuel Jacob5b90b142015-12-19 18:38:42 +0000924 Value *ActualReplacement = Replacement;
925 if (Replacement->getType() != ToReplace->getType()) {
Sanjoy Das89c54912015-05-11 18:49:34 +0000926 ActualReplacement =
Manuel Jacob5b90b142015-12-19 18:38:42 +0000927 Builder.CreateBitCast(Replacement, ToReplace->getType());
Sanjoy Das89c54912015-05-11 18:49:34 +0000928 }
929 ToReplace->replaceAllUsesWith(ActualReplacement);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000930 ToReplace->eraseFromParent();
931
932 MadeChange = true;
933 }
934 return MadeChange;
935}
936
937// Turns this:
938//
939// %base = ...
940// %ptr = gep %base + 15
941// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
942// %base' = relocate(%tok, i32 4, i32 4)
943// %ptr' = relocate(%tok, i32 4, i32 5)
944// %val = load %ptr'
945//
946// into this:
947//
948// %base = ...
949// %ptr = gep %base + 15
950// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
951// %base' = gc.relocate(%tok, i32 4, i32 4)
952// %ptr' = gep %base' + 15
953// %val = load %ptr'
954bool CodeGenPrepare::simplifyOffsetableRelocate(Instruction &I) {
955 bool MadeChange = false;
Manuel Jacob83eefa62016-01-05 04:03:00 +0000956 SmallVector<GCRelocateInst *, 2> AllRelocateCalls;
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000957
958 for (auto *U : I.users())
Manuel Jacob83eefa62016-01-05 04:03:00 +0000959 if (GCRelocateInst *Relocate = dyn_cast<GCRelocateInst>(U))
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000960 // Collect all the relocate calls associated with a statepoint
Manuel Jacob83eefa62016-01-05 04:03:00 +0000961 AllRelocateCalls.push_back(Relocate);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000962
963 // We need atleast one base pointer relocation + one derived pointer
964 // relocation to mangle
965 if (AllRelocateCalls.size() < 2)
966 return false;
967
968 // RelocateInstMap is a mapping from the base relocate instruction to the
969 // corresponding derived relocate instructions
Manuel Jacob83eefa62016-01-05 04:03:00 +0000970 DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>> RelocateInstMap;
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000971 computeBaseDerivedRelocateMap(AllRelocateCalls, RelocateInstMap);
972 if (RelocateInstMap.empty())
973 return false;
974
975 for (auto &Item : RelocateInstMap)
976 // Item.first is the RelocatedBase to offset against
977 // Item.second is the vector of Targets to replace
978 MadeChange = simplifyRelocatesOffABase(Item.first, Item.second);
979 return MadeChange;
980}
981
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000982/// SinkCast - Sink the specified cast instruction into its user blocks
983static bool SinkCast(CastInst *CI) {
Chris Lattnerf2836d12007-03-31 04:06:36 +0000984 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000985
Chris Lattnerf2836d12007-03-31 04:06:36 +0000986 /// InsertedCasts - Only insert a cast in each block once.
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000987 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000988
Chris Lattnerf2836d12007-03-31 04:06:36 +0000989 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000990 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
Chris Lattnerf2836d12007-03-31 04:06:36 +0000991 UI != E; ) {
992 Use &TheUse = UI.getUse();
993 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000994
Chris Lattnerf2836d12007-03-31 04:06:36 +0000995 // Figure out which BB this cast is used in. For PHI's this is the
996 // appropriate predecessor block.
997 BasicBlock *UserBB = User->getParent();
998 if (PHINode *PN = dyn_cast<PHINode>(User)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000999 UserBB = PN->getIncomingBlock(TheUse);
Chris Lattnerf2836d12007-03-31 04:06:36 +00001000 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001001
Chris Lattnerf2836d12007-03-31 04:06:36 +00001002 // Preincrement use iterator so we don't invalidate it.
1003 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001004
David Majnemer0c80e2e2016-04-27 19:36:38 +00001005 // The first insertion point of a block containing an EH pad is after the
1006 // pad. If the pad is the user, we cannot sink the cast past the pad.
1007 if (User->isEHPad())
1008 continue;
1009
Andrew Kaylord0430e82015-11-23 19:16:15 +00001010 // If the block selected to receive the cast is an EH pad that does not
1011 // allow non-PHI instructions before the terminator, we can't sink the
1012 // cast.
1013 if (UserBB->getTerminator()->isEHPad())
1014 continue;
1015
Chris Lattnerf2836d12007-03-31 04:06:36 +00001016 // If this user is in the same block as the cast, don't change the cast.
1017 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001018
Chris Lattnerf2836d12007-03-31 04:06:36 +00001019 // If we have already inserted a cast into this block, use it.
1020 CastInst *&InsertedCast = InsertedCasts[UserBB];
1021
1022 if (!InsertedCast) {
Bill Wendling8ddfc092011-08-16 20:45:24 +00001023 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001024 assert(InsertPt != UserBB->end());
1025 InsertedCast = CastInst::Create(CI->getOpcode(), CI->getOperand(0),
1026 CI->getType(), "", &*InsertPt);
Chris Lattnerf2836d12007-03-31 04:06:36 +00001027 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001028
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001029 // Replace a use of the cast with a use of the new cast.
Chris Lattnerf2836d12007-03-31 04:06:36 +00001030 TheUse = InsertedCast;
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +00001031 MadeChange = true;
Cameron Zwarichced753f2011-01-05 17:27:27 +00001032 ++NumCastUses;
Chris Lattnerf2836d12007-03-31 04:06:36 +00001033 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001034
Chris Lattnerf2836d12007-03-31 04:06:36 +00001035 // If we removed all uses, nuke the cast.
Duncan Sandsafa84da42008-01-20 16:51:46 +00001036 if (CI->use_empty()) {
Adrian Prantl261ac8b2017-11-03 21:55:03 +00001037 salvageDebugInfo(*CI);
Chris Lattnerf2836d12007-03-31 04:06:36 +00001038 CI->eraseFromParent();
Duncan Sandsafa84da42008-01-20 16:51:46 +00001039 MadeChange = true;
1040 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001041
Chris Lattnerf2836d12007-03-31 04:06:36 +00001042 return MadeChange;
1043}
1044
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001045/// If the specified cast instruction is a noop copy (e.g. it's casting from
1046/// one pointer type to another, i32->i8 on PPC), sink it into user blocks to
1047/// reduce the number of virtual registers that must be created and coalesced.
Manuel Jacoba7c48f92014-03-13 13:36:25 +00001048///
1049/// Return true if any changes are made.
Mehdi Amini44ede332015-07-09 02:09:04 +00001050static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI,
1051 const DataLayout &DL) {
Justin Lebar3e50a5b2016-11-21 22:49:15 +00001052 // Sink only "cheap" (or nop) address-space casts. This is a weaker condition
1053 // than sinking only nop casts, but is helpful on some platforms.
1054 if (auto *ASC = dyn_cast<AddrSpaceCastInst>(CI)) {
1055 if (!TLI.isCheapAddrSpaceCast(ASC->getSrcAddressSpace(),
1056 ASC->getDestAddressSpace()))
1057 return false;
1058 }
1059
Manuel Jacoba7c48f92014-03-13 13:36:25 +00001060 // If this is a noop copy,
Mehdi Amini44ede332015-07-09 02:09:04 +00001061 EVT SrcVT = TLI.getValueType(DL, CI->getOperand(0)->getType());
1062 EVT DstVT = TLI.getValueType(DL, CI->getType());
Manuel Jacoba7c48f92014-03-13 13:36:25 +00001063
1064 // This is an fp<->int conversion?
1065 if (SrcVT.isInteger() != DstVT.isInteger())
1066 return false;
1067
1068 // If this is an extension, it will be a zero or sign extension, which
1069 // isn't a noop.
1070 if (SrcVT.bitsLT(DstVT)) return false;
1071
1072 // If these values will be promoted, find out what they will be promoted
1073 // to. This helps us consider truncates on PPC as noop copies when they
1074 // are.
1075 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
1076 TargetLowering::TypePromoteInteger)
1077 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
1078 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
1079 TargetLowering::TypePromoteInteger)
1080 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
1081
1082 // If, after promotion, these are the same types, this is a noop copy.
1083 if (SrcVT != DstVT)
1084 return false;
1085
1086 return SinkCast(CI);
1087}
1088
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001089/// Try to combine CI into a call to the llvm.uadd.with.overflow intrinsic if
1090/// possible.
Sanjoy Dasb6c59142015-04-10 21:07:09 +00001091///
1092/// Return true if any changes were made.
1093static bool CombineUAddWithOverflow(CmpInst *CI) {
1094 Value *A, *B;
1095 Instruction *AddI;
1096 if (!match(CI,
1097 m_UAddWithOverflow(m_Value(A), m_Value(B), m_Instruction(AddI))))
1098 return false;
1099
1100 Type *Ty = AddI->getType();
1101 if (!isa<IntegerType>(Ty))
1102 return false;
1103
1104 // We don't want to move around uses of condition values this late, so we we
1105 // check if it is legal to create the call to the intrinsic in the basic
1106 // block containing the icmp:
1107
1108 if (AddI->getParent() != CI->getParent() && !AddI->hasOneUse())
1109 return false;
1110
1111#ifndef NDEBUG
1112 // Someday m_UAddWithOverflow may get smarter, but this is a safe assumption
1113 // for now:
1114 if (AddI->hasOneUse())
1115 assert(*AddI->user_begin() == CI && "expected!");
1116#endif
1117
Sanjay Patelaf674fb2015-12-14 17:24:23 +00001118 Module *M = CI->getModule();
Sanjoy Dasb6c59142015-04-10 21:07:09 +00001119 Value *F = Intrinsic::getDeclaration(M, Intrinsic::uadd_with_overflow, Ty);
1120
1121 auto *InsertPt = AddI->hasOneUse() ? CI : AddI;
1122
1123 auto *UAddWithOverflow =
1124 CallInst::Create(F, {A, B}, "uadd.overflow", InsertPt);
1125 auto *UAdd = ExtractValueInst::Create(UAddWithOverflow, 0, "uadd", InsertPt);
1126 auto *Overflow =
1127 ExtractValueInst::Create(UAddWithOverflow, 1, "overflow", InsertPt);
1128
1129 CI->replaceAllUsesWith(Overflow);
1130 AddI->replaceAllUsesWith(UAdd);
1131 CI->eraseFromParent();
1132 AddI->eraseFromParent();
1133 return true;
1134}
1135
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001136/// Sink the given CmpInst into user blocks to reduce the number of virtual
1137/// registers that must be created and coalesced. This is a clear win except on
1138/// targets with multiple condition code registers (PowerPC), where it might
1139/// lose; some adjustment may be wanted there.
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001140///
1141/// Return true if any changes are made.
Peter Zotov8efe38a2016-04-03 19:32:13 +00001142static bool SinkCmpExpression(CmpInst *CI, const TargetLowering *TLI) {
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001143 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +00001144
Peter Zotov0b6d7bc2016-04-03 16:36:17 +00001145 // Avoid sinking soft-FP comparisons, since this can move them into a loop.
Peter Zotov8efe38a2016-04-03 19:32:13 +00001146 if (TLI && TLI->useSoftFloat() && isa<FCmpInst>(CI))
Peter Zotov0b6d7bc2016-04-03 16:36:17 +00001147 return false;
1148
1149 // Only insert a cmp in each block once.
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001150 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001151
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001152 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001153 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001154 UI != E; ) {
1155 Use &TheUse = UI.getUse();
1156 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +00001157
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001158 // Preincrement use iterator so we don't invalidate it.
1159 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001160
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001161 // Don't bother for PHI nodes.
1162 if (isa<PHINode>(User))
1163 continue;
1164
1165 // Figure out which BB this cmp is used in.
1166 BasicBlock *UserBB = User->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +00001167
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001168 // If this user is in the same block as the cmp, don't change the cmp.
1169 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001170
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001171 // If we have already inserted a cmp into this block, use it.
1172 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
1173
1174 if (!InsertedCmp) {
Bill Wendling8ddfc092011-08-16 20:45:24 +00001175 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001176 assert(InsertPt != UserBB->end());
Eric Christopherc1ea1492008-09-24 05:32:41 +00001177 InsertedCmp =
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001178 CmpInst::Create(CI->getOpcode(), CI->getPredicate(),
1179 CI->getOperand(0), CI->getOperand(1), "", &*InsertPt);
Wolfgang Piebe51bede2016-10-06 21:43:45 +00001180 // Propagate the debug info.
1181 InsertedCmp->setDebugLoc(CI->getDebugLoc());
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001182 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001183
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001184 // Replace a use of the cmp with a use of the new cmp.
1185 TheUse = InsertedCmp;
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +00001186 MadeChange = true;
Cameron Zwarichced753f2011-01-05 17:27:27 +00001187 ++NumCmpUses;
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001188 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001189
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001190 // If we removed all uses, nuke the cmp.
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +00001191 if (CI->use_empty()) {
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001192 CI->eraseFromParent();
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +00001193 MadeChange = true;
1194 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001195
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001196 return MadeChange;
1197}
1198
Peter Zotovf87e5502016-04-03 17:11:53 +00001199static bool OptimizeCmpExpression(CmpInst *CI, const TargetLowering *TLI) {
Peter Zotov8efe38a2016-04-03 19:32:13 +00001200 if (SinkCmpExpression(CI, TLI))
Sanjoy Dasb6c59142015-04-10 21:07:09 +00001201 return true;
1202
1203 if (CombineUAddWithOverflow(CI))
1204 return true;
1205
1206 return false;
1207}
1208
Geoff Berry5d534b62017-02-21 18:53:14 +00001209/// Duplicate and sink the given 'and' instruction into user blocks where it is
1210/// used in a compare to allow isel to generate better code for targets where
1211/// this operation can be combined.
1212///
1213/// Return true if any changes are made.
1214static bool sinkAndCmp0Expression(Instruction *AndI,
1215 const TargetLowering &TLI,
1216 SetOfInstrs &InsertedInsts) {
1217 // Double-check that we're not trying to optimize an instruction that was
1218 // already optimized by some other part of this pass.
1219 assert(!InsertedInsts.count(AndI) &&
1220 "Attempting to optimize already optimized and instruction");
1221 (void) InsertedInsts;
1222
1223 // Nothing to do for single use in same basic block.
1224 if (AndI->hasOneUse() &&
1225 AndI->getParent() == cast<Instruction>(*AndI->user_begin())->getParent())
1226 return false;
1227
1228 // Try to avoid cases where sinking/duplicating is likely to increase register
1229 // pressure.
1230 if (!isa<ConstantInt>(AndI->getOperand(0)) &&
1231 !isa<ConstantInt>(AndI->getOperand(1)) &&
1232 AndI->getOperand(0)->hasOneUse() && AndI->getOperand(1)->hasOneUse())
1233 return false;
1234
1235 for (auto *U : AndI->users()) {
1236 Instruction *User = cast<Instruction>(U);
1237
1238 // Only sink for and mask feeding icmp with 0.
1239 if (!isa<ICmpInst>(User))
1240 return false;
1241
1242 auto *CmpC = dyn_cast<ConstantInt>(User->getOperand(1));
1243 if (!CmpC || !CmpC->isZero())
1244 return false;
1245 }
1246
1247 if (!TLI.isMaskAndCmp0FoldingBeneficial(*AndI))
1248 return false;
1249
1250 DEBUG(dbgs() << "found 'and' feeding only icmp 0;\n");
1251 DEBUG(AndI->getParent()->dump());
1252
1253 // Push the 'and' into the same block as the icmp 0. There should only be
1254 // one (icmp (and, 0)) in each block, since CSE/GVN should have removed any
1255 // others, so we don't need to keep track of which BBs we insert into.
1256 for (Value::user_iterator UI = AndI->user_begin(), E = AndI->user_end();
1257 UI != E; ) {
1258 Use &TheUse = UI.getUse();
1259 Instruction *User = cast<Instruction>(*UI);
1260
1261 // Preincrement use iterator so we don't invalidate it.
1262 ++UI;
1263
1264 DEBUG(dbgs() << "sinking 'and' use: " << *User << "\n");
1265
1266 // Keep the 'and' in the same place if the use is already in the same block.
1267 Instruction *InsertPt =
1268 User->getParent() == AndI->getParent() ? AndI : User;
1269 Instruction *InsertedAnd =
1270 BinaryOperator::Create(Instruction::And, AndI->getOperand(0),
1271 AndI->getOperand(1), "", InsertPt);
1272 // Propagate the debug info.
1273 InsertedAnd->setDebugLoc(AndI->getDebugLoc());
1274
1275 // Replace a use of the 'and' with a use of the new 'and'.
1276 TheUse = InsertedAnd;
1277 ++NumAndUses;
1278 DEBUG(User->getParent()->dump());
1279 }
1280
1281 // We removed all uses, nuke the and.
1282 AndI->eraseFromParent();
1283 return true;
1284}
1285
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001286/// Check if the candidates could be combined with a shift instruction, which
1287/// includes:
Yi Jiangd069f632014-04-21 19:34:27 +00001288/// 1. Truncate instruction
1289/// 2. And instruction and the imm is a mask of the low bits:
1290/// imm & (imm+1) == 0
Benjamin Kramer322053c2014-04-27 14:54:59 +00001291static bool isExtractBitsCandidateUse(Instruction *User) {
Yi Jiangd069f632014-04-21 19:34:27 +00001292 if (!isa<TruncInst>(User)) {
1293 if (User->getOpcode() != Instruction::And ||
1294 !isa<ConstantInt>(User->getOperand(1)))
1295 return false;
1296
Quentin Colombetd4f44692014-04-22 01:20:34 +00001297 const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue();
Yi Jiangd069f632014-04-21 19:34:27 +00001298
Quentin Colombetd4f44692014-04-22 01:20:34 +00001299 if ((Cimm & (Cimm + 1)).getBoolValue())
Yi Jiangd069f632014-04-21 19:34:27 +00001300 return false;
1301 }
1302 return true;
1303}
1304
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001305/// Sink both shift and truncate instruction to the use of truncate's BB.
Benjamin Kramer322053c2014-04-27 14:54:59 +00001306static bool
Yi Jiangd069f632014-04-21 19:34:27 +00001307SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI,
1308 DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts,
Mehdi Amini44ede332015-07-09 02:09:04 +00001309 const TargetLowering &TLI, const DataLayout &DL) {
Yi Jiangd069f632014-04-21 19:34:27 +00001310 BasicBlock *UserBB = User->getParent();
1311 DenseMap<BasicBlock *, CastInst *> InsertedTruncs;
1312 TruncInst *TruncI = dyn_cast<TruncInst>(User);
1313 bool MadeChange = false;
1314
1315 for (Value::user_iterator TruncUI = TruncI->user_begin(),
1316 TruncE = TruncI->user_end();
1317 TruncUI != TruncE;) {
1318
1319 Use &TruncTheUse = TruncUI.getUse();
1320 Instruction *TruncUser = cast<Instruction>(*TruncUI);
1321 // Preincrement use iterator so we don't invalidate it.
1322
1323 ++TruncUI;
1324
1325 int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode());
1326 if (!ISDOpcode)
1327 continue;
1328
Tim Northovere2239ff2014-07-29 10:20:22 +00001329 // If the use is actually a legal node, there will not be an
1330 // implicit truncate.
1331 // FIXME: always querying the result type is just an
1332 // approximation; some nodes' legality is determined by the
1333 // operand or other means. There's no good way to find out though.
Ahmed Bougacha0788d492014-11-12 22:16:55 +00001334 if (TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00001335 ISDOpcode, TLI.getValueType(DL, TruncUser->getType(), true)))
Yi Jiangd069f632014-04-21 19:34:27 +00001336 continue;
1337
1338 // Don't bother for PHI nodes.
1339 if (isa<PHINode>(TruncUser))
1340 continue;
1341
1342 BasicBlock *TruncUserBB = TruncUser->getParent();
1343
1344 if (UserBB == TruncUserBB)
1345 continue;
1346
1347 BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB];
1348 CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB];
1349
1350 if (!InsertedShift && !InsertedTrunc) {
1351 BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001352 assert(InsertPt != TruncUserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +00001353 // Sink the shift
1354 if (ShiftI->getOpcode() == Instruction::AShr)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001355 InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
1356 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001357 else
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001358 InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
1359 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001360
1361 // Sink the trunc
1362 BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt();
1363 TruncInsertPt++;
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001364 assert(TruncInsertPt != TruncUserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +00001365
1366 InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift,
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001367 TruncI->getType(), "", &*TruncInsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001368
1369 MadeChange = true;
1370
1371 TruncTheUse = InsertedTrunc;
1372 }
1373 }
1374 return MadeChange;
1375}
1376
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001377/// Sink the shift *right* instruction into user blocks if the uses could
1378/// potentially be combined with this shift instruction and generate BitExtract
1379/// instruction. It will only be applied if the architecture supports BitExtract
1380/// instruction. Here is an example:
Yi Jiangd069f632014-04-21 19:34:27 +00001381/// BB1:
1382/// %x.extract.shift = lshr i64 %arg1, 32
1383/// BB2:
1384/// %x.extract.trunc = trunc i64 %x.extract.shift to i16
1385/// ==>
1386///
1387/// BB2:
1388/// %x.extract.shift.1 = lshr i64 %arg1, 32
1389/// %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16
1390///
1391/// CodeGen will recoginze the pattern in BB2 and generate BitExtract
1392/// instruction.
1393/// Return true if any changes are made.
1394static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI,
Mehdi Amini44ede332015-07-09 02:09:04 +00001395 const TargetLowering &TLI,
1396 const DataLayout &DL) {
Yi Jiangd069f632014-04-21 19:34:27 +00001397 BasicBlock *DefBB = ShiftI->getParent();
1398
1399 /// Only insert instructions in each block once.
1400 DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts;
1401
Mehdi Amini44ede332015-07-09 02:09:04 +00001402 bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(DL, ShiftI->getType()));
Yi Jiangd069f632014-04-21 19:34:27 +00001403
1404 bool MadeChange = false;
1405 for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end();
1406 UI != E;) {
1407 Use &TheUse = UI.getUse();
1408 Instruction *User = cast<Instruction>(*UI);
1409 // Preincrement use iterator so we don't invalidate it.
1410 ++UI;
1411
1412 // Don't bother for PHI nodes.
1413 if (isa<PHINode>(User))
1414 continue;
1415
1416 if (!isExtractBitsCandidateUse(User))
1417 continue;
1418
1419 BasicBlock *UserBB = User->getParent();
1420
1421 if (UserBB == DefBB) {
1422 // If the shift and truncate instruction are in the same BB. The use of
1423 // the truncate(TruncUse) may still introduce another truncate if not
1424 // legal. In this case, we would like to sink both shift and truncate
1425 // instruction to the BB of TruncUse.
1426 // for example:
1427 // BB1:
1428 // i64 shift.result = lshr i64 opnd, imm
1429 // trunc.result = trunc shift.result to i16
1430 //
1431 // BB2:
1432 // ----> We will have an implicit truncate here if the architecture does
1433 // not have i16 compare.
1434 // cmp i16 trunc.result, opnd2
1435 //
1436 if (isa<TruncInst>(User) && shiftIsLegal
1437 // If the type of the truncate is legal, no trucate will be
1438 // introduced in other basic blocks.
Mehdi Amini44ede332015-07-09 02:09:04 +00001439 &&
1440 (!TLI.isTypeLegal(TLI.getValueType(DL, User->getType()))))
Yi Jiangd069f632014-04-21 19:34:27 +00001441 MadeChange =
Mehdi Amini44ede332015-07-09 02:09:04 +00001442 SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI, DL);
Yi Jiangd069f632014-04-21 19:34:27 +00001443
1444 continue;
1445 }
1446 // If we have already inserted a shift into this block, use it.
1447 BinaryOperator *&InsertedShift = InsertedShifts[UserBB];
1448
1449 if (!InsertedShift) {
1450 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001451 assert(InsertPt != UserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +00001452
1453 if (ShiftI->getOpcode() == Instruction::AShr)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001454 InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
1455 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001456 else
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001457 InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
1458 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001459
1460 MadeChange = true;
1461 }
1462
1463 // Replace a use of the shift with a use of the new shift.
1464 TheUse = InsertedShift;
1465 }
1466
1467 // If we removed all uses, nuke the shift.
1468 if (ShiftI->use_empty())
1469 ShiftI->eraseFromParent();
1470
1471 return MadeChange;
1472}
1473
Sanjay Patel4699b8a2015-11-19 16:37:10 +00001474/// If counting leading or trailing zeros is an expensive operation and a zero
1475/// input is defined, add a check for zero to avoid calling the intrinsic.
1476///
1477/// We want to transform:
1478/// %z = call i64 @llvm.cttz.i64(i64 %A, i1 false)
1479///
1480/// into:
1481/// entry:
1482/// %cmpz = icmp eq i64 %A, 0
1483/// br i1 %cmpz, label %cond.end, label %cond.false
1484/// cond.false:
1485/// %z = call i64 @llvm.cttz.i64(i64 %A, i1 true)
1486/// br label %cond.end
1487/// cond.end:
1488/// %ctz = phi i64 [ 64, %entry ], [ %z, %cond.false ]
1489///
1490/// If the transform is performed, return true and set ModifiedDT to true.
1491static bool despeculateCountZeros(IntrinsicInst *CountZeros,
1492 const TargetLowering *TLI,
1493 const DataLayout *DL,
1494 bool &ModifiedDT) {
1495 if (!TLI || !DL)
1496 return false;
1497
1498 // If a zero input is undefined, it doesn't make sense to despeculate that.
1499 if (match(CountZeros->getOperand(1), m_One()))
1500 return false;
1501
1502 // If it's cheap to speculate, there's nothing to do.
1503 auto IntrinsicID = CountZeros->getIntrinsicID();
1504 if ((IntrinsicID == Intrinsic::cttz && TLI->isCheapToSpeculateCttz()) ||
1505 (IntrinsicID == Intrinsic::ctlz && TLI->isCheapToSpeculateCtlz()))
1506 return false;
1507
1508 // Only handle legal scalar cases. Anything else requires too much work.
1509 Type *Ty = CountZeros->getType();
1510 unsigned SizeInBits = Ty->getPrimitiveSizeInBits();
Jun Bum Limbe11bdc2016-05-13 18:38:35 +00001511 if (Ty->isVectorTy() || SizeInBits > DL->getLargestLegalIntTypeSizeInBits())
Sanjay Patel4699b8a2015-11-19 16:37:10 +00001512 return false;
1513
1514 // The intrinsic will be sunk behind a compare against zero and branch.
1515 BasicBlock *StartBlock = CountZeros->getParent();
1516 BasicBlock *CallBlock = StartBlock->splitBasicBlock(CountZeros, "cond.false");
1517
1518 // Create another block after the count zero intrinsic. A PHI will be added
1519 // in this block to select the result of the intrinsic or the bit-width
1520 // constant if the input to the intrinsic is zero.
1521 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(CountZeros));
1522 BasicBlock *EndBlock = CallBlock->splitBasicBlock(SplitPt, "cond.end");
1523
1524 // Set up a builder to create a compare, conditional branch, and PHI.
1525 IRBuilder<> Builder(CountZeros->getContext());
1526 Builder.SetInsertPoint(StartBlock->getTerminator());
1527 Builder.SetCurrentDebugLocation(CountZeros->getDebugLoc());
1528
1529 // Replace the unconditional branch that was created by the first split with
1530 // a compare against zero and a conditional branch.
1531 Value *Zero = Constant::getNullValue(Ty);
1532 Value *Cmp = Builder.CreateICmpEQ(CountZeros->getOperand(0), Zero, "cmpz");
1533 Builder.CreateCondBr(Cmp, EndBlock, CallBlock);
1534 StartBlock->getTerminator()->eraseFromParent();
1535
1536 // Create a PHI in the end block to select either the output of the intrinsic
1537 // or the bit width of the operand.
1538 Builder.SetInsertPoint(&EndBlock->front());
1539 PHINode *PN = Builder.CreatePHI(Ty, 2, "ctz");
1540 CountZeros->replaceAllUsesWith(PN);
1541 Value *BitWidth = Builder.getInt(APInt(SizeInBits, SizeInBits));
1542 PN->addIncoming(BitWidth, StartBlock);
1543 PN->addIncoming(CountZeros, CallBlock);
1544
1545 // We are explicitly handling the zero case, so we can set the intrinsic's
1546 // undefined zero argument to 'true'. This will also prevent reprocessing the
1547 // intrinsic; we only despeculate when a zero input is defined.
1548 CountZeros->setArgOperand(1, Builder.getTrue());
1549 ModifiedDT = true;
1550 return true;
1551}
1552
Sanjay Patel3b8974b2017-06-08 20:00:09 +00001553bool CodeGenPrepare::optimizeCallInst(CallInst *CI, bool &ModifiedDT) {
Chris Lattner7a277142011-01-15 07:14:54 +00001554 BasicBlock *BB = CI->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +00001555
Chris Lattner7a277142011-01-15 07:14:54 +00001556 // Lower inline assembly if we can.
1557 // If we found an inline asm expession, and if the target knows how to
1558 // lower it to normal LLVM code, do so now.
1559 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
1560 if (TLI->ExpandInlineAsm(CI)) {
1561 // Avoid invalidating the iterator.
1562 CurInstIterator = BB->begin();
1563 // Avoid processing instructions out of order, which could cause
1564 // reuse before a value is defined.
1565 SunkAddrs.clear();
1566 return true;
1567 }
1568 // Sink address computing for memory operands into the block.
Sanjay Patelfc580a62015-09-21 23:03:16 +00001569 if (optimizeInlineAsmInst(CI))
Chris Lattner7a277142011-01-15 07:14:54 +00001570 return true;
1571 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001572
John Brawn0dbcd652015-03-18 12:01:59 +00001573 // Align the pointer arguments to this call if the target thinks it's a good
1574 // idea
1575 unsigned MinSize, PrefAlign;
Mehdi Amini4fe37982015-07-07 18:45:17 +00001576 if (TLI && TLI->shouldAlignPointerArgs(CI, MinSize, PrefAlign)) {
John Brawn0dbcd652015-03-18 12:01:59 +00001577 for (auto &Arg : CI->arg_operands()) {
1578 // We want to align both objects whose address is used directly and
1579 // objects whose address is used in casts and GEPs, though it only makes
1580 // sense for GEPs if the offset is a multiple of the desired alignment and
1581 // if size - offset meets the size threshold.
1582 if (!Arg->getType()->isPointerTy())
1583 continue;
Elena Demikhovsky945b7e52018-02-14 06:58:08 +00001584 APInt Offset(DL->getIndexSizeInBits(
Mehdi Amini4fe37982015-07-07 18:45:17 +00001585 cast<PointerType>(Arg->getType())->getAddressSpace()),
1586 0);
1587 Value *Val = Arg->stripAndAccumulateInBoundsConstantOffsets(*DL, Offset);
John Brawn0dbcd652015-03-18 12:01:59 +00001588 uint64_t Offset2 = Offset.getLimitedValue();
John Brawne8fd6c82015-04-13 10:47:39 +00001589 if ((Offset2 & (PrefAlign-1)) != 0)
1590 continue;
John Brawn0dbcd652015-03-18 12:01:59 +00001591 AllocaInst *AI;
Mehdi Amini4fe37982015-07-07 18:45:17 +00001592 if ((AI = dyn_cast<AllocaInst>(Val)) && AI->getAlignment() < PrefAlign &&
1593 DL->getTypeAllocSize(AI->getAllocatedType()) >= MinSize + Offset2)
John Brawn0dbcd652015-03-18 12:01:59 +00001594 AI->setAlignment(PrefAlign);
John Brawne8fd6c82015-04-13 10:47:39 +00001595 // Global variables can only be aligned if they are defined in this
1596 // object (i.e. they are uniquely initialized in this object), and
1597 // over-aligning global variables that have an explicit section is
1598 // forbidden.
1599 GlobalVariable *GV;
James Y Knightac03dca2016-01-15 16:33:06 +00001600 if ((GV = dyn_cast<GlobalVariable>(Val)) && GV->canIncreaseAlignment() &&
Tim Northover918f0502016-07-18 18:28:52 +00001601 GV->getPointerAlignment(*DL) < PrefAlign &&
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00001602 DL->getTypeAllocSize(GV->getValueType()) >=
Mehdi Amini4fe37982015-07-07 18:45:17 +00001603 MinSize + Offset2)
John Brawne8fd6c82015-04-13 10:47:39 +00001604 GV->setAlignment(PrefAlign);
John Brawn0dbcd652015-03-18 12:01:59 +00001605 }
1606 // If this is a memcpy (or similar) then we may be able to improve the
1607 // alignment
1608 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(CI)) {
Daniel Neilsonbe58a222018-01-31 17:24:53 +00001609 unsigned DestAlign = getKnownAlignment(MI->getDest(), *DL);
1610 if (DestAlign > MI->getDestAlignment())
1611 MI->setDestAlignment(DestAlign);
1612 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) {
1613 unsigned SrcAlign = getKnownAlignment(MTI->getSource(), *DL);
1614 if (SrcAlign > MTI->getSourceAlignment())
1615 MTI->setSourceAlignment(SrcAlign);
1616 }
John Brawn0dbcd652015-03-18 12:01:59 +00001617 }
1618 }
1619
Philip Reamesac115ed2016-03-09 23:13:12 +00001620 // If we have a cold call site, try to sink addressing computation into the
1621 // cold block. This interacts with our handling for loads and stores to
1622 // ensure that we can fold all uses of a potential addressing computation
1623 // into their uses. TODO: generalize this to work over profiling data
1624 if (!OptSize && CI->hasFnAttr(Attribute::Cold))
1625 for (auto &Arg : CI->arg_operands()) {
1626 if (!Arg->getType()->isPointerTy())
1627 continue;
1628 unsigned AS = Arg->getType()->getPointerAddressSpace();
1629 return optimizeMemoryInst(CI, Arg, Arg->getType(), AS);
1630 }
Junmo Park6098cbb2016-03-11 07:05:32 +00001631
Eric Christopher4b7948e2010-03-11 02:41:03 +00001632 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001633 if (II) {
1634 switch (II->getIntrinsicID()) {
1635 default: break;
1636 case Intrinsic::objectsize: {
1637 // Lower all uses of llvm.objectsize.*
George Burgess IV3f089142016-12-20 23:46:36 +00001638 ConstantInt *RetVal =
1639 lowerObjectSizeCall(II, *DL, TLInfo, /*MustSucceed=*/true);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001640 // Substituting this can cause recursive simplifications, which can
Sanjoy Dase6bca0e2017-05-01 17:07:49 +00001641 // invalidate our iterator. Use a WeakTrackingVH to hold onto it in case
1642 // this
Sanjoy Das2cbeb002017-04-26 16:37:05 +00001643 // happens.
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00001644 Value *CurValue = &*CurInstIterator;
Sanjoy Dase6bca0e2017-05-01 17:07:49 +00001645 WeakTrackingVH IterHandle(CurValue);
Nadav Rotem465834c2012-07-24 10:51:42 +00001646
Sanjay Patel545a4562016-01-20 18:59:16 +00001647 replaceAndRecursivelySimplify(CI, RetVal, TLInfo, nullptr);
Chris Lattner1b93be52011-01-15 07:25:29 +00001648
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001649 // If the iterator instruction was recursively deleted, start over at the
1650 // start of the block.
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00001651 if (IterHandle != CurValue) {
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001652 CurInstIterator = BB->begin();
1653 SunkAddrs.clear();
1654 }
1655 return true;
Chris Lattner86d56c62011-01-18 20:53:04 +00001656 }
Ahmed Bougacha236f9042015-05-22 21:37:17 +00001657 case Intrinsic::aarch64_stlxr:
1658 case Intrinsic::aarch64_stxr: {
1659 ZExtInst *ExtVal = dyn_cast<ZExtInst>(CI->getArgOperand(0));
1660 if (!ExtVal || !ExtVal->hasOneUse() ||
1661 ExtVal->getParent() == CI->getParent())
1662 return false;
1663 // Sink a zext feeding stlxr/stxr before it, so it can be folded into it.
1664 ExtVal->moveBefore(CI);
Ahmed Bougachaf3299142015-06-17 20:44:32 +00001665 // Mark this instruction as "inserted by CGP", so that other
1666 // optimizations don't touch it.
1667 InsertedInsts.insert(ExtVal);
Ahmed Bougacha236f9042015-05-22 21:37:17 +00001668 return true;
1669 }
Piotr Padlewski6c15ec42015-09-15 18:32:14 +00001670 case Intrinsic::invariant_group_barrier:
1671 II->replaceAllUsesWith(II->getArgOperand(0));
1672 II->eraseFromParent();
1673 return true;
Sanjay Patel4699b8a2015-11-19 16:37:10 +00001674
1675 case Intrinsic::cttz:
1676 case Intrinsic::ctlz:
1677 // If counting zeros is expensive, try to avoid it.
1678 return despeculateCountZeros(II, TLI, DL, ModifiedDT);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001679 }
Eric Christopher4b7948e2010-03-11 02:41:03 +00001680
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001681 if (TLI) {
1682 SmallVector<Value*, 2> PtrOps;
1683 Type *AccessTy;
Matt Arsenault1672b1b2017-02-08 07:09:03 +00001684 if (TLI->getAddrModeArguments(II, PtrOps, AccessTy))
1685 while (!PtrOps.empty()) {
1686 Value *PtrVal = PtrOps.pop_back_val();
1687 unsigned AS = PtrVal->getType()->getPointerAddressSpace();
1688 if (optimizeMemoryInst(II, PtrVal, AccessTy, AS))
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001689 return true;
Matt Arsenault1672b1b2017-02-08 07:09:03 +00001690 }
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001691 }
Pete Cooper615fd892012-03-13 20:59:56 +00001692 }
1693
Eric Christopher4b7948e2010-03-11 02:41:03 +00001694 // From here on out we're working with named functions.
Craig Topperc0196b12014-04-14 00:51:57 +00001695 if (!CI->getCalledFunction()) return false;
Devang Patel0da52502011-05-26 21:51:06 +00001696
Benjamin Kramer7b88a492010-03-12 09:27:41 +00001697 // Lower all default uses of _chk calls. This is very similar
1698 // to what InstCombineCalls does, but here we are only lowering calls
Ahmed Bougachae03bef72015-01-12 17:22:43 +00001699 // to fortified library functions (e.g. __memcpy_chk) that have the default
1700 // "don't know" as the objectsize. Anything else should be left alone.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001701 FortifiedLibCallSimplifier Simplifier(TLInfo, true);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00001702 if (Value *V = Simplifier.optimizeCall(CI)) {
1703 CI->replaceAllUsesWith(V);
1704 CI->eraseFromParent();
1705 return true;
1706 }
Zaara Syeda3a7578c2017-05-31 17:12:38 +00001707
Ahmed Bougachae03bef72015-01-12 17:22:43 +00001708 return false;
Eric Christopher4b7948e2010-03-11 02:41:03 +00001709}
Chris Lattner1b93be52011-01-15 07:25:29 +00001710
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001711/// Look for opportunities to duplicate return instructions to the predecessor
1712/// to enable tail call optimizations. The case it is currently looking for is:
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001713/// @code
Evan Cheng0663f232011-03-21 01:19:09 +00001714/// bb0:
1715/// %tmp0 = tail call i32 @f0()
1716/// br label %return
1717/// bb1:
1718/// %tmp1 = tail call i32 @f1()
1719/// br label %return
1720/// bb2:
1721/// %tmp2 = tail call i32 @f2()
1722/// br label %return
1723/// return:
1724/// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
1725/// ret i32 %retval
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001726/// @endcode
Evan Cheng0663f232011-03-21 01:19:09 +00001727///
1728/// =>
1729///
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001730/// @code
Evan Cheng0663f232011-03-21 01:19:09 +00001731/// bb0:
1732/// %tmp0 = tail call i32 @f0()
1733/// ret i32 %tmp0
1734/// bb1:
1735/// %tmp1 = tail call i32 @f1()
1736/// ret i32 %tmp1
1737/// bb2:
1738/// %tmp2 = tail call i32 @f2()
1739/// ret i32 %tmp2
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001740/// @endcode
Sanjay Patelfc580a62015-09-21 23:03:16 +00001741bool CodeGenPrepare::dupRetToEnableTailCallOpts(BasicBlock *BB) {
Cameron Zwarich47e71752011-03-24 04:51:51 +00001742 if (!TLI)
1743 return false;
1744
Michael Kuperstein71321562016-09-07 20:29:49 +00001745 ReturnInst *RetI = dyn_cast<ReturnInst>(BB->getTerminator());
1746 if (!RetI)
Benjamin Kramer455fa352012-11-23 19:17:06 +00001747 return false;
1748
Craig Topperc0196b12014-04-14 00:51:57 +00001749 PHINode *PN = nullptr;
1750 BitCastInst *BCI = nullptr;
Michael Kuperstein71321562016-09-07 20:29:49 +00001751 Value *V = RetI->getReturnValue();
Evan Cheng249716e2012-07-27 21:21:26 +00001752 if (V) {
1753 BCI = dyn_cast<BitCastInst>(V);
1754 if (BCI)
1755 V = BCI->getOperand(0);
1756
1757 PN = dyn_cast<PHINode>(V);
1758 if (!PN)
1759 return false;
1760 }
Evan Cheng0663f232011-03-21 01:19:09 +00001761
Cameron Zwarich4649f172011-03-24 04:52:10 +00001762 if (PN && PN->getParent() != BB)
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001763 return false;
Evan Cheng0663f232011-03-21 01:19:09 +00001764
Cameron Zwarich4649f172011-03-24 04:52:10 +00001765 // Make sure there are no instructions between the PHI and return, or that the
1766 // return is the first instruction in the block.
1767 if (PN) {
1768 BasicBlock::iterator BI = BB->begin();
1769 do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
Evan Cheng249716e2012-07-27 21:21:26 +00001770 if (&*BI == BCI)
1771 // Also skip over the bitcast.
1772 ++BI;
Michael Kuperstein71321562016-09-07 20:29:49 +00001773 if (&*BI != RetI)
Cameron Zwarich4649f172011-03-24 04:52:10 +00001774 return false;
1775 } else {
Cameron Zwarich74157ab2011-03-24 16:34:59 +00001776 BasicBlock::iterator BI = BB->begin();
1777 while (isa<DbgInfoIntrinsic>(BI)) ++BI;
Michael Kuperstein71321562016-09-07 20:29:49 +00001778 if (&*BI != RetI)
Cameron Zwarich4649f172011-03-24 04:52:10 +00001779 return false;
1780 }
Evan Cheng0663f232011-03-21 01:19:09 +00001781
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001782 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
1783 /// call.
Michael Kupersteinf79af6f2016-09-08 00:48:37 +00001784 const Function *F = BB->getParent();
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001785 SmallVector<CallInst*, 4> TailCalls;
Cameron Zwarich4649f172011-03-24 04:52:10 +00001786 if (PN) {
1787 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
1788 CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
1789 // Make sure the phi value is indeed produced by the tail call.
1790 if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
Michael Kupersteinf79af6f2016-09-08 00:48:37 +00001791 TLI->mayBeEmittedAsTailCall(CI) &&
1792 attributesPermitTailCall(F, CI, RetI, *TLI))
Cameron Zwarich4649f172011-03-24 04:52:10 +00001793 TailCalls.push_back(CI);
1794 }
1795 } else {
1796 SmallPtrSet<BasicBlock*, 4> VisitedBBs;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001797 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
David Blaikie70573dc2014-11-19 07:49:26 +00001798 if (!VisitedBBs.insert(*PI).second)
Cameron Zwarich4649f172011-03-24 04:52:10 +00001799 continue;
1800
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001801 BasicBlock::InstListType &InstList = (*PI)->getInstList();
Cameron Zwarich4649f172011-03-24 04:52:10 +00001802 BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
1803 BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
Cameron Zwarich74157ab2011-03-24 16:34:59 +00001804 do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
1805 if (RI == RE)
Cameron Zwarich4649f172011-03-24 04:52:10 +00001806 continue;
Cameron Zwarich74157ab2011-03-24 16:34:59 +00001807
Cameron Zwarich4649f172011-03-24 04:52:10 +00001808 CallInst *CI = dyn_cast<CallInst>(&*RI);
Michael Kupersteinf79af6f2016-09-08 00:48:37 +00001809 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI) &&
1810 attributesPermitTailCall(F, CI, RetI, *TLI))
Cameron Zwarich4649f172011-03-24 04:52:10 +00001811 TailCalls.push_back(CI);
1812 }
Evan Cheng0663f232011-03-21 01:19:09 +00001813 }
1814
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001815 bool Changed = false;
1816 for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
1817 CallInst *CI = TailCalls[i];
1818 CallSite CS(CI);
1819
1820 // Conservatively require the attributes of the call to match those of the
1821 // return. Ignore noalias because it doesn't affect the call sequence.
Reid Klecknerb5180542017-03-21 16:57:19 +00001822 AttributeList CalleeAttrs = CS.getAttributes();
1823 if (AttrBuilder(CalleeAttrs, AttributeList::ReturnIndex)
1824 .removeAttribute(Attribute::NoAlias) !=
1825 AttrBuilder(CalleeAttrs, AttributeList::ReturnIndex)
1826 .removeAttribute(Attribute::NoAlias))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001827 continue;
1828
1829 // Make sure the call instruction is followed by an unconditional branch to
1830 // the return block.
1831 BasicBlock *CallBB = CI->getParent();
1832 BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
1833 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
1834 continue;
1835
1836 // Duplicate the return into CallBB.
Michael Kuperstein71321562016-09-07 20:29:49 +00001837 (void)FoldReturnIntoUncondBranch(RetI, BB, CallBB);
Devang Patel8f606d72011-03-24 15:35:25 +00001838 ModifiedDT = Changed = true;
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001839 ++NumRetsDup;
1840 }
1841
1842 // If we eliminated all predecessors of the block, delete the block now.
Evan Cheng64a223a2012-09-28 23:58:57 +00001843 if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001844 BB->eraseFromParent();
1845
1846 return Changed;
Evan Cheng0663f232011-03-21 01:19:09 +00001847}
1848
Chris Lattner728f9022008-11-25 07:09:13 +00001849//===----------------------------------------------------------------------===//
Chris Lattner728f9022008-11-25 07:09:13 +00001850// Memory Optimization
1851//===----------------------------------------------------------------------===//
1852
Chandler Carruthc8925912013-01-05 02:09:22 +00001853namespace {
1854
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001855/// This is an extended version of TargetLowering::AddrMode
Chandler Carruthc8925912013-01-05 02:09:22 +00001856/// which holds actual Value*'s for register values.
Chandler Carruth95f83e02013-01-07 15:14:13 +00001857struct ExtAddrMode : public TargetLowering::AddrMode {
Eugene Zelenko900b6332017-08-29 22:32:07 +00001858 Value *BaseReg = nullptr;
1859 Value *ScaledReg = nullptr;
John Brawn736bf002017-10-03 13:08:22 +00001860 Value *OriginalValue = nullptr;
1861
1862 enum FieldName {
1863 NoField = 0x00,
1864 BaseRegField = 0x01,
1865 BaseGVField = 0x02,
1866 BaseOffsField = 0x04,
1867 ScaledRegField = 0x08,
1868 ScaleField = 0x10,
1869 MultipleFields = 0xff
1870 };
Eugene Zelenko900b6332017-08-29 22:32:07 +00001871
1872 ExtAddrMode() = default;
1873
Chandler Carruthc8925912013-01-05 02:09:22 +00001874 void print(raw_ostream &OS) const;
1875 void dump() const;
Stephen Lin837bba12013-07-15 17:55:02 +00001876
John Brawn736bf002017-10-03 13:08:22 +00001877 FieldName compare(const ExtAddrMode &other) {
1878 // First check that the types are the same on each field, as differing types
1879 // is something we can't cope with later on.
1880 if (BaseReg && other.BaseReg &&
1881 BaseReg->getType() != other.BaseReg->getType())
1882 return MultipleFields;
1883 if (BaseGV && other.BaseGV &&
1884 BaseGV->getType() != other.BaseGV->getType())
1885 return MultipleFields;
1886 if (ScaledReg && other.ScaledReg &&
1887 ScaledReg->getType() != other.ScaledReg->getType())
1888 return MultipleFields;
1889
1890 // Check each field to see if it differs.
1891 unsigned Result = NoField;
1892 if (BaseReg != other.BaseReg)
1893 Result |= BaseRegField;
1894 if (BaseGV != other.BaseGV)
1895 Result |= BaseGVField;
1896 if (BaseOffs != other.BaseOffs)
1897 Result |= BaseOffsField;
1898 if (ScaledReg != other.ScaledReg)
1899 Result |= ScaledRegField;
1900 // Don't count 0 as being a different scale, because that actually means
1901 // unscaled (which will already be counted by having no ScaledReg).
1902 if (Scale && other.Scale && Scale != other.Scale)
1903 Result |= ScaleField;
1904
1905 if (countPopulation(Result) > 1)
1906 return MultipleFields;
1907 else
1908 return static_cast<FieldName>(Result);
1909 }
1910
John Brawn4b476482017-11-27 11:29:15 +00001911 // An AddrMode is trivial if it involves no calculation i.e. it is just a base
1912 // with no offset.
John Brawn736bf002017-10-03 13:08:22 +00001913 bool isTrivial() {
John Brawn4b476482017-11-27 11:29:15 +00001914 // An AddrMode is (BaseGV + BaseReg + BaseOffs + ScaleReg * Scale) so it is
1915 // trivial if at most one of these terms is nonzero, except that BaseGV and
1916 // BaseReg both being zero actually means a null pointer value, which we
1917 // consider to be 'non-zero' here.
1918 return !BaseOffs && !Scale && !(BaseGV && BaseReg);
Chandler Carruthc8925912013-01-05 02:09:22 +00001919 }
John Brawn70cdb5b2017-11-24 14:10:45 +00001920
1921 Value *GetFieldAsValue(FieldName Field, Type *IntPtrTy) {
1922 switch (Field) {
1923 default:
1924 return nullptr;
1925 case BaseRegField:
1926 return BaseReg;
1927 case BaseGVField:
1928 return BaseGV;
1929 case ScaledRegField:
1930 return ScaledReg;
1931 case BaseOffsField:
1932 return ConstantInt::get(IntPtrTy, BaseOffs);
1933 }
1934 }
1935
1936 void SetCombinedField(FieldName Field, Value *V,
1937 const SmallVectorImpl<ExtAddrMode> &AddrModes) {
1938 switch (Field) {
1939 default:
1940 llvm_unreachable("Unhandled fields are expected to be rejected earlier");
1941 break;
1942 case ExtAddrMode::BaseRegField:
1943 BaseReg = V;
1944 break;
1945 case ExtAddrMode::BaseGVField:
1946 // A combined BaseGV is an Instruction, not a GlobalValue, so it goes
1947 // in the BaseReg field.
1948 assert(BaseReg == nullptr);
1949 BaseReg = V;
1950 BaseGV = nullptr;
1951 break;
1952 case ExtAddrMode::ScaledRegField:
1953 ScaledReg = V;
1954 // If we have a mix of scaled and unscaled addrmodes then we want scale
1955 // to be the scale and not zero.
1956 if (!Scale)
1957 for (const ExtAddrMode &AM : AddrModes)
1958 if (AM.Scale) {
1959 Scale = AM.Scale;
1960 break;
1961 }
1962 break;
1963 case ExtAddrMode::BaseOffsField:
1964 // The offset is no longer a constant, so it goes in ScaledReg with a
1965 // scale of 1.
1966 assert(ScaledReg == nullptr);
1967 ScaledReg = V;
1968 Scale = 1;
1969 BaseOffs = 0;
1970 break;
1971 }
1972 }
Chandler Carruthc8925912013-01-05 02:09:22 +00001973};
1974
Eugene Zelenko900b6332017-08-29 22:32:07 +00001975} // end anonymous namespace
1976
Eli Friedmanc1f1f852013-09-10 23:09:24 +00001977#ifndef NDEBUG
1978static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
1979 AM.print(OS);
1980 return OS;
1981}
1982#endif
1983
Aaron Ballman615eb472017-10-15 14:32:27 +00001984#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Chandler Carruthc8925912013-01-05 02:09:22 +00001985void ExtAddrMode::print(raw_ostream &OS) const {
1986 bool NeedPlus = false;
1987 OS << "[";
1988 if (BaseGV) {
1989 OS << (NeedPlus ? " + " : "")
1990 << "GV:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00001991 BaseGV->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00001992 NeedPlus = true;
1993 }
1994
Richard Trieuc0f91212014-05-30 03:15:17 +00001995 if (BaseOffs) {
1996 OS << (NeedPlus ? " + " : "")
1997 << BaseOffs;
1998 NeedPlus = true;
1999 }
Chandler Carruthc8925912013-01-05 02:09:22 +00002000
2001 if (BaseReg) {
2002 OS << (NeedPlus ? " + " : "")
2003 << "Base:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00002004 BaseReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00002005 NeedPlus = true;
2006 }
2007 if (Scale) {
2008 OS << (NeedPlus ? " + " : "")
2009 << Scale << "*";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00002010 ScaledReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00002011 }
2012
2013 OS << ']';
2014}
2015
Yaron Kereneb2a2542016-01-29 20:50:44 +00002016LLVM_DUMP_METHOD void ExtAddrMode::dump() const {
Chandler Carruthc8925912013-01-05 02:09:22 +00002017 print(dbgs());
2018 dbgs() << '\n';
2019}
2020#endif
2021
Eugene Zelenko900b6332017-08-29 22:32:07 +00002022namespace {
2023
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002024/// \brief This class provides transaction based operation on the IR.
2025/// Every change made through this class is recorded in the internal state and
2026/// can be undone (rollback) until commit is called.
2027class TypePromotionTransaction {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002028 /// \brief This represents the common interface of the individual transaction.
2029 /// Each class implements the logic for doing one specific modification on
2030 /// the IR via the TypePromotionTransaction.
2031 class TypePromotionAction {
2032 protected:
2033 /// The Instruction modified.
2034 Instruction *Inst;
2035
2036 public:
2037 /// \brief Constructor of the action.
2038 /// The constructor performs the related action on the IR.
2039 TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
2040
Eugene Zelenko900b6332017-08-29 22:32:07 +00002041 virtual ~TypePromotionAction() = default;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002042
2043 /// \brief Undo the modification done by this action.
2044 /// When this method is called, the IR must be in the same state as it was
2045 /// before this action was applied.
2046 /// \pre Undoing the action works if and only if the IR is in the exact same
2047 /// state as it was directly after this action was applied.
2048 virtual void undo() = 0;
2049
2050 /// \brief Advocate every change made by this action.
2051 /// When the results on the IR of the action are to be kept, it is important
2052 /// to call this function, otherwise hidden information may be kept forever.
2053 virtual void commit() {
2054 // Nothing to be done, this action is not doing anything.
2055 }
2056 };
2057
2058 /// \brief Utility to remember the position of an instruction.
2059 class InsertionHandler {
2060 /// Position of an instruction.
2061 /// Either an instruction:
2062 /// - Is the first in a basic block: BB is used.
2063 /// - Has a previous instructon: PrevInst is used.
2064 union {
2065 Instruction *PrevInst;
2066 BasicBlock *BB;
2067 } Point;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002068
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002069 /// Remember whether or not the instruction had a previous instruction.
2070 bool HasPrevInstruction;
2071
2072 public:
2073 /// \brief Record the position of \p Inst.
2074 InsertionHandler(Instruction *Inst) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002075 BasicBlock::iterator It = Inst->getIterator();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002076 HasPrevInstruction = (It != (Inst->getParent()->begin()));
2077 if (HasPrevInstruction)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002078 Point.PrevInst = &*--It;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002079 else
2080 Point.BB = Inst->getParent();
2081 }
2082
2083 /// \brief Insert \p Inst at the recorded position.
2084 void insert(Instruction *Inst) {
2085 if (HasPrevInstruction) {
2086 if (Inst->getParent())
2087 Inst->removeFromParent();
2088 Inst->insertAfter(Point.PrevInst);
2089 } else {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002090 Instruction *Position = &*Point.BB->getFirstInsertionPt();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002091 if (Inst->getParent())
2092 Inst->moveBefore(Position);
2093 else
2094 Inst->insertBefore(Position);
2095 }
2096 }
2097 };
2098
2099 /// \brief Move an instruction before another.
2100 class InstructionMoveBefore : public TypePromotionAction {
2101 /// Original position of the instruction.
2102 InsertionHandler Position;
2103
2104 public:
2105 /// \brief Move \p Inst before \p Before.
2106 InstructionMoveBefore(Instruction *Inst, Instruction *Before)
2107 : TypePromotionAction(Inst), Position(Inst) {
2108 DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before << "\n");
2109 Inst->moveBefore(Before);
2110 }
2111
2112 /// \brief Move the instruction back to its original position.
Craig Topper4584cd52014-03-07 09:26:03 +00002113 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002114 DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n");
2115 Position.insert(Inst);
2116 }
2117 };
2118
2119 /// \brief Set the operand of an instruction with a new value.
2120 class OperandSetter : public TypePromotionAction {
2121 /// Original operand of the instruction.
2122 Value *Origin;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002123
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002124 /// Index of the modified instruction.
2125 unsigned Idx;
2126
2127 public:
2128 /// \brief Set \p Idx operand of \p Inst with \p NewVal.
2129 OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
2130 : TypePromotionAction(Inst), Idx(Idx) {
2131 DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"
2132 << "for:" << *Inst << "\n"
2133 << "with:" << *NewVal << "\n");
2134 Origin = Inst->getOperand(Idx);
2135 Inst->setOperand(Idx, NewVal);
2136 }
2137
2138 /// \brief Restore the original value of the instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002139 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002140 DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"
2141 << "for: " << *Inst << "\n"
2142 << "with: " << *Origin << "\n");
2143 Inst->setOperand(Idx, Origin);
2144 }
2145 };
2146
2147 /// \brief Hide the operands of an instruction.
2148 /// Do as if this instruction was not using any of its operands.
2149 class OperandsHider : public TypePromotionAction {
2150 /// The list of original operands.
2151 SmallVector<Value *, 4> OriginalValues;
2152
2153 public:
2154 /// \brief Remove \p Inst from the uses of the operands of \p Inst.
2155 OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
2156 DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n");
2157 unsigned NumOpnds = Inst->getNumOperands();
2158 OriginalValues.reserve(NumOpnds);
2159 for (unsigned It = 0; It < NumOpnds; ++It) {
2160 // Save the current operand.
2161 Value *Val = Inst->getOperand(It);
2162 OriginalValues.push_back(Val);
2163 // Set a dummy one.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00002164 // We could use OperandSetter here, but that would imply an overhead
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002165 // that we are not willing to pay.
2166 Inst->setOperand(It, UndefValue::get(Val->getType()));
2167 }
2168 }
2169
2170 /// \brief Restore the original list of uses.
Craig Topper4584cd52014-03-07 09:26:03 +00002171 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002172 DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n");
2173 for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
2174 Inst->setOperand(It, OriginalValues[It]);
2175 }
2176 };
2177
2178 /// \brief Build a truncate instruction.
2179 class TruncBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00002180 Value *Val;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002181
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002182 public:
2183 /// \brief Build a truncate instruction of \p Opnd producing a \p Ty
2184 /// result.
2185 /// trunc Opnd to Ty.
2186 TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
2187 IRBuilder<> Builder(Opnd);
Quentin Colombetac55b152014-09-16 22:36:07 +00002188 Val = Builder.CreateTrunc(Opnd, Ty, "promoted");
2189 DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002190 }
2191
Quentin Colombetac55b152014-09-16 22:36:07 +00002192 /// \brief Get the built value.
2193 Value *getBuiltValue() { return Val; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002194
2195 /// \brief Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002196 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00002197 DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n");
2198 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2199 IVal->eraseFromParent();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002200 }
2201 };
2202
2203 /// \brief Build a sign extension instruction.
2204 class SExtBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00002205 Value *Val;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002206
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002207 public:
2208 /// \brief Build a sign extension instruction of \p Opnd producing a \p Ty
2209 /// result.
2210 /// sext Opnd to Ty.
2211 SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
Quentin Colombetac55b152014-09-16 22:36:07 +00002212 : TypePromotionAction(InsertPt) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002213 IRBuilder<> Builder(InsertPt);
Quentin Colombetac55b152014-09-16 22:36:07 +00002214 Val = Builder.CreateSExt(Opnd, Ty, "promoted");
2215 DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002216 }
2217
Quentin Colombetac55b152014-09-16 22:36:07 +00002218 /// \brief Get the built value.
2219 Value *getBuiltValue() { return Val; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002220
2221 /// \brief Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002222 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00002223 DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n");
2224 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2225 IVal->eraseFromParent();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002226 }
2227 };
2228
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002229 /// \brief Build a zero extension instruction.
2230 class ZExtBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00002231 Value *Val;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002232
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002233 public:
2234 /// \brief Build a zero extension instruction of \p Opnd producing a \p Ty
2235 /// result.
2236 /// zext Opnd to Ty.
2237 ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
Quentin Colombetac55b152014-09-16 22:36:07 +00002238 : TypePromotionAction(InsertPt) {
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002239 IRBuilder<> Builder(InsertPt);
Quentin Colombetac55b152014-09-16 22:36:07 +00002240 Val = Builder.CreateZExt(Opnd, Ty, "promoted");
2241 DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n");
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002242 }
2243
Quentin Colombetac55b152014-09-16 22:36:07 +00002244 /// \brief Get the built value.
2245 Value *getBuiltValue() { return Val; }
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002246
2247 /// \brief Remove the built instruction.
2248 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00002249 DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n");
2250 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2251 IVal->eraseFromParent();
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002252 }
2253 };
2254
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002255 /// \brief Mutate an instruction to another type.
2256 class TypeMutator : public TypePromotionAction {
2257 /// Record the original type.
2258 Type *OrigTy;
2259
2260 public:
2261 /// \brief Mutate the type of \p Inst into \p NewTy.
2262 TypeMutator(Instruction *Inst, Type *NewTy)
2263 : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
2264 DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy
2265 << "\n");
2266 Inst->mutateType(NewTy);
2267 }
2268
2269 /// \brief Mutate the instruction back to its original type.
Craig Topper4584cd52014-03-07 09:26:03 +00002270 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002271 DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy
2272 << "\n");
2273 Inst->mutateType(OrigTy);
2274 }
2275 };
2276
2277 /// \brief Replace the uses of an instruction by another instruction.
2278 class UsesReplacer : public TypePromotionAction {
2279 /// Helper structure to keep track of the replaced uses.
2280 struct InstructionAndIdx {
2281 /// The instruction using the instruction.
2282 Instruction *Inst;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002283
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002284 /// The index where this instruction is used for Inst.
2285 unsigned Idx;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002286
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002287 InstructionAndIdx(Instruction *Inst, unsigned Idx)
2288 : Inst(Inst), Idx(Idx) {}
2289 };
2290
2291 /// Keep track of the original uses (pair Instruction, Index).
2292 SmallVector<InstructionAndIdx, 4> OriginalUses;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002293
2294 using use_iterator = SmallVectorImpl<InstructionAndIdx>::iterator;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002295
2296 public:
2297 /// \brief Replace all the use of \p Inst by \p New.
2298 UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) {
2299 DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New
2300 << "\n");
2301 // Record the original uses.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002302 for (Use &U : Inst->uses()) {
2303 Instruction *UserI = cast<Instruction>(U.getUser());
2304 OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo()));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002305 }
2306 // Now, we can replace the uses.
2307 Inst->replaceAllUsesWith(New);
2308 }
2309
2310 /// \brief Reassign the original uses of Inst to Inst.
Craig Topper4584cd52014-03-07 09:26:03 +00002311 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002312 DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n");
2313 for (use_iterator UseIt = OriginalUses.begin(),
2314 EndIt = OriginalUses.end();
2315 UseIt != EndIt; ++UseIt) {
2316 UseIt->Inst->setOperand(UseIt->Idx, Inst);
2317 }
2318 }
2319 };
2320
2321 /// \brief Remove an instruction from the IR.
2322 class InstructionRemover : public TypePromotionAction {
2323 /// Original position of the instruction.
2324 InsertionHandler Inserter;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002325
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002326 /// Helper structure to hide all the link to the instruction. In other
2327 /// words, this helps to do as if the instruction was removed.
2328 OperandsHider Hider;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002329
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002330 /// Keep track of the uses replaced, if any.
Eugene Zelenko900b6332017-08-29 22:32:07 +00002331 UsesReplacer *Replacer = nullptr;
2332
Jun Bum Limdee55652017-04-03 19:20:07 +00002333 /// Keep track of instructions removed.
2334 SetOfInstrs &RemovedInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002335
2336 public:
2337 /// \brief Remove all reference of \p Inst and optinally replace all its
2338 /// uses with New.
Jun Bum Limdee55652017-04-03 19:20:07 +00002339 /// \p RemovedInsts Keep track of the instructions removed by this Action.
Craig Topperc0196b12014-04-14 00:51:57 +00002340 /// \pre If !Inst->use_empty(), then New != nullptr
Jun Bum Limdee55652017-04-03 19:20:07 +00002341 InstructionRemover(Instruction *Inst, SetOfInstrs &RemovedInsts,
2342 Value *New = nullptr)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002343 : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
Eugene Zelenko900b6332017-08-29 22:32:07 +00002344 RemovedInsts(RemovedInsts) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002345 if (New)
2346 Replacer = new UsesReplacer(Inst, New);
2347 DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n");
Jun Bum Limdee55652017-04-03 19:20:07 +00002348 RemovedInsts.insert(Inst);
2349 /// The instructions removed here will be freed after completing
2350 /// optimizeBlock() for all blocks as we need to keep track of the
2351 /// removed instructions during promotion.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002352 Inst->removeFromParent();
2353 }
2354
Alexander Kornienkof817c1c2015-04-11 02:11:45 +00002355 ~InstructionRemover() override { delete Replacer; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002356
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002357 /// \brief Resurrect the instruction and reassign it to the proper uses if
2358 /// new value was provided when build this action.
Craig Topper4584cd52014-03-07 09:26:03 +00002359 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002360 DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n");
2361 Inserter.insert(Inst);
2362 if (Replacer)
2363 Replacer->undo();
2364 Hider.undo();
Jun Bum Limdee55652017-04-03 19:20:07 +00002365 RemovedInsts.erase(Inst);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002366 }
2367 };
2368
2369public:
2370 /// Restoration point.
2371 /// The restoration point is a pointer to an action instead of an iterator
2372 /// because the iterator may be invalidated but not the pointer.
Eugene Zelenko900b6332017-08-29 22:32:07 +00002373 using ConstRestorationPt = const TypePromotionAction *;
Jun Bum Limdee55652017-04-03 19:20:07 +00002374
2375 TypePromotionTransaction(SetOfInstrs &RemovedInsts)
2376 : RemovedInsts(RemovedInsts) {}
2377
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002378 /// Advocate every changes made in that transaction.
2379 void commit();
Eugene Zelenko900b6332017-08-29 22:32:07 +00002380
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002381 /// Undo all the changes made after the given point.
2382 void rollback(ConstRestorationPt Point);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002383
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002384 /// Get the current restoration point.
2385 ConstRestorationPt getRestorationPoint() const;
2386
2387 /// \name API for IR modification with state keeping to support rollback.
2388 /// @{
2389 /// Same as Instruction::setOperand.
2390 void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002391
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002392 /// Same as Instruction::eraseFromParent.
Craig Topperc0196b12014-04-14 00:51:57 +00002393 void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002394
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002395 /// Same as Value::replaceAllUsesWith.
2396 void replaceAllUsesWith(Instruction *Inst, Value *New);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002397
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002398 /// Same as Value::mutateType.
2399 void mutateType(Instruction *Inst, Type *NewTy);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002400
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002401 /// Same as IRBuilder::createTrunc.
Quentin Colombetac55b152014-09-16 22:36:07 +00002402 Value *createTrunc(Instruction *Opnd, Type *Ty);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002403
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002404 /// Same as IRBuilder::createSExt.
Quentin Colombetac55b152014-09-16 22:36:07 +00002405 Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002406
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002407 /// Same as IRBuilder::createZExt.
Quentin Colombetac55b152014-09-16 22:36:07 +00002408 Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002409
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002410 /// Same as Instruction::moveBefore.
2411 void moveBefore(Instruction *Inst, Instruction *Before);
2412 /// @}
2413
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002414private:
2415 /// The ordered list of actions made so far.
David Blaikie7620b312014-04-15 06:17:44 +00002416 SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002417
2418 using CommitPt = SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator;
2419
Jun Bum Limdee55652017-04-03 19:20:07 +00002420 SetOfInstrs &RemovedInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002421};
2422
Eugene Zelenko900b6332017-08-29 22:32:07 +00002423} // end anonymous namespace
2424
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002425void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
2426 Value *NewVal) {
Eugene Zelenko900b6332017-08-29 22:32:07 +00002427 Actions.push_back(llvm::make_unique<TypePromotionTransaction::OperandSetter>(
2428 Inst, Idx, NewVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002429}
2430
2431void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
2432 Value *NewVal) {
2433 Actions.push_back(
Eugene Zelenko900b6332017-08-29 22:32:07 +00002434 llvm::make_unique<TypePromotionTransaction::InstructionRemover>(
2435 Inst, RemovedInsts, NewVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002436}
2437
2438void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
2439 Value *New) {
Eugene Zelenko900b6332017-08-29 22:32:07 +00002440 Actions.push_back(
2441 llvm::make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002442}
2443
2444void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
Eugene Zelenko900b6332017-08-29 22:32:07 +00002445 Actions.push_back(
2446 llvm::make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002447}
2448
Quentin Colombetac55b152014-09-16 22:36:07 +00002449Value *TypePromotionTransaction::createTrunc(Instruction *Opnd,
2450 Type *Ty) {
David Blaikie7620b312014-04-15 06:17:44 +00002451 std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002452 Value *Val = Ptr->getBuiltValue();
David Blaikie7620b312014-04-15 06:17:44 +00002453 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002454 return Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002455}
2456
Quentin Colombetac55b152014-09-16 22:36:07 +00002457Value *TypePromotionTransaction::createSExt(Instruction *Inst,
2458 Value *Opnd, Type *Ty) {
David Blaikie7620b312014-04-15 06:17:44 +00002459 std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002460 Value *Val = Ptr->getBuiltValue();
David Blaikie7620b312014-04-15 06:17:44 +00002461 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002462 return Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002463}
2464
Quentin Colombetac55b152014-09-16 22:36:07 +00002465Value *TypePromotionTransaction::createZExt(Instruction *Inst,
2466 Value *Opnd, Type *Ty) {
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002467 std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002468 Value *Val = Ptr->getBuiltValue();
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002469 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002470 return Val;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002471}
2472
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002473void TypePromotionTransaction::moveBefore(Instruction *Inst,
2474 Instruction *Before) {
2475 Actions.push_back(
Eugene Zelenko900b6332017-08-29 22:32:07 +00002476 llvm::make_unique<TypePromotionTransaction::InstructionMoveBefore>(
2477 Inst, Before));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002478}
2479
2480TypePromotionTransaction::ConstRestorationPt
2481TypePromotionTransaction::getRestorationPoint() const {
David Blaikie7620b312014-04-15 06:17:44 +00002482 return !Actions.empty() ? Actions.back().get() : nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002483}
2484
2485void TypePromotionTransaction::commit() {
2486 for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt;
David Blaikie7620b312014-04-15 06:17:44 +00002487 ++It)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002488 (*It)->commit();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002489 Actions.clear();
2490}
2491
2492void TypePromotionTransaction::rollback(
2493 TypePromotionTransaction::ConstRestorationPt Point) {
David Blaikie7620b312014-04-15 06:17:44 +00002494 while (!Actions.empty() && Point != Actions.back().get()) {
2495 std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002496 Curr->undo();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002497 }
2498}
2499
Eugene Zelenko900b6332017-08-29 22:32:07 +00002500namespace {
2501
Chandler Carruthc8925912013-01-05 02:09:22 +00002502/// \brief A helper class for matching addressing modes.
2503///
2504/// This encapsulates the logic for matching the target-legal addressing modes.
2505class AddressingModeMatcher {
2506 SmallVectorImpl<Instruction*> &AddrModeInsts;
2507 const TargetLowering &TLI;
Igor Laevsky3be81ba2017-02-07 13:27:20 +00002508 const TargetRegisterInfo &TRI;
Mehdi Amini4fe37982015-07-07 18:45:17 +00002509 const DataLayout &DL;
Chandler Carruthc8925912013-01-05 02:09:22 +00002510
2511 /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
2512 /// the memory instruction that we're computing this address for.
2513 Type *AccessTy;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002514 unsigned AddrSpace;
Chandler Carruthc8925912013-01-05 02:09:22 +00002515 Instruction *MemoryInst;
Stephen Lin837bba12013-07-15 17:55:02 +00002516
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002517 /// This is the addressing mode that we're building up. This is
Chandler Carruthc8925912013-01-05 02:09:22 +00002518 /// part of the return value of this addressing mode matching stuff.
2519 ExtAddrMode &AddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00002520
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002521 /// The instructions inserted by other CodeGenPrepare optimizations.
2522 const SetOfInstrs &InsertedInsts;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002523
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002524 /// A map from the instructions to their type before promotion.
2525 InstrToOrigTy &PromotedInsts;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002526
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002527 /// The ongoing transaction where every action should be registered.
2528 TypePromotionTransaction &TPT;
2529
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002530 /// This is set to true when we should not do profitability checks.
2531 /// When true, IsProfitableToFoldIntoAddressingMode always returns true.
Chandler Carruthc8925912013-01-05 02:09:22 +00002532 bool IgnoreProfitability;
Stephen Lin837bba12013-07-15 17:55:02 +00002533
Eric Christopherd75c00c2015-02-26 22:38:34 +00002534 AddressingModeMatcher(SmallVectorImpl<Instruction *> &AMI,
Igor Laevsky3be81ba2017-02-07 13:27:20 +00002535 const TargetLowering &TLI,
2536 const TargetRegisterInfo &TRI,
2537 Type *AT, unsigned AS,
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002538 Instruction *MI, ExtAddrMode &AM,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002539 const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002540 InstrToOrigTy &PromotedInsts,
2541 TypePromotionTransaction &TPT)
Igor Laevsky3be81ba2017-02-07 13:27:20 +00002542 : AddrModeInsts(AMI), TLI(TLI), TRI(TRI),
Mehdi Amini4fe37982015-07-07 18:45:17 +00002543 DL(MI->getModule()->getDataLayout()), AccessTy(AT), AddrSpace(AS),
2544 MemoryInst(MI), AddrMode(AM), InsertedInsts(InsertedInsts),
2545 PromotedInsts(PromotedInsts), TPT(TPT) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002546 IgnoreProfitability = false;
2547 }
Stephen Lin837bba12013-07-15 17:55:02 +00002548
Eugene Zelenko900b6332017-08-29 22:32:07 +00002549public:
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002550 /// Find the maximal addressing mode that a load/store of V can fold,
Chandler Carruthc8925912013-01-05 02:09:22 +00002551 /// give an access type of AccessTy. This returns a list of involved
2552 /// instructions in AddrModeInsts.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002553 /// \p InsertedInsts The instructions inserted by other CodeGenPrepare
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002554 /// optimizations.
2555 /// \p PromotedInsts maps the instructions to their type before promotion.
2556 /// \p The ongoing transaction where every action should be registered.
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002557 static ExtAddrMode Match(Value *V, Type *AccessTy, unsigned AS,
Chandler Carruthc8925912013-01-05 02:09:22 +00002558 Instruction *MemoryInst,
2559 SmallVectorImpl<Instruction*> &AddrModeInsts,
Igor Laevsky3be81ba2017-02-07 13:27:20 +00002560 const TargetLowering &TLI,
2561 const TargetRegisterInfo &TRI,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002562 const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002563 InstrToOrigTy &PromotedInsts,
2564 TypePromotionTransaction &TPT) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002565 ExtAddrMode Result;
2566
Igor Laevsky3be81ba2017-02-07 13:27:20 +00002567 bool Success = AddressingModeMatcher(AddrModeInsts, TLI, TRI,
2568 AccessTy, AS,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002569 MemoryInst, Result, InsertedInsts,
Sanjay Patelfc580a62015-09-21 23:03:16 +00002570 PromotedInsts, TPT).matchAddr(V, 0);
Chandler Carruthc8925912013-01-05 02:09:22 +00002571 (void)Success; assert(Success && "Couldn't select *anything*?");
2572 return Result;
2573 }
Eugene Zelenko900b6332017-08-29 22:32:07 +00002574
Chandler Carruthc8925912013-01-05 02:09:22 +00002575private:
Sanjay Patelfc580a62015-09-21 23:03:16 +00002576 bool matchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
2577 bool matchAddr(Value *V, unsigned Depth);
2578 bool matchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth,
Craig Topperc0196b12014-04-14 00:51:57 +00002579 bool *MovedAway = nullptr);
Sanjay Patelfc580a62015-09-21 23:03:16 +00002580 bool isProfitableToFoldIntoAddressingMode(Instruction *I,
Chandler Carruthc8925912013-01-05 02:09:22 +00002581 ExtAddrMode &AMBefore,
2582 ExtAddrMode &AMAfter);
Sanjay Patelfc580a62015-09-21 23:03:16 +00002583 bool valueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
2584 bool isPromotionProfitable(unsigned NewCost, unsigned OldCost,
Quentin Colombet867c5502014-02-14 22:23:22 +00002585 Value *PromotedOperand) const;
Chandler Carruthc8925912013-01-05 02:09:22 +00002586};
2587
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002588/// \brief Keep track of simplification of Phi nodes.
2589/// Accept the set of all phi nodes and erase phi node from this set
2590/// if it is simplified.
2591class SimplificationTracker {
2592 DenseMap<Value *, Value *> Storage;
2593 const SimplifyQuery &SQ;
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00002594 // Tracks newly created Phi nodes. We use a SetVector to get deterministic
2595 // order when iterating over the set in MatchPhiSet.
2596 SmallSetVector<PHINode *, 32> AllPhiNodes;
2597 // Tracks newly created Select nodes.
2598 SmallPtrSet<SelectInst *, 32> AllSelectNodes;
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002599
2600public:
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00002601 SimplificationTracker(const SimplifyQuery &sq)
2602 : SQ(sq) {}
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002603
2604 Value *Get(Value *V) {
2605 do {
2606 auto SV = Storage.find(V);
2607 if (SV == Storage.end())
2608 return V;
2609 V = SV->second;
2610 } while (true);
2611 }
2612
2613 Value *Simplify(Value *Val) {
2614 SmallVector<Value *, 32> WorkList;
2615 SmallPtrSet<Value *, 32> Visited;
2616 WorkList.push_back(Val);
2617 while (!WorkList.empty()) {
2618 auto P = WorkList.pop_back_val();
2619 if (!Visited.insert(P).second)
2620 continue;
2621 if (auto *PI = dyn_cast<Instruction>(P))
2622 if (Value *V = SimplifyInstruction(cast<Instruction>(PI), SQ)) {
2623 for (auto *U : PI->users())
2624 WorkList.push_back(cast<Value>(U));
2625 Put(PI, V);
2626 PI->replaceAllUsesWith(V);
2627 if (auto *PHI = dyn_cast<PHINode>(PI))
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00002628 AllPhiNodes.remove(PHI);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002629 if (auto *Select = dyn_cast<SelectInst>(PI))
2630 AllSelectNodes.erase(Select);
2631 PI->eraseFromParent();
2632 }
2633 }
2634 return Get(Val);
2635 }
2636
2637 void Put(Value *From, Value *To) {
2638 Storage.insert({ From, To });
2639 }
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00002640
2641 void ReplacePhi(PHINode *From, PHINode *To) {
2642 Value* OldReplacement = Get(From);
2643 while (OldReplacement != From) {
2644 From = To;
2645 To = dyn_cast<PHINode>(OldReplacement);
2646 OldReplacement = Get(From);
2647 }
2648 assert(Get(To) == To && "Replacement PHI node is already replaced.");
2649 Put(From, To);
2650 From->replaceAllUsesWith(To);
2651 AllPhiNodes.remove(From);
2652 From->eraseFromParent();
2653 }
2654
2655 SmallSetVector<PHINode *, 32>& newPhiNodes() { return AllPhiNodes; }
2656
2657 void insertNewPhi(PHINode *PN) { AllPhiNodes.insert(PN); }
2658
2659 void insertNewSelect(SelectInst *SI) { AllSelectNodes.insert(SI); }
2660
2661 unsigned countNewPhiNodes() const { return AllPhiNodes.size(); }
2662
2663 unsigned countNewSelectNodes() const { return AllSelectNodes.size(); }
2664
2665 void destroyNewNodes(Type *CommonType) {
2666 // For safe erasing, replace the uses with dummy value first.
2667 auto Dummy = UndefValue::get(CommonType);
2668 for (auto I : AllPhiNodes) {
2669 I->replaceAllUsesWith(Dummy);
2670 I->eraseFromParent();
2671 }
2672 AllPhiNodes.clear();
2673 for (auto I : AllSelectNodes) {
2674 I->replaceAllUsesWith(Dummy);
2675 I->eraseFromParent();
2676 }
2677 AllSelectNodes.clear();
2678 }
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002679};
2680
John Brawn736bf002017-10-03 13:08:22 +00002681/// \brief A helper class for combining addressing modes.
2682class AddressingModeCombiner {
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002683 typedef std::pair<Value *, BasicBlock *> ValueInBB;
2684 typedef DenseMap<ValueInBB, Value *> FoldAddrToValueMapping;
2685 typedef std::pair<PHINode *, PHINode *> PHIPair;
2686
John Brawn736bf002017-10-03 13:08:22 +00002687private:
2688 /// The addressing modes we've collected.
2689 SmallVector<ExtAddrMode, 16> AddrModes;
2690
2691 /// The field in which the AddrModes differ, when we have more than one.
2692 ExtAddrMode::FieldName DifferentField = ExtAddrMode::NoField;
2693
2694 /// Are the AddrModes that we have all just equal to their original values?
2695 bool AllAddrModesTrivial = true;
2696
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002697 /// Common Type for all different fields in addressing modes.
2698 Type *CommonType;
2699
2700 /// SimplifyQuery for simplifyInstruction utility.
2701 const SimplifyQuery &SQ;
2702
2703 /// Original Address.
2704 ValueInBB Original;
2705
John Brawn736bf002017-10-03 13:08:22 +00002706public:
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002707 AddressingModeCombiner(const SimplifyQuery &_SQ, ValueInBB OriginalValue)
2708 : CommonType(nullptr), SQ(_SQ), Original(OriginalValue) {}
2709
John Brawn736bf002017-10-03 13:08:22 +00002710 /// \brief Get the combined AddrMode
2711 const ExtAddrMode &getAddrMode() const {
2712 return AddrModes[0];
2713 }
2714
2715 /// \brief Add a new AddrMode if it's compatible with the AddrModes we already
2716 /// have.
2717 /// \return True iff we succeeded in doing so.
2718 bool addNewAddrMode(ExtAddrMode &NewAddrMode) {
2719 // Take note of if we have any non-trivial AddrModes, as we need to detect
2720 // when all AddrModes are trivial as then we would introduce a phi or select
2721 // which just duplicates what's already there.
2722 AllAddrModesTrivial = AllAddrModesTrivial && NewAddrMode.isTrivial();
2723
2724 // If this is the first addrmode then everything is fine.
2725 if (AddrModes.empty()) {
2726 AddrModes.emplace_back(NewAddrMode);
2727 return true;
2728 }
2729
2730 // Figure out how different this is from the other address modes, which we
2731 // can do just by comparing against the first one given that we only care
2732 // about the cumulative difference.
2733 ExtAddrMode::FieldName ThisDifferentField =
2734 AddrModes[0].compare(NewAddrMode);
2735 if (DifferentField == ExtAddrMode::NoField)
2736 DifferentField = ThisDifferentField;
2737 else if (DifferentField != ThisDifferentField)
2738 DifferentField = ExtAddrMode::MultipleFields;
2739
Serguei Katkov17e57942018-01-23 12:07:49 +00002740 // If NewAddrMode differs in more than one dimension we cannot handle it.
2741 bool CanHandle = DifferentField != ExtAddrMode::MultipleFields;
2742
2743 // If Scale Field is different then we reject.
2744 CanHandle = CanHandle && DifferentField != ExtAddrMode::ScaleField;
2745
Serguei Katkov4d1dd6b2018-01-09 04:37:06 +00002746 // We also must reject the case when base offset is different and
2747 // scale reg is not null, we cannot handle this case due to merge of
2748 // different offsets will be used as ScaleReg.
Serguei Katkov17e57942018-01-23 12:07:49 +00002749 CanHandle = CanHandle && (DifferentField != ExtAddrMode::BaseOffsField ||
2750 !NewAddrMode.ScaledReg);
John Brawn736bf002017-10-03 13:08:22 +00002751
Serguei Katkov17e57942018-01-23 12:07:49 +00002752 // We also must reject the case when GV is different and BaseReg installed
2753 // due to we want to use base reg as a merge of GV values.
2754 CanHandle = CanHandle && (DifferentField != ExtAddrMode::BaseGVField ||
2755 !NewAddrMode.HasBaseReg);
2756
2757 // Even if NewAddMode is the same we still need to collect it due to
2758 // original value is different. And later we will need all original values
2759 // as anchors during finding the common Phi node.
2760 if (CanHandle)
2761 AddrModes.emplace_back(NewAddrMode);
2762 else
2763 AddrModes.clear();
2764
2765 return CanHandle;
John Brawn736bf002017-10-03 13:08:22 +00002766 }
2767
2768 /// \brief Combine the addressing modes we've collected into a single
2769 /// addressing mode.
2770 /// \return True iff we successfully combined them or we only had one so
2771 /// didn't need to combine them anyway.
2772 bool combineAddrModes() {
2773 // If we have no AddrModes then they can't be combined.
2774 if (AddrModes.size() == 0)
2775 return false;
2776
2777 // A single AddrMode can trivially be combined.
Serguei Katkov505359f2017-11-20 05:42:36 +00002778 if (AddrModes.size() == 1 || DifferentField == ExtAddrMode::NoField)
John Brawn736bf002017-10-03 13:08:22 +00002779 return true;
2780
2781 // If the AddrModes we collected are all just equal to the value they are
2782 // derived from then combining them wouldn't do anything useful.
2783 if (AllAddrModesTrivial)
2784 return false;
2785
John Brawn70cdb5b2017-11-24 14:10:45 +00002786 if (!addrModeCombiningAllowed())
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002787 return false;
2788
2789 // Build a map between <original value, basic block where we saw it> to
2790 // value of base register.
Serguei Katkov50364592017-11-29 05:51:26 +00002791 // Bail out if there is no common type.
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002792 FoldAddrToValueMapping Map;
Serguei Katkov50364592017-11-29 05:51:26 +00002793 if (!initializeMap(Map))
2794 return false;
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002795
2796 Value *CommonValue = findCommon(Map);
2797 if (CommonValue)
John Brawn70cdb5b2017-11-24 14:10:45 +00002798 AddrModes[0].SetCombinedField(DifferentField, CommonValue, AddrModes);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002799 return CommonValue != nullptr;
2800 }
2801
2802private:
2803 /// \brief Initialize Map with anchor values. For address seen in some BB
2804 /// we set the value of different field saw in this address.
2805 /// If address is not an instruction than basic block is set to null.
2806 /// At the same time we find a common type for different field we will
2807 /// use to create new Phi/Select nodes. Keep it in CommonType field.
Serguei Katkov50364592017-11-29 05:51:26 +00002808 /// Return false if there is no common type found.
2809 bool initializeMap(FoldAddrToValueMapping &Map) {
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002810 // Keep track of keys where the value is null. We will need to replace it
2811 // with constant null when we know the common type.
2812 SmallVector<ValueInBB, 2> NullValue;
John Brawn70cdb5b2017-11-24 14:10:45 +00002813 Type *IntPtrTy = SQ.DL.getIntPtrType(AddrModes[0].OriginalValue->getType());
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002814 for (auto &AM : AddrModes) {
2815 BasicBlock *BB = nullptr;
2816 if (Instruction *I = dyn_cast<Instruction>(AM.OriginalValue))
2817 BB = I->getParent();
2818
John Brawn70cdb5b2017-11-24 14:10:45 +00002819 Value *DV = AM.GetFieldAsValue(DifferentField, IntPtrTy);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002820 if (DV) {
Serguei Katkov50364592017-11-29 05:51:26 +00002821 auto *Type = DV->getType();
2822 if (CommonType && CommonType != Type)
2823 return false;
2824 CommonType = Type;
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002825 Map[{ AM.OriginalValue, BB }] = DV;
2826 } else {
2827 NullValue.push_back({ AM.OriginalValue, BB });
2828 }
2829 }
2830 assert(CommonType && "At least one non-null value must be!");
2831 for (auto VIBB : NullValue)
2832 Map[VIBB] = Constant::getNullValue(CommonType);
Serguei Katkov50364592017-11-29 05:51:26 +00002833 return true;
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002834 }
2835
2836 /// \brief We have mapping between value A and basic block where value A
2837 /// seen to other value B where B was a field in addressing mode represented
2838 /// by A. Also we have an original value C representin an address in some
2839 /// basic block. Traversing from C through phi and selects we ended up with
2840 /// A's in a map. This utility function tries to find a value V which is a
2841 /// field in addressing mode C and traversing through phi nodes and selects
2842 /// we will end up in corresponded values B in a map.
2843 /// The utility will create a new Phi/Selects if needed.
2844 // The simple example looks as follows:
2845 // BB1:
2846 // p1 = b1 + 40
2847 // br cond BB2, BB3
2848 // BB2:
2849 // p2 = b2 + 40
2850 // br BB3
2851 // BB3:
2852 // p = phi [p1, BB1], [p2, BB2]
2853 // v = load p
2854 // Map is
2855 // <p1, BB1> -> b1
2856 // <p2, BB2> -> b2
2857 // Request is
2858 // <p, BB3> -> ?
2859 // The function tries to find or build phi [b1, BB1], [b2, BB2] in BB3
2860 Value *findCommon(FoldAddrToValueMapping &Map) {
Eric Christopherd72f78e2018-01-09 23:25:38 +00002861 // Tracks the simplification of newly created phi nodes. The reason we use
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002862 // this mapping is because we will add new created Phi nodes in AddrToBase.
2863 // Simplification of Phi nodes is recursive, so some Phi node may
2864 // be simplified after we added it to AddrToBase.
2865 // Using this mapping we can find the current value in AddrToBase.
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00002866 SimplificationTracker ST(SQ);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002867
2868 // First step, DFS to create PHI nodes for all intermediate blocks.
2869 // Also fill traverse order for the second step.
2870 SmallVector<ValueInBB, 32> TraverseOrder;
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00002871 InsertPlaceholders(Map, TraverseOrder, ST);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002872
2873 // Second Step, fill new nodes by merged values and simplify if possible.
2874 FillPlaceholders(Map, TraverseOrder, ST);
2875
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00002876 if (!AddrSinkNewSelects && ST.countNewSelectNodes() > 0) {
2877 ST.destroyNewNodes(CommonType);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002878 return nullptr;
2879 }
2880
2881 // Now we'd like to match New Phi nodes to existed ones.
2882 unsigned PhiNotMatchedCount = 0;
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00002883 if (!MatchPhiSet(ST, AddrSinkNewPhis, PhiNotMatchedCount)) {
2884 ST.destroyNewNodes(CommonType);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002885 return nullptr;
2886 }
2887
2888 auto *Result = ST.Get(Map.find(Original)->second);
2889 if (Result) {
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00002890 NumMemoryInstsPhiCreated += ST.countNewPhiNodes() + PhiNotMatchedCount;
2891 NumMemoryInstsSelectCreated += ST.countNewSelectNodes();
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002892 }
2893 return Result;
2894 }
2895
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002896 /// \brief Try to match PHI node to Candidate.
2897 /// Matcher tracks the matched Phi nodes.
2898 bool MatchPhiNode(PHINode *PHI, PHINode *Candidate,
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00002899 SmallSetVector<PHIPair, 8> &Matcher,
2900 SmallSetVector<PHINode *, 32> &PhiNodesToMatch) {
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002901 SmallVector<PHIPair, 8> WorkList;
2902 Matcher.insert({ PHI, Candidate });
2903 WorkList.push_back({ PHI, Candidate });
2904 SmallSet<PHIPair, 8> Visited;
2905 while (!WorkList.empty()) {
2906 auto Item = WorkList.pop_back_val();
2907 if (!Visited.insert(Item).second)
2908 continue;
2909 // We iterate over all incoming values to Phi to compare them.
2910 // If values are different and both of them Phi and the first one is a
2911 // Phi we added (subject to match) and both of them is in the same basic
2912 // block then we can match our pair if values match. So we state that
2913 // these values match and add it to work list to verify that.
2914 for (auto B : Item.first->blocks()) {
2915 Value *FirstValue = Item.first->getIncomingValueForBlock(B);
2916 Value *SecondValue = Item.second->getIncomingValueForBlock(B);
2917 if (FirstValue == SecondValue)
2918 continue;
2919
2920 PHINode *FirstPhi = dyn_cast<PHINode>(FirstValue);
2921 PHINode *SecondPhi = dyn_cast<PHINode>(SecondValue);
2922
2923 // One of them is not Phi or
2924 // The first one is not Phi node from the set we'd like to match or
2925 // Phi nodes from different basic blocks then
2926 // we will not be able to match.
2927 if (!FirstPhi || !SecondPhi || !PhiNodesToMatch.count(FirstPhi) ||
2928 FirstPhi->getParent() != SecondPhi->getParent())
2929 return false;
2930
2931 // If we already matched them then continue.
2932 if (Matcher.count({ FirstPhi, SecondPhi }))
2933 continue;
2934 // So the values are different and does not match. So we need them to
2935 // match.
2936 Matcher.insert({ FirstPhi, SecondPhi });
2937 // But me must check it.
2938 WorkList.push_back({ FirstPhi, SecondPhi });
2939 }
2940 }
2941 return true;
2942 }
2943
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00002944 /// \brief For the given set of PHI nodes (in the SimplificationTracker) try
2945 /// to find their equivalents.
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002946 /// Returns false if this matching fails and creation of new Phi is disabled.
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00002947 bool MatchPhiSet(SimplificationTracker &ST, bool AllowNewPhiNodes,
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002948 unsigned &PhiNotMatchedCount) {
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00002949 // Use a SetVector for Matched to make sure we do replacements (ReplacePhi)
2950 // in a deterministic order below.
2951 SmallSetVector<PHIPair, 8> Matched;
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002952 SmallPtrSet<PHINode *, 8> WillNotMatch;
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00002953 SmallSetVector<PHINode *, 32> &PhiNodesToMatch = ST.newPhiNodes();
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002954 while (PhiNodesToMatch.size()) {
2955 PHINode *PHI = *PhiNodesToMatch.begin();
2956
2957 // Add us, if no Phi nodes in the basic block we do not match.
2958 WillNotMatch.clear();
2959 WillNotMatch.insert(PHI);
2960
2961 // Traverse all Phis until we found equivalent or fail to do that.
2962 bool IsMatched = false;
2963 for (auto &P : PHI->getParent()->phis()) {
2964 if (&P == PHI)
2965 continue;
2966 if ((IsMatched = MatchPhiNode(PHI, &P, Matched, PhiNodesToMatch)))
2967 break;
2968 // If it does not match, collect all Phi nodes from matcher.
2969 // if we end up with no match, them all these Phi nodes will not match
2970 // later.
2971 for (auto M : Matched)
2972 WillNotMatch.insert(M.first);
2973 Matched.clear();
2974 }
2975 if (IsMatched) {
Serguei Katkova20e05b2018-03-12 03:50:07 +00002976 // Replace all matched values and erase them.
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00002977 for (auto MV : Matched)
2978 ST.ReplacePhi(MV.first, MV.second);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002979 Matched.clear();
2980 continue;
2981 }
2982 // If we are not allowed to create new nodes then bail out.
2983 if (!AllowNewPhiNodes)
2984 return false;
2985 // Just remove all seen values in matcher. They will not match anything.
2986 PhiNotMatchedCount += WillNotMatch.size();
2987 for (auto *P : WillNotMatch)
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00002988 PhiNodesToMatch.remove(P);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002989 }
2990 return true;
2991 }
2992 /// \brief Fill the placeholder with values from predecessors and simplify it.
2993 void FillPlaceholders(FoldAddrToValueMapping &Map,
2994 SmallVectorImpl<ValueInBB> &TraverseOrder,
2995 SimplificationTracker &ST) {
2996 while (!TraverseOrder.empty()) {
2997 auto Current = TraverseOrder.pop_back_val();
2998 assert(Map.find(Current) != Map.end() && "No node to fill!!!");
2999 Value *CurrentValue = Current.first;
3000 BasicBlock *CurrentBlock = Current.second;
3001 Value *V = Map[Current];
3002
3003 if (SelectInst *Select = dyn_cast<SelectInst>(V)) {
3004 // CurrentValue also must be Select.
3005 auto *CurrentSelect = cast<SelectInst>(CurrentValue);
3006 auto *TrueValue = CurrentSelect->getTrueValue();
3007 ValueInBB TrueItem = { TrueValue, isa<Instruction>(TrueValue)
3008 ? CurrentBlock
3009 : nullptr };
3010 assert(Map.find(TrueItem) != Map.end() && "No True Value!");
Serguei Katkovb0b67a82017-12-18 04:25:07 +00003011 Select->setTrueValue(ST.Get(Map[TrueItem]));
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003012 auto *FalseValue = CurrentSelect->getFalseValue();
3013 ValueInBB FalseItem = { FalseValue, isa<Instruction>(FalseValue)
3014 ? CurrentBlock
3015 : nullptr };
3016 assert(Map.find(FalseItem) != Map.end() && "No False Value!");
Serguei Katkovb0b67a82017-12-18 04:25:07 +00003017 Select->setFalseValue(ST.Get(Map[FalseItem]));
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003018 } else {
3019 // Must be a Phi node then.
3020 PHINode *PHI = cast<PHINode>(V);
3021 // Fill the Phi node with values from predecessors.
3022 bool IsDefinedInThisBB =
3023 cast<Instruction>(CurrentValue)->getParent() == CurrentBlock;
3024 auto *CurrentPhi = dyn_cast<PHINode>(CurrentValue);
3025 for (auto B : predecessors(CurrentBlock)) {
3026 Value *PV = IsDefinedInThisBB
3027 ? CurrentPhi->getIncomingValueForBlock(B)
3028 : CurrentValue;
3029 ValueInBB item = { PV, isa<Instruction>(PV) ? B : nullptr };
3030 assert(Map.find(item) != Map.end() && "No predecessor Value!");
3031 PHI->addIncoming(ST.Get(Map[item]), B);
3032 }
3033 }
3034 // Simplify if possible.
3035 Map[Current] = ST.Simplify(V);
3036 }
3037 }
3038
3039 /// Starting from value recursively iterates over predecessors up to known
3040 /// ending values represented in a map. For each traversed block inserts
3041 /// a placeholder Phi or Select.
3042 /// Reports all new created Phi/Select nodes by adding them to set.
3043 /// Also reports and order in what basic blocks have been traversed.
3044 void InsertPlaceholders(FoldAddrToValueMapping &Map,
3045 SmallVectorImpl<ValueInBB> &TraverseOrder,
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003046 SimplificationTracker &ST) {
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003047 SmallVector<ValueInBB, 32> Worklist;
3048 assert((isa<PHINode>(Original.first) || isa<SelectInst>(Original.first)) &&
3049 "Address must be a Phi or Select node");
3050 auto *Dummy = UndefValue::get(CommonType);
3051 Worklist.push_back(Original);
3052 while (!Worklist.empty()) {
3053 auto Current = Worklist.pop_back_val();
3054 // If value is not an instruction it is something global, constant,
3055 // parameter and we can say that this value is observable in any block.
3056 // Set block to null to denote it.
3057 // Also please take into account that it is how we build anchors.
3058 if (!isa<Instruction>(Current.first))
3059 Current.second = nullptr;
3060 // if it is already visited or it is an ending value then skip it.
3061 if (Map.find(Current) != Map.end())
3062 continue;
3063 TraverseOrder.push_back(Current);
3064
3065 Value *CurrentValue = Current.first;
3066 BasicBlock *CurrentBlock = Current.second;
3067 // CurrentValue must be a Phi node or select. All others must be covered
3068 // by anchors.
3069 Instruction *CurrentI = cast<Instruction>(CurrentValue);
3070 bool IsDefinedInThisBB = CurrentI->getParent() == CurrentBlock;
3071
3072 unsigned PredCount =
3073 std::distance(pred_begin(CurrentBlock), pred_end(CurrentBlock));
3074 // if Current Value is not defined in this basic block we are interested
3075 // in values in predecessors.
3076 if (!IsDefinedInThisBB) {
3077 assert(PredCount && "Unreachable block?!");
3078 PHINode *PHI = PHINode::Create(CommonType, PredCount, "sunk_phi",
3079 &CurrentBlock->front());
3080 Map[Current] = PHI;
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003081 ST.insertNewPhi(PHI);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003082 // Add all predecessors in work list.
3083 for (auto B : predecessors(CurrentBlock))
3084 Worklist.push_back({ CurrentValue, B });
3085 continue;
3086 }
3087 // Value is defined in this basic block.
3088 if (SelectInst *OrigSelect = dyn_cast<SelectInst>(CurrentI)) {
3089 // Is it OK to get metadata from OrigSelect?!
3090 // Create a Select placeholder with dummy value.
3091 SelectInst *Select =
3092 SelectInst::Create(OrigSelect->getCondition(), Dummy, Dummy,
3093 OrigSelect->getName(), OrigSelect, OrigSelect);
3094 Map[Current] = Select;
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003095 ST.insertNewSelect(Select);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003096 // We are interested in True and False value in this basic block.
3097 Worklist.push_back({ OrigSelect->getTrueValue(), CurrentBlock });
3098 Worklist.push_back({ OrigSelect->getFalseValue(), CurrentBlock });
3099 } else {
3100 // It must be a Phi node then.
3101 auto *CurrentPhi = cast<PHINode>(CurrentI);
3102 // Create new Phi node for merge of bases.
3103 assert(PredCount && "Unreachable block?!");
3104 PHINode *PHI = PHINode::Create(CommonType, PredCount, "sunk_phi",
3105 &CurrentBlock->front());
3106 Map[Current] = PHI;
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003107 ST.insertNewPhi(PHI);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003108
3109 // Add all predecessors in work list.
3110 for (auto B : predecessors(CurrentBlock))
3111 Worklist.push_back({ CurrentPhi->getIncomingValueForBlock(B), B });
3112 }
3113 }
John Brawn736bf002017-10-03 13:08:22 +00003114 }
John Brawn70cdb5b2017-11-24 14:10:45 +00003115
3116 bool addrModeCombiningAllowed() {
3117 if (DisableComplexAddrModes)
3118 return false;
3119 switch (DifferentField) {
3120 default:
3121 return false;
3122 case ExtAddrMode::BaseRegField:
3123 return AddrSinkCombineBaseReg;
3124 case ExtAddrMode::BaseGVField:
3125 return AddrSinkCombineBaseGV;
3126 case ExtAddrMode::BaseOffsField:
3127 return AddrSinkCombineBaseOffs;
3128 case ExtAddrMode::ScaledRegField:
3129 return AddrSinkCombineScaledReg;
3130 }
3131 }
John Brawn736bf002017-10-03 13:08:22 +00003132};
Eugene Zelenko900b6332017-08-29 22:32:07 +00003133} // end anonymous namespace
3134
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003135/// Try adding ScaleReg*Scale to the current addressing mode.
Chandler Carruthc8925912013-01-05 02:09:22 +00003136/// Return true and update AddrMode if this addr mode is legal for the target,
3137/// false if not.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003138bool AddressingModeMatcher::matchScaledValue(Value *ScaleReg, int64_t Scale,
Chandler Carruthc8925912013-01-05 02:09:22 +00003139 unsigned Depth) {
3140 // If Scale is 1, then this is the same as adding ScaleReg to the addressing
3141 // mode. Just process that directly.
3142 if (Scale == 1)
Sanjay Patelfc580a62015-09-21 23:03:16 +00003143 return matchAddr(ScaleReg, Depth);
Stephen Lin837bba12013-07-15 17:55:02 +00003144
Chandler Carruthc8925912013-01-05 02:09:22 +00003145 // If the scale is 0, it takes nothing to add this.
3146 if (Scale == 0)
3147 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003148
Chandler Carruthc8925912013-01-05 02:09:22 +00003149 // If we already have a scale of this value, we can add to it, otherwise, we
3150 // need an available scale field.
3151 if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
3152 return false;
3153
3154 ExtAddrMode TestAddrMode = AddrMode;
3155
3156 // Add scale to turn X*4+X*3 -> X*7. This could also do things like
3157 // [A+B + A*7] -> [B+A*8].
3158 TestAddrMode.Scale += Scale;
3159 TestAddrMode.ScaledReg = ScaleReg;
3160
3161 // If the new address isn't legal, bail out.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003162 if (!TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003163 return false;
3164
3165 // It was legal, so commit it.
3166 AddrMode = TestAddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00003167
Chandler Carruthc8925912013-01-05 02:09:22 +00003168 // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
3169 // to see if ScaleReg is actually X+C. If so, we can turn this into adding
3170 // X*Scale + C*Scale to addr mode.
Craig Topperc0196b12014-04-14 00:51:57 +00003171 ConstantInt *CI = nullptr; Value *AddLHS = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003172 if (isa<Instruction>(ScaleReg) && // not a constant expr.
3173 match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
3174 TestAddrMode.ScaledReg = AddLHS;
3175 TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00003176
Chandler Carruthc8925912013-01-05 02:09:22 +00003177 // If this addressing mode is legal, commit it and remember that we folded
3178 // this instruction.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003179 if (TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003180 AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
3181 AddrMode = TestAddrMode;
3182 return true;
3183 }
3184 }
3185
3186 // Otherwise, not (x+c)*scale, just return what we have.
3187 return true;
3188}
3189
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003190/// This is a little filter, which returns true if an addressing computation
3191/// involving I might be folded into a load/store accessing it.
3192/// This doesn't need to be perfect, but needs to accept at least
Chandler Carruthc8925912013-01-05 02:09:22 +00003193/// the set of instructions that MatchOperationAddr can.
3194static bool MightBeFoldableInst(Instruction *I) {
3195 switch (I->getOpcode()) {
3196 case Instruction::BitCast:
Eli Benderskyf13a0562014-05-22 00:02:52 +00003197 case Instruction::AddrSpaceCast:
Chandler Carruthc8925912013-01-05 02:09:22 +00003198 // Don't touch identity bitcasts.
3199 if (I->getType() == I->getOperand(0)->getType())
3200 return false;
3201 return I->getType()->isPointerTy() || I->getType()->isIntegerTy();
3202 case Instruction::PtrToInt:
3203 // PtrToInt is always a noop, as we know that the int type is pointer sized.
3204 return true;
3205 case Instruction::IntToPtr:
3206 // We know the input is intptr_t, so this is foldable.
3207 return true;
3208 case Instruction::Add:
3209 return true;
3210 case Instruction::Mul:
3211 case Instruction::Shl:
3212 // Can only handle X*C and X << C.
3213 return isa<ConstantInt>(I->getOperand(1));
3214 case Instruction::GetElementPtr:
3215 return true;
3216 default:
3217 return false;
3218 }
3219}
3220
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003221/// \brief Check whether or not \p Val is a legal instruction for \p TLI.
3222/// \note \p Val is assumed to be the product of some type promotion.
3223/// Therefore if \p Val has an undefined state in \p TLI, this is assumed
3224/// to be legal, as the non-promoted value would have had the same state.
Mehdi Amini44ede332015-07-09 02:09:04 +00003225static bool isPromotedInstructionLegal(const TargetLowering &TLI,
3226 const DataLayout &DL, Value *Val) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003227 Instruction *PromotedInst = dyn_cast<Instruction>(Val);
3228 if (!PromotedInst)
3229 return false;
3230 int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode());
3231 // If the ISDOpcode is undefined, it was undefined before the promotion.
3232 if (!ISDOpcode)
3233 return true;
3234 // Otherwise, check if the promoted instruction is legal or not.
3235 return TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00003236 ISDOpcode, TLI.getValueType(DL, PromotedInst->getType()));
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003237}
3238
Eugene Zelenko900b6332017-08-29 22:32:07 +00003239namespace {
3240
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003241/// \brief Hepler class to perform type promotion.
3242class TypePromotionHelper {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003243 /// \brief Utility function to check whether or not a sign or zero extension
3244 /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by
3245 /// either using the operands of \p Inst or promoting \p Inst.
3246 /// The type of the extension is defined by \p IsSExt.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003247 /// In other words, check if:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003248 /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003249 /// #1 Promotion applies:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003250 /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...).
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003251 /// #2 Operand reuses:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003252 /// ext opnd1 to ConsideredExtType.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003253 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003254 static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType,
3255 const InstrToOrigTy &PromotedInsts, bool IsSExt);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003256
3257 /// \brief Utility function to determine if \p OpIdx should be promoted when
3258 /// promoting \p Inst.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003259 static bool shouldExtOperand(const Instruction *Inst, int OpIdx) {
Rafael Espindola84921b92015-10-24 23:11:13 +00003260 return !(isa<SelectInst>(Inst) && OpIdx == 0);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003261 }
3262
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003263 /// \brief Utility function to promote the operand of \p Ext when this
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003264 /// operand is a promotable trunc or sext or zext.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003265 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003266 /// \p CreatedInstsCost[out] contains the cost of all instructions
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003267 /// created to promote the operand of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003268 /// Newly added extensions are inserted in \p Exts.
3269 /// Newly added truncates are inserted in \p Truncs.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003270 /// Should never be called directly.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003271 /// \return The promoted value which is used instead of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003272 static Value *promoteOperandForTruncAndAnyExt(
3273 Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003274 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003275 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003276 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003277
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003278 /// \brief Utility function to promote the operand of \p Ext when this
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003279 /// operand is promotable and is not a supported trunc or sext.
3280 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003281 /// \p CreatedInstsCost[out] contains the cost of all the instructions
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003282 /// created to promote the operand of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003283 /// Newly added extensions are inserted in \p Exts.
3284 /// Newly added truncates are inserted in \p Truncs.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003285 /// Should never be called directly.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003286 /// \return The promoted value which is used instead of Ext.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003287 static Value *promoteOperandForOther(Instruction *Ext,
3288 TypePromotionTransaction &TPT,
3289 InstrToOrigTy &PromotedInsts,
3290 unsigned &CreatedInstsCost,
3291 SmallVectorImpl<Instruction *> *Exts,
3292 SmallVectorImpl<Instruction *> *Truncs,
3293 const TargetLowering &TLI, bool IsSExt);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003294
3295 /// \see promoteOperandForOther.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003296 static Value *signExtendOperandForOther(
3297 Instruction *Ext, TypePromotionTransaction &TPT,
3298 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
3299 SmallVectorImpl<Instruction *> *Exts,
3300 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
3301 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
3302 Exts, Truncs, TLI, true);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003303 }
3304
3305 /// \see promoteOperandForOther.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003306 static Value *zeroExtendOperandForOther(
3307 Instruction *Ext, TypePromotionTransaction &TPT,
3308 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
3309 SmallVectorImpl<Instruction *> *Exts,
3310 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
3311 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
3312 Exts, Truncs, TLI, false);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003313 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003314
3315public:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003316 /// Type for the utility function that promotes the operand of Ext.
Eugene Zelenko900b6332017-08-29 22:32:07 +00003317 using Action = Value *(*)(Instruction *Ext, TypePromotionTransaction &TPT,
3318 InstrToOrigTy &PromotedInsts,
3319 unsigned &CreatedInstsCost,
3320 SmallVectorImpl<Instruction *> *Exts,
3321 SmallVectorImpl<Instruction *> *Truncs,
3322 const TargetLowering &TLI);
3323
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003324 /// \brief Given a sign/zero extend instruction \p Ext, return the approriate
3325 /// action to promote the operand of \p Ext instead of using Ext.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003326 /// \return NULL if no promotable action is possible with the current
3327 /// sign extension.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003328 /// \p InsertedInsts keeps track of all the instructions inserted by the
3329 /// other CodeGenPrepare optimizations. This information is important
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003330 /// because we do not want to promote these instructions as CodeGenPrepare
3331 /// will reinsert them later. Thus creating an infinite loop: create/remove.
3332 /// \p PromotedInsts maps the instructions to their type before promotion.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003333 static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003334 const TargetLowering &TLI,
3335 const InstrToOrigTy &PromotedInsts);
3336};
3337
Eugene Zelenko900b6332017-08-29 22:32:07 +00003338} // end anonymous namespace
3339
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003340bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003341 Type *ConsideredExtType,
3342 const InstrToOrigTy &PromotedInsts,
3343 bool IsSExt) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003344 // The promotion helper does not know how to deal with vector types yet.
3345 // To be able to fix that, we would need to fix the places where we
3346 // statically extend, e.g., constants and such.
3347 if (Inst->getType()->isVectorTy())
3348 return false;
3349
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003350 // We can always get through zext.
3351 if (isa<ZExtInst>(Inst))
3352 return true;
3353
3354 // sext(sext) is ok too.
3355 if (IsSExt && isa<SExtInst>(Inst))
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003356 return true;
3357
3358 // We can get through binary operator, if it is legal. In other words, the
3359 // binary operator must have a nuw or nsw flag.
3360 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
3361 if (BinOp && isa<OverflowingBinaryOperator>(BinOp) &&
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003362 ((!IsSExt && BinOp->hasNoUnsignedWrap()) ||
3363 (IsSExt && BinOp->hasNoSignedWrap())))
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003364 return true;
3365
3366 // Check if we can do the following simplification.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003367 // ext(trunc(opnd)) --> ext(opnd)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003368 if (!isa<TruncInst>(Inst))
3369 return false;
3370
3371 Value *OpndVal = Inst->getOperand(0);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003372 // Check if we can use this operand in the extension.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003373 // If the type is larger than the result type of the extension, we cannot.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003374 if (!OpndVal->getType()->isIntegerTy() ||
3375 OpndVal->getType()->getIntegerBitWidth() >
3376 ConsideredExtType->getIntegerBitWidth())
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003377 return false;
3378
3379 // If the operand of the truncate is not an instruction, we will not have
3380 // any information on the dropped bits.
3381 // (Actually we could for constant but it is not worth the extra logic).
3382 Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
3383 if (!Opnd)
3384 return false;
3385
3386 // Check if the source of the type is narrow enough.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003387 // I.e., check that trunc just drops extended bits of the same kind of
3388 // the extension.
3389 // #1 get the type of the operand and check the kind of the extended bits.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003390 const Type *OpndType;
3391 InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
Benjamin Kramer4cd5faa2015-07-31 17:00:39 +00003392 if (It != PromotedInsts.end() && It->second.getInt() == IsSExt)
3393 OpndType = It->second.getPointer();
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003394 else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd)))
3395 OpndType = Opnd->getOperand(0)->getType();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003396 else
3397 return false;
3398
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003399 // #2 check that the truncate just drops extended bits.
Rafael Espindola84921b92015-10-24 23:11:13 +00003400 return Inst->getType()->getIntegerBitWidth() >=
3401 OpndType->getIntegerBitWidth();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003402}
3403
3404TypePromotionHelper::Action TypePromotionHelper::getAction(
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003405 Instruction *Ext, const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003406 const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003407 assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
3408 "Unexpected instruction type");
3409 Instruction *ExtOpnd = dyn_cast<Instruction>(Ext->getOperand(0));
3410 Type *ExtTy = Ext->getType();
3411 bool IsSExt = isa<SExtInst>(Ext);
3412 // If the operand of the extension is not an instruction, we cannot
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003413 // get through.
3414 // If it, check we can get through.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003415 if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt))
Craig Topperc0196b12014-04-14 00:51:57 +00003416 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003417
3418 // Do not promote if the operand has been added by codegenprepare.
3419 // Otherwise, it means we are undoing an optimization that is likely to be
3420 // redone, thus causing potential infinite loop.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003421 if (isa<TruncInst>(ExtOpnd) && InsertedInsts.count(ExtOpnd))
Craig Topperc0196b12014-04-14 00:51:57 +00003422 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003423
3424 // SExt or Trunc instructions.
3425 // Return the related handler.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003426 if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) ||
3427 isa<ZExtInst>(ExtOpnd))
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003428 return promoteOperandForTruncAndAnyExt;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003429
3430 // Regular instruction.
3431 // Abort early if we will have to insert non-free instructions.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003432 if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(ExtTy, ExtOpnd->getType()))
Craig Topperc0196b12014-04-14 00:51:57 +00003433 return nullptr;
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003434 return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003435}
3436
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003437Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt(
Eugene Zelenko900b6332017-08-29 22:32:07 +00003438 Instruction *SExt, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003439 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003440 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003441 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003442 // By construction, the operand of SExt is an instruction. Otherwise we cannot
3443 // get through it and this method should not be called.
3444 Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
Quentin Colombetac55b152014-09-16 22:36:07 +00003445 Value *ExtVal = SExt;
Quentin Colombet1b274f92015-03-10 21:48:15 +00003446 bool HasMergedNonFreeExt = false;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003447 if (isa<ZExtInst>(SExtOpnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003448 // Replace s|zext(zext(opnd))
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003449 // => zext(opnd).
Quentin Colombet1b274f92015-03-10 21:48:15 +00003450 HasMergedNonFreeExt = !TLI.isExtFree(SExtOpnd);
Quentin Colombetac55b152014-09-16 22:36:07 +00003451 Value *ZExt =
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003452 TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType());
3453 TPT.replaceAllUsesWith(SExt, ZExt);
3454 TPT.eraseInstruction(SExt);
Quentin Colombetac55b152014-09-16 22:36:07 +00003455 ExtVal = ZExt;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003456 } else {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003457 // Replace z|sext(trunc(opnd)) or sext(sext(opnd))
3458 // => z|sext(opnd).
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003459 TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
3460 }
Quentin Colombet1b274f92015-03-10 21:48:15 +00003461 CreatedInstsCost = 0;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003462
3463 // Remove dead code.
3464 if (SExtOpnd->use_empty())
3465 TPT.eraseInstruction(SExtOpnd);
3466
Quentin Colombet9dcb7242014-09-15 18:26:58 +00003467 // Check if the extension is still needed.
Quentin Colombetac55b152014-09-16 22:36:07 +00003468 Instruction *ExtInst = dyn_cast<Instruction>(ExtVal);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003469 if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType()) {
Quentin Colombet1b274f92015-03-10 21:48:15 +00003470 if (ExtInst) {
3471 if (Exts)
3472 Exts->push_back(ExtInst);
3473 CreatedInstsCost = !TLI.isExtFree(ExtInst) && !HasMergedNonFreeExt;
3474 }
Quentin Colombetac55b152014-09-16 22:36:07 +00003475 return ExtVal;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003476 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003477
Quentin Colombet9dcb7242014-09-15 18:26:58 +00003478 // At this point we have: ext ty opnd to ty.
3479 // Reassign the uses of ExtInst to the opnd and remove ExtInst.
3480 Value *NextVal = ExtInst->getOperand(0);
3481 TPT.eraseInstruction(ExtInst, NextVal);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003482 return NextVal;
3483}
3484
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003485Value *TypePromotionHelper::promoteOperandForOther(
3486 Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003487 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003488 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003489 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI,
3490 bool IsSExt) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003491 // By construction, the operand of Ext is an instruction. Otherwise we cannot
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003492 // get through it and this method should not be called.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003493 Instruction *ExtOpnd = cast<Instruction>(Ext->getOperand(0));
Quentin Colombet1b274f92015-03-10 21:48:15 +00003494 CreatedInstsCost = 0;
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003495 if (!ExtOpnd->hasOneUse()) {
3496 // ExtOpnd will be promoted.
3497 // All its uses, but Ext, will need to use a truncated value of the
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003498 // promoted version.
3499 // Create the truncate now.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003500 Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->getType());
Quentin Colombetac55b152014-09-16 22:36:07 +00003501 if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) {
Quentin Colombetac55b152014-09-16 22:36:07 +00003502 // Insert it just after the definition.
Sanjay Patel674d2c22017-08-29 14:07:48 +00003503 ITrunc->moveAfter(ExtOpnd);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003504 if (Truncs)
3505 Truncs->push_back(ITrunc);
Quentin Colombetac55b152014-09-16 22:36:07 +00003506 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003507
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003508 TPT.replaceAllUsesWith(ExtOpnd, Trunc);
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003509 // Restore the operand of Ext (which has been replaced by the previous call
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003510 // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003511 TPT.setOperand(Ext, 0, ExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003512 }
3513
3514 // Get through the Instruction:
3515 // 1. Update its type.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003516 // 2. Replace the uses of Ext by Inst.
3517 // 3. Extend each operand that needs to be extended.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003518
3519 // Remember the original type of the instruction before promotion.
3520 // This is useful to know that the high bits are sign extended bits.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003521 PromotedInsts.insert(std::pair<Instruction *, TypeIsSExt>(
3522 ExtOpnd, TypeIsSExt(ExtOpnd->getType(), IsSExt)));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003523 // Step #1.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003524 TPT.mutateType(ExtOpnd, Ext->getType());
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003525 // Step #2.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003526 TPT.replaceAllUsesWith(Ext, ExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003527 // Step #3.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003528 Instruction *ExtForOpnd = Ext;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003529
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003530 DEBUG(dbgs() << "Propagate Ext to operands\n");
3531 for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003532 ++OpIdx) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003533 DEBUG(dbgs() << "Operand:\n" << *(ExtOpnd->getOperand(OpIdx)) << '\n');
3534 if (ExtOpnd->getOperand(OpIdx)->getType() == Ext->getType() ||
3535 !shouldExtOperand(ExtOpnd, OpIdx)) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003536 DEBUG(dbgs() << "No need to propagate\n");
3537 continue;
3538 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003539 // Check if we can statically extend the operand.
3540 Value *Opnd = ExtOpnd->getOperand(OpIdx);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003541 if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003542 DEBUG(dbgs() << "Statically extend\n");
3543 unsigned BitWidth = Ext->getType()->getIntegerBitWidth();
3544 APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth)
3545 : Cst->getValue().zext(BitWidth);
3546 TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->getType(), CstVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003547 continue;
3548 }
3549 // UndefValue are typed, so we have to statically sign extend them.
3550 if (isa<UndefValue>(Opnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003551 DEBUG(dbgs() << "Statically extend\n");
3552 TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->getType()));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003553 continue;
3554 }
3555
3556 // Otherwise we have to explicity sign extend the operand.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003557 // Check if Ext was reused to extend an operand.
3558 if (!ExtForOpnd) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003559 // If yes, create a new one.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003560 DEBUG(dbgs() << "More operands to ext\n");
Quentin Colombet84f89cc2014-12-22 18:11:52 +00003561 Value *ValForExtOpnd = IsSExt ? TPT.createSExt(Ext, Opnd, Ext->getType())
3562 : TPT.createZExt(Ext, Opnd, Ext->getType());
3563 if (!isa<Instruction>(ValForExtOpnd)) {
3564 TPT.setOperand(ExtOpnd, OpIdx, ValForExtOpnd);
3565 continue;
3566 }
3567 ExtForOpnd = cast<Instruction>(ValForExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003568 }
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003569 if (Exts)
3570 Exts->push_back(ExtForOpnd);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003571 TPT.setOperand(ExtForOpnd, 0, Opnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003572
3573 // Move the sign extension before the insertion point.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003574 TPT.moveBefore(ExtForOpnd, ExtOpnd);
3575 TPT.setOperand(ExtOpnd, OpIdx, ExtForOpnd);
Quentin Colombet1b274f92015-03-10 21:48:15 +00003576 CreatedInstsCost += !TLI.isExtFree(ExtForOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003577 // If more sext are required, new instructions will have to be created.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003578 ExtForOpnd = nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003579 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003580 if (ExtForOpnd == Ext) {
3581 DEBUG(dbgs() << "Extension is useless now\n");
3582 TPT.eraseInstruction(Ext);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003583 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003584 return ExtOpnd;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003585}
3586
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003587/// Check whether or not promoting an instruction to a wider type is profitable.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003588/// \p NewCost gives the cost of extension instructions created by the
3589/// promotion.
3590/// \p OldCost gives the cost of extension instructions before the promotion
3591/// plus the number of instructions that have been
3592/// matched in the addressing mode the promotion.
Quentin Colombet867c5502014-02-14 22:23:22 +00003593/// \p PromotedOperand is the value that has been promoted.
3594/// \return True if the promotion is profitable, false otherwise.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003595bool AddressingModeMatcher::isPromotionProfitable(
Quentin Colombet1b274f92015-03-10 21:48:15 +00003596 unsigned NewCost, unsigned OldCost, Value *PromotedOperand) const {
3597 DEBUG(dbgs() << "OldCost: " << OldCost << "\tNewCost: " << NewCost << '\n');
3598 // The cost of the new extensions is greater than the cost of the
3599 // old extension plus what we folded.
Quentin Colombet867c5502014-02-14 22:23:22 +00003600 // This is not profitable.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003601 if (NewCost > OldCost)
Quentin Colombet867c5502014-02-14 22:23:22 +00003602 return false;
Quentin Colombet1b274f92015-03-10 21:48:15 +00003603 if (NewCost < OldCost)
Quentin Colombet867c5502014-02-14 22:23:22 +00003604 return true;
3605 // The promotion is neutral but it may help folding the sign extension in
3606 // loads for instance.
3607 // Check that we did not create an illegal instruction.
Mehdi Amini44ede332015-07-09 02:09:04 +00003608 return isPromotedInstructionLegal(TLI, DL, PromotedOperand);
Quentin Colombet867c5502014-02-14 22:23:22 +00003609}
3610
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003611/// Given an instruction or constant expr, see if we can fold the operation
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003612/// into the addressing mode. If so, update the addressing mode and return
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003613/// true, otherwise return false without modifying AddrMode.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003614/// If \p MovedAway is not NULL, it contains the information of whether or
3615/// not AddrInst has to be folded into the addressing mode on success.
3616/// If \p MovedAway == true, \p AddrInst will not be part of the addressing
3617/// because it has been moved away.
3618/// Thus AddrInst must not be added in the matched instructions.
3619/// This state can happen when AddrInst is a sext, since it may be moved away.
3620/// Therefore, AddrInst may not be valid when MovedAway is true and it must
3621/// not be referenced anymore.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003622bool AddressingModeMatcher::matchOperationAddr(User *AddrInst, unsigned Opcode,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003623 unsigned Depth,
3624 bool *MovedAway) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003625 // Avoid exponential behavior on extremely deep expression trees.
3626 if (Depth >= 5) return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003627
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003628 // By default, all matched instructions stay in place.
3629 if (MovedAway)
3630 *MovedAway = false;
3631
Chandler Carruthc8925912013-01-05 02:09:22 +00003632 switch (Opcode) {
3633 case Instruction::PtrToInt:
3634 // PtrToInt is always a noop, as we know that the int type is pointer sized.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003635 return matchAddr(AddrInst->getOperand(0), Depth);
Mehdi Amini44ede332015-07-09 02:09:04 +00003636 case Instruction::IntToPtr: {
3637 auto AS = AddrInst->getType()->getPointerAddressSpace();
3638 auto PtrTy = MVT::getIntegerVT(DL.getPointerSizeInBits(AS));
Chandler Carruthc8925912013-01-05 02:09:22 +00003639 // This inttoptr is a no-op if the integer type is pointer sized.
Mehdi Amini44ede332015-07-09 02:09:04 +00003640 if (TLI.getValueType(DL, AddrInst->getOperand(0)->getType()) == PtrTy)
Sanjay Patelfc580a62015-09-21 23:03:16 +00003641 return matchAddr(AddrInst->getOperand(0), Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00003642 return false;
Mehdi Amini44ede332015-07-09 02:09:04 +00003643 }
Chandler Carruthc8925912013-01-05 02:09:22 +00003644 case Instruction::BitCast:
3645 // BitCast is always a noop, and we can handle it as long as it is
3646 // int->int or pointer->pointer (we don't want int<->fp or something).
3647 if ((AddrInst->getOperand(0)->getType()->isPointerTy() ||
3648 AddrInst->getOperand(0)->getType()->isIntegerTy()) &&
3649 // Don't touch identity bitcasts. These were probably put here by LSR,
3650 // and we don't want to mess around with them. Assume it knows what it
3651 // is doing.
3652 AddrInst->getOperand(0)->getType() != AddrInst->getType())
Sanjay Patelfc580a62015-09-21 23:03:16 +00003653 return matchAddr(AddrInst->getOperand(0), Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00003654 return false;
Matt Arsenaultf05b0232015-05-26 16:59:43 +00003655 case Instruction::AddrSpaceCast: {
3656 unsigned SrcAS
3657 = AddrInst->getOperand(0)->getType()->getPointerAddressSpace();
3658 unsigned DestAS = AddrInst->getType()->getPointerAddressSpace();
3659 if (TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
Sanjay Patelfc580a62015-09-21 23:03:16 +00003660 return matchAddr(AddrInst->getOperand(0), Depth);
Matt Arsenaultf05b0232015-05-26 16:59:43 +00003661 return false;
3662 }
Chandler Carruthc8925912013-01-05 02:09:22 +00003663 case Instruction::Add: {
3664 // Check to see if we can merge in the RHS then the LHS. If so, we win.
3665 ExtAddrMode BackupAddrMode = AddrMode;
3666 unsigned OldSize = AddrModeInsts.size();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003667 // Start a transaction at this point.
3668 // The LHS may match but not the RHS.
3669 // Therefore, we need a higher level restoration point to undo partially
3670 // matched operation.
3671 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3672 TPT.getRestorationPoint();
3673
Sanjay Patelfc580a62015-09-21 23:03:16 +00003674 if (matchAddr(AddrInst->getOperand(1), Depth+1) &&
3675 matchAddr(AddrInst->getOperand(0), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00003676 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003677
Chandler Carruthc8925912013-01-05 02:09:22 +00003678 // Restore the old addr mode info.
3679 AddrMode = BackupAddrMode;
3680 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003681 TPT.rollback(LastKnownGood);
Stephen Lin837bba12013-07-15 17:55:02 +00003682
Chandler Carruthc8925912013-01-05 02:09:22 +00003683 // Otherwise this was over-aggressive. Try merging in the LHS then the RHS.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003684 if (matchAddr(AddrInst->getOperand(0), Depth+1) &&
3685 matchAddr(AddrInst->getOperand(1), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00003686 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003687
Chandler Carruthc8925912013-01-05 02:09:22 +00003688 // Otherwise we definitely can't merge the ADD in.
3689 AddrMode = BackupAddrMode;
3690 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003691 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003692 break;
3693 }
3694 //case Instruction::Or:
3695 // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
3696 //break;
3697 case Instruction::Mul:
3698 case Instruction::Shl: {
3699 // Can only handle X*C and X << C.
3700 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
Philip Reames9c3cbee2017-10-30 23:59:51 +00003701 if (!RHS || RHS->getBitWidth() > 64)
Sanjay Pateld3bbfa12014-07-16 22:40:28 +00003702 return false;
Chandler Carruthc8925912013-01-05 02:09:22 +00003703 int64_t Scale = RHS->getSExtValue();
3704 if (Opcode == Instruction::Shl)
3705 Scale = 1LL << Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00003706
Sanjay Patelfc580a62015-09-21 23:03:16 +00003707 return matchScaledValue(AddrInst->getOperand(0), Scale, Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00003708 }
3709 case Instruction::GetElementPtr: {
3710 // Scan the GEP. We check it if it contains constant offsets and at most
3711 // one variable offset.
3712 int VariableOperand = -1;
3713 unsigned VariableScale = 0;
Stephen Lin837bba12013-07-15 17:55:02 +00003714
Chandler Carruthc8925912013-01-05 02:09:22 +00003715 int64_t ConstantOffset = 0;
Chandler Carruthc8925912013-01-05 02:09:22 +00003716 gep_type_iterator GTI = gep_type_begin(AddrInst);
3717 for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
Peter Collingbourneab85225b2016-12-02 02:24:42 +00003718 if (StructType *STy = GTI.getStructTypeOrNull()) {
Mehdi Amini4fe37982015-07-07 18:45:17 +00003719 const StructLayout *SL = DL.getStructLayout(STy);
Chandler Carruthc8925912013-01-05 02:09:22 +00003720 unsigned Idx =
3721 cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
3722 ConstantOffset += SL->getElementOffset(Idx);
3723 } else {
Mehdi Amini4fe37982015-07-07 18:45:17 +00003724 uint64_t TypeSize = DL.getTypeAllocSize(GTI.getIndexedType());
Chandler Carruthc8925912013-01-05 02:09:22 +00003725 if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
Haicheng Wu0be88252017-12-19 20:53:32 +00003726 ConstantOffset += CI->getSExtValue() * TypeSize;
Chandler Carruthc8925912013-01-05 02:09:22 +00003727 } else if (TypeSize) { // Scales of zero don't do anything.
3728 // We only allow one variable index at the moment.
3729 if (VariableOperand != -1)
3730 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003731
Chandler Carruthc8925912013-01-05 02:09:22 +00003732 // Remember the variable index.
3733 VariableOperand = i;
3734 VariableScale = TypeSize;
3735 }
3736 }
3737 }
Stephen Lin837bba12013-07-15 17:55:02 +00003738
Chandler Carruthc8925912013-01-05 02:09:22 +00003739 // A common case is for the GEP to only do a constant offset. In this case,
3740 // just add it to the disp field and check validity.
3741 if (VariableOperand == -1) {
3742 AddrMode.BaseOffs += ConstantOffset;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003743 if (ConstantOffset == 0 ||
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003744 TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003745 // Check to see if we can fold the base pointer in too.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003746 if (matchAddr(AddrInst->getOperand(0), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00003747 return true;
3748 }
3749 AddrMode.BaseOffs -= ConstantOffset;
3750 return false;
3751 }
3752
3753 // Save the valid addressing mode in case we can't match.
3754 ExtAddrMode BackupAddrMode = AddrMode;
3755 unsigned OldSize = AddrModeInsts.size();
3756
3757 // See if the scale and offset amount is valid for this target.
3758 AddrMode.BaseOffs += ConstantOffset;
3759
3760 // Match the base operand of the GEP.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003761 if (!matchAddr(AddrInst->getOperand(0), Depth+1)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003762 // If it couldn't be matched, just stuff the value in a register.
3763 if (AddrMode.HasBaseReg) {
3764 AddrMode = BackupAddrMode;
3765 AddrModeInsts.resize(OldSize);
3766 return false;
3767 }
3768 AddrMode.HasBaseReg = true;
3769 AddrMode.BaseReg = AddrInst->getOperand(0);
3770 }
3771
3772 // Match the remaining variable portion of the GEP.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003773 if (!matchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
Chandler Carruthc8925912013-01-05 02:09:22 +00003774 Depth)) {
3775 // If it couldn't be matched, try stuffing the base into a register
3776 // instead of matching it, and retrying the match of the scale.
3777 AddrMode = BackupAddrMode;
3778 AddrModeInsts.resize(OldSize);
3779 if (AddrMode.HasBaseReg)
3780 return false;
3781 AddrMode.HasBaseReg = true;
3782 AddrMode.BaseReg = AddrInst->getOperand(0);
3783 AddrMode.BaseOffs += ConstantOffset;
Sanjay Patelfc580a62015-09-21 23:03:16 +00003784 if (!matchScaledValue(AddrInst->getOperand(VariableOperand),
Chandler Carruthc8925912013-01-05 02:09:22 +00003785 VariableScale, Depth)) {
3786 // If even that didn't work, bail.
3787 AddrMode = BackupAddrMode;
3788 AddrModeInsts.resize(OldSize);
3789 return false;
3790 }
3791 }
3792
3793 return true;
3794 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003795 case Instruction::SExt:
3796 case Instruction::ZExt: {
3797 Instruction *Ext = dyn_cast<Instruction>(AddrInst);
3798 if (!Ext)
Sanjay Pateld3bbfa12014-07-16 22:40:28 +00003799 return false;
Sanjay Patelab60d042014-07-16 21:08:10 +00003800
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003801 // Try to move this ext out of the way of the addressing mode.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003802 // Ask for a method for doing so.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003803 TypePromotionHelper::Action TPH =
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003804 TypePromotionHelper::getAction(Ext, InsertedInsts, TLI, PromotedInsts);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003805 if (!TPH)
3806 return false;
3807
3808 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3809 TPT.getRestorationPoint();
Quentin Colombet1b274f92015-03-10 21:48:15 +00003810 unsigned CreatedInstsCost = 0;
3811 unsigned ExtCost = !TLI.isExtFree(Ext);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003812 Value *PromotedOperand =
Quentin Colombet1b274f92015-03-10 21:48:15 +00003813 TPH(Ext, TPT, PromotedInsts, CreatedInstsCost, nullptr, nullptr, TLI);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003814 // SExt has been moved away.
3815 // Thus either it will be rematched later in the recursive calls or it is
3816 // gone. Anyway, we must not fold it into the addressing mode at this point.
3817 // E.g.,
3818 // op = add opnd, 1
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003819 // idx = ext op
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003820 // addr = gep base, idx
3821 // is now:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003822 // promotedOpnd = ext opnd <- no match here
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003823 // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls)
3824 // addr = gep base, op <- match
3825 if (MovedAway)
3826 *MovedAway = true;
3827
3828 assert(PromotedOperand &&
3829 "TypePromotionHelper should have filtered out those cases");
3830
3831 ExtAddrMode BackupAddrMode = AddrMode;
3832 unsigned OldSize = AddrModeInsts.size();
3833
Sanjay Patelfc580a62015-09-21 23:03:16 +00003834 if (!matchAddr(PromotedOperand, Depth) ||
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003835 // The total of the new cost is equal to the cost of the created
Quentin Colombet1b274f92015-03-10 21:48:15 +00003836 // instructions.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003837 // The total of the old cost is equal to the cost of the extension plus
Quentin Colombet1b274f92015-03-10 21:48:15 +00003838 // what we have saved in the addressing mode.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003839 !isPromotionProfitable(CreatedInstsCost,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003840 ExtCost + (AddrModeInsts.size() - OldSize),
Quentin Colombet867c5502014-02-14 22:23:22 +00003841 PromotedOperand)) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003842 AddrMode = BackupAddrMode;
3843 AddrModeInsts.resize(OldSize);
3844 DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
3845 TPT.rollback(LastKnownGood);
3846 return false;
3847 }
3848 return true;
3849 }
Chandler Carruthc8925912013-01-05 02:09:22 +00003850 }
3851 return false;
3852}
3853
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003854/// If we can, try to add the value of 'Addr' into the current addressing mode.
3855/// If Addr can't be added to AddrMode this returns false and leaves AddrMode
3856/// unmodified. This assumes that Addr is either a pointer type or intptr_t
3857/// for the target.
Chandler Carruthc8925912013-01-05 02:09:22 +00003858///
Sanjay Patelfc580a62015-09-21 23:03:16 +00003859bool AddressingModeMatcher::matchAddr(Value *Addr, unsigned Depth) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003860 // Start a transaction at this point that we will rollback if the matching
3861 // fails.
3862 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3863 TPT.getRestorationPoint();
Chandler Carruthc8925912013-01-05 02:09:22 +00003864 if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
3865 // Fold in immediates if legal for the target.
3866 AddrMode.BaseOffs += CI->getSExtValue();
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003867 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003868 return true;
3869 AddrMode.BaseOffs -= CI->getSExtValue();
3870 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
3871 // If this is a global variable, try to fold it into the addressing mode.
Craig Topperc0196b12014-04-14 00:51:57 +00003872 if (!AddrMode.BaseGV) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003873 AddrMode.BaseGV = GV;
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003874 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003875 return true;
Craig Topperc0196b12014-04-14 00:51:57 +00003876 AddrMode.BaseGV = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003877 }
3878 } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
3879 ExtAddrMode BackupAddrMode = AddrMode;
3880 unsigned OldSize = AddrModeInsts.size();
3881
3882 // Check to see if it is possible to fold this operation.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003883 bool MovedAway = false;
Sanjay Patelfc580a62015-09-21 23:03:16 +00003884 if (matchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003885 // This instruction may have been moved away. If so, there is nothing
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003886 // to check here.
3887 if (MovedAway)
3888 return true;
Chandler Carruthc8925912013-01-05 02:09:22 +00003889 // Okay, it's possible to fold this. Check to see if it is actually
3890 // *profitable* to do so. We use a simple cost model to avoid increasing
3891 // register pressure too much.
3892 if (I->hasOneUse() ||
Sanjay Patelfc580a62015-09-21 23:03:16 +00003893 isProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003894 AddrModeInsts.push_back(I);
3895 return true;
3896 }
Stephen Lin837bba12013-07-15 17:55:02 +00003897
Chandler Carruthc8925912013-01-05 02:09:22 +00003898 // It isn't profitable to do this, roll back.
3899 //cerr << "NOT FOLDING: " << *I;
3900 AddrMode = BackupAddrMode;
3901 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003902 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003903 }
3904 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
Sanjay Patelfc580a62015-09-21 23:03:16 +00003905 if (matchOperationAddr(CE, CE->getOpcode(), Depth))
Chandler Carruthc8925912013-01-05 02:09:22 +00003906 return true;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003907 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003908 } else if (isa<ConstantPointerNull>(Addr)) {
3909 // Null pointer gets folded without affecting the addressing mode.
3910 return true;
3911 }
3912
3913 // Worse case, the target should support [reg] addressing modes. :)
3914 if (!AddrMode.HasBaseReg) {
3915 AddrMode.HasBaseReg = true;
3916 AddrMode.BaseReg = Addr;
3917 // Still check for legality in case the target supports [imm] but not [i+r].
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003918 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003919 return true;
3920 AddrMode.HasBaseReg = false;
Craig Topperc0196b12014-04-14 00:51:57 +00003921 AddrMode.BaseReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003922 }
3923
3924 // If the base register is already taken, see if we can do [r+r].
3925 if (AddrMode.Scale == 0) {
3926 AddrMode.Scale = 1;
3927 AddrMode.ScaledReg = Addr;
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003928 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003929 return true;
3930 AddrMode.Scale = 0;
Craig Topperc0196b12014-04-14 00:51:57 +00003931 AddrMode.ScaledReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003932 }
3933 // Couldn't match.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003934 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003935 return false;
3936}
3937
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003938/// Check to see if all uses of OpVal by the specified inline asm call are due
3939/// to memory operands. If so, return true, otherwise return false.
Chandler Carruthc8925912013-01-05 02:09:22 +00003940static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
Igor Laevsky3be81ba2017-02-07 13:27:20 +00003941 const TargetLowering &TLI,
3942 const TargetRegisterInfo &TRI) {
Sanjay Patel4137d512017-06-07 14:29:52 +00003943 const Function *F = CI->getFunction();
Eric Christopherd75c00c2015-02-26 22:38:34 +00003944 TargetLowering::AsmOperandInfoVector TargetConstraints =
Igor Laevsky3be81ba2017-02-07 13:27:20 +00003945 TLI.ParseConstraints(F->getParent()->getDataLayout(), &TRI,
Mehdi Amini8ac7a9d2015-07-07 19:07:19 +00003946 ImmutableCallSite(CI));
Igor Laevsky3be81ba2017-02-07 13:27:20 +00003947
Chandler Carruthc8925912013-01-05 02:09:22 +00003948 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
3949 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Stephen Lin837bba12013-07-15 17:55:02 +00003950
Chandler Carruthc8925912013-01-05 02:09:22 +00003951 // Compute the constraint code and ConstraintType to use.
Igor Laevsky3be81ba2017-02-07 13:27:20 +00003952 TLI.ComputeConstraintToUse(OpInfo, SDValue());
Chandler Carruthc8925912013-01-05 02:09:22 +00003953
3954 // If this asm operand is our Value*, and if it isn't an indirect memory
3955 // operand, we can't fold it!
3956 if (OpInfo.CallOperandVal == OpVal &&
3957 (OpInfo.ConstraintType != TargetLowering::C_Memory ||
3958 !OpInfo.isIndirect))
3959 return false;
3960 }
3961
3962 return true;
3963}
3964
Benjamin Kramerfc638c12017-07-24 16:18:09 +00003965// Max number of memory uses to look at before aborting the search to conserve
3966// compile time.
3967static constexpr int MaxMemoryUsesToScan = 20;
3968
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003969/// Recursively walk all the uses of I until we find a memory use.
3970/// If we find an obviously non-foldable instruction, return true.
Chandler Carruthc8925912013-01-05 02:09:22 +00003971/// Add the ultimately found memory instructions to MemoryUses.
Eric Christopher11e4df72015-02-26 22:38:43 +00003972static bool FindAllMemoryUses(
3973 Instruction *I,
3974 SmallVectorImpl<std::pair<Instruction *, unsigned>> &MemoryUses,
Benjamin Kramerfc638c12017-07-24 16:18:09 +00003975 SmallPtrSetImpl<Instruction *> &ConsideredInsts, const TargetLowering &TLI,
3976 const TargetRegisterInfo &TRI, int SeenInsts = 0) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003977 // If we already considered this instruction, we're done.
David Blaikie70573dc2014-11-19 07:49:26 +00003978 if (!ConsideredInsts.insert(I).second)
Chandler Carruthc8925912013-01-05 02:09:22 +00003979 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003980
Chandler Carruthc8925912013-01-05 02:09:22 +00003981 // If this is an obviously unfoldable instruction, bail out.
3982 if (!MightBeFoldableInst(I))
3983 return true;
3984
Philip Reamesac115ed2016-03-09 23:13:12 +00003985 const bool OptSize = I->getFunction()->optForSize();
3986
Chandler Carruthc8925912013-01-05 02:09:22 +00003987 // Loop over all the uses, recursively processing them.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003988 for (Use &U : I->uses()) {
Benjamin Kramerfc638c12017-07-24 16:18:09 +00003989 // Conservatively return true if we're seeing a large number or a deep chain
3990 // of users. This avoids excessive compilation times in pathological cases.
3991 if (SeenInsts++ >= MaxMemoryUsesToScan)
3992 return true;
Chandler Carruthc8925912013-01-05 02:09:22 +00003993
Benjamin Kramerfc638c12017-07-24 16:18:09 +00003994 Instruction *UserI = cast<Instruction>(U.getUser());
Chandler Carruthcdf47882014-03-09 03:16:01 +00003995 if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
3996 MemoryUses.push_back(std::make_pair(LI, U.getOperandNo()));
Chandler Carruthc8925912013-01-05 02:09:22 +00003997 continue;
3998 }
Stephen Lin837bba12013-07-15 17:55:02 +00003999
Chandler Carruthcdf47882014-03-09 03:16:01 +00004000 if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
4001 unsigned opNo = U.getOperandNo();
Matt Arsenault02d915b2017-03-15 22:35:20 +00004002 if (opNo != StoreInst::getPointerOperandIndex())
4003 return true; // Storing addr, not into addr.
Chandler Carruthc8925912013-01-05 02:09:22 +00004004 MemoryUses.push_back(std::make_pair(SI, opNo));
4005 continue;
4006 }
Stephen Lin837bba12013-07-15 17:55:02 +00004007
Matt Arsenault02d915b2017-03-15 22:35:20 +00004008 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(UserI)) {
4009 unsigned opNo = U.getOperandNo();
4010 if (opNo != AtomicRMWInst::getPointerOperandIndex())
4011 return true; // Storing addr, not into addr.
4012 MemoryUses.push_back(std::make_pair(RMW, opNo));
4013 continue;
4014 }
4015
4016 if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(UserI)) {
4017 unsigned opNo = U.getOperandNo();
4018 if (opNo != AtomicCmpXchgInst::getPointerOperandIndex())
4019 return true; // Storing addr, not into addr.
4020 MemoryUses.push_back(std::make_pair(CmpX, opNo));
4021 continue;
4022 }
4023
Chandler Carruthcdf47882014-03-09 03:16:01 +00004024 if (CallInst *CI = dyn_cast<CallInst>(UserI)) {
Philip Reamesac115ed2016-03-09 23:13:12 +00004025 // If this is a cold call, we can sink the addressing calculation into
4026 // the cold path. See optimizeCallInst
4027 if (!OptSize && CI->hasFnAttr(Attribute::Cold))
4028 continue;
Junmo Park6098cbb2016-03-11 07:05:32 +00004029
Chandler Carruthc8925912013-01-05 02:09:22 +00004030 InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
4031 if (!IA) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00004032
Chandler Carruthc8925912013-01-05 02:09:22 +00004033 // If this is a memory operand, we're cool, otherwise bail out.
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004034 if (!IsOperandAMemoryOperand(CI, IA, I, TLI, TRI))
Chandler Carruthc8925912013-01-05 02:09:22 +00004035 return true;
4036 continue;
4037 }
Stephen Lin837bba12013-07-15 17:55:02 +00004038
Benjamin Kramerfc638c12017-07-24 16:18:09 +00004039 if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TLI, TRI,
4040 SeenInsts))
Chandler Carruthc8925912013-01-05 02:09:22 +00004041 return true;
4042 }
4043
4044 return false;
4045}
4046
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00004047/// Return true if Val is already known to be live at the use site that we're
4048/// folding it into. If so, there is no cost to include it in the addressing
4049/// mode. KnownLive1 and KnownLive2 are two values that we know are live at the
4050/// instruction already.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004051bool AddressingModeMatcher::valueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
Chandler Carruthc8925912013-01-05 02:09:22 +00004052 Value *KnownLive2) {
4053 // If Val is either of the known-live values, we know it is live!
Craig Topperc0196b12014-04-14 00:51:57 +00004054 if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2)
Chandler Carruthc8925912013-01-05 02:09:22 +00004055 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00004056
Chandler Carruthc8925912013-01-05 02:09:22 +00004057 // All values other than instructions and arguments (e.g. constants) are live.
4058 if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00004059
Chandler Carruthc8925912013-01-05 02:09:22 +00004060 // If Val is a constant sized alloca in the entry block, it is live, this is
4061 // true because it is just a reference to the stack/frame pointer, which is
4062 // live for the whole function.
4063 if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
4064 if (AI->isStaticAlloca())
4065 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00004066
Chandler Carruthc8925912013-01-05 02:09:22 +00004067 // Check to see if this value is already used in the memory instruction's
4068 // block. If so, it's already live into the block at the very least, so we
4069 // can reasonably fold it.
4070 return Val->isUsedInBasicBlock(MemoryInst->getParent());
4071}
4072
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004073/// It is possible for the addressing mode of the machine to fold the specified
4074/// instruction into a load or store that ultimately uses it.
4075/// However, the specified instruction has multiple uses.
4076/// Given this, it may actually increase register pressure to fold it
4077/// into the load. For example, consider this code:
Chandler Carruthc8925912013-01-05 02:09:22 +00004078///
4079/// X = ...
4080/// Y = X+1
4081/// use(Y) -> nonload/store
4082/// Z = Y+1
4083/// load Z
4084///
4085/// In this case, Y has multiple uses, and can be folded into the load of Z
4086/// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to
4087/// be live at the use(Y) line. If we don't fold Y into load Z, we use one
4088/// fewer register. Since Y can't be folded into "use(Y)" we don't increase the
4089/// number of computations either.
4090///
4091/// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If
4092/// X was live across 'load Z' for other reasons, we actually *would* want to
4093/// fold the addressing mode in the Z case. This would make Y die earlier.
4094bool AddressingModeMatcher::
Sanjay Patelfc580a62015-09-21 23:03:16 +00004095isProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
Chandler Carruthc8925912013-01-05 02:09:22 +00004096 ExtAddrMode &AMAfter) {
4097 if (IgnoreProfitability) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00004098
Chandler Carruthc8925912013-01-05 02:09:22 +00004099 // AMBefore is the addressing mode before this instruction was folded into it,
4100 // and AMAfter is the addressing mode after the instruction was folded. Get
4101 // the set of registers referenced by AMAfter and subtract out those
4102 // referenced by AMBefore: this is the set of values which folding in this
4103 // address extends the lifetime of.
4104 //
4105 // Note that there are only two potential values being referenced here,
4106 // BaseReg and ScaleReg (global addresses are always available, as are any
4107 // folded immediates).
4108 Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
Stephen Lin837bba12013-07-15 17:55:02 +00004109
Chandler Carruthc8925912013-01-05 02:09:22 +00004110 // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
4111 // lifetime wasn't extended by adding this instruction.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004112 if (valueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
Craig Topperc0196b12014-04-14 00:51:57 +00004113 BaseReg = nullptr;
Sanjay Patelfc580a62015-09-21 23:03:16 +00004114 if (valueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
Craig Topperc0196b12014-04-14 00:51:57 +00004115 ScaledReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00004116
4117 // If folding this instruction (and it's subexprs) didn't extend any live
4118 // ranges, we're ok with it.
Craig Topperc0196b12014-04-14 00:51:57 +00004119 if (!BaseReg && !ScaledReg)
Chandler Carruthc8925912013-01-05 02:09:22 +00004120 return true;
4121
Philip Reamesac115ed2016-03-09 23:13:12 +00004122 // If all uses of this instruction can have the address mode sunk into them,
4123 // we can remove the addressing mode and effectively trade one live register
4124 // for another (at worst.) In this context, folding an addressing mode into
Junmo Park6098cbb2016-03-11 07:05:32 +00004125 // the use is just a particularly nice way of sinking it.
Chandler Carruthc8925912013-01-05 02:09:22 +00004126 SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
4127 SmallPtrSet<Instruction*, 16> ConsideredInsts;
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004128 if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TLI, TRI))
Chandler Carruthc8925912013-01-05 02:09:22 +00004129 return false; // Has a non-memory, non-foldable use!
Stephen Lin837bba12013-07-15 17:55:02 +00004130
Chandler Carruthc8925912013-01-05 02:09:22 +00004131 // Now that we know that all uses of this instruction are part of a chain of
4132 // computation involving only operations that could theoretically be folded
Philip Reamesac115ed2016-03-09 23:13:12 +00004133 // into a memory use, loop over each of these memory operation uses and see
4134 // if they could *actually* fold the instruction. The assumption is that
4135 // addressing modes are cheap and that duplicating the computation involved
4136 // many times is worthwhile, even on a fastpath. For sinking candidates
4137 // (i.e. cold call sites), this serves as a way to prevent excessive code
4138 // growth since most architectures have some reasonable small and fast way to
4139 // compute an effective address. (i.e LEA on x86)
Chandler Carruthc8925912013-01-05 02:09:22 +00004140 SmallVector<Instruction*, 32> MatchedAddrModeInsts;
4141 for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
4142 Instruction *User = MemoryUses[i].first;
4143 unsigned OpNo = MemoryUses[i].second;
Stephen Lin837bba12013-07-15 17:55:02 +00004144
Chandler Carruthc8925912013-01-05 02:09:22 +00004145 // Get the access type of this use. If the use isn't a pointer, we don't
4146 // know what it accesses.
4147 Value *Address = User->getOperand(OpNo);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00004148 PointerType *AddrTy = dyn_cast<PointerType>(Address->getType());
4149 if (!AddrTy)
Chandler Carruthc8925912013-01-05 02:09:22 +00004150 return false;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00004151 Type *AddressAccessTy = AddrTy->getElementType();
4152 unsigned AS = AddrTy->getAddressSpace();
Stephen Lin837bba12013-07-15 17:55:02 +00004153
Chandler Carruthc8925912013-01-05 02:09:22 +00004154 // Do a match against the root of this address, ignoring profitability. This
4155 // will tell us if the addressing mode for the memory operation will
4156 // *actually* cover the shared instruction.
4157 ExtAddrMode Result;
Quentin Colombet5a69dda2014-02-11 01:59:02 +00004158 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4159 TPT.getRestorationPoint();
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004160 AddressingModeMatcher Matcher(MatchedAddrModeInsts, TLI, TRI,
4161 AddressAccessTy, AS,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00004162 MemoryInst, Result, InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004163 PromotedInsts, TPT);
Chandler Carruthc8925912013-01-05 02:09:22 +00004164 Matcher.IgnoreProfitability = true;
Sanjay Patelfc580a62015-09-21 23:03:16 +00004165 bool Success = Matcher.matchAddr(Address, 0);
Chandler Carruthc8925912013-01-05 02:09:22 +00004166 (void)Success; assert(Success && "Couldn't select *anything*?");
4167
Quentin Colombet5a69dda2014-02-11 01:59:02 +00004168 // The match was to check the profitability, the changes made are not
4169 // part of the original matcher. Therefore, they should be dropped
4170 // otherwise the original matcher will not present the right state.
4171 TPT.rollback(LastKnownGood);
4172
Chandler Carruthc8925912013-01-05 02:09:22 +00004173 // If the match didn't cover I, then it won't be shared by it.
David Majnemer0d955d02016-08-11 22:21:41 +00004174 if (!is_contained(MatchedAddrModeInsts, I))
Chandler Carruthc8925912013-01-05 02:09:22 +00004175 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00004176
Chandler Carruthc8925912013-01-05 02:09:22 +00004177 MatchedAddrModeInsts.clear();
4178 }
Stephen Lin837bba12013-07-15 17:55:02 +00004179
Chandler Carruthc8925912013-01-05 02:09:22 +00004180 return true;
4181}
4182
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004183/// Return true if the specified values are defined in a
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004184/// different basic block than BB.
4185static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
4186 if (Instruction *I = dyn_cast<Instruction>(V))
4187 return I->getParent() != BB;
4188 return false;
4189}
4190
Philip Reamesac115ed2016-03-09 23:13:12 +00004191/// Sink addressing mode computation immediate before MemoryInst if doing so
4192/// can be done without increasing register pressure. The need for the
4193/// register pressure constraint means this can end up being an all or nothing
4194/// decision for all uses of the same addressing computation.
4195///
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004196/// Load and Store Instructions often have addressing modes that can do
4197/// significant amounts of computation. As such, instruction selection will try
4198/// to get the load or store to do as much computation as possible for the
4199/// program. The problem is that isel can only see within a single block. As
4200/// such, we sink as much legal addressing mode work into the block as possible.
Chris Lattner728f9022008-11-25 07:09:13 +00004201///
4202/// This method is used to optimize both load/store and inline asms with memory
Philip Reamesac115ed2016-03-09 23:13:12 +00004203/// operands. It's also used to sink addressing computations feeding into cold
4204/// call sites into their (cold) basic block.
4205///
4206/// The motivation for handling sinking into cold blocks is that doing so can
4207/// both enable other address mode sinking (by satisfying the register pressure
4208/// constraint above), and reduce register pressure globally (by removing the
4209/// addressing mode computation from the fast path entirely.).
Sanjay Patelfc580a62015-09-21 23:03:16 +00004210bool CodeGenPrepare::optimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00004211 Type *AccessTy, unsigned AddrSpace) {
Owen Anderson8ba5f392010-11-27 08:15:55 +00004212 Value *Repl = Addr;
Nadav Rotem465834c2012-07-24 10:51:42 +00004213
4214 // Try to collapse single-value PHI nodes. This is necessary to undo
Owen Andersondfb8c3b2010-11-19 22:15:03 +00004215 // unprofitable PRE transformations.
Cameron Zwarich43cecb12011-01-03 06:33:01 +00004216 SmallVector<Value*, 8> worklist;
4217 SmallPtrSet<Value*, 16> Visited;
Owen Anderson8ba5f392010-11-27 08:15:55 +00004218 worklist.push_back(Addr);
Nadav Rotem465834c2012-07-24 10:51:42 +00004219
John Brawneb83c752017-10-03 13:04:15 +00004220 // Use a worklist to iteratively look through PHI and select nodes, and
4221 // ensure that the addressing mode obtained from the non-PHI/select roots of
John Brawn736bf002017-10-03 13:08:22 +00004222 // the graph are compatible.
John Brawneb83c752017-10-03 13:04:15 +00004223 bool PhiOrSelectSeen = false;
Owen Anderson8ba5f392010-11-27 08:15:55 +00004224 SmallVector<Instruction*, 16> AddrModeInsts;
Serguei Katkovaee63752017-11-05 07:59:02 +00004225 const SimplifyQuery SQ(*DL, TLInfo);
4226 AddressingModeCombiner AddrModes(SQ, { Addr, MemoryInst->getParent() });
Jun Bum Limdee55652017-04-03 19:20:07 +00004227 TypePromotionTransaction TPT(RemovedInsts);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004228 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4229 TPT.getRestorationPoint();
Owen Anderson8ba5f392010-11-27 08:15:55 +00004230 while (!worklist.empty()) {
4231 Value *V = worklist.back();
4232 worklist.pop_back();
Nadav Rotem465834c2012-07-24 10:51:42 +00004233
Serguei Katkov4ea855e2017-07-19 04:49:17 +00004234 // We allow traversing cyclic Phi nodes.
4235 // In case of success after this loop we ensure that traversing through
4236 // Phi nodes ends up with all cases to compute address of the form
4237 // BaseGV + Base + Scale * Index + Offset
4238 // where Scale and Offset are constans and BaseGV, Base and Index
4239 // are exactly the same Values in all cases.
4240 // It means that BaseGV, Scale and Offset dominate our memory instruction
4241 // and have the same value as they had in address computation represented
4242 // as Phi. So we can safely sink address computation to memory instruction.
4243 if (!Visited.insert(V).second)
4244 continue;
Nadav Rotem465834c2012-07-24 10:51:42 +00004245
Owen Anderson8ba5f392010-11-27 08:15:55 +00004246 // For a PHI node, push all of its incoming values.
4247 if (PHINode *P = dyn_cast<PHINode>(V)) {
Pete Cooper833f34d2015-05-12 20:05:31 +00004248 for (Value *IncValue : P->incoming_values())
4249 worklist.push_back(IncValue);
John Brawneb83c752017-10-03 13:04:15 +00004250 PhiOrSelectSeen = true;
4251 continue;
4252 }
4253 // Similar for select.
4254 if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
4255 worklist.push_back(SI->getFalseValue());
4256 worklist.push_back(SI->getTrueValue());
4257 PhiOrSelectSeen = true;
Owen Anderson8ba5f392010-11-27 08:15:55 +00004258 continue;
4259 }
Nadav Rotem465834c2012-07-24 10:51:42 +00004260
Philip Reamesac115ed2016-03-09 23:13:12 +00004261 // For non-PHIs, determine the addressing mode being computed. Note that
4262 // the result may differ depending on what other uses our candidate
4263 // addressing instructions might have.
Serguei Katkova6fba3d2017-07-18 05:16:38 +00004264 AddrModeInsts.clear();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004265 ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
Serguei Katkova6fba3d2017-07-18 05:16:38 +00004266 V, AccessTy, AddrSpace, MemoryInst, AddrModeInsts, *TLI, *TRI,
4267 InsertedInsts, PromotedInsts, TPT);
John Brawn736bf002017-10-03 13:08:22 +00004268 NewAddrMode.OriginalValue = V;
Cameron Zwarich13c885d2011-03-05 08:12:26 +00004269
John Brawn736bf002017-10-03 13:08:22 +00004270 if (!AddrModes.addNewAddrMode(NewAddrMode))
4271 break;
Owen Andersondfb8c3b2010-11-19 22:15:03 +00004272 }
Nadav Rotem465834c2012-07-24 10:51:42 +00004273
John Brawn736bf002017-10-03 13:08:22 +00004274 // Try to combine the AddrModes we've collected. If we couldn't collect any,
4275 // or we have multiple but either couldn't combine them or combining them
4276 // wouldn't do anything useful, bail out now.
4277 if (!AddrModes.combineAddrModes()) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004278 TPT.rollback(LastKnownGood);
4279 return false;
4280 }
4281 TPT.commit();
Nadav Rotem465834c2012-07-24 10:51:42 +00004282
John Brawn736bf002017-10-03 13:08:22 +00004283 // Get the combined AddrMode (or the only AddrMode, if we only had one).
4284 ExtAddrMode AddrMode = AddrModes.getAddrMode();
4285
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004286 // If all the instructions matched are already in this BB, don't do anything.
John Brawneb83c752017-10-03 13:04:15 +00004287 // If we saw a Phi node then it is not local definitely, and if we saw a select
4288 // then we want to push the address calculation past it even if it's already
4289 // in this BB.
4290 if (!PhiOrSelectSeen && none_of(AddrModeInsts, [&](Value *V) {
Justin Lebar838c7f52016-11-21 22:49:11 +00004291 return IsNonLocalValue(V, MemoryInst->getParent());
Serguei Katkov0b7b59a2017-07-11 06:24:44 +00004292 })) {
David Greene74e2d492010-01-05 01:27:11 +00004293 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004294 return false;
4295 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00004296
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004297 // Insert this computation right after this user. Since our caller is
4298 // scanning from the top of the BB to the bottom, reuse of the expr are
4299 // guaranteed to happen later.
Devang Patelc10e52a2011-09-06 18:49:53 +00004300 IRBuilder<> Builder(MemoryInst);
Eric Christopherc1ea1492008-09-24 05:32:41 +00004301
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004302 // Now that we determined the addressing expression we want to use and know
4303 // that we have to sink it into this block. Check to see if we have already
Simon Dardis230f4532017-11-24 16:45:28 +00004304 // done this for some other load/store instr in this block. If so, reuse
4305 // the computation. Before attempting reuse, check if the address is valid
4306 // as it may have been erased.
4307
4308 WeakTrackingVH SunkAddrVH = SunkAddrs[Addr];
4309
4310 Value * SunkAddr = SunkAddrVH.pointsToAliveValue() ? SunkAddrVH : nullptr;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004311 if (SunkAddr) {
David Greene74e2d492010-01-05 01:27:11 +00004312 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00004313 << *MemoryInst << "\n");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004314 if (SunkAddr->getType() != Addr->getType())
Eli Friedmanc12a5a72017-02-24 20:51:36 +00004315 SunkAddr = Builder.CreatePointerCast(SunkAddr, Addr->getType());
Eric Christopherfccff372015-01-27 01:01:38 +00004316 } else if (AddrSinkUsingGEPs ||
4317 (!AddrSinkUsingGEPs.getNumOccurrences() && TM &&
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004318 SubtargetInfo->useAA())) {
Hal Finkelc3998302014-04-12 00:59:48 +00004319 // By default, we use the GEP-based method when AA is used later. This
4320 // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities.
4321 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00004322 << *MemoryInst << "\n");
Mehdi Amini4fe37982015-07-07 18:45:17 +00004323 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
Craig Topperc0196b12014-04-14 00:51:57 +00004324 Value *ResultPtr = nullptr, *ResultIndex = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00004325
4326 // First, find the pointer.
4327 if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) {
4328 ResultPtr = AddrMode.BaseReg;
Craig Topperc0196b12014-04-14 00:51:57 +00004329 AddrMode.BaseReg = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00004330 }
4331
4332 if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) {
4333 // We can't add more than one pointer together, nor can we scale a
4334 // pointer (both of which seem meaningless).
4335 if (ResultPtr || AddrMode.Scale != 1)
4336 return false;
4337
4338 ResultPtr = AddrMode.ScaledReg;
4339 AddrMode.Scale = 0;
4340 }
4341
Eli Friedman6f7c9ad2017-07-12 23:30:02 +00004342 // It is only safe to sign extend the BaseReg if we know that the math
4343 // required to create it did not overflow before we extend it. Since
4344 // the original IR value was tossed in favor of a constant back when
4345 // the AddrMode was created we need to bail out gracefully if widths
4346 // do not match instead of extending it.
4347 //
4348 // (See below for code to add the scale.)
4349 if (AddrMode.Scale) {
4350 Type *ScaledRegTy = AddrMode.ScaledReg->getType();
4351 if (cast<IntegerType>(IntPtrTy)->getBitWidth() >
4352 cast<IntegerType>(ScaledRegTy)->getBitWidth())
4353 return false;
4354 }
4355
Hal Finkelc3998302014-04-12 00:59:48 +00004356 if (AddrMode.BaseGV) {
4357 if (ResultPtr)
4358 return false;
4359
4360 ResultPtr = AddrMode.BaseGV;
4361 }
4362
4363 // If the real base value actually came from an inttoptr, then the matcher
4364 // will look through it and provide only the integer value. In that case,
4365 // use it here.
Keno Fischer05e4ac22017-06-29 20:28:59 +00004366 if (!DL->isNonIntegralPointerType(Addr->getType())) {
4367 if (!ResultPtr && AddrMode.BaseReg) {
4368 ResultPtr = Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(),
4369 "sunkaddr");
4370 AddrMode.BaseReg = nullptr;
4371 } else if (!ResultPtr && AddrMode.Scale == 1) {
4372 ResultPtr = Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(),
4373 "sunkaddr");
4374 AddrMode.Scale = 0;
4375 }
Hal Finkelc3998302014-04-12 00:59:48 +00004376 }
4377
4378 if (!ResultPtr &&
4379 !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) {
4380 SunkAddr = Constant::getNullValue(Addr->getType());
4381 } else if (!ResultPtr) {
4382 return false;
4383 } else {
4384 Type *I8PtrTy =
David Blaikie3909da72015-03-30 20:42:56 +00004385 Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace());
4386 Type *I8Ty = Builder.getInt8Ty();
Hal Finkelc3998302014-04-12 00:59:48 +00004387
4388 // Start with the base register. Do this first so that subsequent address
4389 // matching finds it last, which will prevent it from trying to match it
4390 // as the scaled value in case it happens to be a mul. That would be
4391 // problematic if we've sunk a different mul for the scale, because then
4392 // we'd end up sinking both muls.
4393 if (AddrMode.BaseReg) {
4394 Value *V = AddrMode.BaseReg;
4395 if (V->getType() != IntPtrTy)
4396 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
4397
4398 ResultIndex = V;
4399 }
4400
4401 // Add the scale value.
4402 if (AddrMode.Scale) {
4403 Value *V = AddrMode.ScaledReg;
4404 if (V->getType() == IntPtrTy) {
4405 // done.
Hal Finkelc3998302014-04-12 00:59:48 +00004406 } else {
Eli Friedman6f7c9ad2017-07-12 23:30:02 +00004407 assert(cast<IntegerType>(IntPtrTy)->getBitWidth() <
4408 cast<IntegerType>(V->getType())->getBitWidth() &&
4409 "We can't transform if ScaledReg is too narrow");
4410 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
Hal Finkelc3998302014-04-12 00:59:48 +00004411 }
4412
4413 if (AddrMode.Scale != 1)
4414 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
4415 "sunkaddr");
4416 if (ResultIndex)
4417 ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr");
4418 else
4419 ResultIndex = V;
4420 }
4421
4422 // Add in the Base Offset if present.
4423 if (AddrMode.BaseOffs) {
4424 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
4425 if (ResultIndex) {
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00004426 // We need to add this separately from the scale above to help with
4427 // SDAG consecutive load/store merging.
Hal Finkelc3998302014-04-12 00:59:48 +00004428 if (ResultPtr->getType() != I8PtrTy)
Eli Friedmanc12a5a72017-02-24 20:51:36 +00004429 ResultPtr = Builder.CreatePointerCast(ResultPtr, I8PtrTy);
David Blaikie3909da72015-03-30 20:42:56 +00004430 ResultPtr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
Hal Finkelc3998302014-04-12 00:59:48 +00004431 }
4432
4433 ResultIndex = V;
4434 }
4435
4436 if (!ResultIndex) {
4437 SunkAddr = ResultPtr;
4438 } else {
4439 if (ResultPtr->getType() != I8PtrTy)
Eli Friedmanc12a5a72017-02-24 20:51:36 +00004440 ResultPtr = Builder.CreatePointerCast(ResultPtr, I8PtrTy);
David Blaikie3909da72015-03-30 20:42:56 +00004441 SunkAddr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
Hal Finkelc3998302014-04-12 00:59:48 +00004442 }
4443
4444 if (SunkAddr->getType() != Addr->getType())
Eli Friedmanc12a5a72017-02-24 20:51:36 +00004445 SunkAddr = Builder.CreatePointerCast(SunkAddr, Addr->getType());
Hal Finkelc3998302014-04-12 00:59:48 +00004446 }
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004447 } else {
Keno Fischer05e4ac22017-06-29 20:28:59 +00004448 // We'd require a ptrtoint/inttoptr down the line, which we can't do for
4449 // non-integral pointers, so in that case bail out now.
4450 Type *BaseTy = AddrMode.BaseReg ? AddrMode.BaseReg->getType() : nullptr;
4451 Type *ScaleTy = AddrMode.Scale ? AddrMode.ScaledReg->getType() : nullptr;
4452 PointerType *BasePtrTy = dyn_cast_or_null<PointerType>(BaseTy);
4453 PointerType *ScalePtrTy = dyn_cast_or_null<PointerType>(ScaleTy);
4454 if (DL->isNonIntegralPointerType(Addr->getType()) ||
4455 (BasePtrTy && DL->isNonIntegralPointerType(BasePtrTy)) ||
4456 (ScalePtrTy && DL->isNonIntegralPointerType(ScalePtrTy)) ||
4457 (AddrMode.BaseGV &&
4458 DL->isNonIntegralPointerType(AddrMode.BaseGV->getType())))
4459 return false;
4460
David Greene74e2d492010-01-05 01:27:11 +00004461 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00004462 << *MemoryInst << "\n");
Mehdi Amini4fe37982015-07-07 18:45:17 +00004463 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
Craig Topperc0196b12014-04-14 00:51:57 +00004464 Value *Result = nullptr;
Dan Gohmanca194452010-01-19 22:45:06 +00004465
4466 // Start with the base register. Do this first so that subsequent address
4467 // matching finds it last, which will prevent it from trying to match it
4468 // as the scaled value in case it happens to be a mul. That would be
4469 // problematic if we've sunk a different mul for the scale, because then
4470 // we'd end up sinking both muls.
4471 if (AddrMode.BaseReg) {
4472 Value *V = AddrMode.BaseReg;
Duncan Sands19d0b472010-02-16 11:11:14 +00004473 if (V->getType()->isPointerTy())
Devang Patelc10e52a2011-09-06 18:49:53 +00004474 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00004475 if (V->getType() != IntPtrTy)
Devang Patelc10e52a2011-09-06 18:49:53 +00004476 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00004477 Result = V;
4478 }
4479
4480 // Add the scale value.
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004481 if (AddrMode.Scale) {
4482 Value *V = AddrMode.ScaledReg;
4483 if (V->getType() == IntPtrTy) {
4484 // done.
Duncan Sands19d0b472010-02-16 11:11:14 +00004485 } else if (V->getType()->isPointerTy()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00004486 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004487 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
4488 cast<IntegerType>(V->getType())->getBitWidth()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00004489 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004490 } else {
Jim Grosbached2cd392014-03-26 17:27:01 +00004491 // It is only safe to sign extend the BaseReg if we know that the math
4492 // required to create it did not overflow before we extend it. Since
4493 // the original IR value was tossed in favor of a constant back when
4494 // the AddrMode was created we need to bail out gracefully if widths
4495 // do not match instead of extending it.
Joey Gouly12a8bf02014-05-13 15:42:45 +00004496 Instruction *I = dyn_cast_or_null<Instruction>(Result);
Jim Grosbach83b44e12014-04-10 00:27:45 +00004497 if (I && (Result != AddrMode.BaseReg))
4498 I->eraseFromParent();
Jim Grosbached2cd392014-03-26 17:27:01 +00004499 return false;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004500 }
4501 if (AddrMode.Scale != 1)
Devang Patelc10e52a2011-09-06 18:49:53 +00004502 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
4503 "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004504 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00004505 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004506 else
4507 Result = V;
4508 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00004509
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004510 // Add in the BaseGV if present.
4511 if (AddrMode.BaseGV) {
Devang Patelc10e52a2011-09-06 18:49:53 +00004512 Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004513 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00004514 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004515 else
4516 Result = V;
4517 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00004518
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004519 // Add in the Base Offset if present.
4520 if (AddrMode.BaseOffs) {
Owen Andersonedb4a702009-07-24 23:12:02 +00004521 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004522 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00004523 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004524 else
4525 Result = V;
4526 }
4527
Craig Topperc0196b12014-04-14 00:51:57 +00004528 if (!Result)
Owen Anderson5a1acd92009-07-31 20:28:14 +00004529 SunkAddr = Constant::getNullValue(Addr->getType());
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004530 else
Devang Patelc10e52a2011-09-06 18:49:53 +00004531 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004532 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00004533
Owen Andersondfb8c3b2010-11-19 22:15:03 +00004534 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
Simon Dardis230f4532017-11-24 16:45:28 +00004535 // Store the newly computed address into the cache. In the case we reused a
4536 // value, this should be idempotent.
4537 SunkAddrs[Addr] = WeakTrackingVH(SunkAddr);
Eric Christopherc1ea1492008-09-24 05:32:41 +00004538
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004539 // If we have no uses, recursively delete the value and all dead instructions
4540 // using it.
Owen Andersondfb8c3b2010-11-19 22:15:03 +00004541 if (Repl->use_empty()) {
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004542 // This can cause recursive deletion, which can invalidate our iterator.
Sanjoy Dase6bca0e2017-05-01 17:07:49 +00004543 // Use a WeakTrackingVH to hold onto it in case this happens.
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00004544 Value *CurValue = &*CurInstIterator;
Sanjoy Dase6bca0e2017-05-01 17:07:49 +00004545 WeakTrackingVH IterHandle(CurValue);
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004546 BasicBlock *BB = CurInstIterator->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +00004547
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00004548 RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004549
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00004550 if (IterHandle != CurValue) {
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004551 // If the iterator instruction was recursively deleted, start over at the
4552 // start of the block.
4553 CurInstIterator = BB->begin();
4554 SunkAddrs.clear();
Nadav Rotem465834c2012-07-24 10:51:42 +00004555 }
Dale Johannesenb67a6e662010-03-31 20:37:15 +00004556 }
Cameron Zwarichced753f2011-01-05 17:27:27 +00004557 ++NumMemoryInsts;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004558 return true;
4559}
4560
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004561/// If there are any memory operands, use OptimizeMemoryInst to sink their
4562/// address computing into the block when possible / profitable.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004563bool CodeGenPrepare::optimizeInlineAsmInst(CallInst *CS) {
Evan Cheng1da25002008-02-26 02:42:37 +00004564 bool MadeChange = false;
Evan Cheng1da25002008-02-26 02:42:37 +00004565
Eric Christopher11e4df72015-02-26 22:38:43 +00004566 const TargetRegisterInfo *TRI =
Sanjay Patel4137d512017-06-07 14:29:52 +00004567 TM->getSubtargetImpl(*CS->getFunction())->getRegisterInfo();
Mehdi Amini8ac7a9d2015-07-07 19:07:19 +00004568 TargetLowering::AsmOperandInfoVector TargetConstraints =
4569 TLI->ParseConstraints(*DL, TRI, CS);
Dale Johannesenf95f59a2010-09-16 18:30:55 +00004570 unsigned ArgNo = 0;
John Thompson1094c802010-09-13 18:15:37 +00004571 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
4572 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Nadav Rotem465834c2012-07-24 10:51:42 +00004573
Evan Cheng1da25002008-02-26 02:42:37 +00004574 // Compute the constraint code and ConstraintType to use.
Dale Johannesence97d552010-06-25 21:55:36 +00004575 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Evan Cheng1da25002008-02-26 02:42:37 +00004576
Eli Friedman666bbe32008-02-26 18:37:49 +00004577 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
4578 OpInfo.isIndirect) {
Chris Lattner7a277142011-01-15 07:14:54 +00004579 Value *OpVal = CS->getArgOperand(ArgNo++);
Sanjay Patelfc580a62015-09-21 23:03:16 +00004580 MadeChange |= optimizeMemoryInst(CS, OpVal, OpVal->getType(), ~0u);
Dale Johannesenf95f59a2010-09-16 18:30:55 +00004581 } else if (OpInfo.Type == InlineAsm::isInput)
4582 ArgNo++;
Evan Cheng1da25002008-02-26 02:42:37 +00004583 }
4584
4585 return MadeChange;
4586}
4587
Jun Bum Lim42301012017-03-17 19:05:21 +00004588/// \brief Check if all the uses of \p Val are equivalent (or free) zero or
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004589/// sign extensions.
Jun Bum Lim42301012017-03-17 19:05:21 +00004590static bool hasSameExtUse(Value *Val, const TargetLowering &TLI) {
4591 assert(!Val->use_empty() && "Input must have at least one use");
4592 const Instruction *FirstUser = cast<Instruction>(*Val->user_begin());
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004593 bool IsSExt = isa<SExtInst>(FirstUser);
4594 Type *ExtTy = FirstUser->getType();
Jun Bum Lim42301012017-03-17 19:05:21 +00004595 for (const User *U : Val->users()) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004596 const Instruction *UI = cast<Instruction>(U);
4597 if ((IsSExt && !isa<SExtInst>(UI)) || (!IsSExt && !isa<ZExtInst>(UI)))
4598 return false;
4599 Type *CurTy = UI->getType();
4600 // Same input and output types: Same instruction after CSE.
4601 if (CurTy == ExtTy)
4602 continue;
4603
4604 // If IsSExt is true, we are in this situation:
Jun Bum Lim42301012017-03-17 19:05:21 +00004605 // a = Val
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004606 // b = sext ty1 a to ty2
4607 // c = sext ty1 a to ty3
4608 // Assuming ty2 is shorter than ty3, this could be turned into:
Jun Bum Lim42301012017-03-17 19:05:21 +00004609 // a = Val
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004610 // b = sext ty1 a to ty2
4611 // c = sext ty2 b to ty3
4612 // However, the last sext is not free.
4613 if (IsSExt)
4614 return false;
4615
4616 // This is a ZExt, maybe this is free to extend from one type to another.
4617 // In that case, we would not account for a different use.
4618 Type *NarrowTy;
4619 Type *LargeTy;
4620 if (ExtTy->getScalarType()->getIntegerBitWidth() >
4621 CurTy->getScalarType()->getIntegerBitWidth()) {
4622 NarrowTy = CurTy;
4623 LargeTy = ExtTy;
4624 } else {
4625 NarrowTy = ExtTy;
4626 LargeTy = CurTy;
4627 }
4628
4629 if (!TLI.isZExtFree(NarrowTy, LargeTy))
4630 return false;
4631 }
4632 // All uses are the same or can be derived from one another for free.
4633 return true;
4634}
4635
Jun Bum Lim42301012017-03-17 19:05:21 +00004636/// \brief Try to speculatively promote extensions in \p Exts and continue
4637/// promoting through newly promoted operands recursively as far as doing so is
4638/// profitable. Save extensions profitably moved up, in \p ProfitablyMovedExts.
4639/// When some promotion happened, \p TPT contains the proper state to revert
4640/// them.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004641///
Jun Bum Lim42301012017-03-17 19:05:21 +00004642/// \return true if some promotion happened, false otherwise.
Jun Bum Lim42301012017-03-17 19:05:21 +00004643bool CodeGenPrepare::tryToPromoteExts(
4644 TypePromotionTransaction &TPT, const SmallVectorImpl<Instruction *> &Exts,
4645 SmallVectorImpl<Instruction *> &ProfitablyMovedExts,
4646 unsigned CreatedInstsCost) {
4647 bool Promoted = false;
4648
4649 // Iterate over all the extensions to try to promote them.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004650 for (auto I : Exts) {
Jun Bum Lim42301012017-03-17 19:05:21 +00004651 // Early check if we directly have ext(load).
4652 if (isa<LoadInst>(I->getOperand(0))) {
4653 ProfitablyMovedExts.push_back(I);
4654 continue;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004655 }
Jun Bum Lim42301012017-03-17 19:05:21 +00004656
4657 // Check whether or not we want to do any promotion. The reason we have
4658 // this check inside the for loop is to catch the case where an extension
4659 // is directly fed by a load because in such case the extension can be moved
4660 // up without any promotion on its operands.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004661 if (!TLI || !TLI->enableExtLdPromotion() || DisableExtLdPromotion)
Jun Bum Lim42301012017-03-17 19:05:21 +00004662 return false;
4663
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004664 // Get the action to perform the promotion.
Jun Bum Lim42301012017-03-17 19:05:21 +00004665 TypePromotionHelper::Action TPH =
4666 TypePromotionHelper::getAction(I, InsertedInsts, *TLI, PromotedInsts);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004667 // Check if we can promote.
Jun Bum Lim42301012017-03-17 19:05:21 +00004668 if (!TPH) {
4669 // Save the current extension as we cannot move up through its operand.
4670 ProfitablyMovedExts.push_back(I);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004671 continue;
Jun Bum Lim42301012017-03-17 19:05:21 +00004672 }
4673
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004674 // Save the current state.
4675 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4676 TPT.getRestorationPoint();
4677 SmallVector<Instruction *, 4> NewExts;
Quentin Colombet1b274f92015-03-10 21:48:15 +00004678 unsigned NewCreatedInstsCost = 0;
4679 unsigned ExtCost = !TLI->isExtFree(I);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004680 // Promote.
Quentin Colombet1b274f92015-03-10 21:48:15 +00004681 Value *PromotedVal = TPH(I, TPT, PromotedInsts, NewCreatedInstsCost,
4682 &NewExts, nullptr, *TLI);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004683 assert(PromotedVal &&
4684 "TypePromotionHelper should have filtered out those cases");
4685
4686 // We would be able to merge only one extension in a load.
4687 // Therefore, if we have more than 1 new extension we heuristically
4688 // cut this search path, because it means we degrade the code quality.
4689 // With exactly 2, the transformation is neutral, because we will merge
4690 // one extension but leave one. However, we optimistically keep going,
4691 // because the new extension may be removed too.
Quentin Colombet1b274f92015-03-10 21:48:15 +00004692 long long TotalCreatedInstsCost = CreatedInstsCost + NewCreatedInstsCost;
Jun Bum Limb99a06b2017-01-27 17:16:37 +00004693 // FIXME: It would be possible to propagate a negative value instead of
Jun Bum Lim42301012017-03-17 19:05:21 +00004694 // conservatively ceiling it to 0.
Jun Bum Limb99a06b2017-01-27 17:16:37 +00004695 TotalCreatedInstsCost =
4696 std::max((long long)0, (TotalCreatedInstsCost - ExtCost));
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004697 if (!StressExtLdPromotion &&
Quentin Colombet1b274f92015-03-10 21:48:15 +00004698 (TotalCreatedInstsCost > 1 ||
Mehdi Amini44ede332015-07-09 02:09:04 +00004699 !isPromotedInstructionLegal(*TLI, *DL, PromotedVal))) {
Jun Bum Lim42301012017-03-17 19:05:21 +00004700 // This promotion is not profitable, rollback to the previous state, and
4701 // save the current extension in ProfitablyMovedExts as the latest
4702 // speculative promotion turned out to be unprofitable.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004703 TPT.rollback(LastKnownGood);
Jun Bum Lim42301012017-03-17 19:05:21 +00004704 ProfitablyMovedExts.push_back(I);
4705 continue;
4706 }
4707 // Continue promoting NewExts as far as doing so is profitable.
4708 SmallVector<Instruction *, 2> NewlyMovedExts;
4709 (void)tryToPromoteExts(TPT, NewExts, NewlyMovedExts, TotalCreatedInstsCost);
4710 bool NewPromoted = false;
4711 for (auto ExtInst : NewlyMovedExts) {
4712 Instruction *MovedExt = cast<Instruction>(ExtInst);
4713 Value *ExtOperand = MovedExt->getOperand(0);
4714 // If we have reached to a load, we need this extra profitability check
4715 // as it could potentially be merged into an ext(load).
4716 if (isa<LoadInst>(ExtOperand) &&
4717 !(StressExtLdPromotion || NewCreatedInstsCost <= ExtCost ||
4718 (ExtOperand->hasOneUse() || hasSameExtUse(ExtOperand, *TLI))))
4719 continue;
4720
4721 ProfitablyMovedExts.push_back(MovedExt);
4722 NewPromoted = true;
4723 }
4724
4725 // If none of speculative promotions for NewExts is profitable, rollback
4726 // and save the current extension (I) as the last profitable extension.
4727 if (!NewPromoted) {
4728 TPT.rollback(LastKnownGood);
4729 ProfitablyMovedExts.push_back(I);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004730 continue;
4731 }
4732 // The promotion is profitable.
Jun Bum Lim42301012017-03-17 19:05:21 +00004733 Promoted = true;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004734 }
Jun Bum Lim42301012017-03-17 19:05:21 +00004735 return Promoted;
4736}
4737
Jun Bum Limdee55652017-04-03 19:20:07 +00004738/// Merging redundant sexts when one is dominating the other.
4739bool CodeGenPrepare::mergeSExts(Function &F) {
4740 DominatorTree DT(F);
4741 bool Changed = false;
4742 for (auto &Entry : ValToSExtendedUses) {
4743 SExts &Insts = Entry.second;
4744 SExts CurPts;
4745 for (Instruction *Inst : Insts) {
4746 if (RemovedInsts.count(Inst) || !isa<SExtInst>(Inst) ||
4747 Inst->getOperand(0) != Entry.first)
4748 continue;
4749 bool inserted = false;
4750 for (auto &Pt : CurPts) {
4751 if (DT.dominates(Inst, Pt)) {
4752 Pt->replaceAllUsesWith(Inst);
4753 RemovedInsts.insert(Pt);
4754 Pt->removeFromParent();
4755 Pt = Inst;
4756 inserted = true;
4757 Changed = true;
4758 break;
4759 }
4760 if (!DT.dominates(Pt, Inst))
4761 // Give up if we need to merge in a common dominator as the
4762 // expermients show it is not profitable.
4763 continue;
4764 Inst->replaceAllUsesWith(Pt);
4765 RemovedInsts.insert(Inst);
4766 Inst->removeFromParent();
4767 inserted = true;
4768 Changed = true;
4769 break;
4770 }
4771 if (!inserted)
4772 CurPts.push_back(Inst);
4773 }
4774 }
4775 return Changed;
4776}
4777
Jun Bum Lim42301012017-03-17 19:05:21 +00004778/// Return true, if an ext(load) can be formed from an extension in
4779/// \p MovedExts.
4780bool CodeGenPrepare::canFormExtLd(
4781 const SmallVectorImpl<Instruction *> &MovedExts, LoadInst *&LI,
4782 Instruction *&Inst, bool HasPromoted) {
4783 for (auto *MovedExtInst : MovedExts) {
4784 if (isa<LoadInst>(MovedExtInst->getOperand(0))) {
4785 LI = cast<LoadInst>(MovedExtInst->getOperand(0));
4786 Inst = MovedExtInst;
4787 break;
4788 }
4789 }
4790 if (!LI)
4791 return false;
4792
4793 // If they're already in the same block, there's nothing to do.
4794 // Make the cheap checks first if we did not promote.
4795 // If we promoted, we need to check if it is indeed profitable.
4796 if (!HasPromoted && LI->getParent() == Inst->getParent())
4797 return false;
4798
Haicheng Wuabdef9e2017-07-15 02:12:16 +00004799 return TLI->isExtLoad(LI, Inst, *DL);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004800}
4801
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004802/// Move a zext or sext fed by a load into the same basic block as the load,
4803/// unless conditions are unfavorable. This allows SelectionDAG to fold the
4804/// extend into the load.
Dan Gohman99429a02009-10-16 20:59:35 +00004805///
Jun Bum Limdee55652017-04-03 19:20:07 +00004806/// E.g.,
4807/// \code
4808/// %ld = load i32* %addr
4809/// %add = add nuw i32 %ld, 4
4810/// %zext = zext i32 %add to i64
4811// \endcode
4812/// =>
4813/// \code
4814/// %ld = load i32* %addr
4815/// %zext = zext i32 %ld to i64
4816/// %add = add nuw i64 %zext, 4
4817/// \encode
4818/// Note that the promotion in %add to i64 is done in tryToPromoteExts(), which
4819/// allow us to match zext(load i32*) to i64.
4820///
4821/// Also, try to promote the computations used to obtain a sign extended
4822/// value used into memory accesses.
4823/// E.g.,
4824/// \code
4825/// a = add nsw i32 b, 3
4826/// d = sext i32 a to i64
4827/// e = getelementptr ..., i64 d
4828/// \endcode
4829/// =>
4830/// \code
4831/// f = sext i32 b to i64
4832/// a = add nsw i64 f, 3
4833/// e = getelementptr ..., i64 a
4834/// \endcode
4835///
4836/// \p Inst[in/out] the extension may be modified during the process if some
4837/// promotions apply.
4838bool CodeGenPrepare::optimizeExt(Instruction *&Inst) {
4839 // ExtLoad formation and address type promotion infrastructure requires TLI to
4840 // be effective.
Chandler Carruth0f139b42016-11-04 06:54:00 +00004841 if (!TLI)
4842 return false;
4843
Jun Bum Limdee55652017-04-03 19:20:07 +00004844 bool AllowPromotionWithoutCommonHeader = false;
4845 /// See if it is an interesting sext operations for the address type
4846 /// promotion before trying to promote it, e.g., the ones with the right
4847 /// type and used in memory accesses.
4848 bool ATPConsiderable = TTI->shouldConsiderAddressTypePromotion(
4849 *Inst, AllowPromotionWithoutCommonHeader);
4850 TypePromotionTransaction TPT(RemovedInsts);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004851 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
Jun Bum Lim42301012017-03-17 19:05:21 +00004852 TPT.getRestorationPoint();
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004853 SmallVector<Instruction *, 1> Exts;
Jun Bum Limdee55652017-04-03 19:20:07 +00004854 SmallVector<Instruction *, 2> SpeculativelyMovedExts;
4855 Exts.push_back(Inst);
Jun Bum Lim42301012017-03-17 19:05:21 +00004856
Jun Bum Limdee55652017-04-03 19:20:07 +00004857 bool HasPromoted = tryToPromoteExts(TPT, Exts, SpeculativelyMovedExts);
Jun Bum Lim42301012017-03-17 19:05:21 +00004858
Dan Gohman99429a02009-10-16 20:59:35 +00004859 // Look for a load being extended.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004860 LoadInst *LI = nullptr;
Jun Bum Limdee55652017-04-03 19:20:07 +00004861 Instruction *ExtFedByLoad;
4862
4863 // Try to promote a chain of computation if it allows to form an extended
4864 // load.
4865 if (canFormExtLd(SpeculativelyMovedExts, LI, ExtFedByLoad, HasPromoted)) {
4866 assert(LI && ExtFedByLoad && "Expect a valid load and extension");
4867 TPT.commit();
4868 // Move the extend into the same block as the load
Sanjay Patel674d2c22017-08-29 14:07:48 +00004869 ExtFedByLoad->moveAfter(LI);
Jun Bum Limdee55652017-04-03 19:20:07 +00004870 // CGP does not check if the zext would be speculatively executed when moved
4871 // to the same basic block as the load. Preserving its original location
4872 // would pessimize the debugging experience, as well as negatively impact
4873 // the quality of sample pgo. We don't want to use "line 0" as that has a
4874 // size cost in the line-table section and logically the zext can be seen as
4875 // part of the load. Therefore we conservatively reuse the same debug
4876 // location for the load and the zext.
4877 ExtFedByLoad->setDebugLoc(LI->getDebugLoc());
4878 ++NumExtsMoved;
4879 Inst = ExtFedByLoad;
4880 return true;
4881 }
4882
4883 // Continue promoting SExts if known as considerable depending on targets.
4884 if (ATPConsiderable &&
4885 performAddressTypePromotion(Inst, AllowPromotionWithoutCommonHeader,
4886 HasPromoted, TPT, SpeculativelyMovedExts))
4887 return true;
4888
4889 TPT.rollback(LastKnownGood);
4890 return false;
4891}
4892
4893// Perform address type promotion if doing so is profitable.
4894// If AllowPromotionWithoutCommonHeader == false, we should find other sext
4895// instructions that sign extended the same initial value. However, if
4896// AllowPromotionWithoutCommonHeader == true, we expect promoting the
4897// extension is just profitable.
4898bool CodeGenPrepare::performAddressTypePromotion(
4899 Instruction *&Inst, bool AllowPromotionWithoutCommonHeader,
4900 bool HasPromoted, TypePromotionTransaction &TPT,
4901 SmallVectorImpl<Instruction *> &SpeculativelyMovedExts) {
4902 bool Promoted = false;
4903 SmallPtrSet<Instruction *, 1> UnhandledExts;
4904 bool AllSeenFirst = true;
4905 for (auto I : SpeculativelyMovedExts) {
4906 Value *HeadOfChain = I->getOperand(0);
4907 DenseMap<Value *, Instruction *>::iterator AlreadySeen =
4908 SeenChainsForSExt.find(HeadOfChain);
4909 // If there is an unhandled SExt which has the same header, try to promote
4910 // it as well.
4911 if (AlreadySeen != SeenChainsForSExt.end()) {
4912 if (AlreadySeen->second != nullptr)
4913 UnhandledExts.insert(AlreadySeen->second);
4914 AllSeenFirst = false;
4915 }
4916 }
4917
4918 if (!AllSeenFirst || (AllowPromotionWithoutCommonHeader &&
4919 SpeculativelyMovedExts.size() == 1)) {
4920 TPT.commit();
4921 if (HasPromoted)
4922 Promoted = true;
4923 for (auto I : SpeculativelyMovedExts) {
4924 Value *HeadOfChain = I->getOperand(0);
4925 SeenChainsForSExt[HeadOfChain] = nullptr;
4926 ValToSExtendedUses[HeadOfChain].push_back(I);
4927 }
4928 // Update Inst as promotion happen.
4929 Inst = SpeculativelyMovedExts.pop_back_val();
4930 } else {
4931 // This is the first chain visited from the header, keep the current chain
4932 // as unhandled. Defer to promote this until we encounter another SExt
4933 // chain derived from the same header.
4934 for (auto I : SpeculativelyMovedExts) {
4935 Value *HeadOfChain = I->getOperand(0);
4936 SeenChainsForSExt[HeadOfChain] = Inst;
4937 }
Dan Gohman99429a02009-10-16 20:59:35 +00004938 return false;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004939 }
Dan Gohman99429a02009-10-16 20:59:35 +00004940
Jun Bum Limdee55652017-04-03 19:20:07 +00004941 if (!AllSeenFirst && !UnhandledExts.empty())
4942 for (auto VisitedSExt : UnhandledExts) {
4943 if (RemovedInsts.count(VisitedSExt))
4944 continue;
4945 TypePromotionTransaction TPT(RemovedInsts);
4946 SmallVector<Instruction *, 1> Exts;
4947 SmallVector<Instruction *, 2> Chains;
4948 Exts.push_back(VisitedSExt);
4949 bool HasPromoted = tryToPromoteExts(TPT, Exts, Chains);
4950 TPT.commit();
4951 if (HasPromoted)
4952 Promoted = true;
4953 for (auto I : Chains) {
4954 Value *HeadOfChain = I->getOperand(0);
4955 // Mark this as handled.
4956 SeenChainsForSExt[HeadOfChain] = nullptr;
4957 ValToSExtendedUses[HeadOfChain].push_back(I);
4958 }
4959 }
4960 return Promoted;
Dan Gohman99429a02009-10-16 20:59:35 +00004961}
4962
Sanjay Patelfc580a62015-09-21 23:03:16 +00004963bool CodeGenPrepare::optimizeExtUses(Instruction *I) {
Evan Chengd3d80172007-12-05 23:58:20 +00004964 BasicBlock *DefBB = I->getParent();
4965
Bob Wilsonff714f92010-09-21 21:44:14 +00004966 // If the result of a {s|z}ext and its source are both live out, rewrite all
Evan Chengd3d80172007-12-05 23:58:20 +00004967 // other uses of the source with result of extension.
4968 Value *Src = I->getOperand(0);
4969 if (Src->hasOneUse())
4970 return false;
4971
Evan Cheng2011df42007-12-13 07:50:36 +00004972 // Only do this xform if truncating is free.
Gabor Greifaa261722008-02-26 19:13:21 +00004973 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
Evan Cheng37c36ed2007-12-13 03:32:53 +00004974 return false;
4975
Evan Cheng7bc89422007-12-12 00:51:06 +00004976 // Only safe to perform the optimization if the source is also defined in
Evan Cheng63d33cf2007-12-12 02:53:41 +00004977 // this block.
4978 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
Evan Cheng7bc89422007-12-12 00:51:06 +00004979 return false;
4980
Evan Chengd3d80172007-12-05 23:58:20 +00004981 bool DefIsLiveOut = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00004982 for (User *U : I->users()) {
4983 Instruction *UI = cast<Instruction>(U);
Evan Chengd3d80172007-12-05 23:58:20 +00004984
4985 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004986 BasicBlock *UserBB = UI->getParent();
Evan Chengd3d80172007-12-05 23:58:20 +00004987 if (UserBB == DefBB) continue;
4988 DefIsLiveOut = true;
4989 break;
4990 }
4991 if (!DefIsLiveOut)
4992 return false;
4993
Jim Grosbach0f38c1e2013-04-15 17:40:48 +00004994 // Make sure none of the uses are PHI nodes.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004995 for (User *U : Src->users()) {
4996 Instruction *UI = cast<Instruction>(U);
4997 BasicBlock *UserBB = UI->getParent();
Evan Cheng37c36ed2007-12-13 03:32:53 +00004998 if (UserBB == DefBB) continue;
4999 // Be conservative. We don't want this xform to end up introducing
5000 // reloads just before load / store instructions.
Chandler Carruthcdf47882014-03-09 03:16:01 +00005001 if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI))
Evan Cheng63d33cf2007-12-12 02:53:41 +00005002 return false;
5003 }
5004
Evan Chengd3d80172007-12-05 23:58:20 +00005005 // InsertedTruncs - Only insert one trunc in each block once.
5006 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
5007
5008 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00005009 for (Use &U : Src->uses()) {
5010 Instruction *User = cast<Instruction>(U.getUser());
Evan Chengd3d80172007-12-05 23:58:20 +00005011
5012 // Figure out which BB this ext is used in.
5013 BasicBlock *UserBB = User->getParent();
5014 if (UserBB == DefBB) continue;
5015
5016 // Both src and def are live in this block. Rewrite the use.
5017 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
5018
5019 if (!InsertedTrunc) {
Bill Wendling8ddfc092011-08-16 20:45:24 +00005020 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00005021 assert(InsertPt != UserBB->end());
5022 InsertedTrunc = new TruncInst(I, Src->getType(), "", &*InsertPt);
Ahmed Bougachaf3299142015-06-17 20:44:32 +00005023 InsertedInsts.insert(InsertedTrunc);
Evan Chengd3d80172007-12-05 23:58:20 +00005024 }
5025
5026 // Replace a use of the {s|z}ext source with a use of the result.
Chandler Carruthcdf47882014-03-09 03:16:01 +00005027 U = InsertedTrunc;
Cameron Zwarichced753f2011-01-05 17:27:27 +00005028 ++NumExtUses;
Evan Chengd3d80172007-12-05 23:58:20 +00005029 MadeChange = true;
5030 }
5031
5032 return MadeChange;
5033}
5034
Geoff Berry5256fca2015-11-20 22:34:39 +00005035// Find loads whose uses only use some of the loaded value's bits. Add an "and"
5036// just after the load if the target can fold this into one extload instruction,
5037// with the hope of eliminating some of the other later "and" instructions using
5038// the loaded value. "and"s that are made trivially redundant by the insertion
5039// of the new "and" are removed by this function, while others (e.g. those whose
5040// path from the load goes through a phi) are left for isel to potentially
5041// remove.
5042//
5043// For example:
5044//
5045// b0:
5046// x = load i32
5047// ...
5048// b1:
5049// y = and x, 0xff
5050// z = use y
5051//
5052// becomes:
5053//
5054// b0:
5055// x = load i32
5056// x' = and x, 0xff
5057// ...
5058// b1:
5059// z = use x'
5060//
5061// whereas:
5062//
5063// b0:
5064// x1 = load i32
5065// ...
5066// b1:
5067// x2 = load i32
5068// ...
5069// b2:
5070// x = phi x1, x2
5071// y = and x, 0xff
5072//
5073// becomes (after a call to optimizeLoadExt for each load):
5074//
5075// b0:
5076// x1 = load i32
5077// x1' = and x1, 0xff
5078// ...
5079// b1:
5080// x2 = load i32
5081// x2' = and x2, 0xff
5082// ...
5083// b2:
5084// x = phi x1', x2'
5085// y = and x, 0xff
Geoff Berry5256fca2015-11-20 22:34:39 +00005086bool CodeGenPrepare::optimizeLoadExt(LoadInst *Load) {
Geoff Berry5256fca2015-11-20 22:34:39 +00005087 if (!Load->isSimple() ||
5088 !(Load->getType()->isIntegerTy() || Load->getType()->isPointerTy()))
5089 return false;
5090
Geoff Berry5d534b62017-02-21 18:53:14 +00005091 // Skip loads we've already transformed.
5092 if (Load->hasOneUse() &&
5093 InsertedInsts.count(cast<Instruction>(*Load->user_begin())))
5094 return false;
Geoff Berry5256fca2015-11-20 22:34:39 +00005095
5096 // Look at all uses of Load, looking through phis, to determine how many bits
5097 // of the loaded value are needed.
5098 SmallVector<Instruction *, 8> WorkList;
5099 SmallPtrSet<Instruction *, 16> Visited;
5100 SmallVector<Instruction *, 8> AndsToMaybeRemove;
5101 for (auto *U : Load->users())
5102 WorkList.push_back(cast<Instruction>(U));
5103
5104 EVT LoadResultVT = TLI->getValueType(*DL, Load->getType());
5105 unsigned BitWidth = LoadResultVT.getSizeInBits();
5106 APInt DemandBits(BitWidth, 0);
5107 APInt WidestAndBits(BitWidth, 0);
5108
5109 while (!WorkList.empty()) {
5110 Instruction *I = WorkList.back();
5111 WorkList.pop_back();
5112
5113 // Break use-def graph loops.
5114 if (!Visited.insert(I).second)
5115 continue;
5116
5117 // For a PHI node, push all of its users.
5118 if (auto *Phi = dyn_cast<PHINode>(I)) {
5119 for (auto *U : Phi->users())
5120 WorkList.push_back(cast<Instruction>(U));
5121 continue;
5122 }
5123
5124 switch (I->getOpcode()) {
Eugene Zelenko900b6332017-08-29 22:32:07 +00005125 case Instruction::And: {
Geoff Berry5256fca2015-11-20 22:34:39 +00005126 auto *AndC = dyn_cast<ConstantInt>(I->getOperand(1));
5127 if (!AndC)
5128 return false;
5129 APInt AndBits = AndC->getValue();
5130 DemandBits |= AndBits;
5131 // Keep track of the widest and mask we see.
5132 if (AndBits.ugt(WidestAndBits))
5133 WidestAndBits = AndBits;
5134 if (AndBits == WidestAndBits && I->getOperand(0) == Load)
5135 AndsToMaybeRemove.push_back(I);
5136 break;
5137 }
5138
Eugene Zelenko900b6332017-08-29 22:32:07 +00005139 case Instruction::Shl: {
Geoff Berry5256fca2015-11-20 22:34:39 +00005140 auto *ShlC = dyn_cast<ConstantInt>(I->getOperand(1));
5141 if (!ShlC)
5142 return false;
5143 uint64_t ShiftAmt = ShlC->getLimitedValue(BitWidth - 1);
Craig Topperfc947bc2017-04-18 17:14:21 +00005144 DemandBits.setLowBits(BitWidth - ShiftAmt);
Geoff Berry5256fca2015-11-20 22:34:39 +00005145 break;
5146 }
5147
Eugene Zelenko900b6332017-08-29 22:32:07 +00005148 case Instruction::Trunc: {
Geoff Berry5256fca2015-11-20 22:34:39 +00005149 EVT TruncVT = TLI->getValueType(*DL, I->getType());
5150 unsigned TruncBitWidth = TruncVT.getSizeInBits();
Craig Topperfc947bc2017-04-18 17:14:21 +00005151 DemandBits.setLowBits(TruncBitWidth);
Geoff Berry5256fca2015-11-20 22:34:39 +00005152 break;
5153 }
5154
5155 default:
5156 return false;
5157 }
5158 }
5159
5160 uint32_t ActiveBits = DemandBits.getActiveBits();
5161 // Avoid hoisting (and (load x) 1) since it is unlikely to be folded by the
5162 // target even if isLoadExtLegal says an i1 EXTLOAD is valid. For example,
5163 // for the AArch64 target isLoadExtLegal(ZEXTLOAD, i32, i1) returns true, but
5164 // (and (load x) 1) is not matched as a single instruction, rather as a LDR
5165 // followed by an AND.
5166 // TODO: Look into removing this restriction by fixing backends to either
5167 // return false for isLoadExtLegal for i1 or have them select this pattern to
5168 // a single instruction.
5169 //
5170 // Also avoid hoisting if we didn't see any ands with the exact DemandBits
5171 // mask, since these are the only ands that will be removed by isel.
Craig Topperd33ee1b2017-04-03 16:34:59 +00005172 if (ActiveBits <= 1 || !DemandBits.isMask(ActiveBits) ||
Geoff Berry5256fca2015-11-20 22:34:39 +00005173 WidestAndBits != DemandBits)
5174 return false;
5175
5176 LLVMContext &Ctx = Load->getType()->getContext();
5177 Type *TruncTy = Type::getIntNTy(Ctx, ActiveBits);
5178 EVT TruncVT = TLI->getValueType(*DL, TruncTy);
5179
5180 // Reject cases that won't be matched as extloads.
5181 if (!LoadResultVT.bitsGT(TruncVT) || !TruncVT.isRound() ||
5182 !TLI->isLoadExtLegal(ISD::ZEXTLOAD, LoadResultVT, TruncVT))
5183 return false;
5184
5185 IRBuilder<> Builder(Load->getNextNode());
5186 auto *NewAnd = dyn_cast<Instruction>(
5187 Builder.CreateAnd(Load, ConstantInt::get(Ctx, DemandBits)));
Geoff Berry5d534b62017-02-21 18:53:14 +00005188 // Mark this instruction as "inserted by CGP", so that other
5189 // optimizations don't touch it.
5190 InsertedInsts.insert(NewAnd);
Geoff Berry5256fca2015-11-20 22:34:39 +00005191
5192 // Replace all uses of load with new and (except for the use of load in the
5193 // new and itself).
5194 Load->replaceAllUsesWith(NewAnd);
5195 NewAnd->setOperand(0, Load);
5196
5197 // Remove any and instructions that are now redundant.
5198 for (auto *And : AndsToMaybeRemove)
5199 // Check that the and mask is the same as the one we decided to put on the
5200 // new and.
5201 if (cast<ConstantInt>(And->getOperand(1))->getValue() == DemandBits) {
5202 And->replaceAllUsesWith(NewAnd);
5203 if (&*CurInstIterator == And)
5204 CurInstIterator = std::next(And->getIterator());
5205 And->eraseFromParent();
5206 ++NumAndUses;
5207 }
5208
5209 ++NumAndsAdded;
5210 return true;
5211}
5212
Sanjay Patel69a50a12015-10-19 21:59:12 +00005213/// Check if V (an operand of a select instruction) is an expensive instruction
5214/// that is only used once.
5215static bool sinkSelectOperand(const TargetTransformInfo *TTI, Value *V) {
5216 auto *I = dyn_cast<Instruction>(V);
5217 // If it's safe to speculatively execute, then it should not have side
5218 // effects; therefore, it's safe to sink and possibly *not* execute.
Rafael Espindola84921b92015-10-24 23:11:13 +00005219 return I && I->hasOneUse() && isSafeToSpeculativelyExecute(I) &&
5220 TTI->getUserCost(I) >= TargetTransformInfo::TCC_Expensive;
Sanjay Patel69a50a12015-10-19 21:59:12 +00005221}
5222
Sanjay Patel4ac6b112015-09-21 22:47:23 +00005223/// Returns true if a SelectInst should be turned into an explicit branch.
Sanjay Patel69a50a12015-10-19 21:59:12 +00005224static bool isFormingBranchFromSelectProfitable(const TargetTransformInfo *TTI,
Sanjay Pateld66607b2016-04-26 17:11:17 +00005225 const TargetLowering *TLI,
Sanjay Patel69a50a12015-10-19 21:59:12 +00005226 SelectInst *SI) {
Sanjay Pateld66607b2016-04-26 17:11:17 +00005227 // If even a predictable select is cheap, then a branch can't be cheaper.
5228 if (!TLI->isPredictableSelectExpensive())
5229 return false;
5230
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005231 // FIXME: This should use the same heuristics as IfConversion to determine
Sanjay Pateld66607b2016-04-26 17:11:17 +00005232 // whether a select is better represented as a branch.
5233
5234 // If metadata tells us that the select condition is obviously predictable,
5235 // then we want to replace the select with a branch.
5236 uint64_t TrueWeight, FalseWeight;
5237 if (SI->extractProfMetadata(TrueWeight, FalseWeight)) {
5238 uint64_t Max = std::max(TrueWeight, FalseWeight);
5239 uint64_t Sum = TrueWeight + FalseWeight;
Sanjay Patelc7b91e62016-05-09 17:31:55 +00005240 if (Sum != 0) {
5241 auto Probability = BranchProbability::getBranchProbability(Max, Sum);
5242 if (Probability > TLI->getPredictableBranchThreshold())
5243 return true;
5244 }
Sanjay Pateld66607b2016-04-26 17:11:17 +00005245 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005246
5247 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
5248
Sanjay Patel4e652762015-09-28 22:14:51 +00005249 // If a branch is predictable, an out-of-order CPU can avoid blocking on its
5250 // comparison condition. If the compare has more than one use, there's
5251 // probably another cmov or setcc around, so it's not worth emitting a branch.
Sanjay Patel5e5f0e92015-09-28 21:44:46 +00005252 if (!Cmp || !Cmp->hasOneUse())
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005253 return false;
5254
Sanjay Patel69a50a12015-10-19 21:59:12 +00005255 // If either operand of the select is expensive and only needed on one side
5256 // of the select, we should form a branch.
5257 if (sinkSelectOperand(TTI, SI->getTrueValue()) ||
5258 sinkSelectOperand(TTI, SI->getFalseValue()))
5259 return true;
5260
5261 return false;
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005262}
5263
Dehao Chen9bbb9412016-09-12 20:23:28 +00005264/// If \p isTrue is true, return the true value of \p SI, otherwise return
5265/// false value of \p SI. If the true/false value of \p SI is defined by any
5266/// select instructions in \p Selects, look through the defining select
5267/// instruction until the true/false value is not defined in \p Selects.
5268static Value *getTrueOrFalseValue(
5269 SelectInst *SI, bool isTrue,
5270 const SmallPtrSet<const Instruction *, 2> &Selects) {
5271 Value *V;
5272
5273 for (SelectInst *DefSI = SI; DefSI != nullptr && Selects.count(DefSI);
5274 DefSI = dyn_cast<SelectInst>(V)) {
Dehao Chenc32d7122016-09-12 20:29:54 +00005275 assert(DefSI->getCondition() == SI->getCondition() &&
Dehao Chen9bbb9412016-09-12 20:23:28 +00005276 "The condition of DefSI does not match with SI");
5277 V = (isTrue ? DefSI->getTrueValue() : DefSI->getFalseValue());
5278 }
5279 return V;
5280}
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005281
Nadav Rotem9d832022012-09-02 12:10:19 +00005282/// If we have a SelectInst that will likely profit from branch prediction,
5283/// turn it into a branch.
Sanjay Patelfc580a62015-09-21 23:03:16 +00005284bool CodeGenPrepare::optimizeSelectInst(SelectInst *SI) {
Dehao Chen9bbb9412016-09-12 20:23:28 +00005285 // Find all consecutive select instructions that share the same condition.
5286 SmallVector<SelectInst *, 2> ASI;
5287 ASI.push_back(SI);
5288 for (BasicBlock::iterator It = ++BasicBlock::iterator(SI);
5289 It != SI->getParent()->end(); ++It) {
5290 SelectInst *I = dyn_cast<SelectInst>(&*It);
5291 if (I && SI->getCondition() == I->getCondition()) {
5292 ASI.push_back(I);
5293 } else {
5294 break;
5295 }
5296 }
5297
5298 SelectInst *LastSI = ASI.back();
5299 // Increment the current iterator to skip all the rest of select instructions
5300 // because they will be either "not lowered" or "all lowered" to branch.
5301 CurInstIterator = std::next(LastSI->getIterator());
5302
Nadav Rotem9d832022012-09-02 12:10:19 +00005303 bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
5304
5305 // Can we convert the 'select' to CF ?
Sanjay Patela31b0c02016-04-26 00:47:39 +00005306 if (DisableSelectToBranch || OptSize || !TLI || VectorCond ||
5307 SI->getMetadata(LLVMContext::MD_unpredictable))
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005308 return false;
5309
Nadav Rotem9d832022012-09-02 12:10:19 +00005310 TargetLowering::SelectSupportKind SelectKind;
5311 if (VectorCond)
5312 SelectKind = TargetLowering::VectorMaskSelect;
5313 else if (SI->getType()->isVectorTy())
5314 SelectKind = TargetLowering::ScalarCondVectorVal;
5315 else
5316 SelectKind = TargetLowering::ScalarValSelect;
5317
Sanjay Pateld66607b2016-04-26 17:11:17 +00005318 if (TLI->isSelectSupported(SelectKind) &&
5319 !isFormingBranchFromSelectProfitable(TTI, TLI, SI))
5320 return false;
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005321
5322 ModifiedDT = true;
5323
Sanjay Patel69a50a12015-10-19 21:59:12 +00005324 // Transform a sequence like this:
5325 // start:
5326 // %cmp = cmp uge i32 %a, %b
5327 // %sel = select i1 %cmp, i32 %c, i32 %d
5328 //
5329 // Into:
5330 // start:
5331 // %cmp = cmp uge i32 %a, %b
5332 // br i1 %cmp, label %select.true, label %select.false
5333 // select.true:
5334 // br label %select.end
5335 // select.false:
5336 // br label %select.end
5337 // select.end:
5338 // %sel = phi i32 [ %c, %select.true ], [ %d, %select.false ]
5339 //
5340 // In addition, we may sink instructions that produce %c or %d from
5341 // the entry block into the destination(s) of the new branch.
5342 // If the true or false blocks do not contain a sunken instruction, that
5343 // block and its branch may be optimized away. In that case, one side of the
5344 // first branch will point directly to select.end, and the corresponding PHI
5345 // predecessor block will be the start block.
5346
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005347 // First, we split the block containing the select into 2 blocks.
5348 BasicBlock *StartBlock = SI->getParent();
Dehao Chen9bbb9412016-09-12 20:23:28 +00005349 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(LastSI));
Sanjay Patel69a50a12015-10-19 21:59:12 +00005350 BasicBlock *EndBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005351
Sanjay Patel69a50a12015-10-19 21:59:12 +00005352 // Delete the unconditional branch that was just created by the split.
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005353 StartBlock->getTerminator()->eraseFromParent();
Sanjay Patel69a50a12015-10-19 21:59:12 +00005354
5355 // These are the new basic blocks for the conditional branch.
5356 // At least one will become an actual new basic block.
5357 BasicBlock *TrueBlock = nullptr;
5358 BasicBlock *FalseBlock = nullptr;
Dehao Chen9bbb9412016-09-12 20:23:28 +00005359 BranchInst *TrueBranch = nullptr;
5360 BranchInst *FalseBranch = nullptr;
Sanjay Patel69a50a12015-10-19 21:59:12 +00005361
5362 // Sink expensive instructions into the conditional blocks to avoid executing
5363 // them speculatively.
Dehao Chen9bbb9412016-09-12 20:23:28 +00005364 for (SelectInst *SI : ASI) {
5365 if (sinkSelectOperand(TTI, SI->getTrueValue())) {
5366 if (TrueBlock == nullptr) {
5367 TrueBlock = BasicBlock::Create(SI->getContext(), "select.true.sink",
5368 EndBlock->getParent(), EndBlock);
5369 TrueBranch = BranchInst::Create(EndBlock, TrueBlock);
5370 }
5371 auto *TrueInst = cast<Instruction>(SI->getTrueValue());
5372 TrueInst->moveBefore(TrueBranch);
5373 }
5374 if (sinkSelectOperand(TTI, SI->getFalseValue())) {
5375 if (FalseBlock == nullptr) {
5376 FalseBlock = BasicBlock::Create(SI->getContext(), "select.false.sink",
5377 EndBlock->getParent(), EndBlock);
5378 FalseBranch = BranchInst::Create(EndBlock, FalseBlock);
5379 }
5380 auto *FalseInst = cast<Instruction>(SI->getFalseValue());
5381 FalseInst->moveBefore(FalseBranch);
5382 }
Sanjay Patel69a50a12015-10-19 21:59:12 +00005383 }
5384
5385 // If there was nothing to sink, then arbitrarily choose the 'false' side
5386 // for a new input value to the PHI.
5387 if (TrueBlock == FalseBlock) {
5388 assert(TrueBlock == nullptr &&
5389 "Unexpected basic block transform while optimizing select");
5390
5391 FalseBlock = BasicBlock::Create(SI->getContext(), "select.false",
5392 EndBlock->getParent(), EndBlock);
5393 BranchInst::Create(EndBlock, FalseBlock);
5394 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005395
5396 // Insert the real conditional branch based on the original condition.
Sanjay Patel69a50a12015-10-19 21:59:12 +00005397 // If we did not create a new block for one of the 'true' or 'false' paths
5398 // of the condition, it means that side of the branch goes to the end block
5399 // directly and the path originates from the start block from the point of
5400 // view of the new PHI.
Xinliang David Li241e6c72016-09-03 21:26:36 +00005401 BasicBlock *TT, *FT;
Sanjay Patel69a50a12015-10-19 21:59:12 +00005402 if (TrueBlock == nullptr) {
Xinliang David Li241e6c72016-09-03 21:26:36 +00005403 TT = EndBlock;
5404 FT = FalseBlock;
Sanjay Patel69a50a12015-10-19 21:59:12 +00005405 TrueBlock = StartBlock;
5406 } else if (FalseBlock == nullptr) {
Xinliang David Li241e6c72016-09-03 21:26:36 +00005407 TT = TrueBlock;
5408 FT = EndBlock;
Sanjay Patel69a50a12015-10-19 21:59:12 +00005409 FalseBlock = StartBlock;
5410 } else {
Xinliang David Li241e6c72016-09-03 21:26:36 +00005411 TT = TrueBlock;
5412 FT = FalseBlock;
Sanjay Patel69a50a12015-10-19 21:59:12 +00005413 }
Xinliang David Li241e6c72016-09-03 21:26:36 +00005414 IRBuilder<>(SI).CreateCondBr(SI->getCondition(), TT, FT, SI);
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005415
Dehao Chen9bbb9412016-09-12 20:23:28 +00005416 SmallPtrSet<const Instruction *, 2> INS;
5417 INS.insert(ASI.begin(), ASI.end());
5418 // Use reverse iterator because later select may use the value of the
5419 // earlier select, and we need to propagate value through earlier select
5420 // to get the PHI operand.
5421 for (auto It = ASI.rbegin(); It != ASI.rend(); ++It) {
5422 SelectInst *SI = *It;
5423 // The select itself is replaced with a PHI Node.
5424 PHINode *PN = PHINode::Create(SI->getType(), 2, "", &EndBlock->front());
5425 PN->takeName(SI);
5426 PN->addIncoming(getTrueOrFalseValue(SI, true, INS), TrueBlock);
5427 PN->addIncoming(getTrueOrFalseValue(SI, false, INS), FalseBlock);
Sanjay Patel69a50a12015-10-19 21:59:12 +00005428
Dehao Chen9bbb9412016-09-12 20:23:28 +00005429 SI->replaceAllUsesWith(PN);
5430 SI->eraseFromParent();
5431 INS.erase(SI);
5432 ++NumSelectsExpanded;
5433 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005434
5435 // Instruct OptimizeBlock to skip to the next block.
5436 CurInstIterator = StartBlock->end();
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005437 return true;
5438}
5439
Benjamin Kramer573ff362014-03-01 17:24:40 +00005440static bool isBroadcastShuffle(ShuffleVectorInst *SVI) {
Tim Northoveraeb8e062014-02-19 10:02:43 +00005441 SmallVector<int, 16> Mask(SVI->getShuffleMask());
5442 int SplatElem = -1;
5443 for (unsigned i = 0; i < Mask.size(); ++i) {
5444 if (SplatElem != -1 && Mask[i] != -1 && Mask[i] != SplatElem)
5445 return false;
5446 SplatElem = Mask[i];
5447 }
5448
5449 return true;
5450}
5451
5452/// Some targets have expensive vector shifts if the lanes aren't all the same
5453/// (e.g. x86 only introduced "vpsllvd" and friends with AVX2). In these cases
5454/// it's often worth sinking a shufflevector splat down to its use so that
5455/// codegen can spot all lanes are identical.
Sanjay Patelfc580a62015-09-21 23:03:16 +00005456bool CodeGenPrepare::optimizeShuffleVectorInst(ShuffleVectorInst *SVI) {
Tim Northoveraeb8e062014-02-19 10:02:43 +00005457 BasicBlock *DefBB = SVI->getParent();
5458
5459 // Only do this xform if variable vector shifts are particularly expensive.
5460 if (!TLI || !TLI->isVectorShiftByScalarCheap(SVI->getType()))
5461 return false;
5462
5463 // We only expect better codegen by sinking a shuffle if we can recognise a
5464 // constant splat.
5465 if (!isBroadcastShuffle(SVI))
5466 return false;
5467
5468 // InsertedShuffles - Only insert a shuffle in each block once.
5469 DenseMap<BasicBlock*, Instruction*> InsertedShuffles;
5470
5471 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00005472 for (User *U : SVI->users()) {
5473 Instruction *UI = cast<Instruction>(U);
Tim Northoveraeb8e062014-02-19 10:02:43 +00005474
5475 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00005476 BasicBlock *UserBB = UI->getParent();
Tim Northoveraeb8e062014-02-19 10:02:43 +00005477 if (UserBB == DefBB) continue;
5478
5479 // For now only apply this when the splat is used by a shift instruction.
Chandler Carruthcdf47882014-03-09 03:16:01 +00005480 if (!UI->isShift()) continue;
Tim Northoveraeb8e062014-02-19 10:02:43 +00005481
5482 // Everything checks out, sink the shuffle if the user's block doesn't
5483 // already have a copy.
5484 Instruction *&InsertedShuffle = InsertedShuffles[UserBB];
5485
5486 if (!InsertedShuffle) {
5487 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00005488 assert(InsertPt != UserBB->end());
5489 InsertedShuffle =
5490 new ShuffleVectorInst(SVI->getOperand(0), SVI->getOperand(1),
5491 SVI->getOperand(2), "", &*InsertPt);
Tim Northoveraeb8e062014-02-19 10:02:43 +00005492 }
5493
Chandler Carruthcdf47882014-03-09 03:16:01 +00005494 UI->replaceUsesOfWith(SVI, InsertedShuffle);
Tim Northoveraeb8e062014-02-19 10:02:43 +00005495 MadeChange = true;
5496 }
5497
5498 // If we removed all uses, nuke the shuffle.
5499 if (SVI->use_empty()) {
5500 SVI->eraseFromParent();
5501 MadeChange = true;
5502 }
5503
5504 return MadeChange;
5505}
5506
Sanjay Patel0ed9aea2015-11-02 23:22:49 +00005507bool CodeGenPrepare::optimizeSwitchInst(SwitchInst *SI) {
5508 if (!TLI || !DL)
5509 return false;
5510
5511 Value *Cond = SI->getCondition();
5512 Type *OldType = Cond->getType();
5513 LLVMContext &Context = Cond->getContext();
5514 MVT RegType = TLI->getRegisterType(Context, TLI->getValueType(*DL, OldType));
5515 unsigned RegWidth = RegType.getSizeInBits();
5516
5517 if (RegWidth <= cast<IntegerType>(OldType)->getBitWidth())
5518 return false;
5519
5520 // If the register width is greater than the type width, expand the condition
5521 // of the switch instruction and each case constant to the width of the
5522 // register. By widening the type of the switch condition, subsequent
5523 // comparisons (for case comparisons) will not need to be extended to the
5524 // preferred register width, so we will potentially eliminate N-1 extends,
5525 // where N is the number of cases in the switch.
5526 auto *NewType = Type::getIntNTy(Context, RegWidth);
5527
5528 // Zero-extend the switch condition and case constants unless the switch
5529 // condition is a function argument that is already being sign-extended.
5530 // In that case, we can avoid an unnecessary mask/extension by sign-extending
5531 // everything instead.
5532 Instruction::CastOps ExtType = Instruction::ZExt;
5533 if (auto *Arg = dyn_cast<Argument>(Cond))
5534 if (Arg->hasSExtAttr())
5535 ExtType = Instruction::SExt;
5536
5537 auto *ExtInst = CastInst::Create(ExtType, Cond, NewType);
5538 ExtInst->insertBefore(SI);
5539 SI->setCondition(ExtInst);
Chandler Carruth927d8e62017-04-12 07:27:28 +00005540 for (auto Case : SI->cases()) {
Sanjay Patel0ed9aea2015-11-02 23:22:49 +00005541 APInt NarrowConst = Case.getCaseValue()->getValue();
5542 APInt WideConst = (ExtType == Instruction::ZExt) ?
5543 NarrowConst.zext(RegWidth) : NarrowConst.sext(RegWidth);
5544 Case.setValue(ConstantInt::get(Context, WideConst));
5545 }
5546
5547 return true;
5548}
5549
Zaara Syeda3a7578c2017-05-31 17:12:38 +00005550
Quentin Colombetc32615d2014-10-31 17:52:53 +00005551namespace {
Eugene Zelenko900b6332017-08-29 22:32:07 +00005552
Quentin Colombetc32615d2014-10-31 17:52:53 +00005553/// \brief Helper class to promote a scalar operation to a vector one.
5554/// This class is used to move downward extractelement transition.
5555/// E.g.,
5556/// a = vector_op <2 x i32>
5557/// b = extractelement <2 x i32> a, i32 0
5558/// c = scalar_op b
5559/// store c
5560///
5561/// =>
5562/// a = vector_op <2 x i32>
5563/// c = vector_op a (equivalent to scalar_op on the related lane)
5564/// * d = extractelement <2 x i32> c, i32 0
5565/// * store d
5566/// Assuming both extractelement and store can be combine, we get rid of the
5567/// transition.
5568class VectorPromoteHelper {
Mehdi Amini44ede332015-07-09 02:09:04 +00005569 /// DataLayout associated with the current module.
5570 const DataLayout &DL;
5571
Quentin Colombetc32615d2014-10-31 17:52:53 +00005572 /// Used to perform some checks on the legality of vector operations.
5573 const TargetLowering &TLI;
5574
5575 /// Used to estimated the cost of the promoted chain.
5576 const TargetTransformInfo &TTI;
5577
5578 /// The transition being moved downwards.
5579 Instruction *Transition;
Eugene Zelenko900b6332017-08-29 22:32:07 +00005580
Quentin Colombetc32615d2014-10-31 17:52:53 +00005581 /// The sequence of instructions to be promoted.
5582 SmallVector<Instruction *, 4> InstsToBePromoted;
Eugene Zelenko900b6332017-08-29 22:32:07 +00005583
Quentin Colombetc32615d2014-10-31 17:52:53 +00005584 /// Cost of combining a store and an extract.
5585 unsigned StoreExtractCombineCost;
Eugene Zelenko900b6332017-08-29 22:32:07 +00005586
Quentin Colombetc32615d2014-10-31 17:52:53 +00005587 /// Instruction that will be combined with the transition.
Eugene Zelenko900b6332017-08-29 22:32:07 +00005588 Instruction *CombineInst = nullptr;
Quentin Colombetc32615d2014-10-31 17:52:53 +00005589
5590 /// \brief The instruction that represents the current end of the transition.
5591 /// Since we are faking the promotion until we reach the end of the chain
5592 /// of computation, we need a way to get the current end of the transition.
5593 Instruction *getEndOfTransition() const {
5594 if (InstsToBePromoted.empty())
5595 return Transition;
5596 return InstsToBePromoted.back();
5597 }
5598
5599 /// \brief Return the index of the original value in the transition.
5600 /// E.g., for "extractelement <2 x i32> c, i32 1" the original value,
5601 /// c, is at index 0.
5602 unsigned getTransitionOriginalValueIdx() const {
5603 assert(isa<ExtractElementInst>(Transition) &&
5604 "Other kind of transitions are not supported yet");
5605 return 0;
5606 }
5607
5608 /// \brief Return the index of the index in the transition.
5609 /// E.g., for "extractelement <2 x i32> c, i32 0" the index
5610 /// is at index 1.
5611 unsigned getTransitionIdx() const {
5612 assert(isa<ExtractElementInst>(Transition) &&
5613 "Other kind of transitions are not supported yet");
5614 return 1;
5615 }
5616
5617 /// \brief Get the type of the transition.
5618 /// This is the type of the original value.
5619 /// E.g., for "extractelement <2 x i32> c, i32 1" the type of the
5620 /// transition is <2 x i32>.
5621 Type *getTransitionType() const {
5622 return Transition->getOperand(getTransitionOriginalValueIdx())->getType();
5623 }
5624
5625 /// \brief Promote \p ToBePromoted by moving \p Def downward through.
5626 /// I.e., we have the following sequence:
5627 /// Def = Transition <ty1> a to <ty2>
5628 /// b = ToBePromoted <ty2> Def, ...
5629 /// =>
5630 /// b = ToBePromoted <ty1> a, ...
5631 /// Def = Transition <ty1> ToBePromoted to <ty2>
5632 void promoteImpl(Instruction *ToBePromoted);
5633
5634 /// \brief Check whether or not it is profitable to promote all the
5635 /// instructions enqueued to be promoted.
5636 bool isProfitableToPromote() {
5637 Value *ValIdx = Transition->getOperand(getTransitionOriginalValueIdx());
5638 unsigned Index = isa<ConstantInt>(ValIdx)
5639 ? cast<ConstantInt>(ValIdx)->getZExtValue()
5640 : -1;
5641 Type *PromotedType = getTransitionType();
5642
5643 StoreInst *ST = cast<StoreInst>(CombineInst);
5644 unsigned AS = ST->getPointerAddressSpace();
5645 unsigned Align = ST->getAlignment();
5646 // Check if this store is supported.
5647 if (!TLI.allowsMisalignedMemoryAccesses(
Mehdi Amini44ede332015-07-09 02:09:04 +00005648 TLI.getValueType(DL, ST->getValueOperand()->getType()), AS,
5649 Align)) {
Quentin Colombetc32615d2014-10-31 17:52:53 +00005650 // If this is not supported, there is no way we can combine
5651 // the extract with the store.
5652 return false;
5653 }
5654
5655 // The scalar chain of computation has to pay for the transition
5656 // scalar to vector.
5657 // The vector chain has to account for the combining cost.
5658 uint64_t ScalarCost =
5659 TTI.getVectorInstrCost(Transition->getOpcode(), PromotedType, Index);
5660 uint64_t VectorCost = StoreExtractCombineCost;
5661 for (const auto &Inst : InstsToBePromoted) {
5662 // Compute the cost.
5663 // By construction, all instructions being promoted are arithmetic ones.
5664 // Moreover, one argument is a constant that can be viewed as a splat
5665 // constant.
5666 Value *Arg0 = Inst->getOperand(0);
5667 bool IsArg0Constant = isa<UndefValue>(Arg0) || isa<ConstantInt>(Arg0) ||
5668 isa<ConstantFP>(Arg0);
5669 TargetTransformInfo::OperandValueKind Arg0OVK =
5670 IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
5671 : TargetTransformInfo::OK_AnyValue;
5672 TargetTransformInfo::OperandValueKind Arg1OVK =
5673 !IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
5674 : TargetTransformInfo::OK_AnyValue;
5675 ScalarCost += TTI.getArithmeticInstrCost(
5676 Inst->getOpcode(), Inst->getType(), Arg0OVK, Arg1OVK);
5677 VectorCost += TTI.getArithmeticInstrCost(Inst->getOpcode(), PromotedType,
5678 Arg0OVK, Arg1OVK);
5679 }
5680 DEBUG(dbgs() << "Estimated cost of computation to be promoted:\nScalar: "
5681 << ScalarCost << "\nVector: " << VectorCost << '\n');
5682 return ScalarCost > VectorCost;
5683 }
5684
5685 /// \brief Generate a constant vector with \p Val with the same
5686 /// number of elements as the transition.
5687 /// \p UseSplat defines whether or not \p Val should be replicated
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00005688 /// across the whole vector.
Quentin Colombetc32615d2014-10-31 17:52:53 +00005689 /// In other words, if UseSplat == true, we generate <Val, Val, ..., Val>,
5690 /// otherwise we generate a vector with as many undef as possible:
5691 /// <undef, ..., undef, Val, undef, ..., undef> where \p Val is only
5692 /// used at the index of the extract.
5693 Value *getConstantVector(Constant *Val, bool UseSplat) const {
Eugene Zelenko900b6332017-08-29 22:32:07 +00005694 unsigned ExtractIdx = std::numeric_limits<unsigned>::max();
Quentin Colombetc32615d2014-10-31 17:52:53 +00005695 if (!UseSplat) {
5696 // If we cannot determine where the constant must be, we have to
5697 // use a splat constant.
5698 Value *ValExtractIdx = Transition->getOperand(getTransitionIdx());
5699 if (ConstantInt *CstVal = dyn_cast<ConstantInt>(ValExtractIdx))
5700 ExtractIdx = CstVal->getSExtValue();
5701 else
5702 UseSplat = true;
5703 }
5704
5705 unsigned End = getTransitionType()->getVectorNumElements();
5706 if (UseSplat)
5707 return ConstantVector::getSplat(End, Val);
5708
5709 SmallVector<Constant *, 4> ConstVec;
5710 UndefValue *UndefVal = UndefValue::get(Val->getType());
5711 for (unsigned Idx = 0; Idx != End; ++Idx) {
5712 if (Idx == ExtractIdx)
5713 ConstVec.push_back(Val);
5714 else
5715 ConstVec.push_back(UndefVal);
5716 }
5717 return ConstantVector::get(ConstVec);
5718 }
5719
5720 /// \brief Check if promoting to a vector type an operand at \p OperandIdx
5721 /// in \p Use can trigger undefined behavior.
5722 static bool canCauseUndefinedBehavior(const Instruction *Use,
5723 unsigned OperandIdx) {
5724 // This is not safe to introduce undef when the operand is on
5725 // the right hand side of a division-like instruction.
5726 if (OperandIdx != 1)
5727 return false;
5728 switch (Use->getOpcode()) {
5729 default:
5730 return false;
5731 case Instruction::SDiv:
5732 case Instruction::UDiv:
5733 case Instruction::SRem:
5734 case Instruction::URem:
5735 return true;
5736 case Instruction::FDiv:
5737 case Instruction::FRem:
5738 return !Use->hasNoNaNs();
5739 }
5740 llvm_unreachable(nullptr);
5741 }
5742
5743public:
Mehdi Amini44ede332015-07-09 02:09:04 +00005744 VectorPromoteHelper(const DataLayout &DL, const TargetLowering &TLI,
5745 const TargetTransformInfo &TTI, Instruction *Transition,
5746 unsigned CombineCost)
5747 : DL(DL), TLI(TLI), TTI(TTI), Transition(Transition),
Eugene Zelenko900b6332017-08-29 22:32:07 +00005748 StoreExtractCombineCost(CombineCost) {
Quentin Colombetc32615d2014-10-31 17:52:53 +00005749 assert(Transition && "Do not know how to promote null");
5750 }
5751
5752 /// \brief Check if we can promote \p ToBePromoted to \p Type.
5753 bool canPromote(const Instruction *ToBePromoted) const {
5754 // We could support CastInst too.
5755 return isa<BinaryOperator>(ToBePromoted);
5756 }
5757
5758 /// \brief Check if it is profitable to promote \p ToBePromoted
5759 /// by moving downward the transition through.
5760 bool shouldPromote(const Instruction *ToBePromoted) const {
5761 // Promote only if all the operands can be statically expanded.
5762 // Indeed, we do not want to introduce any new kind of transitions.
5763 for (const Use &U : ToBePromoted->operands()) {
5764 const Value *Val = U.get();
5765 if (Val == getEndOfTransition()) {
5766 // If the use is a division and the transition is on the rhs,
5767 // we cannot promote the operation, otherwise we may create a
5768 // division by zero.
5769 if (canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()))
5770 return false;
5771 continue;
5772 }
5773 if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) &&
5774 !isa<ConstantFP>(Val))
5775 return false;
5776 }
5777 // Check that the resulting operation is legal.
5778 int ISDOpcode = TLI.InstructionOpcodeToISD(ToBePromoted->getOpcode());
5779 if (!ISDOpcode)
5780 return false;
5781 return StressStoreExtract ||
Ahmed Bougacha026600d2014-11-12 23:05:03 +00005782 TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00005783 ISDOpcode, TLI.getValueType(DL, getTransitionType(), true));
Quentin Colombetc32615d2014-10-31 17:52:53 +00005784 }
5785
5786 /// \brief Check whether or not \p Use can be combined
5787 /// with the transition.
5788 /// I.e., is it possible to do Use(Transition) => AnotherUse?
5789 bool canCombine(const Instruction *Use) { return isa<StoreInst>(Use); }
5790
5791 /// \brief Record \p ToBePromoted as part of the chain to be promoted.
5792 void enqueueForPromotion(Instruction *ToBePromoted) {
5793 InstsToBePromoted.push_back(ToBePromoted);
5794 }
5795
5796 /// \brief Set the instruction that will be combined with the transition.
5797 void recordCombineInstruction(Instruction *ToBeCombined) {
5798 assert(canCombine(ToBeCombined) && "Unsupported instruction to combine");
5799 CombineInst = ToBeCombined;
5800 }
5801
5802 /// \brief Promote all the instructions enqueued for promotion if it is
5803 /// is profitable.
5804 /// \return True if the promotion happened, false otherwise.
5805 bool promote() {
5806 // Check if there is something to promote.
5807 // Right now, if we do not have anything to combine with,
5808 // we assume the promotion is not profitable.
5809 if (InstsToBePromoted.empty() || !CombineInst)
5810 return false;
5811
5812 // Check cost.
5813 if (!StressStoreExtract && !isProfitableToPromote())
5814 return false;
5815
5816 // Promote.
5817 for (auto &ToBePromoted : InstsToBePromoted)
5818 promoteImpl(ToBePromoted);
5819 InstsToBePromoted.clear();
5820 return true;
5821 }
5822};
Eugene Zelenko900b6332017-08-29 22:32:07 +00005823
5824} // end anonymous namespace
Quentin Colombetc32615d2014-10-31 17:52:53 +00005825
5826void VectorPromoteHelper::promoteImpl(Instruction *ToBePromoted) {
5827 // At this point, we know that all the operands of ToBePromoted but Def
5828 // can be statically promoted.
5829 // For Def, we need to use its parameter in ToBePromoted:
5830 // b = ToBePromoted ty1 a
5831 // Def = Transition ty1 b to ty2
5832 // Move the transition down.
5833 // 1. Replace all uses of the promoted operation by the transition.
5834 // = ... b => = ... Def.
5835 assert(ToBePromoted->getType() == Transition->getType() &&
5836 "The type of the result of the transition does not match "
5837 "the final type");
5838 ToBePromoted->replaceAllUsesWith(Transition);
5839 // 2. Update the type of the uses.
5840 // b = ToBePromoted ty2 Def => b = ToBePromoted ty1 Def.
5841 Type *TransitionTy = getTransitionType();
5842 ToBePromoted->mutateType(TransitionTy);
5843 // 3. Update all the operands of the promoted operation with promoted
5844 // operands.
5845 // b = ToBePromoted ty1 Def => b = ToBePromoted ty1 a.
5846 for (Use &U : ToBePromoted->operands()) {
5847 Value *Val = U.get();
5848 Value *NewVal = nullptr;
5849 if (Val == Transition)
5850 NewVal = Transition->getOperand(getTransitionOriginalValueIdx());
5851 else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) ||
5852 isa<ConstantFP>(Val)) {
5853 // Use a splat constant if it is not safe to use undef.
5854 NewVal = getConstantVector(
5855 cast<Constant>(Val),
5856 isa<UndefValue>(Val) ||
5857 canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()));
5858 } else
Craig Topperd3c02f12015-01-05 10:15:49 +00005859 llvm_unreachable("Did you modified shouldPromote and forgot to update "
5860 "this?");
Quentin Colombetc32615d2014-10-31 17:52:53 +00005861 ToBePromoted->setOperand(U.getOperandNo(), NewVal);
5862 }
Sanjay Patel674d2c22017-08-29 14:07:48 +00005863 Transition->moveAfter(ToBePromoted);
Quentin Colombetc32615d2014-10-31 17:52:53 +00005864 Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted);
5865}
5866
5867/// Some targets can do store(extractelement) with one instruction.
5868/// Try to push the extractelement towards the stores when the target
5869/// has this feature and this is profitable.
Sanjay Patelfc580a62015-09-21 23:03:16 +00005870bool CodeGenPrepare::optimizeExtractElementInst(Instruction *Inst) {
Eugene Zelenko900b6332017-08-29 22:32:07 +00005871 unsigned CombineCost = std::numeric_limits<unsigned>::max();
Quentin Colombetc32615d2014-10-31 17:52:53 +00005872 if (DisableStoreExtract || !TLI ||
5873 (!StressStoreExtract &&
5874 !TLI->canCombineStoreAndExtract(Inst->getOperand(0)->getType(),
5875 Inst->getOperand(1), CombineCost)))
5876 return false;
5877
5878 // At this point we know that Inst is a vector to scalar transition.
5879 // Try to move it down the def-use chain, until:
5880 // - We can combine the transition with its single use
5881 // => we got rid of the transition.
5882 // - We escape the current basic block
5883 // => we would need to check that we are moving it at a cheaper place and
5884 // we do not do that for now.
5885 BasicBlock *Parent = Inst->getParent();
5886 DEBUG(dbgs() << "Found an interesting transition: " << *Inst << '\n');
Mehdi Amini44ede332015-07-09 02:09:04 +00005887 VectorPromoteHelper VPH(*DL, *TLI, *TTI, Inst, CombineCost);
Quentin Colombetc32615d2014-10-31 17:52:53 +00005888 // If the transition has more than one use, assume this is not going to be
5889 // beneficial.
5890 while (Inst->hasOneUse()) {
5891 Instruction *ToBePromoted = cast<Instruction>(*Inst->user_begin());
5892 DEBUG(dbgs() << "Use: " << *ToBePromoted << '\n');
5893
5894 if (ToBePromoted->getParent() != Parent) {
5895 DEBUG(dbgs() << "Instruction to promote is in a different block ("
5896 << ToBePromoted->getParent()->getName()
5897 << ") than the transition (" << Parent->getName() << ").\n");
5898 return false;
5899 }
5900
5901 if (VPH.canCombine(ToBePromoted)) {
5902 DEBUG(dbgs() << "Assume " << *Inst << '\n'
5903 << "will be combined with: " << *ToBePromoted << '\n');
5904 VPH.recordCombineInstruction(ToBePromoted);
5905 bool Changed = VPH.promote();
5906 NumStoreExtractExposed += Changed;
5907 return Changed;
5908 }
5909
5910 DEBUG(dbgs() << "Try promoting.\n");
5911 if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted))
5912 return false;
5913
5914 DEBUG(dbgs() << "Promoting is possible... Enqueue for promotion!\n");
5915
5916 VPH.enqueueForPromotion(ToBePromoted);
5917 Inst = ToBePromoted;
5918 }
5919 return false;
5920}
5921
Wei Mia2f0b592016-12-22 19:44:45 +00005922/// For the instruction sequence of store below, F and I values
5923/// are bundled together as an i64 value before being stored into memory.
5924/// Sometimes it is more efficent to generate separate stores for F and I,
5925/// which can remove the bitwise instructions or sink them to colder places.
5926///
5927/// (store (or (zext (bitcast F to i32) to i64),
5928/// (shl (zext I to i64), 32)), addr) -->
5929/// (store F, addr) and (store I, addr+4)
5930///
5931/// Similarly, splitting for other merged store can also be beneficial, like:
5932/// For pair of {i32, i32}, i64 store --> two i32 stores.
5933/// For pair of {i32, i16}, i64 store --> two i32 stores.
5934/// For pair of {i16, i16}, i32 store --> two i16 stores.
5935/// For pair of {i16, i8}, i32 store --> two i16 stores.
5936/// For pair of {i8, i8}, i16 store --> two i8 stores.
5937///
5938/// We allow each target to determine specifically which kind of splitting is
5939/// supported.
5940///
5941/// The store patterns are commonly seen from the simple code snippet below
5942/// if only std::make_pair(...) is sroa transformed before inlined into hoo.
5943/// void goo(const std::pair<int, float> &);
5944/// hoo() {
5945/// ...
5946/// goo(std::make_pair(tmp, ftmp));
5947/// ...
5948/// }
5949///
5950/// Although we already have similar splitting in DAG Combine, we duplicate
5951/// it in CodeGenPrepare to catch the case in which pattern is across
5952/// multiple BBs. The logic in DAG Combine is kept to catch case generated
5953/// during code expansion.
5954static bool splitMergedValStore(StoreInst &SI, const DataLayout &DL,
5955 const TargetLowering &TLI) {
5956 // Handle simple but common cases only.
5957 Type *StoreType = SI.getValueOperand()->getType();
5958 if (DL.getTypeStoreSizeInBits(StoreType) != DL.getTypeSizeInBits(StoreType) ||
5959 DL.getTypeSizeInBits(StoreType) == 0)
5960 return false;
5961
5962 unsigned HalfValBitSize = DL.getTypeSizeInBits(StoreType) / 2;
5963 Type *SplitStoreType = Type::getIntNTy(SI.getContext(), HalfValBitSize);
5964 if (DL.getTypeStoreSizeInBits(SplitStoreType) !=
5965 DL.getTypeSizeInBits(SplitStoreType))
5966 return false;
5967
5968 // Match the following patterns:
5969 // (store (or (zext LValue to i64),
5970 // (shl (zext HValue to i64), 32)), HalfValBitSize)
5971 // or
5972 // (store (or (shl (zext HValue to i64), 32)), HalfValBitSize)
5973 // (zext LValue to i64),
5974 // Expect both operands of OR and the first operand of SHL have only
5975 // one use.
5976 Value *LValue, *HValue;
5977 if (!match(SI.getValueOperand(),
5978 m_c_Or(m_OneUse(m_ZExt(m_Value(LValue))),
5979 m_OneUse(m_Shl(m_OneUse(m_ZExt(m_Value(HValue))),
5980 m_SpecificInt(HalfValBitSize))))))
5981 return false;
5982
5983 // Check LValue and HValue are int with size less or equal than 32.
5984 if (!LValue->getType()->isIntegerTy() ||
5985 DL.getTypeSizeInBits(LValue->getType()) > HalfValBitSize ||
5986 !HValue->getType()->isIntegerTy() ||
5987 DL.getTypeSizeInBits(HValue->getType()) > HalfValBitSize)
5988 return false;
5989
5990 // If LValue/HValue is a bitcast instruction, use the EVT before bitcast
5991 // as the input of target query.
5992 auto *LBC = dyn_cast<BitCastInst>(LValue);
5993 auto *HBC = dyn_cast<BitCastInst>(HValue);
5994 EVT LowTy = LBC ? EVT::getEVT(LBC->getOperand(0)->getType())
5995 : EVT::getEVT(LValue->getType());
5996 EVT HighTy = HBC ? EVT::getEVT(HBC->getOperand(0)->getType())
5997 : EVT::getEVT(HValue->getType());
5998 if (!ForceSplitStore && !TLI.isMultiStoresCheaperThanBitsMerge(LowTy, HighTy))
5999 return false;
6000
6001 // Start to split store.
6002 IRBuilder<> Builder(SI.getContext());
6003 Builder.SetInsertPoint(&SI);
6004
6005 // If LValue/HValue is a bitcast in another BB, create a new one in current
6006 // BB so it may be merged with the splitted stores by dag combiner.
6007 if (LBC && LBC->getParent() != SI.getParent())
6008 LValue = Builder.CreateBitCast(LBC->getOperand(0), LBC->getType());
6009 if (HBC && HBC->getParent() != SI.getParent())
6010 HValue = Builder.CreateBitCast(HBC->getOperand(0), HBC->getType());
6011
Jonas Paulsson5612bb22018-03-13 08:36:20 +00006012 bool IsLE = SI.getModule()->getDataLayout().isLittleEndian();
Wei Mia2f0b592016-12-22 19:44:45 +00006013 auto CreateSplitStore = [&](Value *V, bool Upper) {
6014 V = Builder.CreateZExtOrBitCast(V, SplitStoreType);
6015 Value *Addr = Builder.CreateBitCast(
6016 SI.getOperand(1),
6017 SplitStoreType->getPointerTo(SI.getPointerAddressSpace()));
Jonas Paulsson5612bb22018-03-13 08:36:20 +00006018 if ((IsLE && Upper) || (!IsLE && !Upper))
Wei Mia2f0b592016-12-22 19:44:45 +00006019 Addr = Builder.CreateGEP(
6020 SplitStoreType, Addr,
6021 ConstantInt::get(Type::getInt32Ty(SI.getContext()), 1));
6022 Builder.CreateAlignedStore(
6023 V, Addr, Upper ? SI.getAlignment() / 2 : SI.getAlignment());
6024 };
6025
6026 CreateSplitStore(LValue, false);
6027 CreateSplitStore(HValue, true);
6028
6029 // Delete the old store.
6030 SI.eraseFromParent();
6031 return true;
6032}
6033
Hiroshi Yamauchi93644322017-09-11 17:52:08 +00006034// Return true if the GEP has two operands, the first operand is of a sequential
6035// type, and the second operand is a constant.
6036static bool GEPSequentialConstIndexed(GetElementPtrInst *GEP) {
6037 gep_type_iterator I = gep_type_begin(*GEP);
6038 return GEP->getNumOperands() == 2 &&
6039 I.isSequential() &&
6040 isa<ConstantInt>(GEP->getOperand(1));
6041}
6042
6043// Try unmerging GEPs to reduce liveness interference (register pressure) across
6044// IndirectBr edges. Since IndirectBr edges tend to touch on many blocks,
6045// reducing liveness interference across those edges benefits global register
6046// allocation. Currently handles only certain cases.
6047//
6048// For example, unmerge %GEPI and %UGEPI as below.
6049//
6050// ---------- BEFORE ----------
6051// SrcBlock:
6052// ...
6053// %GEPIOp = ...
6054// ...
6055// %GEPI = gep %GEPIOp, Idx
6056// ...
6057// indirectbr ... [ label %DstB0, label %DstB1, ... label %DstBi ... ]
6058// (* %GEPI is alive on the indirectbr edges due to other uses ahead)
6059// (* %GEPIOp is alive on the indirectbr edges only because of it's used by
6060// %UGEPI)
6061//
6062// DstB0: ... (there may be a gep similar to %UGEPI to be unmerged)
6063// DstB1: ... (there may be a gep similar to %UGEPI to be unmerged)
6064// ...
6065//
6066// DstBi:
6067// ...
6068// %UGEPI = gep %GEPIOp, UIdx
6069// ...
6070// ---------------------------
6071//
6072// ---------- AFTER ----------
6073// SrcBlock:
6074// ... (same as above)
6075// (* %GEPI is still alive on the indirectbr edges)
6076// (* %GEPIOp is no longer alive on the indirectbr edges as a result of the
6077// unmerging)
6078// ...
6079//
6080// DstBi:
6081// ...
6082// %UGEPI = gep %GEPI, (UIdx-Idx)
6083// ...
6084// ---------------------------
6085//
6086// The register pressure on the IndirectBr edges is reduced because %GEPIOp is
6087// no longer alive on them.
6088//
6089// We try to unmerge GEPs here in CodGenPrepare, as opposed to limiting merging
6090// of GEPs in the first place in InstCombiner::visitGetElementPtrInst() so as
6091// not to disable further simplications and optimizations as a result of GEP
6092// merging.
6093//
6094// Note this unmerging may increase the length of the data flow critical path
6095// (the path from %GEPIOp to %UGEPI would go through %GEPI), which is a tradeoff
6096// between the register pressure and the length of data-flow critical
6097// path. Restricting this to the uncommon IndirectBr case would minimize the
6098// impact of potentially longer critical path, if any, and the impact on compile
6099// time.
6100static bool tryUnmergingGEPsAcrossIndirectBr(GetElementPtrInst *GEPI,
6101 const TargetTransformInfo *TTI) {
6102 BasicBlock *SrcBlock = GEPI->getParent();
6103 // Check that SrcBlock ends with an IndirectBr. If not, give up. The common
6104 // (non-IndirectBr) cases exit early here.
6105 if (!isa<IndirectBrInst>(SrcBlock->getTerminator()))
6106 return false;
6107 // Check that GEPI is a simple gep with a single constant index.
6108 if (!GEPSequentialConstIndexed(GEPI))
6109 return false;
6110 ConstantInt *GEPIIdx = cast<ConstantInt>(GEPI->getOperand(1));
6111 // Check that GEPI is a cheap one.
6112 if (TTI->getIntImmCost(GEPIIdx->getValue(), GEPIIdx->getType())
6113 > TargetTransformInfo::TCC_Basic)
6114 return false;
6115 Value *GEPIOp = GEPI->getOperand(0);
6116 // Check that GEPIOp is an instruction that's also defined in SrcBlock.
6117 if (!isa<Instruction>(GEPIOp))
6118 return false;
6119 auto *GEPIOpI = cast<Instruction>(GEPIOp);
6120 if (GEPIOpI->getParent() != SrcBlock)
6121 return false;
6122 // Check that GEP is used outside the block, meaning it's alive on the
6123 // IndirectBr edge(s).
6124 if (find_if(GEPI->users(), [&](User *Usr) {
6125 if (auto *I = dyn_cast<Instruction>(Usr)) {
6126 if (I->getParent() != SrcBlock) {
6127 return true;
6128 }
6129 }
6130 return false;
6131 }) == GEPI->users().end())
6132 return false;
6133 // The second elements of the GEP chains to be unmerged.
6134 std::vector<GetElementPtrInst *> UGEPIs;
6135 // Check each user of GEPIOp to check if unmerging would make GEPIOp not alive
6136 // on IndirectBr edges.
6137 for (User *Usr : GEPIOp->users()) {
6138 if (Usr == GEPI) continue;
6139 // Check if Usr is an Instruction. If not, give up.
6140 if (!isa<Instruction>(Usr))
6141 return false;
6142 auto *UI = cast<Instruction>(Usr);
6143 // Check if Usr in the same block as GEPIOp, which is fine, skip.
6144 if (UI->getParent() == SrcBlock)
6145 continue;
6146 // Check if Usr is a GEP. If not, give up.
6147 if (!isa<GetElementPtrInst>(Usr))
6148 return false;
6149 auto *UGEPI = cast<GetElementPtrInst>(Usr);
6150 // Check if UGEPI is a simple gep with a single constant index and GEPIOp is
6151 // the pointer operand to it. If so, record it in the vector. If not, give
6152 // up.
6153 if (!GEPSequentialConstIndexed(UGEPI))
6154 return false;
6155 if (UGEPI->getOperand(0) != GEPIOp)
6156 return false;
6157 if (GEPIIdx->getType() !=
6158 cast<ConstantInt>(UGEPI->getOperand(1))->getType())
6159 return false;
6160 ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1));
6161 if (TTI->getIntImmCost(UGEPIIdx->getValue(), UGEPIIdx->getType())
6162 > TargetTransformInfo::TCC_Basic)
6163 return false;
6164 UGEPIs.push_back(UGEPI);
6165 }
6166 if (UGEPIs.size() == 0)
6167 return false;
6168 // Check the materializing cost of (Uidx-Idx).
6169 for (GetElementPtrInst *UGEPI : UGEPIs) {
6170 ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1));
6171 APInt NewIdx = UGEPIIdx->getValue() - GEPIIdx->getValue();
6172 unsigned ImmCost = TTI->getIntImmCost(NewIdx, GEPIIdx->getType());
6173 if (ImmCost > TargetTransformInfo::TCC_Basic)
6174 return false;
6175 }
6176 // Now unmerge between GEPI and UGEPIs.
6177 for (GetElementPtrInst *UGEPI : UGEPIs) {
6178 UGEPI->setOperand(0, GEPI);
6179 ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1));
6180 Constant *NewUGEPIIdx =
6181 ConstantInt::get(GEPIIdx->getType(),
6182 UGEPIIdx->getValue() - GEPIIdx->getValue());
6183 UGEPI->setOperand(1, NewUGEPIIdx);
6184 // If GEPI is not inbounds but UGEPI is inbounds, change UGEPI to not
6185 // inbounds to avoid UB.
6186 if (!GEPI->isInBounds()) {
6187 UGEPI->setIsInBounds(false);
6188 }
6189 }
6190 // After unmerging, verify that GEPIOp is actually only used in SrcBlock (not
6191 // alive on IndirectBr edges).
6192 assert(find_if(GEPIOp->users(), [&](User *Usr) {
6193 return cast<Instruction>(Usr)->getParent() != SrcBlock;
6194 }) == GEPIOp->users().end() && "GEPIOp is used outside SrcBlock");
6195 return true;
6196}
6197
Sanjay Patel3b8974b2017-06-08 20:00:09 +00006198bool CodeGenPrepare::optimizeInst(Instruction *I, bool &ModifiedDT) {
Ahmed Bougachaf3299142015-06-17 20:44:32 +00006199 // Bail out if we inserted the instruction to prevent optimizations from
6200 // stepping on each other's toes.
6201 if (InsertedInsts.count(I))
6202 return false;
6203
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006204 if (PHINode *P = dyn_cast<PHINode>(I)) {
6205 // It is possible for very late stage optimizations (such as SimplifyCFG)
6206 // to introduce PHI nodes too late to be cleaned up. If we detect such a
6207 // trivial PHI, go ahead and zap it here.
Daniel Berlin4d0fe642017-04-28 19:55:38 +00006208 if (Value *V = SimplifyInstruction(P, {*DL, TLInfo})) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006209 P->replaceAllUsesWith(V);
6210 P->eraseFromParent();
6211 ++NumPHIsElim;
Chris Lattneree588de2011-01-15 07:29:01 +00006212 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006213 }
Chris Lattneree588de2011-01-15 07:29:01 +00006214 return false;
6215 }
Nadav Rotem465834c2012-07-24 10:51:42 +00006216
Chris Lattneree588de2011-01-15 07:29:01 +00006217 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006218 // If the source of the cast is a constant, then this should have
6219 // already been constant folded. The only reason NOT to constant fold
6220 // it is if something (e.g. LSR) was careful to place the constant
6221 // evaluation in a block other than then one that uses it (e.g. to hoist
6222 // the address of globals out of a loop). If this is the case, we don't
6223 // want to forward-subst the cast.
6224 if (isa<Constant>(CI->getOperand(0)))
6225 return false;
6226
Mehdi Amini44ede332015-07-09 02:09:04 +00006227 if (TLI && OptimizeNoopCopyExpression(CI, *TLI, *DL))
Chris Lattneree588de2011-01-15 07:29:01 +00006228 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006229
Chris Lattneree588de2011-01-15 07:29:01 +00006230 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +00006231 /// Sink a zext or sext into its user blocks if the target type doesn't
6232 /// fit in one register
Mehdi Amini44ede332015-07-09 02:09:04 +00006233 if (TLI &&
6234 TLI->getTypeAction(CI->getContext(),
6235 TLI->getValueType(*DL, CI->getType())) ==
6236 TargetLowering::TypeExpandInteger) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +00006237 return SinkCast(CI);
6238 } else {
Jun Bum Limdee55652017-04-03 19:20:07 +00006239 bool MadeChange = optimizeExt(I);
Sanjay Patelfc580a62015-09-21 23:03:16 +00006240 return MadeChange | optimizeExtUses(I);
Manuel Jacoba7c48f92014-03-13 13:36:25 +00006241 }
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006242 }
Chris Lattneree588de2011-01-15 07:29:01 +00006243 return false;
6244 }
Nadav Rotem465834c2012-07-24 10:51:42 +00006245
Chris Lattneree588de2011-01-15 07:29:01 +00006246 if (CmpInst *CI = dyn_cast<CmpInst>(I))
Hal Finkeldecb0242014-01-02 21:13:43 +00006247 if (!TLI || !TLI->hasMultipleConditionRegisters())
Peter Zotovf87e5502016-04-03 17:11:53 +00006248 return OptimizeCmpExpression(CI, TLI);
Nadav Rotem465834c2012-07-24 10:51:42 +00006249
Chris Lattneree588de2011-01-15 07:29:01 +00006250 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Sanjoy Das00757272016-12-16 20:29:39 +00006251 LI->setMetadata(LLVMContext::MD_invariant_group, nullptr);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00006252 if (TLI) {
Geoff Berry5256fca2015-11-20 22:34:39 +00006253 bool Modified = optimizeLoadExt(LI);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00006254 unsigned AS = LI->getPointerAddressSpace();
Geoff Berry5256fca2015-11-20 22:34:39 +00006255 Modified |= optimizeMemoryInst(I, I->getOperand(0), LI->getType(), AS);
6256 return Modified;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00006257 }
Hans Wennborgf3254832012-10-30 11:23:25 +00006258 return false;
Chris Lattneree588de2011-01-15 07:29:01 +00006259 }
Nadav Rotem465834c2012-07-24 10:51:42 +00006260
Chris Lattneree588de2011-01-15 07:29:01 +00006261 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Wei Mia2f0b592016-12-22 19:44:45 +00006262 if (TLI && splitMergedValStore(*SI, *DL, *TLI))
6263 return true;
Sanjoy Das00757272016-12-16 20:29:39 +00006264 SI->setMetadata(LLVMContext::MD_invariant_group, nullptr);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00006265 if (TLI) {
6266 unsigned AS = SI->getPointerAddressSpace();
Sanjay Patelfc580a62015-09-21 23:03:16 +00006267 return optimizeMemoryInst(I, SI->getOperand(1),
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00006268 SI->getOperand(0)->getType(), AS);
6269 }
Chris Lattneree588de2011-01-15 07:29:01 +00006270 return false;
6271 }
Nadav Rotem465834c2012-07-24 10:51:42 +00006272
Matt Arsenault02d915b2017-03-15 22:35:20 +00006273 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
6274 unsigned AS = RMW->getPointerAddressSpace();
6275 return optimizeMemoryInst(I, RMW->getPointerOperand(),
6276 RMW->getType(), AS);
6277 }
6278
6279 if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(I)) {
6280 unsigned AS = CmpX->getPointerAddressSpace();
6281 return optimizeMemoryInst(I, CmpX->getPointerOperand(),
6282 CmpX->getCompareOperand()->getType(), AS);
6283 }
6284
Yi Jiangd069f632014-04-21 19:34:27 +00006285 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I);
6286
Geoff Berry5d534b62017-02-21 18:53:14 +00006287 if (BinOp && (BinOp->getOpcode() == Instruction::And) &&
6288 EnableAndCmpSinking && TLI)
6289 return sinkAndCmp0Expression(BinOp, *TLI, InsertedInsts);
6290
Yi Jiangd069f632014-04-21 19:34:27 +00006291 if (BinOp && (BinOp->getOpcode() == Instruction::AShr ||
6292 BinOp->getOpcode() == Instruction::LShr)) {
6293 ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1));
6294 if (TLI && CI && TLI->hasExtractBitsInsn())
Mehdi Amini44ede332015-07-09 02:09:04 +00006295 return OptimizeExtractBits(BinOp, CI, *TLI, *DL);
Yi Jiangd069f632014-04-21 19:34:27 +00006296
6297 return false;
6298 }
6299
Chris Lattneree588de2011-01-15 07:29:01 +00006300 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00006301 if (GEPI->hasAllZeroIndices()) {
6302 /// The GEP operand must be a pointer, so must its result -> BitCast
6303 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
6304 GEPI->getName(), GEPI);
6305 GEPI->replaceAllUsesWith(NC);
6306 GEPI->eraseFromParent();
6307 ++NumGEPsElim;
Sanjay Patelfc580a62015-09-21 23:03:16 +00006308 optimizeInst(NC, ModifiedDT);
Chris Lattneree588de2011-01-15 07:29:01 +00006309 return true;
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00006310 }
Hiroshi Yamauchi93644322017-09-11 17:52:08 +00006311 if (tryUnmergingGEPsAcrossIndirectBr(GEPI, TTI)) {
6312 return true;
6313 }
Chris Lattneree588de2011-01-15 07:29:01 +00006314 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006315 }
Nadav Rotem465834c2012-07-24 10:51:42 +00006316
Chris Lattneree588de2011-01-15 07:29:01 +00006317 if (CallInst *CI = dyn_cast<CallInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00006318 return optimizeCallInst(CI, ModifiedDT);
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006319
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00006320 if (SelectInst *SI = dyn_cast<SelectInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00006321 return optimizeSelectInst(SI);
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00006322
Tim Northoveraeb8e062014-02-19 10:02:43 +00006323 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00006324 return optimizeShuffleVectorInst(SVI);
Tim Northoveraeb8e062014-02-19 10:02:43 +00006325
Sanjay Patel0ed9aea2015-11-02 23:22:49 +00006326 if (auto *Switch = dyn_cast<SwitchInst>(I))
6327 return optimizeSwitchInst(Switch);
6328
Quentin Colombetc32615d2014-10-31 17:52:53 +00006329 if (isa<ExtractElementInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00006330 return optimizeExtractElementInst(I);
Quentin Colombetc32615d2014-10-31 17:52:53 +00006331
Chris Lattneree588de2011-01-15 07:29:01 +00006332 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006333}
6334
James Molloyf01488e2016-01-15 09:20:19 +00006335/// Given an OR instruction, check to see if this is a bitreverse
6336/// idiom. If so, insert the new intrinsic and return true.
6337static bool makeBitReverse(Instruction &I, const DataLayout &DL,
6338 const TargetLowering &TLI) {
6339 if (!I.getType()->isIntegerTy() ||
6340 !TLI.isOperationLegalOrCustom(ISD::BITREVERSE,
6341 TLI.getValueType(DL, I.getType(), true)))
6342 return false;
6343
6344 SmallVector<Instruction*, 4> Insts;
Chad Rosiera00df492016-05-25 16:22:14 +00006345 if (!recognizeBSwapOrBitReverseIdiom(&I, false, true, Insts))
James Molloyf01488e2016-01-15 09:20:19 +00006346 return false;
6347 Instruction *LastInst = Insts.back();
6348 I.replaceAllUsesWith(LastInst);
6349 RecursivelyDeleteTriviallyDeadInstructions(&I);
6350 return true;
6351}
6352
Chris Lattnerf2836d12007-03-31 04:06:36 +00006353// In this pass we look for GEP and cast instructions that are used
6354// across basic blocks and rewrite them to improve basic-block-at-a-time
6355// selection.
Sanjay Patel3b8974b2017-06-08 20:00:09 +00006356bool CodeGenPrepare::optimizeBlock(BasicBlock &BB, bool &ModifiedDT) {
Cameron Zwarichce3b9302011-01-06 00:42:50 +00006357 SunkAddrs.clear();
Cameron Zwarich5dd2aa22011-03-02 03:31:46 +00006358 bool MadeChange = false;
Eric Christopherc1ea1492008-09-24 05:32:41 +00006359
Chris Lattner7a277142011-01-15 07:14:54 +00006360 CurInstIterator = BB.begin();
Elena Demikhovsky87700a72014-12-28 08:54:45 +00006361 while (CurInstIterator != BB.end()) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00006362 MadeChange |= optimizeInst(&*CurInstIterator++, ModifiedDT);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00006363 if (ModifiedDT)
6364 return true;
6365 }
Benjamin Kramer455fa352012-11-23 19:17:06 +00006366
James Molloyf01488e2016-01-15 09:20:19 +00006367 bool MadeBitReverse = true;
6368 while (TLI && MadeBitReverse) {
6369 MadeBitReverse = false;
6370 for (auto &I : reverse(BB)) {
6371 if (makeBitReverse(I, *DL, *TLI)) {
6372 MadeBitReverse = MadeChange = true;
George Burgess IVd4febd12016-03-22 21:25:08 +00006373 ModifiedDT = true;
James Molloyf01488e2016-01-15 09:20:19 +00006374 break;
6375 }
6376 }
6377 }
James Molloy3ef84c42016-01-15 10:36:01 +00006378 MadeChange |= dupRetToEnableTailCallOpts(&BB);
Junmo Park7d6c5f12016-01-28 09:42:39 +00006379
Chris Lattnerf2836d12007-03-31 04:06:36 +00006380 return MadeChange;
6381}
Devang Patel53771ba2011-08-18 00:50:51 +00006382
6383// llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotem465834c2012-07-24 10:51:42 +00006384// handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patel53771ba2011-08-18 00:50:51 +00006385// find a node corresponding to the value.
Sanjay Patelfc580a62015-09-21 23:03:16 +00006386bool CodeGenPrepare::placeDbgValues(Function &F) {
Devang Patel53771ba2011-08-18 00:50:51 +00006387 bool MadeChange = false;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +00006388 for (BasicBlock &BB : F) {
Craig Topperc0196b12014-04-14 00:51:57 +00006389 Instruction *PrevNonDbgInst = nullptr;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +00006390 for (BasicBlock::iterator BI = BB.begin(), BE = BB.end(); BI != BE;) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00006391 Instruction *Insn = &*BI++;
Devang Patel53771ba2011-08-18 00:50:51 +00006392 DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
Adrian Prantl32da8892014-04-25 20:49:25 +00006393 // Leave dbg.values that refer to an alloca alone. These
Craig Topper87e715f2017-11-07 20:56:17 +00006394 // intrinsics describe the address of a variable (= the alloca)
Adrian Prantl32da8892014-04-25 20:49:25 +00006395 // being taken. They should not be moved next to the alloca
6396 // (and to the beginning of the scope), but rather stay close to
6397 // where said address is used.
6398 if (!DVI || (DVI->getValue() && isa<AllocaInst>(DVI->getValue()))) {
Devang Patel53771ba2011-08-18 00:50:51 +00006399 PrevNonDbgInst = Insn;
6400 continue;
6401 }
6402
6403 Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
6404 if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
Reid Kleckner8de1fe22015-12-08 23:00:03 +00006405 // If VI is a phi in a block with an EHPad terminator, we can't insert
6406 // after it.
6407 if (isa<PHINode>(VI) && VI->getParent()->getTerminator()->isEHPad())
6408 continue;
Devang Patel53771ba2011-08-18 00:50:51 +00006409 DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
6410 DVI->removeFromParent();
Reid Klecknere18f92b2015-12-08 22:33:23 +00006411 if (isa<PHINode>(VI))
6412 DVI->insertBefore(&*VI->getParent()->getFirstInsertionPt());
6413 else
6414 DVI->insertAfter(VI);
Devang Patel53771ba2011-08-18 00:50:51 +00006415 MadeChange = true;
6416 ++NumDbgValueMoved;
6417 }
6418 }
6419 }
6420 return MadeChange;
6421}
Tim Northovercea0abb2014-03-29 08:22:29 +00006422
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006423/// \brief Scale down both weights to fit into uint32_t.
6424static void scaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) {
6425 uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
Eugene Zelenko900b6332017-08-29 22:32:07 +00006426 uint32_t Scale = (NewMax / std::numeric_limits<uint32_t>::max()) + 1;
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006427 NewTrue = NewTrue / Scale;
6428 NewFalse = NewFalse / Scale;
6429}
6430
6431/// \brief Some targets prefer to split a conditional branch like:
6432/// \code
6433/// %0 = icmp ne i32 %a, 0
6434/// %1 = icmp ne i32 %b, 0
6435/// %or.cond = or i1 %0, %1
6436/// br i1 %or.cond, label %TrueBB, label %FalseBB
6437/// \endcode
6438/// into multiple branch instructions like:
6439/// \code
6440/// bb1:
6441/// %0 = icmp ne i32 %a, 0
6442/// br i1 %0, label %TrueBB, label %bb2
6443/// bb2:
6444/// %1 = icmp ne i32 %b, 0
6445/// br i1 %1, label %TrueBB, label %FalseBB
6446/// \endcode
6447/// This usually allows instruction selection to do even further optimizations
6448/// and combine the compare with the branch instruction. Currently this is
6449/// applied for targets which have "cheap" jump instructions.
6450///
6451/// FIXME: Remove the (equivalent?) implementation in SelectionDAG.
6452///
6453bool CodeGenPrepare::splitBranchCondition(Function &F) {
David Blaikiedc3f01e2015-03-09 01:57:13 +00006454 if (!TM || !TM->Options.EnableFastISel || !TLI || TLI->isJumpExpensive())
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006455 return false;
6456
6457 bool MadeChange = false;
6458 for (auto &BB : F) {
6459 // Does this BB end with the following?
6460 // %cond1 = icmp|fcmp|binary instruction ...
6461 // %cond2 = icmp|fcmp|binary instruction ...
6462 // %cond.or = or|and i1 %cond1, cond2
6463 // br i1 %cond.or label %dest1, label %dest2"
6464 BinaryOperator *LogicOp;
6465 BasicBlock *TBB, *FBB;
6466 if (!match(BB.getTerminator(), m_Br(m_OneUse(m_BinOp(LogicOp)), TBB, FBB)))
6467 continue;
6468
Sanjay Patel42574202015-09-02 19:23:23 +00006469 auto *Br1 = cast<BranchInst>(BB.getTerminator());
6470 if (Br1->getMetadata(LLVMContext::MD_unpredictable))
6471 continue;
6472
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006473 unsigned Opc;
Juergen Ributzka8bda7382014-12-09 17:50:10 +00006474 Value *Cond1, *Cond2;
6475 if (match(LogicOp, m_And(m_OneUse(m_Value(Cond1)),
6476 m_OneUse(m_Value(Cond2)))))
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006477 Opc = Instruction::And;
Juergen Ributzka8bda7382014-12-09 17:50:10 +00006478 else if (match(LogicOp, m_Or(m_OneUse(m_Value(Cond1)),
6479 m_OneUse(m_Value(Cond2)))))
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006480 Opc = Instruction::Or;
6481 else
6482 continue;
6483
6484 if (!match(Cond1, m_CombineOr(m_Cmp(), m_BinOp())) ||
6485 !match(Cond2, m_CombineOr(m_Cmp(), m_BinOp())) )
6486 continue;
6487
6488 DEBUG(dbgs() << "Before branch condition splitting\n"; BB.dump());
6489
6490 // Create a new BB.
Duncan P. N. Exon Smitha848c472016-02-21 19:52:15 +00006491 auto TmpBB =
6492 BasicBlock::Create(BB.getContext(), BB.getName() + ".cond.split",
6493 BB.getParent(), BB.getNextNode());
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006494
6495 // Update original basic block by using the first condition directly by the
6496 // branch instruction and removing the no longer needed and/or instruction.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006497 Br1->setCondition(Cond1);
6498 LogicOp->eraseFromParent();
Juergen Ributzka8bda7382014-12-09 17:50:10 +00006499
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006500 // Depending on the conditon we have to either replace the true or the false
6501 // successor of the original branch instruction.
6502 if (Opc == Instruction::And)
6503 Br1->setSuccessor(0, TmpBB);
6504 else
6505 Br1->setSuccessor(1, TmpBB);
6506
6507 // Fill in the new basic block.
6508 auto *Br2 = IRBuilder<>(TmpBB).CreateCondBr(Cond2, TBB, FBB);
Juergen Ributzka8bda7382014-12-09 17:50:10 +00006509 if (auto *I = dyn_cast<Instruction>(Cond2)) {
6510 I->removeFromParent();
6511 I->insertBefore(Br2);
6512 }
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006513
6514 // Update PHI nodes in both successors. The original BB needs to be
Hiroshi Inoue6a391bb2017-06-27 10:35:37 +00006515 // replaced in one successor's PHI nodes, because the branch comes now from
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006516 // the newly generated BB (NewBB). In the other successor we need to add one
6517 // incoming edge to the PHI nodes, because both branch instructions target
6518 // now the same successor. Depending on the original branch condition
6519 // (and/or) we have to swap the successors (TrueDest, FalseDest), so that
Simon Pilgrimf2fbf432016-11-20 13:47:59 +00006520 // we perform the correct update for the PHI nodes.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006521 // This doesn't change the successor order of the just created branch
6522 // instruction (or any other instruction).
6523 if (Opc == Instruction::Or)
6524 std::swap(TBB, FBB);
6525
6526 // Replace the old BB with the new BB.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +00006527 for (PHINode &PN : TBB->phis()) {
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006528 int i;
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +00006529 while ((i = PN.getBasicBlockIndex(&BB)) >= 0)
6530 PN.setIncomingBlock(i, TmpBB);
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006531 }
6532
6533 // Add another incoming edge form the new BB.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +00006534 for (PHINode &PN : FBB->phis()) {
6535 auto *Val = PN.getIncomingValueForBlock(&BB);
6536 PN.addIncoming(Val, TmpBB);
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006537 }
6538
6539 // Update the branch weights (from SelectionDAGBuilder::
6540 // FindMergedConditions).
6541 if (Opc == Instruction::Or) {
6542 // Codegen X | Y as:
6543 // BB1:
6544 // jmp_if_X TBB
6545 // jmp TmpBB
6546 // TmpBB:
6547 // jmp_if_Y TBB
6548 // jmp FBB
6549 //
6550
6551 // We have flexibility in setting Prob for BB1 and Prob for NewBB.
6552 // The requirement is that
6553 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
6554 // = TrueProb for orignal BB.
6555 // Assuming the orignal weights are A and B, one choice is to set BB1's
6556 // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice
6557 // assumes that
6558 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
6559 // Another choice is to assume TrueProb for BB1 equals to TrueProb for
6560 // TmpBB, but the math is more complicated.
6561 uint64_t TrueWeight, FalseWeight;
Sanjay Pateldc88bd62016-04-23 20:01:22 +00006562 if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) {
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006563 uint64_t NewTrueWeight = TrueWeight;
6564 uint64_t NewFalseWeight = TrueWeight + 2 * FalseWeight;
6565 scaleWeights(NewTrueWeight, NewFalseWeight);
6566 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
6567 .createBranchWeights(TrueWeight, FalseWeight));
6568
6569 NewTrueWeight = TrueWeight;
6570 NewFalseWeight = 2 * FalseWeight;
6571 scaleWeights(NewTrueWeight, NewFalseWeight);
6572 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
6573 .createBranchWeights(TrueWeight, FalseWeight));
6574 }
6575 } else {
6576 // Codegen X & Y as:
6577 // BB1:
6578 // jmp_if_X TmpBB
6579 // jmp FBB
6580 // TmpBB:
6581 // jmp_if_Y TBB
6582 // jmp FBB
6583 //
6584 // This requires creation of TmpBB after CurBB.
6585
6586 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
6587 // The requirement is that
6588 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
6589 // = FalseProb for orignal BB.
6590 // Assuming the orignal weights are A and B, one choice is to set BB1's
6591 // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice
6592 // assumes that
6593 // FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB.
6594 uint64_t TrueWeight, FalseWeight;
Sanjay Pateldc88bd62016-04-23 20:01:22 +00006595 if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) {
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006596 uint64_t NewTrueWeight = 2 * TrueWeight + FalseWeight;
6597 uint64_t NewFalseWeight = FalseWeight;
6598 scaleWeights(NewTrueWeight, NewFalseWeight);
6599 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
6600 .createBranchWeights(TrueWeight, FalseWeight));
6601
6602 NewTrueWeight = 2 * TrueWeight;
6603 NewFalseWeight = FalseWeight;
6604 scaleWeights(NewTrueWeight, NewFalseWeight);
6605 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
6606 .createBranchWeights(TrueWeight, FalseWeight));
6607 }
6608 }
6609
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006610 // Note: No point in getting fancy here, since the DT info is never
Quentin Colombet7bdd50d2015-03-18 23:17:28 +00006611 // available to CodeGenPrepare.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006612 ModifiedDT = true;
6613
6614 MadeChange = true;
6615
6616 DEBUG(dbgs() << "After branch condition splitting\n"; BB.dump();
6617 TmpBB->dump());
6618 }
6619 return MadeChange;
6620}